Explaining the differences between dim, shape, rank, dimension and axis in numpy

后端 未结 3 1434
难免孤独
难免孤独 2021-02-06 03:35

I\'m new to python and numpy in general. I read several tutorials and still so confused between the differences in dim, ranks, shape, aixes and dimensions. My mind seems to be s

3条回答
  •  一生所求
    2021-02-06 04:15

    In your case,

    1. A is a 2D array, namely a matrix, with its shape being (2, 3). From docstring of numpy.matrix:

      A matrix is a specialized 2-D array that retains its 2-D nature through operations.

    2. numpy.rank return the number of dimensions of an array, which is quite different from the concept of rank in linear algebra, e.g. A is an array of dimension/rank 2.

    3. np.dot(V, M), or V.dot(M) multiplies matrix V with M. Note that numpy.dot do the multiplication as far as possible. If V is N:1 and M is N:N, V.dot(M) would raise an ValueError.

    e.g.:

    In [125]: a
    Out[125]: 
    array([[1],
           [2]])
    
    In [126]: b
    Out[126]: 
    array([[2, 3],
           [1, 2]])
    
    In [127]: a.dot(b)
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
     in ()
    ----> 1 a.dot(b)
    
    ValueError: objects are not aligned
    

    EDIT:

    I don't understand the difference between Shape of (N,) and (N,1) and it relates to the dot() documentation.

    V of shape (N,) implies an 1D array of length N, whilst shape (N, 1) implies a 2D array with N rows, 1 column:

    In [2]: V = np.arange(2)
    
    In [3]: V.shape
    Out[3]: (2,)
    
    In [4]: Q = V[:, np.newaxis]
    
    In [5]: Q.shape
    Out[5]: (2, 1)
    
    In [6]: Q
    Out[6]: 
    array([[0],
           [1]])
    

    As the docstring of np.dot says:

    For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation).

    It also performs vector-matrix multiplication if one of the parameters is a vector. Say V.shape==(2,); M.shape==(2,2):

    In [17]: V
    Out[17]: array([0, 1])
    
    In [18]: M
    Out[18]: 
    array([[2, 3],
           [4, 5]])
    
    In [19]: np.dot(V, M)  #treats V as a 1*N 2D array
    Out[19]: array([4, 5]) #note the result is a 1D array of shape (2,), not (1, 2)
    
    In [20]: np.dot(M, V)  #treats V as a N*1 2D array
    Out[20]: array([3, 5]) #result is still a 1D array of shape (2,), not (2, 1)
    
    In [21]: Q             #a 2D array of shape (2, 1)
    Out[21]: 
    array([[0],
           [1]])
    
    In [22]: np.dot(M, Q)  #matrix multiplication
    Out[22]: 
    array([[3],            #gets a result of shape (2, 1)
           [5]])
    

提交回复
热议问题