[:, :, None, None]操作的理解

[:, None, None]是改变数组维度的方式

在这里插入图片描述

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]]]

理解:

  • 把 冒号: 看做剥层器,一个冒号,就可以剥开最外层的 中括号,它是用来确定None的加中括号的位置,而不是吧外层的中括号给去掉!!
  • 把None,看做加中括号的操作,一个None就是加一层中括号的操作

切片[:, None, None]的含义

[:, :, None, None]操作

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])

查看内容:

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]]]])

切片

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]
  • 在单引号切片操作中,中括号内第一个位置的数字表示的是起始位置,第二个数字表示的是结束位置,到这里结束但是不包含这个数。
  • 在双引号切片操作中,中括号内第一个数字表示的是起始位置,第二个数字表示的是步长或叫间隔。

切片操作

猜你喜欢

转载自blog.csdn.net/weixin_43845922/article/details/129837362