主成分分析python代码实现

版本一:使用numpy、panda

python 复制代码
import numpy as np
import pandas as pd

#PCA:principal component analysis 主成分分析法

#读取数据,以outcome.xlsx为例
data=pd.read_excel('outcome.xlsx',sheet_name='人均消费(元)')
data=data.set_index('省份')

#获取样本数量、指标数量
n,p=data.shape
print(f'样本数量:{n},指标数量:{p}')

#1、Z标准化{消除量纲影响}
data_Z=(data-data.mean(axis=0))/data.std(axis=0)

#2、计算协方差矩阵[相关系数矩阵]
data_cov=data_Z.cov()


#1、2 等价于计算相关系数矩阵
# data_corr=data.corr()

#3、计算相关系数矩阵的特征值与特征向量
eigValues,eigVectors=np.linalg.eig(data_cov)

# 获取特征值的排序索引
sorted_indices = np.argsort(eigValues)[::-1]

# 使用排序索引重新排列特征值和特征向量
sorted_eigValues = eigValues[sorted_indices]
sorted_eigVectors = eigVectors[:, sorted_indices]
#特征向量标准化
sorted_eigVectors = sorted_eigVectors / np.linalg.norm(sorted_eigVectors, axis=0)

#4、计算特征值贡献率与累计贡献率
sorted_eigValues_rate = sorted_eigValues/sorted_eigValues.sum()
sorted_eigVectors_cumrate=sorted_eigValues_rate.cumsum()

print(f'贡献率为   {sorted_eigValues_rate}')
print(f'累计贡献率为  {sorted_eigVectors_cumrate}')

#5、决定主成分数量
m=int(input('选择你需要的主成分数量:'))

#6、获取各主成分中各指标线性组合系数
Reduce_Matrix=sorted_eigVectors[:,0:m]
print(Reduce_Matrix)

版本二:使用sklearn库中的PCA模块

python 复制代码
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

# 读取数据,以outcome.xlsx为例
data = pd.read_excel('outcome.xlsx', sheet_name='人均消费(元)')
data = data.set_index('省份')

# 获取样本数量、指标数量
n, p = data.shape
print(f'样本数量: {n}, 指标数量: {p}')

# 1、Z标准化{消除量纲影响}
scaler = StandardScaler()
data_Z = scaler.fit_transform(data)

# 2、使用PCA进行主成分分析
pca = PCA()
pca.fit(data_Z)

# 3、计算特征值贡献率与累计贡献率
explained_variance_ratio = pca.explained_variance_ratio_
cumulative_explained_variance_ratio = np.cumsum(explained_variance_ratio)

print(f'贡献率为   {explained_variance_ratio}')
print(f'累计贡献率为  {cumulative_explained_variance_ratio}')

# 4、决定主成分数量
m = int(input('选择你需要的主成分数量:'))

# 5、获取主成分中各指标线性组合的系数
components = pca.components_.T[:,:m]
# 将系数转换为DataFrame以便更好地查看
components_df = pd.DataFrame(components, index=data.columns, columns=[f'主成分{i+1}' for i in range(m)])
print(components_df)

# 6、计算降维后的矩阵并输出
pca = PCA(n_components=m)
Reduce_Matrix = pca.fit_transform(data_Z)
col = [f'主成分{i+1}' for i in range(m)]
New_outcome = pd.DataFrame(data=Reduce_Matrix, index=data.index, columns=col)
print(New_outcome)
相关推荐
这里有鱼汤2 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩12 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在17 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP19 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780511 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
c8i1 天前
python中类的基本结构、特殊属性于MRO理解
python
echoarts1 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
liwulin05061 天前
【ESP32-CAM】HELLO WORLD
python
Aomnitrix1 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式