numpy中函数shape的用法

  shape函数是numpy.core.fromnumeric中的函数,它的功能是读取矩阵的长度,比如shape[0]就是读取矩阵第一维度的长度。它的输入参数可以使一个整数表示维度,也可以是一个矩阵。这么说你可能不太理解,我们还是用各种例子来说明他的用法:

  1. 一维矩阵[1]返回值为(1L,)               

    >>> z.shape
    (1,)

  2. 二维矩阵,返回两个值  

    >>> m = np.zeros((2,3))
    >>> m.shape
    (2, 3)

  3. 一个单独的数字,返回值为空 

    >>> m = np.zeros(0)
    >>> m.shape
    (0,)

  4. 我们还可以将shape作为矩阵的方法来调用,下面先创建了一个单位矩阵y

    >>> 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.]]])

  5. 我们可以快速读取y的形状       

    >>> y.shape
    (2, 3, 4)

  6. 假如我们只想读取y的维度,如下所示:  

    >>> z.shape[0]
    1
    >>> y.shape[0]
    2
    >>> y.shape[-1]
    4
    >>> y.shape[-2]
    3
    >>> y.shape[2]
    4
    >>> y.shape[1]

猜你喜欢

转载自www.cnblogs.com/dylancao/p/9842147.html
今日推荐