python中numpy.ndarray.shape的用法

  今天用到了shape,就顺便学习一下,这个shape的作用就是要把矩阵进行行列转换,请看下面的几个例子就明白了:

>>> import numpy as np
>>> x = np.array([1,2,3,4])
>>> x.shape
(4,)
>>> y = np.zeros([2,3,4])
>>> y.shape
(2, 3, 4)
>>> y.shape = (3,8)
>>> y
array([[0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.]])
>>> y.shape = (3,6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot reshape array of size 24 into shape (3,6)
>>> y.shape = (4,6)
>>> y.shape
(4, 6)
>>> y
array([[0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0.]])
>>> y = np.zeros([2,3,4])
>>> y
array([[[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]],

       [[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]]])
>>> y.shape = (-1,2)
>>> y
array([[0., 0.],
       [0., 0.],
       [0., 0.],
       [0., 0.],
       [0., 0.],
       [0., 0.],
       [0., 0.],
       [0., 0.],
       [0., 0.],
       [0., 0.],
       [0., 0.],
       [0., 0.]])
>>> x.shape
(4,)
>>> x.shape = (-1,2)
>>> x
array([[1, 2],
       [3, 4]])
>>> 

参考文档: https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html

原文地址:https://www.cnblogs.com/dylancao/p/9485901.html