溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Pytorch中index_select() 函數(shù)的實現(xiàn)理解

發(fā)布時間:2020-10-08 14:31:14 來源:腳本之家 閱讀:178 作者:清晨的光明 欄目:開發(fā)技術

函數(shù)形式:

index_select(
 dim,
 index
)

參數(shù):

  • dim:表示從第幾維挑選數(shù)據(jù),類型為int值;
  • index:表示從第一個參數(shù)維度中的哪個位置挑選數(shù)據(jù),類型為torch.Tensor類的實例;

剛開始學習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表示按列進行索引,第三個參數(shù)是一個tensor,就是索引的序號,比如b里面tensor[0, 2]表示第0行和第2行,c里面tensor[1, 3]表示第1列和第3列。

輸出結果如下:

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)

運行結果: 

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)容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI