why do we need np.squeeze()?

后端 未结 4 624
北恋
北恋 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条回答
  •  广开言路
    2021-01-30 13:38

    When you squeeze a (2,1) array, you get (2,) which works as both (2,1) and (1,2):

    >>> a = np.ones(2)
    >>> a.shape
    (2,)
    >>> a.T.shape
    (2,)
    >>> X = np.ones((2,2))*2
    >>> np.dot(a,X)
    [4. 4.]
    >>> np.dot(X,a)
    [4. 4.]
    

    This cannot happen with a (2,1) array:

    >>> b = np.ones((2,1))
    >>> np.dot(b,X)
    Traceback (most recent call last):
    ValueError: shapes (2,1) and (2,2) not aligned: 1 (dim 1) != 2 (dim 0)
    

提交回复
热议问题