import numpy as np
from sklearn.decomposition import PCA
from sklearn import datasets
import matplotlib
import matplotlib.pyplot as plt
#加载数据
data = np.loadtxt(open("./data/task1.csv","r"),delimiter=",",skiprows=0)
#设置主成分参数:pc个数,数值求解器的类型
pca = PCA(n_components=10, svd_solver='full')
#得到score vectors
Data_transformed = pca.fit(data).transform(data)
#输出第一个对象在first PC 上的值,即score vectors 的第一行
print(np.round(Data_transformed[0][0],3))
#2输出第一个对象在second PC 上的值
print(np.round(Data_transformed[0][1],3))
#得到variance explained
explained_variance = np.cumsum(pca.explained_variance_ratio_)
#3当使用前两个主成分时的variance explained
print(np.round(explained_variance[1],3))
plt.plot(np.arange(10), np.round(explained_variance,3), ls = '-')
plt.show()
#4variance explained 大于0.85时应该使用前几个主成分
for i in range(0,10):
if explained_variance[i]>0.85:
print(i+1)
break
#5
plt.plot(Data_transformed[:60, 0], Data_transformed[:60, 1], 'o', markerfacecolor='red', markeredgecolor='k', markersize=8)
plt.show()
使用score vectors 和 loading vectors 重构原始图像
import numpy as np
scores = np.genfromtxt('./data/task12_score.csv', delimiter=';')
loadings = np.genfromtxt('./data/task12_loading.csv', delimiter=';')
values = np.dot(scores,loadings.T)
import matplotlib.pyplot as plt
#1
plt.imshow(values, cmap='Greys_r')
plt.show()