Tensor——索引和切片

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])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章