主成分分析
以下引自百度百科和wiki:
主成分分析(Principal Component Analysis,PCA), 是一种统计方法。通过正交变换将一组可能存在相关性的变量转换为一组线性不相关的变量,转换后的这组变量叫主成分。在实际课题中,为了全面分析问题,往往提出很多与此有关的变量(或因素),因为每个变量都在不同程度上反映这个课题的某些信息。主成分分析首先是由K.皮尔森(Karl Pearson)对非随机变量引入的,尔后H.霍特林将此方法推广到随机向量的情形。信息的大小通常用离差平方和或方差来衡量。
Principal component analysis (PCA) is a mathematical procedure that uses an orthogonal transformation to convert a set of observations of possibly correlated variables into a set of values of linearly uncorrelated variables called principal components. The number of principal components is less than or equal to the number of original variables. This transformation is defined in such a way that the first principal component has the largest possible variance (that is, accounts for as much of the variability in the data as possible), and each succeeding component in turn has the highest variance possible under the constraint that it be orthogonal to (i.e., uncorrelated with) the preceding components. Principal components are guaranteed to be independent if the data set is jointly normally distributed. PCA is sensitive to the relative scaling of the original variables.
1、步骤
- 将d维度原始数据标准化。
- 构建协方差矩阵(因为已经对数据进行标准化,所以协方差矩阵也为原始数据的相关系数矩阵)。
- 求解协方差矩阵的特征向量和特征值。
- 选择值最大的k个特征值对应的特征向量,k就是新特征空间的维度,k<<d;或者也可以选择累计方差贡献率大于85%以上的前k个特征。
- 利用前k特征向量构建映射矩阵W。
- 将原始数据d维度的数据集X,通过映射矩阵W转换到k维度的特征子空间。
2、Python实现
在Python中,主成分分析的函数位于Scikit-Learn中:
sklearn.decomposition.pca(n_components=None, copy=True,whiten=False)
导入:
from sklearn.decomposition import PCA
参数说明:
- n_components
意义:PCA算法中要保留的主成分个数n,也即经过线性变换后保留下来的特征个数n,起到降维的效果。
类型:int或者string。缺省时默认为None,所有成分被保留,可以通过explained_variance_ratio属性得到每个主成分的方差解释率。赋值为int,比如n_components=3,将把原始数据降到三个维度。赋值为string,比如n_components=‘mle’,将自动选取特征个数n,使得满足所要求的的方差百分比。
pca=PCA(n_components=None)
X_train_pca=pca.fit_transform(X_train_std)
pca.explained_variance_ratio_
- copy
类型:bool,True或者False,缺省时默认为True。
意义:表示是否在运行算法时,将原始训练数据复制一份,若为True,则运行PCA算法后,原始训练数据的值不会有任何改变。因为是在原始数据的副本上进行运算的;若为False,在运算PCA算法后,原始训练数据的值会改变,因为是在原始数据上进行降维计算。 - whiten
类型:bool,缺省时默认为False。
意义:白化,使得每个特征具有相同的方差。
3、案例
使用《Python数据分析与挖掘实战》的principal_component.csv数据作为原始数据进行分析。
import pandas as pd
from sklearn.decomposition import PCA
data=pd.read_csv("D:/anaconda/data/principal_component.csv",header=None)
data.shape
(14, 8) #数据有14个观测,8个特征。
pca=PCA(n_components=None)
pca.fit(data)
pca.components_ #显示各特征的特征向量。
array([[ 0.56788461, 0.2280431 , 0.23281436, 0.22427336, 0.3358618 ,
0.43679539