python numpy.matrix.reshape函数详解

python numpy.matrix.reshape函数详解

The criterion to satisfy for providing the new shape is that ‘The new shape should be compatible with the original shape’

numpy allows us to give one of new shape parameter as -1(eg:(2,-1) or (-1,3) but not (-1,-1). It simply means that it is an unknown dimension and we want to numpy to figure it out. And numpy will figure this by looking at the ‘length of the array and remaining dimensions’ and making sure it satisfies the above mentioned criteria.

请看下面这个例子,看完就懂了。

import numpy as np
if __name__ == '__main__':
    a = np.matrix([[1,2,3,4],
                   [5,6,7,8],
                   [9,10,11,12]])

    b = a.reshape((1,12))
    print(b)
    c = a.reshape((1,-1))
    print(c)
    d = a.reshape((4,3))
    print(d)
    e = a.reshape((-1,3))
    print(e)
    f = a.reshape((-1,-1))
    print(f)

输出结果如下:

[[ 1  2  3  4  5  6  7  8  9 10 11 12]]
[[ 1  2  3  4  5  6  7  8  9 10 11 12]]
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
Traceback (most recent call last):
  File "test33.py", line 15, in 
    f = a.reshape((-1,-1))
ValueError: can only specify one unknown dimension

可以看到前面4个正常输出,最后一个无法输出。
原因即在于,两个-1,均没有指定维度,则numpy不知道最后的维度到底是多少。所以报出了can only specify one unknown dimension的错误。

你可能感兴趣的:(Python)