# 获取主成分的权重向量 components = pca.components_ # 打印每个主成分对应的方差解释比例 for i, ratio in enumerate(explained_variance_ratio): print(f"主成分{i+1}的方差解释比例:{ratio}") # 打印每个食材对应的主成分权重 for i, component in enumerate(components): print(f"主成分{i+1}的主成分权重:{component}") # 计算每个主成分的贡献率 explained_variance_ratio_percentage = explained_variance_ratio * 100 # 打印每个主成分的贡献率 for i, percentage in enumerate(explained_variance_ratio_percentage): print(f"主成分{i+1}的贡献率:{percentage}%") 怎么在代码中加入累积主成分贡献率

时间: 2024-04-16 19:27:22 浏览: 19
要计算累积主成分贡献率,您可以使用 numpy 库中的 cumsum 函数。以下是修改后的代码示例: ```python # 获取主成分的权重向量 components = pca.components_ # 打印每个主成分对应的方差解释比例和累积主成分贡献率 explained_variance_ratio = pca.explained_variance_ratio_ explained_variance_ratio_percentage = explained_variance_ratio * 100 cumulative_variance_ratio_percentage = np.cumsum(explained_variance_ratio_percentage) for i, ratio in enumerate(explained_variance_ratio_percentage): print(f"主成分{i+1}的方差解释比例:{ratio}%") for i, percentage in enumerate(cumulative_variance_ratio_percentage): print(f"前{i+1}个主成分的累积贡献率:{percentage}%") # 打印每个食材对应的主成分权重 for i, component in enumerate(components): print(f"主成分{i+1}的主成分权重:{component}") ``` 在上述代码中,我们使用 `np.cumsum` 函数计算了累积主成分贡献率,并将其存储在变量 `cumulative_variance_ratio_percentage` 中。然后,我们在循环中打印了每个主成分的方差解释比例和相应的累积贡献率。 这样,您就可以得到每个主成分的方差解释比例、累积贡献率以及每个食材对应的主成分权重。

相关推荐

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,如何修改

import pandas as pd import numpy as np from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt # 读取数据 data = pd.read_csv('D:/pythonProject/venv/BostonHousing2.csv') # 提取前13个指标的数据 X = data.iloc[:, 5:18].values # 数据标准化 scaler = StandardScaler() X_scaled = scaler.fit_transform(X) # 主成分分析 pca = PCA() X_pca = pca.fit_transform(X_scaled) # 特征值和特征向量 eigenvalues = pca.explained_variance_ eigenvectors = pca.components_.T # 碎石图 variance_explained = np.cumsum(eigenvalues / np.sum(eigenvalues)) plt.plot(range(6, 19), variance_explained, marker='o') plt.xlabel('Number of Components') plt.ylabel('Cumulative Proportion of Variance Explained') plt.title('Scree Plot') plt.show() # 选择主成分个数 n_components = np.sum(variance_explained <= 0.95) + 1 # 前2个主成分的载荷图 loadings = pd.DataFrame(eigenvectors[:, 0:2], columns=['PC1', 'PC2'], index=data.columns[0:13]) plt.figure(figsize=(10, 6)) plt.scatter(loadings['PC1'], loadings['PC2'], alpha=0.7) for i, feature in enumerate(loadings.index): plt.text(loadings['PC1'][i], loadings['PC2'][i], feature) plt.xlabel('PC1') plt.ylabel('PC2') plt.title('Loading Plot') plt.grid() plt.show() # 主成分得分图 scores = pd.DataFrame(X_pca[:, 0:n_components], columns=['PC{}'.format(i+1) for i in range(n_components)]) plt.figure(figsize=(10, 6)) plt.scatter(scores['PC1'], scores['PC2'], alpha=0.7) for i, label in enumerate(data['MEDV']): plt.text(scores['PC1'][i], scores['PC2'][i], label) plt.xlabel('PC1') plt.ylabel('PC2') plt.title('Scores Plot') plt.grid() plt.show() # 综合评估和排序 data['PC1_score'] = X_pca[:, 0] sorted_data = data.sort_values(by='PC1_score') # 主成分回归模型 from sklearn.linear_model import LinearRegression Y = data['MEDV'].values.reshape(-1, 1) X_pca_regression = X_pca[:, 0].reshape(-1, 1) regression_model = LinearRegression() regression_model.fit(X_pca_regression, Y) # 回归方程 intercept = regression_model.intercept_[0] slope = regression_model.coef_[0][0] equation = "MEDV = {:.2f} + {:.2f} * PC1".format(intercept, slope) print("Regression Equation:", equation) # 最小二乘估计结果 from statsmodels.api import OLS X_const = np.concatenate((np.ones((506, 1)), X_pca_regression), axis=1) ols_model = OLS(Y, X_const).fit() print("OLS Regression Summary:") print(ols_model.summary())

import pandas as pd import numpy as np from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt # 读取数据 data = pd.read_csv('D:\\pythonProject\\venv\\BostonHousing2.csv') # 提取前13个指标的数据 X = data.iloc[:, 5:18].values # 数据标准化 scaler = StandardScaler() X_scaled = scaler.fit_transform(X) # 主成分分析 pca = PCA() X_pca = pca.fit_transform(X_scaled) # 特征值和特征向量 eigenvalues = pca.explained_variance_ eigenvectors = pca.components_.T # 碎石图 # variance_explained我给你放到下一个cell里面了,这里用eigenvalues代替variance_explained plt.plot(range(1, 14), eigenvalues, marker='o') plt.xlabel('Number of Components') plt.ylabel('Cumulative Proportion of Variance Explained') plt.title('Scree Plot') plt.show() # 选择主成分个数 variance_explained = np.cumsum(eigenvalues / np.sum(eigenvalues)) n_components = np.sum(variance_explained <= 0.95) + 1 # 前2个主成分的载荷图 loadings = pd.DataFrame(eigenvectors[:, 0:2], columns=['PC1', 'PC2'], index=data.columns[0:13]) plt.figure(figsize=(10, 6)) plt.scatter(loadings['PC1'], loadings['PC2'], alpha=0.7) for i, feature in enumerate(loadings.index): plt.text(loadings['PC1'][i], loadings['PC2'][i], feature) plt.xlabel('PC1') plt.ylabel('PC2') plt.title('Loading Plot') plt.grid() plt.show() # 主成分得分图 scores = pd.DataFrame(X_pca[:, 0:n_components], columns=['PC{}'.format(i+1) for i in range(n_components)]) plt.figure(figsize=(10, 6)) plt.scatter(scores['PC1'], scores['PC2'], alpha=0.7) for i, label in enumerate(data['medv']): plt.text(scores['PC1'][i], scores['PC2'][i], label) plt.xlabel('PC1') plt.ylabel('PC2') plt.title('Scores Plot') plt.grid() plt.show() # 综合评估和排序 data['PC1_score'] = X_pca[:, 0] sorted_data = data.sort_values(by='PC1_score') # 主成分回归模型 from sklearn.linear_model import LinearRegression Y = data['medv'].values.reshape(-1, 1) X_pca_regression = X_pca[:, 0].reshape(-1, 1) regression_model = LinearRegression() regression_model.fit(X_pca_regression, Y) # 回归方程 intercept = regression_model.intercept_[0] slope = regression_model.coef_[0][0] equation = "medv = {:.2f} + {:.2f} * PC1".format(intercept, slope) print("Regression Equation:", equation) # 最小二乘估计结果 from statsmodels.api import OLS X_const = np.concatenate((np.ones((506, 1)), X_pca_regression), axis=1) ols_model = OLS(Y, X_const).fit() print("OLS Regression Summary:") print(ols_model.summary())

最新推荐

recommend-type

具体介绍sklearn库中:主成分分析(PCA)的参数、属性、方法

主成分分析(Principal components analysis,以下简称PCA)的思想是将n维特征映射到k维上(k&lt;n),这k维是全新的正交特征(新的坐标系)。这k维特征称为主元,是重新构造出来的k维特征,而不是简单地从n维特征中...
recommend-type

安装NumPy教程-详细版

附件是安装NumPy教程_详细版,文件绿色安全,请大家放心下载,仅供交流学习使用,无任何商业目的!
recommend-type

语音端点检测及其在Matlab中的实现.zip

语音端点检测及其在Matlab中的实现.zip
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

可见光定位LED及其供电硬件具体型号,广角镜头和探测器,实验设计具体流程步骤,

1. 可见光定位LED型号:一般可使用5mm或3mm的普通白色LED,也可以选择专门用于定位的LED,例如OSRAM公司的SFH 4715AS或Vishay公司的VLMU3500-385-120。 2. 供电硬件型号:可以使用常见的直流电源供电,也可以选择专门的LED驱动器,例如Meanwell公司的ELG-75-C或ELG-150-C系列。 3. 广角镜头和探测器型号:一般可采用广角透镜和CMOS摄像头或光电二极管探测器,例如Omron公司的B5W-LA或Murata公司的IRS-B210ST01。 4. 实验设计流程步骤: 1)确定实验目的和研究对象,例如车辆或机器人的定位和导航。
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这