索引方式
#[B,C,H,W]
a = torch.tensor([ [[[ 1, 2, 3],[ 4, 5, 6],[ 7, 8, 9]],
[[10,11,12],[13,14,15],[16,17,18]],
[[19,20,21],[22,23,24],[25,26,27]]],
[[[28,29,30],[31,32,33],[34,35,36]],
[[37,38,39],[40,41,42],[43,44,45]],
[[46,47,48],[49,50,51],[52,53,54]]] ])[B,C,H,W]
a.shape
#out:
torch.Size([2, 3, 3, 3])
a[0] # 第一个维度的所有值
#out:
tensor([[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],
[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]],
[[19, 20, 21],
[22, 23, 24],
[25, 26, 27]]])
#
a[0].shape
#out:
a[0].shape
torch.Size([3, 3, 3])
#同理a[0,1],就是第一个维度上的第2个维度
a[0,1]
#out:
tensor([[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])
#a[0,1,2,2]
a[0,1,2,2]
tensor(18)
切片
#看成2张图片,3通道,3x3 大小
#在第一个维度上,0 到 1,不包含1,那就只有第一张图片
a[:1]
#out:
tensor([[[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],
[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]],
[[19, 20, 21],
[22, 23, 24],
[25, 26, 27]]]])
#
a[:1,:1,:1,:1]
tensor([[[[1]]]])
#
a[1:2,-1:,:,:]
#out:
tensor([[[[46, 47, 48],
[49, 50, 51],
[52, 53, 54]]]])
## 如果两个冒号,隔行采样 start:end:step