CH04算法进阶_PCA主成分分析
2019-01-02 本文已影响63人
BeautifulSoulpy
理论部分







python实现PCA主成分分析
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
import os
%matplotlib inline
# 二维数据降维
# 数据创建
rng=np.random.RandomState(8)
data=np.dot(rng.rand(2,2),rng.randn(2,200)).T #np.dot方法是一个矩阵相乘的方法;
df = pd.DataFrame({'X1':data[:,0],
'X2':data[:,1]})
print(df.head())
print(df.shape)
plt.scatter(df['X1'],df['X2'],alpha=0.8,marker='.')
plt.axis('equal')
plt.grid()
#生成图表格
X1 X2
0 -1.174787 -1.404131
1 -1.374449 -1.294660
2 -2.316007 -2.166109
3 0.947847 1.460480
4 1.762375 1.640622
(200, 2)

# 二维数据降维
# 构建模型,分析主成分
from sklearn.decomposition import PCA
pca=PCA(n_components=1) #n_components=1 -降为1维
pca.fit(df) #构建模型
#sklearn.decomposition.PCA(n_components=None, copy=True ,white=False)
# n_components: PCA算法中所要保留的主成分个数n,也即保留下来的特征个数n
# copy: True或者False ,默认为True - 表示是否在运行算法时,将原始训练数据复制一份
# fit(X,y=None) - 调用fit方法的对象本身,比如pca,fit(X),表示用X对pca这个对象进行训练;
print(pca.explained_variance_) #特征值
print(pca.components_) #2个特征向量
print(pca.n_components) #1个主成分
# 这里是shape(200,2)降为shape(200,1),只有1个特征值,对应2个特征向量;
# 降维后主成分A1=0.7788006*X1 + 0.62727158*X2
x_pca=pca.transform(df) #数据转换
#x_pca #训练后的一维数据;
x_new=pca.inverse_transform(x_pca) # 将降维后的数据转换成新的原始数据
print('orihinal shape:',df.shape)
print('transformed shape:',x_pca.shape)
print(x_pca[:5])
print('-----------------------------')
# 主成分分析,生成新的向量x_pca
# fit_transform(X) - 用X来训练PCA模型,同时返回降维后的数据,这里x_pca就是降维后的数据;
# inverse_transform() -将降维后的数据转换成原始数据;
plt.scatter(df['X1'],df['X2'],alpha=0.8,marker='.')
plt.scatter(x_new[:,0],x_new[:,1],alpha=0.8,marker='.',color='r')
plt.axis('equal')
plt.grid()
#生成图表
[2.79699086]
[[-0.7788006 -0.62727158]]
1
orihinal shape: (200, 2)
transformed shape: (200, 1)
[[ 1.77885258]
[ 1.8656813 ]
[ 3.14560277]
[-1.67114513]
[-2.41849842]]
-----------------------------
</pre>
