Explain this 4D numpy array indexing intuitively

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

提交回复
热议问题