Explain this 4D numpy array indexing intuitively

前端 未结 3 1594
被撕碎了的回忆
被撕碎了的回忆 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.

    0 讨论(0)
  • 2021-01-03 11:12

    This page explains the concept of higher dimensional arrays with a very clear analogy together with some illustrations. I recommend to those people looking for an answer to this question

    https://cognitiveclass.ai/blog/nested-lists-multidimensional-numpy-arrays

    0 讨论(0)
  • 2021-01-03 11:15

    A 4d numpy array is an array nested 4 layers deep, so at the top level it would look like this:

    [ # 1st level Array (Outer)
        [ # 2nd level Array
            [[1, 2], [3, 4]], # 3rd level arrays, containing 2 4th level arrays
            [[5, 6], [7, 8]]
        ], 
        [ # 2nd Level array
            [[9, 10], [11, 12]], 
            [[13, 14], [15, 16]]
        ]
    ]
    

    x[1,1] expands to x[1][1], Let's unpack this one expression at a time, the first expression x[1] selects the first element from the global array which is the following object from the earlier array:

    [
        [[1, 2], [3, 4]],
        [[5, 6], [7, 8]]
    ]
    

    The next expression now looks like this:

    [
        [[1, 2], [3, 4]],
        [[5, 6], [7, 8]]
    ][1]
    

    So evaluating that (selecting the first element in the array) gives us the following result:

    [[1, 2], [3, 4]]
    

    As you can see selecting an element in a 4d array gives us a 3d array, selecting an element from a 3d array gives a 2d array and selecting an element from a 2d array gives us a 1d array.

    0 讨论(0)
提交回复
热议问题