Indexing
dim 0 first
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a[0].shape
torch.Size([3, 28, 28])
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a[0,0].shape
torch.Size([28, 28])
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a[0,0,0].shape
torch.Size([28])
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a[0,0,2,4]
tensor(0.4089)
select first/last N(连续索引)
索引全部数据:
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a.shape
torch.Size([4, 3, 28, 28])
a[:2]:表示从第0张图片索引,直到第2张,但不包括第二张。故0、1一共是2张。
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a[:2].shape
torch.Size([2, 3, 28, 28])
a[:2,:1,:,:]: 从最开始的通道索引直到第1 个通道,不包括第一个通道。故0一共1个通道; 而冒号后边没有数字,则表示索引全部。
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a[:2,:1,:,:].shape
torch.Size([2, 1, 28, 28])
a[:2,1:,:,:]:表示从第一个通道开始索引,直到最后。故1、2一共2个通道。
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a[:2,1:,:,:].shape
torch.Size([2, 2, 28, 28])
a[:2,-2:,::]:假如有[a,b,c,d],正常索引顺序为:0,1,2,3;倒着索引便是:-4、-3
、-2、-1。 表示从-2开始到最后,故-2、-1一共有2个通道。
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a[:2,-2:,::].shape
torch.Size([2, 2, 28, 28])
select by steps(有间隔索引)
隔帧采样
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a[:,:,0:28:2,0:28:2].shape
torch.Size([4, 3, 14, 14])
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a[:,:,::2,::2].shape
torch.Size([4, 3, 14, 14])
冒号用法总结,打出来好麻烦,写纸上了:
select by specific index
index_select(dim,index)
索引图片:
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a.index_select(0,torch.tensor([0,2])).shape
torch.Size([2, 3, 28, 28])
索引维度:
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a.index_select(1,torch.tensor([1,2])).shape
torch.Size([4, 3, 28, 28])
索引长度:
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a.index_select(2,torch.arange(28)).shape
torch.Size([4, 3, 28, 28])
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a.index_select(2,torch.arange(8)).shape
torch.Size([4, 3, 8, 28])
…
没有什么卵用,但感觉用完代码显得很高级哈哈哈哈哈~
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a[...].shape
torch.Size([4, 3, 28, 28])
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a[0,...].shape
torch.Size([3, 28, 28])
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a[:,1,...].shape
torch.Size([4, 28, 28])
>>> import torch
>>> a = torch.rand(4,3,28,28)
>>> a[...,2:].shape
torch.Size([4, 3, 28, 26])
select by mask(掩码)
masked_select
>>> import torch
>>> x = torch.randn(3,4)
>>> mask = x.ge(0.5)
>>> torch.masked_select(x,mask)
tensor([0.5046, 1.0212, 0.6565, 1.2455])
select by index
take
>>> import torch
>>> src = torch.tensor([[4,3,5],[6,7,8]])
>>> torch.take(src,torch.tensor([0,2,5]))
tensor([4, 5, 8])