主成分分析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)
相关推荐
前端付豪14 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽14 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战14 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋20 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者2 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时2 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构