在numpy的广播问题

问题描述 投票:0回答:3

我想,以适应PCA在火车上和测试数据。

X_train.shape

(2735, 219)

PCA:

pca = PCA(n_components=30)
X_train = pca.fit_transform(X_train)

测试数据:

test_values.shape
(395, 219)

转型:

test_values = pca.transform(test_values)

错误:

ValueError: operands could not be broadcast together with shapes (395,219) (30,)

我不知道为什么有广播的错误,无论是numpy的阵列具有相同的列219的任何建议,请

python numpy scikit-learn numpy-broadcasting
3个回答
0
投票

我敢打赌,这是一个保存变量的问题,如果你正在使用IPython中,笔记本电脑或类似的东西。如果不是的话,你可能会忽略这个答案。

考虑下面的细胞。

enter image description here

当我运行这些细胞中,一切都很好。但是,如果我尝试再次运行第二单元我得到这个错误:

ValueError: operands could not be broadcast together with shapes (395,219) (30,)

这是因为X_train现在是一个2735, 30矩阵和PCA装上这个矩阵,因此预计n, 30矩阵。

如果您清除变量或重新组织你的代码,使得它不适合于已经转换的数据,这个问题是可以解决的。


0
投票

这是不是一个真正的答案。但是,以帮助您了解的情况,我张贴这个!

import numpy as np
from sklearn.decomposition import PCA
X = np.random.randn(2735, 219)
pca = PCA(n_components=30)
pca.fit(X)

test_values = np.random.randn(395 , 219)

pca.transform(test_values)

上面的代码工作得很好!


0
投票

我试图模仿你的榜样,和一切工作正常:

x_train = np.random.randint(10, size=50).reshape(10, 5)
pca = PCA(n_components=3)
print(x_train.shape)
x_train = pca.fit_transform(x_train)
test_values = np.random.randint(10, size=100).reshape(20, 5)
print(test_values.shape)
test_values = pca.transform(test_values)
print(test_values.shape)

该代码输出:

(10, 5)
(20, 5)
(20, 3)

检查与PCA行出现错误。看起来你正在做一些操作与错误的形状的阵列。

© www.soinside.com 2019 - 2024. All rights reserved.