>>> a = np.array([[1,2,3], [4,5,6]])
>>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
array([[1, 2],
[3, 4],
[5, 6]]) >>> a = np.array([[1,2,3], [4,5,6]]) >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2 array([[1, 2], [3, 4], [5, 6]])
因为 a 总共有 6 个元素,reshape 成一个二维数组,指定第一维的长度是3(即 3 行),numpy 可以自动推断出第二维的长度是 2 (6 除以 3 等于 2)。
我们可以再试一下如果有多个维度没有指定长度的话会怎样。
>>> np.reshape(a, (-1,-1))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 224, in reshape
return reshape(newshape, order=order)
ValueError: can only specify one unknown dimension >>> np.reshape(a, (-1,-1)) Traceback (most recent call last): File "
", line 1, in
File "/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 224, in reshape return reshape(newshape, order=order) ValueError: can only specify one unknown dimension
如果出现了无法整除的情况呢?
np.reshape(a, (4,-1))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 224, in reshapereturn reshape(newshape, order=order)
ValueError: total size of new array must be
np.reshape(a, (4,-1)) Traceback (most recent call last): File "
", line 1, in
File "/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 224, in reshapereturn reshape(newshape, order=order) ValueError: total size of new array must be
>>> a = np.array([[1,2,3], [4,5,6]]) >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2 array([[1, 2], [3, 4], [5, 6]]) 因为 a 总共有 6 个元素,reshape 成一个二维数组,指定第一维的长度是3(即 3 行),numpy 可以自动推断出第二维的长度是 2 (6 除以 3 等于 2)。 我们可以再试一下如果有多个维度没有指定长度的话会怎样。 >>> np.reshape(a, (-1,-1)) Traceback (most recent call last): File "
", line 1, in
File "/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 224, in reshape return reshape(newshape, order=order) ValueError: can only specify one unknown dimension 如果出现了无法整除的情况呢? np.reshape(a, (4,-1)) Traceback (most recent call last): File "
", line 1, in
File "/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 224, in reshapereturn reshape(newshape, order=order) ValueError: total size of new array must be