[:, :, None, None] operation comprehension

[:, None, None] is the way to change the dimension of the array

insert image description here

import numpy as np 
a=np.array([[3,3,3],[4,4,4],[5,5,5]])
print(a[:,None])

output:

[[[3 3 3]]

 [[4 4 4]]

 [[5 5 5]]]

understand:

  • Think of the colon: as a stripper, a colon can strip the outermost brackets. It is used to determine the position of the brackets of None, instead of removing the outer brackets! !
  • Think of None as the operation of adding square brackets, and a None is the operation of adding a layer of square brackets

Meaning of slice[:, None, None]

[:, :, None, None] operation

import torch 
time = torch.randn(2,3)
print(time.shape)  # torch.Size([2, 3])

c = time[:, :, None, None]
print(c.shape) # torch.Size([2, 3, 1, 1])

View content:

print(time)
print(c) 
tensor([[ 1.4890,  0.0489, -0.5257],
        [-0.6525,  1.0431, -0.2119]])
tensor([[[[ 1.4890]],

         [[ 0.0489]],

         [[-0.5257]]],


        [[[-0.6525]],

         [[ 1.0431]],

         [[-0.2119]]]])
print(time)
print(time[:,None,None])
tensor([[ 1.4890,  0.0489, -0.5257],
        [-0.6525,  1.0431, -0.2119]])
tensor([[[[ 1.4890,  0.0489, -0.5257]]],


        [[[-0.6525,  1.0431, -0.2119]]]])

slice

import numpy as np 
a = np.arange(0, 9)
print(a)  # [0 1 2 3 4 5 6 7 8]
print(a[1:3]) # [1 2]
print(a[:3])# [0 1 2]
print(a[1:])# [1 2 3 4 5 6 7 8]
print(a[1:-2])# [1 2 3 4 5 6]
print(a[1::3]) # [1 4 7]
  • In single quote slicing operations, the number in the first position in the square brackets indicates the starting position, and the second number indicates the end position, which ends here but does not include this number.
  • In the double quotes slice operation, the first number in the square brackets indicates the starting position, and the second number indicates the step size or interval.

slice operation

Guess you like

Origin blog.csdn.net/weixin_43845922/article/details/129837362