简单介绍
主成分析是要找到维度中有用的部分,那么就要知道什么样的维度是没有用的:
- 不能反映出个体之间的差别
- 和其他的维度的相关性很高,会随着其他维度的变化有规律的变化
第一点可以用方差来衡量,而第二点可以用协方差来衡量,这样就有下面PCA的代码了。
代码实现
代码是用python写的,用到numpy:
from numpy import *;
import Image;
def pca(data, dimen) :
'''
data:
an array of sample, normalization processed.
dimen:
dimension of the main component.
'''
# process the data.
avgs = [];
for d in data :
avg = mean(d, axis=0);
d -= avg;
avgs.append(avg);
# covariance matrix.
c = cov(data);
# get eigenvalues and eigenvectors.
values,vectors = linalg.eig(c);
# get the max values.
index = (argsort(values)[::-1])[0:dimen];
values = values[:,index];
vectors = vectors[:,index];
new_data = dot(transpose(vectors), data);
restore = dot(vectors, new_data);
print '------ old ------'
print data;
print '------ new ------'
print restore;
return vectors;
# TEST
if __name__ == '__main__' :
data = array([[1,5,6],[4,3,9],[4,2,9],[4,7,2]]);
pca(data, 2); ----------
END
PCA算法原理与Python实现
本文详细介绍了主成分分析(PCA)的概念,如何通过方差和协方差判断无效维度,并提供了一个使用Python和numpy库实现PCA的示例代码。
1万+

被折叠的 条评论
为什么被折叠?



