【问题标题】:using principal component analysis to visualize data使用主成分分析来可视化数据
【发布时间】:2020-02-12 13:03:41
【问题描述】:

我正在尝试使用 pca 来可视化我的数据。我有一个包含 4 个变量(日期、地下水位、降雨量、温度)Here is an example of my dataset 的数据集。我想看看降雨量和 gwl 以及 temp 和 gwl 之间是否存在关系。

我听说我可以使用 pca 或回归来尝试这个。我对此很陌生,对如何去做这件事有点困惑。

我按照网上的教程,但最后我得到了一个错误:

 >>>> **TypeError: invalid type comparison**. 

我很困惑,因为目标不是简单的 0 或 1,而是地下水位 (gwl)。我想看看地下水位和温度之间是否有任何相关性

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_excel("C:/Users/Tamarie/Downloads/joined1.xlsx")
print(df.dtypes)
df.head()
df.info()

from sklearn.preprocessing import StandardScaler
features = ['rainfall', 'temperature', 'Evapotrans']
# Separating out the features
x = df.loc[:, features].values
# Separating out the target
y = df.loc[:,['gwl']].values
# Standardizing the features
x = StandardScaler().fit_transform(x)

from sklearn.decomposition import PCA
pca = PCA(n_components=2)
principalComponents = pca.fit_transform(x)
principalDf = pd.DataFrame(data = principalComponents
             , columns = ['principal component 1', 'principal component 2'])

finalDf = pd.concat([principalDf, df[['gwl']]], axis = 1)
fig = plt.figure(figsize = (8,8))
ax = fig.add_subplot(1,1,1) 
ax.set_xlabel('Principal Component 1', fontsize = 15)
ax.set_ylabel('Principal Component 2', fontsize = 15)
ax.set_title('2 component PCA', fontsize = 20)
targets = ['gwl']
colors = ['r', 'g', 'b']
for target, color in zip(targets,colors):
    indicesToKeep = finalDf['gwl'] == target
    ax.scatter(finalDf.loc[indicesToKeep, 'principal component 1']
               , finalDf.loc[indicesToKeep, 'principal component 2']
               , c = color
               , s = 50)
ax.legend(targets)
ax.grid()

【问题讨论】:

  • 您能告诉我们数据框中变量的类型吗?以便其他人可以帮助您。
  • 请提供MVE
  • @Justice_Lords 我已经编辑了我的问题以包含我的数据集示例
  • 为什么不使用散点图?还有相关矩阵热图?查看 seaborn 中的pairplot。我不明白为什么 PCA 会在这里帮助你......
  • @Dan 最终这样做了,谢谢

标签: python pandas pca


【解决方案1】:
targets = ['gwl']
colors = ['r', 'g', 'b']
for target, color in zip(targets,colors):
    indicesToKeep = finalDf['gwl'] == target 

在这一行中,为什么要将 finalDf['gwl'] 浮点列表与目标字符串进行比较

不过,如果你想看看地下水位和温度之间是否有任何相关性

那么你可以在地下水位和温度列之间绘制散点图

【讨论】:

  • 我最终使用了散点图,因为我完全不确定我在这里做什么。谢谢
  • 别担心,你很快就会知道的。看,当我们的数据中有更多的 3 个特征列时,显然我们无法将其可视化,因此为了可视化具有超过 3 个特征的数据,我们使用 PCA。 PCA 将我们的列转换为 2 或 3 个主成分,然后我们可以可视化这些新列。 PCA 是一种降维技术。
猜你喜欢
  • 1970-01-01
  • 2014-06-10
  • 1970-01-01
  • 2020-06-23
  • 2012-01-14
  • 2012-11-10
  • 1970-01-01
  • 2016-01-16
  • 2013-08-24
相关资源
最近更新 更多