无法在数据集上运行PCA

时间:2019-10-21 09:06:53

标签: python numpy pca

我正在尝试在贷款数据集上运行PCA-在此处找到testtrain

代码段如下,

from sklearn.decomposition import PCA
pca = PCA(n_components = 2)
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)
explained_variance = pca.explained_variance_ratio_

但是,在运行相同命令时,出现以下错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-102-829bdba63de3> in <module>
      3 pca = PCA(n_components = 2)
      4 X_train = pca.fit_transform(X_train)
----> 5 X_test = pca.transform(X_test)
      6 explained_variance = pca.explained_variance_ratio_

C:\Anaconda\lib\site-packages\sklearn\decomposition\base.py in transform(self, X)
    127         X = check_array(X)
    128         if self.mean_ is not None:
--> 129             X = X - self.mean_
    130         X_transformed = np.dot(X, self.components_.T)
    131         if self.whiten:

ValueError: operands could not be broadcast together with shapes (185,112) (2,) 

有人可以帮我吗? 我不是哪里错了。

1 个答案:

答案 0 :(得分:1)

仅需进行一次PCA:

import numpy as np
from sklearn.decomposition import PCA
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
pca = PCA(n_components=2)
pca.fit(X) 

也许您应该在火车上放下标签,参加测试并训练然后再进行PCA。