import pandas as pd #导入处理二维表格的库
import numpy as np #导入数值计算的库
from sklearn.preprocessing import StandardScaler #导入数据标准化模块
import matplotlib.pyplot as plt #导入画图的包
from sklearn.decomposition import PCA #导入主成分分析的类
# 导入数据
data_FI=pd.read_excel(r"C:\Users\a2044\Desktop\Subject document\大数据\投资学\FI.xlsx")
data_FI.head(5)#展示数据前5行
# 数据预处理
scaler=StandardScaler() #实例化标准处理的类
standard_FI=pd.DataFrame(scaler.fit_transform(data_FI))#标准化数据:Standard_FI=(data_FI-μ)/σ
# 确认重要的变量M:变量方差大(因为方差小的变量去掉了,不会有什么影响,方差小的变量之间的相关性大,可以相互替代)
pca=PCA(n_components=13)#百分百,先不去掉指标,即13个指标都要
reduced_x=pca.fit_transform(standard_FI)#对标准化后的数据进行主成分分析
covper=pca.explained_variance_ #把主成分分析指标的方差存储
covper=pd.DataFrame(np.round(covper,3)) #处理数据,保留方差三位有效数字
plt.plot(covper,'b*--')#画出碎石图
plt.xlabel('Component')#指标
plt.ylabel('Variance')#方差
plt.show()
pca=PCA(n_components=5)#重新实例化PCA,只取5个方差比较大的指标,对平均值影响大
reduced_x=pca.fit_transform(standard_FI)#对标准化后的数据进行主成分分析
covper=pca.explained_variance_ #把主成分分析指标的方差存储
covper=pd.DataFrame(np.round(covper,3)) #处理数据,保留方差三位有效数字
plt.plot(covper,'rx-')
plt.xlabel('Component')#指标
plt.ylabel('Variance')#方差
plt.show()
result=pd.DataFrame(np.round(reduced_x,3))
result.head(10)
# 新生成的5个指标与13个指标的权重关系
coefficient=pd.DataFrame(np.round(pca.components_,3),columns=data_FI.columns)
coefficient.head(10)#行名为主成分,列名为指标名,里面的数据为系数(载荷因子);主成分为指标的线性组合