1. 程式人生 > >Numpy的reshape中-1的意思

Numpy的reshape中-1的意思

轉載自知乎


numpy.reshape(a, newshape, order='C')[source],引數`newshape`是啥意思?

根據Numpy文件(docs.scipy.org/doc/nump)的解釋:

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**
.

大意是說,陣列新的shape屬性應該要與原來的配套,如果等於-1的話,那麼Numpy會根據剩下的維度計算出陣列的另外一個shape屬性值。

舉幾個例子或許就清楚了,有一個數組z,它的shape屬性是(4, 4)

z = np.array([[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12],
          [13, 14, 15, 16]])
z.shape
(4, 4)
z.reshape(-1)
z.reshape(-1)
array([ 1,  2,  3,  4
, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
z.reshape(-1, 1)

也就是說,先前我們不知道z的shape屬性是多少,但是想讓z變成只有一列,行數不知道多少,通過`z.reshape(-1,1)`,Numpy自動計算出有12行,新的陣列shape屬性為(16, 1),與原來的(4, 4)配套。

z.reshape(-1,1)
 array([[ 1],
        [ 2],
        [ 3],
        [ 4],
        [ 5],
        [ 6],
        [
7], [ 8], [ 9], [10], [11], [12], [13], [14], [15], [16]])
z.reshape(-1, 2)

newshape等於-1,列數等於2,行數未知,reshape後的shape等於(8, 2)

 z.reshape(-1, 2)
 array([[ 1,  2],
        [ 3,  4],
        [ 5,  6],
        [ 7,  8],
        [ 9, 10],
        [11, 12],
        [13, 14],
        [15, 16]])
 

同理,只給定行數,newshape等於-1,Numpy也可以自動計算出新陣列的列數。