> For the complete documentation index, see [llms.txt](https://json007.gitbook.io/svm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://json007.gitbook.io/svm/math-linear_algebra/pca.md).

# PCA

## 算法过程

假设原始数据是$$X\_{m\times n}$$，其中m表示数据大小，n表示维度大小。

1. 将X中的数据进行零均值化，即每一列都减去其均值。
2. 计算协方差矩阵$$C=\frac{1}{m}X^T X$$
3. 求出C的特征值和特征向量
4. 将特征向量按对应特征值大小从上到下按行排列成矩阵，取前k行组成矩阵P
5. $$Y=XP$$就是降维到k维后的数据。

如何定义k？\
方差百分比: $$\frac {\sum\_{j=1}^k \lambda\_j} {\sum\_{j=1}^n \lambda\_j}$$ 。$$\lambda$$为特征值，从小到大排列。\
[主成分分析(PCA)——基于python+numpy](http://blog.csdn.net/u012162613/article/details/42177327)

## 原理

最大化方差法：

PCA 可以用来做降维，但通俗一点说，其本质应该是**线性空间坐标系的转换**，从原始的空间坐标系，转换到一个“合适的”的坐标系来表达，在这个坐标系中，主要信息都集中在了某几个坐标轴上，所以只保留这个“关键”的坐标系上的表达，就能很大程度approximate原信号。

所以用特征向量组成的基来表达样本。

投影后方差$$\frac {1}{N} \sum\_{n=1}^N {u\_1^T x\_n - u\_1^T \overline {x} }^2 = u\_1^T S u\_1$$

S就是你说的“去均值的原矩阵(**去均值的原矩阵的协方差矩阵的特征向量作为列向量形成的矩阵**）”。

因为 u有约束条件 $$u\_1^T u =1$$ ,所以用乘子法：$$u\_1^T S u\_1 + \lambda (u\_1^T u)$$ ，对$$u\_1$$求导，得到 $$Su\_1=\lambda u\_1$$

待完善

[主成分分析（PCA）原理总结](http://www.cnblogs.com/pinard/p/6239403.html)

![](/files/-M7DeSs-D2UeE-DY-Swx)

[求pca的时候，能不能不用协方差矩阵？](https://www.zhihu.com/question/39234760/answer/80323126)

[PCA降维，特征值分解，SVD， KPCA](https://zhuanlan.zhihu.com/p/50647881)

## code

[【机器学习算法实现】主成分分析(PCA)——基于python+numpy](http://blog.csdn.net/u012162613/article/details/42177327)\
[PCA](https://github.com/csuldw/MachineLearning/tree/master/PCA)

```
import numpy as np
import matplotlib.pyplot as plt

def zeroMean(dataMat):        
    meanVal=np.mean(dataMat,axis=0)     #按列求均值，即求各个特征的均值  
    newData=dataMat-meanVal  
    return newData,meanVal  

def percentage2n(eigVals,percentage):  
    sortArray=np.sort(eigVals)   #升序  
    sortArray=sortArray[-1::-1]  #逆转，即降序  
    arraySum=sum(sortArray)  
    tmpSum=0  
    num=0
    for i in sortArray:
        tmpSum+=i 
        num+=1 
        if tmpSum>=arraySum*percentage: 
            return num 

def pca(dataMat,percentage=0.99):  
    newData,meanVal=zeroMean(dataMat)  
    covMat=np.cov(newData,rowvar=0)    #求协方差矩阵,return ndarray；若rowvar非0，一列代表一个样本，为0，一行代表一个样本  
    eigVals,eigVects=np.linalg.eig(np.mat(covMat))#求特征值和特征向量,特征向量是按列放的，即一列代表一个特征向量  
    n=percentage2n(eigVals,percentage)                 #要达到percent的方差百分比，需要前n个特征向量  
    eigValIndice=np.argsort(eigVals)            #对特征值从小到大排序  
    n_eigValIndice=eigValIndice[-1:-(n+1):-1]   #最大的n个特征值的下标  
    n_eigVect=eigVects[:,n_eigValIndice]        #最大的n个特征值对应的特征向量  
    lowDDataMat=newData*n_eigVect               #低维特征空间的数据  
    reconMat=(lowDDataMat*n_eigVect.T)+meanVal  #重构数据  
    return lowDDataMat,reconMat 

if __name__ == "__main__":
    p1 = plt.subplot(121)
    #XMat = np.array(pd.read_csv(datafile,sep="\t",header=-1)).astype(np.float)
    XMat = np.loadtxt("pca.txt",delimiter="\t",dtype="float")
    #XMat = lines[1:,:4].astype('float')
    #XMat = np.array(pd.read_csv(datafile,sep="\t",header=-1)).astype(np.float)
    p1.plot(XMat[:,0],XMat[:,1],'.')
    finalData, reconMat = pca(XMat)
    #p1.plot(recon_data[:,0],recon_data[:,1],'*')
    p1.plot(finalData[:,0],finalData[:,1],'*')
    plt.savefig("outfile.png")
    plt.show()
```

Kernel PCA

[http://zhanxw.com/blog/2011/02/kernel-pca-%E5%8E%9F%E7%90%86%E5%92%8C%E6%BC%94%E7%A4%BA/](http://zhanxw.com/blog/2011/02/kernel-pca-原理和演示/) Kernel PCA 原理和演示

![](/files/-M7DeSs1SUPHh07EAA1F)

## Robust PCA

[最优化之Robust PCA](http://www.cnblogs.com/quarryman/p/robust_pca.html)

核范数||A|| \* 是指矩阵奇异值的和,英文称呼叫Nuclear Norm.\
MATLAB code\
`s= svd(A); nulear_norm = sum(diag(s));`

![](/files/-M7DeSs22GxEMGKtoFJi)

[机器学习中的范数规则化之（一）L0、L1与L2范数](http://blog.csdn.net/zouxy09/article/details/24971995)\
[机器学习中的范数规则化之（二）核范数与规则项参数选择](http://blog.csdn.net/zouxy09/article/details/24972869)

[基于TensorFlow理解三大降维技术：PCA、t-SNE 和自编码器](https://mp.weixin.qq.com/s?__biz=MzA3MzI4MjgzMw==\&mid=2650728960\&idx=1\&sn=8b9e10a0c4170a136658262253c7b993)

![](/files/-M7DeSs3pbbMWxGo9JFQ)

[为什么核范数能凸近似矩阵的秩？为什么核范数是凸的？](https://www.zhihu.com/question/26471536)\
[Singular Value Thresholding (SVT) 奇异值阈值](http://blog.csdn.net/shanglianlm/article/details/46009387)

[PCA原理分析](http://zhouyichu.com/machine-learning/PCA-Tutorial.html)\
[主成分分析PCA算法：为什么去均值以后的高维矩阵乘以其协方差矩阵的特征向量矩阵就是“投影”](https://www.zhihu.com/question/30094611)\
[A Tutorial on Principal Component Analysis](http://120.52.73.79/arxiv.org/pdf/1404.1100.pdf)

[PCA模型加先验](http://www.algorithmdog.com/pca模型加先验)

[核PCA与PCA的精髓和核函数的映射实质](http://blog.csdn.net/qianhen123/article/details/40863753)

[主成份分析(PCA)最详细和全面的诠释](http://mp.weixin.qq.com/s?__biz=MzI2MzAxMTA1Ng==\&mid=2649499654\&idx=2\&sn=23f750ea4c67ac366e60067d8eb448ec\&chksm=f25ae799c52d6e8fb2caf0c43e0b47cb4b0df55b1c627186baefad97b3a6deee190400d992de\&mpshare=1\&scene=25\&srcid=0927Ddf4Tr7vrTgZCKdUVyF2\&from=timeline\&isappinstalled=0#wechat_redirect​)

[本征向量、PCA和熵的基础教程](https://deeplearning4j.org/cn/eigenvector)

[Sparse PCA 稀疏主成分分析](http://blog.csdn.net/zhoudi2010/article/details/53489319)

[【机器学习算法系列之三】简述多种降维算法](https://chenrudan.github.io/blog/2016/04/01/dimensionalityreduction.html)

[协方差矩阵的几何解释](http://blog.csdn.net/u010182633/article/details/45937051)

[机器学习-异常检测算法（三）：Principal Component Analysis](https://zhuanlan.zhihu.com/p/29091645)

[（概率）PCA和（变分）自编码器](https://www.jianshu.com/p/3085936e8bc3)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://json007.gitbook.io/svm/math-linear_algebra/pca.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
