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()报错'numpy.float64' object is not iterable,如何修改
时间: 2024-03-21 09:42:07 浏览: 127
python数据分析与可视化 import pandas as pd import numpy as np import m
出现这个错误是因为在创建字典时,某些值被错误地设置为单个浮点数,而不是列表或数组。请将以下代码:
```
result={
'explained_variance_:',pca.explained_variance_,
'explained_variance_ratio_:',pca.explained_variance_ratio_,
'total explained variance ratio:',np.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_)]
}
```
这样就会将每个值包装在一个单元素列表中,以便字典能够正确地创建。
阅读全文