python - PCA、truncated_svd 和 svds 在 numpy 和 sklearn 上的不同结果

标签 python numpy machine-learning scikit-learn svd

在 sklearn 和 numpy 中,有不同的方法来计算第一个主成分。 我对每种方法都得到了不同的结果。为什么?

import matplotlib.pyplot as pl
from sklearn import decomposition
import scipy as sp
import sklearn.preprocessing
import numpy as np
import sklearn as sk

def gen_data_3_1():
    #### generate the data 3.1
    m=1000 # number of samples
    n=10 # number of variables
    d1=np.random.normal(loc=0,scale=100,size=(m,1))
    d2=np.random.normal(loc=0,scale=121,size=(m,1))
    d3=-0.2*d1+0.9*d2
    z=np.zeros(shape=(m,1))

    for i in range(4):
        z=np.hstack([z,d1+np.random.normal(size=(m,1))])

    for i in range(4):
        z=np.hstack([z,d2+np.random.normal(size=(m,1))])
    for i in range(2):
        z=np.hstack([z,d3+np.random.normal(size=(m,1))])
    z=z[:,1:11]  
    z=sk.preprocessing.scale(z,axis=0)
    return z

x=gen_data_3_1() #generate the sample dataset

x=sk.preprocessing.scale(x) #normalize the data
pca=sk.decomposition.PCA().fit(x) #compute the PCA of x and print the first princ comp.
print "first pca components=",pca.components_[:,0]
u,s,v=sp.sparse.linalg.svds(x) # the first column of v.T is the first princ comp
print "first svd components=",v.T[:,0]

trsvd=sk.decomposition.TruncatedSVD(n_components=3).fit(x) #the first components is the                          
                                                           #first princ comp
print "first component TruncatedSVD=",trsvd.components_[0,]

--

   first pca components= [-0.04201262  0.49555992  0.53885401 -0.67007959  0.0217131  -0.02535204
      0.03105254 -0.07313795 -0.07640555 -0.00442718]
    first svd components= [ 0.02535204 -0.1317925   0.12071112 -0.0323422   0.20165568 -0.25104996
     -0.0278177   0.17856688 -0.69344318  0.59089451]
    first component TruncatedSVD= [-0.04201262 -0.04230353 -0.04213402 -0.04221069  0.4058159   0.40584108
      0.40581564  0.40584842  0.40872029  0.40870925]

最佳答案

因为PCA、SVD、截断SVD的方法不一样。 PCA称为SVD,但它之前也对数据进行中心化。截断 SVD 截断向量。 svds 是与 svd 不同的方法,因为它是稀疏的。

关于python - PCA、truncated_svd 和 svds 在 numpy 和 sklearn 上的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20681972/

相关文章:

python - numpy 什么时候停止接受 float 作为索引

python - 使用 Python 获取 Windows 系统内部信息

python - 在Python中读取JSON文件并获取没有不可见字符的值的最佳方法是什么?

python - 在 Python 中用双引号而不是单引号打印空字符串

python - 将 PyTorch 张量与 scikit-learn 结合使用

python - 从 numpy 数组中随机选择行

python - scikit-learn 将额外数据添加到 SGDClassifier

machine-learning - 为什么我们需要机器学习的标准化和规范化?

python - 如何在numpy中指定一个随机数生成器

asp.net-mvc - MVC UI 与 python 后端