主成分分析,即Principal Component Analysis(PCA),是多元统计中的重要内容,也广泛应用于机器学习和其它领域。它的主要作用是对高维数据进行降维。PCA把原先的n个特征用数目更少的k个特征取代,新特征是旧特征的线性组合,这些线性组合最大化样本方差,尽量使新的k个特征互不相关。关于PCA的更多介绍,请参考:https://en.wikipedia.org/wiki/Principal_component_analysis.
PCA的主要算法如下:
- 组织数据形式,以便于模型使用;
- 计算样本每个特征的平均值;
- 每个样本数据减去该特征的平均值(归一化处理);
- 求协方差矩阵;
- 找到协方差矩阵的特征值和特征向量;
- 对特征值和特征向量重新排列(特征值从大到小排列);
- 对特征值求取累计贡献率;
- 对累计贡献率按照某个特定比例选取特征向量集的子集合;
- 对原始数据(第三步后)进行转换。
其中协方差矩阵的分解可以通过按对称矩阵的特征向量来,也可以通过分解矩阵的SVD来实现,而在Scikit-learn中,也是采用SVD来实现PCA算法的。关于SVD的介绍及其原理,可以参考:矩阵的奇异值分解(SVD)(理论)。
本文将用三种方法来实现PCA算法,一种是原始算法,即上面所描述的算法过程,具体的计算方法和过程,可以参考:A tutorial on Principal Components Analysis, Lindsay I Smith. 一种是带SVD的原始算法,在Python的Numpy模块中已经实现了SVD算法,并且将特征值从大从小排列,省去了对特征值和特征向量重新排列这一步。最后一种方法是用Python的Scikit-learn模块实现的PCA类直接进行计算,来验证前面两种方法的正确性。
用以上三种方法来实现PCA的完整的Python如下:
1 import numpy as np 2 from sklearn.decomposition import PCA 3 import sys 4 #returns choosing how many main factors 5 def index_lst(lst, component=0, rate=0): 6 #component: numbers of main factors 7 #rate: rate of sum(main factors)/sum(all factors) 8 #rate range suggest: (0.8,1) 9 #if you choose rate parameter, return index = 0 or less than len(lst) 10 if component and rate: 11 print('Component and rate must choose only one!') 12 sys.exit(0) 13 if not component and not rate: 14 print('Invalid parameter for numbers of components!') 15 sys.exit(0) 16 elif component: 17 print('Choosing by component, components are %s......'%component) 18 return component 19 else: 20 print('Choosing by rate, rate is %s ......'%rate) 21 for i in range(1, len(lst)): 22 if sum(lst[:i])/sum(lst) >= rate: 23 return i 24 return 0 25 26 def main(): 27 # test data 28 mat = [[-1,-1,0,2,1],[2,0,0,-1,-1],[2,0,1,1,0]] 29 30 # simple transform of test data 31 Mat = np.array(mat, dtype='float64') 32 print('Before PCA transforMation, data is: ', Mat) 33 print(' Method 1: PCA by original algorithm:') 34 p,n = np.shape(Mat) # shape of Mat 35 t = np.mean(Mat, 0) # mean of each column 36 37 # substract the mean of each column 38 for i in range(p): 39 for j in range(n): 40 Mat[i,j] = float(Mat[i,j]-t[j]) 41 42 # covariance Matrix 43 cov_Mat = np.dot(Mat.T, Mat)/(p-1) 44 45 # PCA by original algorithm 46 # eigvalues and eigenvectors of covariance Matrix with eigvalues descending 47 U,V = np.linalg.eigh(cov_Mat) 48 # Rearrange the eigenvectors and eigenvalues 49 U = U[::-1] 50 for i in range(n): 51 V[i,:] = V[i,:][::-1] 52 # choose eigenvalue by component or rate, not both of them euqal to 0 53 Index = index_lst(U, component=2) # choose how many main factors 54 if Index: 55 v = V[:,:Index] # subset of Unitary matrix 56 else: # improper rate choice may return Index=0 57 print('Invalid rate choice. Please adjust the rate.') 58 print('Rate distribute follows:') 59 print([sum(U[:i])/sum(U) for i in range(1, len(U)+1)]) 60 sys.exit(0) 61 # data transformation 62 T1 = np.dot(Mat, v) 63 # print the transformed data 64 print('We choose %d main factors.'%Index) 65 print('After PCA transformation, data becomes: ',T1) 66 67 # PCA by original algorithm using SVD 68 print(' Method 2: PCA by original algorithm using SVD:') 69 # u: Unitary matrix, eigenvectors in columns 70 # d: list of the singular values, sorted in descending order 71 u,d,v = np.linalg.svd(cov_Mat) 72 Index = index_lst(d, rate=0.95) # choose how many main factors 73 T2 = np.dot(Mat, u[:,:Index]) # transformed data 74 print('We choose %d main factors.'%Index) 75 print('After PCA transformation, data becomes: ',T2) 76 77 # PCA by Scikit-learn 78 pca = PCA(n_components=2) # n_components can be integer or float in (0,1) 79 pca.fit(mat) # fit the model 80 print(' Method 3: PCA by Scikit-learn:') 81 print('After PCA transformation, data becomes:') 82 print(pca.fit_transform(mat)) # transformed data 83 84 main()
运行以上代码,输出结果为:
这说明用以上三种方法来实现PCA都是可行的。这样我们就能理解PCA的具体实现过程啦~~有兴趣的读者可以用其它语言实现一下哈~~
参考文献:
- PCA 维基百科: https://en.wikipedia.org/wiki/Principal_component_analysis.
- 讲解详细又全面的PCA教程: A tutorial on Principal Components Analysis, Lindsay I Smith.
- 博客:矩阵的奇异值分解(SVD)(理论):http://www.cnblogs.com/jclian91/p/8022426.html.
- 博客:主成分分析PCA: https://www.cnblogs.com/zhangchaoyang/articles/2222048.html.
- Scikit-learn的PCA介绍:http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html.