Explain this 4D numpy array indexing intuitively

前端 未结 3 1595
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 10:49
x = np.random.randn(4, 3, 3, 2)
print(x[1,1])

output:
[[ 1.68158825 -0.03701415]
[ 1.0907524  -1.94530359]
[ 0.25659178  0.00475093]]

I am python n

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-03 11:06

    A 2D array is a matrix : an array of arrays.

    A 4D array is basically a matrix of matrices:

    Specifying one index gives you an array of matrices:

    >>> x[1]
    array([[[-0.37387191, -0.19582887],
            [-2.88810217, -0.8249608 ],
            [-0.46763329,  1.18628611]],
    
           [[-1.52766397, -0.2922034 ],
            [ 0.27643125, -0.87816021],
            [-0.49936658,  0.84011388]],
    
           [[ 0.41885001,  0.16037164],
            [ 1.21510322,  0.01923682],
            [ 0.96039904, -0.22761806]]])
    

    Specifying two indices gives you a matrix:

    >>> x[1, 1]
    array([[-1.52766397, -0.2922034 ],
           [ 0.27643125, -0.87816021],
           [-0.49936658,  0.84011388]])
    

    Specifying three indices gives you an array:

    >>> x[1, 1, 1]
    array([ 0.27643125, -0.87816021])
    

    Specifying four indices gives you a single element:

    >>> x[1, 1, 1, 1]
    -0.87816021212791107
    

    x[1,1] gives you the small matrix that was saved in the 2nd column of the 2nd row of the large matrix.

提交回复
热议问题