[英]Numpy reshape sub-list
For some reason, numpy reports the shape of 1-dimensional numpy-arrays without the number of rows. 由于某些原因,numpy报告一维numpy数组的形状而没有行数。 A numpy array with 784 elements has the shape:
(784,)
. 具有784个元素的numpy数组的形状为
(784,)
。 This is a problem, because the library I use expect a correct shape property (eg (784, 1)
). 这是一个问题,因为我使用的库期望正确的shape属性(例如
(784, 1)
)。
If I just have a single array, I can do this: train_y = train_y.reshape((train_y.shape[0], 1)
But is there a way to reshape sub-arrays without doing a for-loop? I have an array with shape 如果我只有一个数组,可以这样做:
train_y = train_y.reshape((train_y.shape[0], 1)
但是有没有一种方法可以不进行for循环而重塑子数组?与形状
(60000, 784)
, however, the sub-arrays have the shape (784,)
and I would like them to be (784,1)
instead. (60000, 784)
,但是,子数组的形状为(784,)
,我希望它们的形状为(784,1)
。
NumPy is an n-dimensional array library, not a matrix library. NumPy是n维数组库,而不是矩阵库。 1D arrays don't have rows.
一维数组不具备行。
If you want a view of an arbitrary array with an extra length-1 axis stuck on the end, you can do that: 如果要查看任意一个数组,并在其末端附加一个长度为1的轴,则可以执行以下操作:
train_y = train_y[..., np.newaxis]
# or
train_y = train_y.reshape(train_y.shape + (1,))
though it may be better to change how you're initially creating this train_y
array. 尽管最好更改最初创建此
train_y
数组的方式。
This will generate an array with shape (60000, 784, 1)
. 这将生成形状为
(60000, 784, 1)
的数组。 Depending on your expectations, this might be exactly what you want, or you might consider it an abomination. 根据您的期望,这可能正是您想要的,或者您可能认为这是可憎的。 In any case,
train_y[0]
will have shape (784, 1)
. 无论如何,
train_y[0]
将具有形状(784, 1)
train_y[0]
(784, 1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.