例子
- 例1:
>>>import numpy as np >>>a = np.matrix([[1, 2, 3, 4], [5, 6, 7, 8]]) >>>np.reshape(a, -1) matrix([[1, 2, 3, 4, 5, 6, 7, 8]])
- 例2:
>>>a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) >>>a.reshape(a.shape[0], -1) array([[1, 2, 3, 4,], [5, 6, 7, 8]])
解释
简单的说,-1表示自适应。
例子:
对有8个元素的numpy数组或矩阵,reshape(-1, 1)规定了列数,从而行数为8/1=8;
对有8个元素的numpy数组或矩阵,reshape(1, -1)规定了行数,从而列数为8/1=8;
引用stackoverflow上的一个例子
import numpy as np
x = np.array([[2,3,4], [5,6,7]])
# Convert any shape to 1D shape
x = np.reshape(x, (-1)) # Making it 1 row -> (6,)
# When you don't care about rows and just want to fix number of columns
x = np.reshape(x, (-1, 1)) # Making it 1 column -> (6, 1)
x = np.reshape(x, (-1, 2)) # Making it 2 column -> (3, 2)
x = np.reshape(x, (-1, 3)) # Making it 3 column -> (2, 3)
# When you don't care about columns and just want to fix number of rows
x = np.reshape(x, (1, -1)) # Making it 1 row -> (1, 6)
x = np.reshape(x, (2, -1)) # Making it 2 row -> (2, 3)
x = np.reshape(x, (3, -1)) # Making it 3 row -> (3, 2)