Pytorch中index_select() 函數(shù)的實現(xiàn)理解
函數(shù)形式:
index_select( dim, index )
參數(shù):
- dim:表示從第幾維挑選數(shù)據(jù),類型為int值;
- index:表示從第一個參數(shù)維度中的哪個位置挑選數(shù)據(jù),類型為torch.Tensor類的實例;
剛開始學(xué)習(xí)pytorch,遇到了index_select(),一開始不太明白幾個參數(shù)的意思,后來查了一下資料,算是明白了一點。
a = torch.linspace(1, 12, steps=12).view(3, 4) print(a) b = torch.index_select(a, 0, torch.tensor([0, 2])) print(b) print(a.index_select(0, torch.tensor([0, 2]))) c = torch.index_select(a, 1, torch.tensor([1, 3])) print(c)
先定義了一個tensor,這里用到了linspace和view方法。
第一個參數(shù)是索引的對象,第二個參數(shù)0表示按行索引,1表示按列進(jìn)行索引,第三個參數(shù)是一個tensor,就是索引的序號,比如b里面tensor[0, 2]表示第0行和第2行,c里面tensor[1, 3]表示第1列和第3列。
輸出結(jié)果如下:
tensor([[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.]])
tensor([[ 1., 2., 3., 4.],
[ 9., 10., 11., 12.]])
tensor([[ 1., 2., 3., 4.],
[ 9., 10., 11., 12.]])
tensor([[ 2., 4.],
[ 6., 8.],
[10., 12.]])
功能:從張量的某個維度的指定位置選取數(shù)據(jù)。
代碼實例:
t = torch.arange(24).reshape(2, 3, 4) # 初始化一個tensor,從0到23,形狀為(2,3,4)
print("t--->", t)
index = torch.tensor([1, 2]) # 要選取數(shù)據(jù)的位置
print("index--->", index)
data1 = t.index_select(1, index) # 第一個參數(shù):從第1維挑選, 第二個參數(shù):從該維中挑選的位置
print("data1--->", data1)
data2 = t.index_select(2, index) # 第一個參數(shù):從第2維挑選, 第二個參數(shù):從該維中挑選的位置
print("data2--->", data2)
運行結(jié)果:
t---> tensor([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
index---> tensor([1, 2])
data1---> tensor([[[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[16, 17, 18, 19],
[20, 21, 22, 23]]])
data2---> tensor([[[ 1, 2],
[ 5, 6],
[ 9, 10]],
[[13, 14],
[17, 18],
[21, 22]]])
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解pytorch tensor和ndarray轉(zhuǎn)換相關(guān)總結(jié)
這篇文章主要介紹了詳解pytorch tensor和ndarray轉(zhuǎn)換相關(guān)總結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09

