import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from mpl_toolkits.mplot3d import Axes3D from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler data=pd.read_csv('H:/analysis_results/mean_HN.csv') data.head() x=data.iloc[:,1:7] y=data.iloc[:,6] scaler=StandardScaler() scaler.fit(x) x_scaler=scaler.transform(x) print(x_scaler.shape) pca=PCA(n_components=3) x_pca=pca.fit_transform(x_scaler) print(x_pca.shape) #查看各个主成分对应的方差大小和占全部方差的比例 #可以看到前2个主成分已经解释了样本分布的90%的差异了 print('explained_variance_:',pca.explained_variance_) print('explained_variance_ratio_:',pca.explained_variance_ratio_) print('total explained variance ratio of first 6 principal components:',sum(pca.explained_variance_ratio_)) #将分析的结果保存成字典 result={ 'explained_variance_:',pca.explained_variance_, 'explained_variance_ratio_:',pca.explained_variance_ratio_, 'total explained variance ratio:',np.sum(pca.explained_variance_ratio_)} df=pd.DataFrame.from_dict(result,orient='index',columns=['value']) df.to_csv('H:/analysis_results/Cluster analysis/pca_explained_variance_HN.csv') #可视化各个主成分贡献的方差 #fig1=plt.figure(figsize=(10,10)) #plt.rcParams['figure.dpi'] = 300#设置像素参数值 plt.rcParams['path.simplify'] = False#禁用抗锯齿效果 plt.figure() plt.plot(np.arange(1,4),pca.explained_variance_,color='blue', linestyle='-',linewidth=2) plt.xticks(np.arange(1, 4, 1))#修改X轴间隔为1 plt.title('PCA_plot_HN') plt.xlabel('components_n',fontsize=16) plt.ylabel('explained_variance_',fontsize=16) #plt.savefig('H:/analysis_results/Cluster analysis/pca_explained_variance_HN.png') plt.show()报错unhashable type: 'numpy.ndarray',如何修改
时间: 2024-03-21 20:40:04 浏览: 142
python数据分析与可视化 import pandas as pd import numpy as np import m
这个错误通常是由于字典中存在不可哈希对象 (unhashable type),比如 numpy 数组,而字典的键必须是可哈希的对象。你可以将 numpy 数组转换为列表,然后再保存到字典中,例如:
```
result={
'explained_variance_': pca.explained_variance_.tolist(),
'explained_variance_ratio_': pca.explained_variance_ratio_.tolist(),
'total explained variance ratio': np.sum(pca.explained_variance_ratio_)
}
```
这样就可以避免 unhashable type 错误了。
阅读全文