【发布时间】: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 最终这样做了,谢谢