使用numpy计算PCA

时间:2017-06-13 13:23:45

标签: python numpy pca

我是python编程的新手,想在numpy中询问PCA(主成分分析)。 我有一个包含2d numpy数组的数据集。如何使用numpy在此数据集上找到PCA。什么是最好的方法?

Output of the list:

[[  9.59440303 -30.33995167  -9.56393401 ...,  20.47675724  21.32716639
    4.72543396]
 [  9.51383834 -29.91598995 -15.53265741 ...,  29.3551776   22.27276737
    0.21362916]
 [  9.51410643 -29.76027936 -14.61218821 ...,  26.02439054   4.7944802
   -4.97069797]
 ..., 
 [ 10.18460025 -25.08264383  -8.48524125 ...,  -3.86304594  -7.48117144
    0.49041786]
 [ 10.11421507 -27.23984612  -8.57355611 ...,   1.86266657  -5.25912341
    4.07026804]
 [ 11.86344836 -29.08311293  -6.40004177 ...,   3.81287345  -8.21500311
   18.31793505]]

例如给定数据,但实际数据包含可以核心化的非常长的数据。您可以使用Iris数据或其他虚拟数据。

2 个答案:

答案 0 :(得分:3)

正如Nils建议的那样,最简单的解决方案是使用scikit-learn包中的PCA类。如果由于某种原因你不能使用scikit-learn,那么PCA算法本身就相当简单。在scikit-learn的源代码中,您可以在此处找到它: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/decomposition/pca.py#L408

简化摘要:

centered_data = data - np.mean(data)
U, S, V = np.linalg.svd(centered_data, full_matrices=False)
components = V
coefficients = np.dot(U, np.diag(S))

答案 1 :(得分:1)