用python做主成分分析PCA

晚上才写完,还没有经过数据的测试。不过还是想先贴出来,出来再测试修改完善下。

要用到三个库,pandas打开excel获取数据,numpy做矩阵处理和math函数。

import numpy as np
import math
import pandas as pd

data_frame = pd.read_excel('data.xls', sheet_name= '表1' )
A = np.array(data_frame)
#print(A)
size = A.shape
name = A[: , 0]
AA = A
#print(name)
for j in range(1, size[1]):
    uj = 0
    for i in range(0, size[0]):
        uj = uj + A[i][j]
    uj = uj / size[0]
    s = 0
    for i in range(0, size[0]):
        s = s + (A[i][j] - uj)*(A[i][j] - uj)
    s = s / (size[0] - 1) # 方差是无偏估计
    s = math.sqrt(s)
    for i in range(0, size[0]):
        A[i][j] = (A[i][j] - uj) / s

AA = A[:, 1:size[1]+1]
AA = AA.T #转置
B = np.cov(AA.astype(float)) #astype转格式
eigenvalue, eigenvector = np.linalg.eig(B)
#eigenvalue = sorted(eigenvalue)
sum = np.sum(eigenvalue)
m = 0
acr = 0
for i in range(0, eigenvalue.shape[0]):
    acr = acr + eigenvalue[i] / sum
    if acr > 0.85:
        m = i
        break

print("选取"+str(m+1)+"个主成分")
print("系数矩阵:")
for i in range(0, m+1):
    for j in range(0, size[1] - 1):
        print(eigenvector[i][j], end='')
        print('  ', end='')
    print('')

 

你可能感兴趣的:(信计上机作业,python)