why do we need np.squeeze()?

后端 未结 4 619
北恋
北恋 2021-01-30 12:56

Very often, arrays are squeezed with np.squeeze(). In the documentation, it says

Remove single-dimensional entries from the shape of a.

4条回答
  •  梦毁少年i
    2021-01-30 13:36

    One example of the importance is when multiplying arrays. Two 2-dimensional arrays will multiply each value at a time

    e.g.

    >>> x = np.ones((2, 1))*2
    >>> y = np.ones((2, 1))*3
    >>> x.shape
    (2,1)
    >>> x*y
    array([[ 6.],
           [ 6.]])
    

    If you multiply a 1d array by a 2d array then the behaviour is different

    >>> z = np.ones((2,))*3
    >>> x*z
    array([[ 6.,  6.],
           [ 6.,  6.]])
    

    Secondly, you also might want to squeeze the earlier dimensions e.g. a.shape = (1,2,2) to a.shape = (2,2)

提交回复
热议问题