机器学习——主成分分析Python实现

本文介绍了主成分分析(PCA)的基本概念,并详细阐述了PCA的实施步骤,包括数据标准化、协方差矩阵计算、特征向量选择等。在Python中,PCA可通过Scikit-Learn库实现,调整n_components参数进行降维。最后,文章以《Python数据分析与挖掘实战》数据集为例,展示了PCA的实际应用。
摘要由CSDN通过智能技术生成

主成分分析

以下引自百度百科和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、步骤

  1. 将d维度原始数据标准化。
  2. 构建协方差矩阵(因为已经对数据进行标准化,所以协方差矩阵也为原始数据的相关系数矩阵)。
  3. 求解协方差矩阵的特征向量和特征值。
  4. 选择值最大的k个特征值对应的特征向量,k就是新特征空间的维度,k<<d;或者也可以选择累计方差贡献率大于85%以上的前k个特征。
  5. 利用前k特征向量构建映射矩阵W。
  6. 将原始数据d维度的数据集X,通过映射矩阵W转换到k维度的特征子空间。

2、Python实现

在Python中,主成分分析的函数位于Scikit-Learn中:

sklearn.decomposition.pca(n_components=None, copy=True,whiten=False)

导入:

from sklearn.decomposition import PCA

参数说明:

  1. 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_
  1. copy
    类型:bool,True或者False,缺省时默认为True。
    意义:表示是否在运行算法时,将原始训练数据复制一份,若为True,则运行PCA算法后,原始训练数据的值不会有任何改变。因为是在原始数据的副本上进行运算的;若为False,在运算PCA算法后,原始训练数据的值会改变,因为是在原始数据上进行降维计算。
  2. 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
  • 1
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值