About reshaping numpy array

送分小仙女□ 提交于 2019-12-13 03:41:33

问题


trainX.size == 43120000
trainX = trainX.reshape([-1, 28, 28, 1])

(1)Does reshape accept a list as an argment instead of a tuple?

(2)Are the following two statements equivalent?

trainX = trainX.reshape([-1, 28, 28, 1])
trainX = trainX.reshape((55000, 28, 28, 1))

回答1:


Try the variations:

In [1]: np.arange(12).reshape(3,4)
Out[1]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [2]: np.arange(12).reshape([3,4])
Out[2]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [3]: np.arange(12).reshape((3,4))
Out[3]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

With the reshape method, the shape can be arguments, a tuple or a list. In the reshape function is has to be in a list or tuple, to separate them from the first array argument

In [4]: np.reshape(np.arange(12), (3,4))
Out[4]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

and yes, one -1 can be used. The total size of the reshape is fixed, so one value can be deduced from the others.

In [5]: np.arange(12).reshape(-1,4)
Out[5]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

The method documentation has this note:

Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example, a.reshape(10, 11) is equivalent to a.reshape((10, 11)).

It's a builtin function, but the signature looks like x.reshape(*shape), and it tries to be flexible as long as the values make sense.




回答2:


From the numpy documentation:

newshape : int or tuple of ints

The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

So yes, -1 for one dimension is fine and your two statements are equivalent. About the tuple requirement,

>>> import numpy as np
>>> a = np.arange(9)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> a.reshape([3,3])
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> 

So apparently a list is good as well.



来源:https://stackoverflow.com/questions/48558012/about-reshaping-numpy-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!