简体   繁体   中英

Numpy reshape sub-list

For some reason, numpy reports the shape of 1-dimensional numpy-arrays without the number of rows. A numpy array with 784 elements has the shape: (784,) . This is a problem, because the library I use expect a correct shape property (eg (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
(60000, 784) , however, the sub-arrays have the shape (784,) and I would like them to be (784,1) instead.

NumPy is an n-dimensional array library, not a matrix library. 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:

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.

This will generate an array with shape (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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM