Numpy TypeError:仅长度为1的数组可以转换为Python标量(重塑)
在Python中,如果我改变数组的形状,那么我一般不会有问题:
In Python, if I reshape an array, I have no problem in general:
arr1 = np.array([1,2,3,4])
print np.reshape(arr1, (2, 2, 1))
但是当我尝试重塑10240 x 62 numpy ndarray时,我遇到了一个问题:
But I have a problem when I try to reshape a 10240 x 62 numpy ndarray:
a1 = np.reshape(X_train_s, (X_train_s[0], X_train_s[1], 1))
错误是:
...in reshape
return reshape(newshape, order=order)
TypeError: only length-1 arrays can be converted to Python scalars
ndarray X_train_s包含float32数字.为什么我不能重塑数组?
The ndarray X_train_s contains float32 numbers. Why can't I reshape the array?
您想要X_train_s
的第一维和第二维的长度,但是当您这样做时
You wanted the lengths of the first and second dimensions of X_train_s
, but when you did
(X_train_s[0], X_train_s[1], 1)
您选择了第一行和第二行整行,而不是第一维和第二维的长度.如果要访问尺寸长度,则应已索引数组的shape
:
you took the first and second entire rows, not the lengths of the first and second dimensions. If you wanted to access dimension lengths, you should have indexed the array's shape
:
(X_train_s.shape[0], X_train_s.shape[1], 1)
您可能还想考虑将这个额外的长度为1的轴添加到数组的其他方法,例如使用np.newaxis
(又称为None
)建立索引:
You might also want to consider other ways of adding this extra length-1 axis to the array, such as indexing with np.newaxis
(a.k.a. None
):
a1 = X_train_s[:, :, np.newaxis]