机器人之人工智障学习笔记——机器学习(11)PCA降维
小标 2018-10-17 来源 : 阅读 1238 评论 0

摘要:本文主要向大家介绍了机器人之人工智障学习笔记——机器学习(11)PCA降维,通过具体的内容向大家展现,希望对大家学习机器人有所帮助。

本文主要向大家介绍了机器人之人工智障学习笔记——机器学习(11)PCA降维,通过具体的内容向大家展现,希望对大家学习机器人有所帮助。

一.概念

Principal Component Analysis(PCA):主成分分析法,是最常用的线性降维方法,它的目标是通过某种线性投影,将高维的数据映射到低维的空间中表示,即把原先的n个特征用数目更少的m个特征取代,新特征是旧特征的线性组合。并期望在所投影的维度上数据的方差最大,尽量使新的m个特征互不相关。从旧特征到新特征的映射捕获数据中的固有变异性。以此使用较少的数据维度,同时保留住较多的原数据点的特性。


二.算法

1.对所有样本进行中心化操作
2.计算样本的协方差矩阵
3.对协方差矩阵做特征值分解
4.取最大的d个特征值对应的特征向量,构造投影矩阵W
通常低维空间维数d的选取有两种方法:
1)通过交叉验证法选取较好的d  
2)从算法原理的角度设置一个阈值,比如t=0.95,然后选取似的下式成立的最小的d值:
    Σ(i->d)λi/Σ(i->n)λi>=t,其中λi从大到小排列
PCA降维的准则有以下两个:
最近重构性:重构后的点距离原来的点的误差之和最小
最大可分性:样本点在低维空间的投影尽可能分开


三.sklearn提供的API

sklearn的decomposition提供了PCA一系列降维的方法


"""The :mod:`sklearn.decomposition` module includes matrix decompositionalgorithms, including among others PCA, NMF or ICA. Most of the algorithms ofthis module can be regarded as dimensionality reduction techniques."""from .nmf import NMF, non_negative_factorizationfrom .pca import PCA, RandomizedPCAfrom .incremental_pca import IncrementalPCAfrom .kernel_pca import KernelPCAfrom .sparse_pca import SparsePCA, MiniBatchSparsePCAfrom .truncated_svd import TruncatedSVDfrom .fastica_ import FastICA, fasticafrom .dict_learning import (dict_learning, dict_learning_online, sparse_encode,DictionaryLearning, MiniBatchDictionaryLearning,SparseCoder)from .factor_analysis import FactorAnalysisfrom ..utils.extmath import randomized_svdfrom .online_lda import LatentDirichletAllocation__all__ = ['DictionaryLearning','FastICA','IncrementalPCA','KernelPCA','MiniBatchDictionaryLearning','MiniBatchSparsePCA','NMF','PCA','RandomizedPCA','SparseCoder','SparsePCA','dict_learning','dict_learning_online','fastica','non_negative_factorization','randomized_svd','sparse_encode','FactorAnalysis','TruncatedSVD','LatentDirichletAllocation']


其中,KernelPCA可以选择适用的核函数,主要针对非线性的数据降维。RandomizedPCA是采用随机奇异值的线性降维,将数据投影到较低维空间的奇异向量。IncrementalPCA主要是解决单机内存限制,IncrementalPCA先将数据分成多个batch,然后对每个batch依次递增调用partial_fit函数,这样一步步的得到最终的样本最优降维。SparsePCA和MiniBatchSparsePCA使用了L1的正则化,这样可以将很多非主要成分的影响度降为0,,避免了一些噪声之类的因素对我们PCA降维的影响。SparsePCA和MiniBatchSparsePCA之间的区别是MiniBatchSparsePCA通过使用一部分样本特征和给定的迭代次数来进行PCA降维,以解决在大样本时特征分解过慢的问题,当然,代价就是PCA降维的精确度可能会降低。使用SparsePCA和MiniBatchSparsePCA需要对L1正则化参数进行调参。


PCA主要参数:

n_components:这个参数可以帮我们指定希望PCA降维后的特征维度数目
whiten :判断是否进行白化,就是对降维后的数据的每个特征进行归一化
svd_solver:即指定奇异值分解SVD的方法


Parameters----------n_components : int, float, None or stringNumber of components to keep.if n_components is not set all components are kept::n_components == min(n_samples, n_features)if n_components == 'mle' and svd_solver == 'full', Minka\'s MLE is used        to guess the dimension        if ``0 < n_components < 1`` and svd_solver == 'full', select the number        of components such that the amount of variance that needs to be        explained is greater than the percentage specified by n_components        n_components cannot be equal to n_features for svd_solver == 'arpack'.    copy : bool (default True)        If False, data passed to fit are overwritten and running        fit(X).transform(X) will not yield the expected results,        use fit_transform(X) instead.    whiten : bool, optional (default False)        When True (False by default) the `components_` vectors are multiplied        by the square root of n_samples and then divided by the singular values        to ensure uncorrelated outputs with unit component-wise variances.        Whitening will remove some information from the transformed signal        (the relative variance scales of the components) but can sometime        improve the predictive accuracy of the downstream estimators by        making their data respect some hard-wired assumptions.    svd_solver : string {'auto', 'full', 'arpack', 'randomized'}        auto :            the solver is selected by a default policy based on `X.shape` and            `n_components`: if the input data is larger than 500x500 and the            number of components to extract is lower than 80% of the smallest            dimension of the data, then the more efficient 'randomized'            method is enabled. Otherwise the exact full SVD is computed and            optionally truncated afterwards.        full :            run exact full SVD calling the standard LAPACK solver via            `scipy.linalg.svd` and select the components by postprocessing        arpack :            run SVD truncated to n_components calling ARPACK solver via            `scipy.sparse.linalg.svds`. It requires strictly            0 < n_components < X.shape[1]        randomized :            run randomized SVD by the method of Halko et al.        .. versionadded:: 0.18.0    tol : float >= 0, optional (default .0)        Tolerance for singular values computed by svd_solver == 'arpack'.        .. versionadded:: 0.18.0    iterated_power : int >= 0, or 'auto', (default 'auto')        Number of iterations for the power method computed by        svd_solver == 'randomized'.        .. versionadded:: 0.18.0    random_state : int, RandomState instance or None, optional (default None)        If int, random_state is the seed used by the random number generator;        If RandomState instance, random_state is the random number generator;        If None, the random number generator is the RandomState instance used        by `np.random`. Used when ``svd_solver`` == 'arpack' or 'randomized'.


def __init__(self, n_components=None, copy=True, whiten=False,                 svd_solver='auto', tol=0.0, iterated_power='auto',                 random_state=None):self.n_components = n_componentsself.copy = copyself.whiten = whitenself.svd_solver = svd_solverself.tol = tolself.iterated_power = iterated_powerself.random_state = random_state


PCA的输出就是Y = W‘X,由X的原始维度降低到了k维。除此之外,PCA还有两个重要的成员值:
explained_variance_,代表降维后的各主成分的方差值。方差值越大,则说明越是重要的主成分。
explained_variance_ratio_,它代表降维后的各主成分的方差值占总方差值的比例,这个比例越大,则越是重要的主成分。


代码如下:


import numpy as npimport matplotlib.pyplot as pltfrom sklearn import datasets,decomposition,manifoldfrom itertools import cycledef load_data():iris=datasets.load_iris()return iris.data,iris.targetPCA_Set=[decomposition.PCA(n_components=None),decomposition.PCA(svd_solver = 'randomized'),decomposition.SparsePCA(n_components=None),decomposition.IncrementalPCA(n_components=None),decomposition.KernelPCA(n_components=None,kernel='linear'),decomposition.KernelPCA(n_components=None,kernel='rbf'),decomposition.KernelPCA(n_components=None,kernel='poly'),decomposition.KernelPCA(n_components=None,kernel='sigmoid'),decomposition.FastICA(n_components=None)]PCA_Set_Name=['Default','Randomized','Sparse','Incremental','Kernel(linear)','Kernel(rbf)','Kernel(poly)','Kernel(sigmoid)','ICA']def plot_PCA(*data):X,Y=datafig=plt.figure("PCA",figsize=(20, 8))ax=fig.add_subplot(2,5,1)colors=cycle('rgbcmykw')for label,color in zip(np.unique(Y),colors):position=Y==labelax.scatter(X[position,0],X[position,1],label="target=%d"%label,color=color)plt.xticks(fontsize=10, color="darkorange")plt.yticks(fontsize=10, color="darkorange")ax.set_title('Original')for i,PCA in enumerate(PCA_Set):pca=PCApca.fit(X)X_r=pca.transform(X)if i==0:print("各主成分的方差值:"+str(pca.explained_variance_))print("各主成分的方差值比:"+str(pca.explained_variance_ratio_))ax=fig.add_subplot(2,5,i+2)colors=cycle('rgbcmykw')for label,color in zip(np.unique(Y),colors):position=Y==labelax.scatter(X_r[position,0],X_r[position,1],label="target=%d"%label,color=color)plt.xticks(fontsize=10, color="darkorange")plt.yticks(fontsize=10, color="darkorange")ax.set_title(PCA_Set_Name[i])plt.show()X,Y=load_data()plot_PCA(X,Y)



PS:ICA是独立成分分析法。虽然看起来和PCA有些相似,但完全不是干这个事的。我只是拿来客串凑个数的~

四.总结

PCA是多变量分析中较为古老的技术,它来源于通信理论中的K-L变换,其实质就是在尽可能好的代表原特征情况下,将原特征进行线性变换、映射至低纬度空间。PCA追求的是在降维之后能够最大化保持数据的内在信息,并通过衡量在投影方向上的数据方差的大小来衡量该方向的重要性。但是这样投影以后对数据的区分作用并不大,反而可能使得数据点揉杂在一起无法区分。这也是PCA存在的最大一个问题,这导致使用PCA在很多情况下的分类效果并不好。


本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标人工智能智能机器人频道!


本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程