解析Pytorch中的torch.gather()函數(shù)
參數(shù)說明
以官方說明為例,gather()函數(shù)需要三個參數(shù),輸入input,維度dim,以及索引index
input必須為Tensor類型
dim為int類型,代表從哪個維度進行索引
index為LongTensor類型
舉例說明
input=torch.tensor([[1,2,3],[4,5,6]]) #作為輸入 index1=torch.tensor([[0,1,1],[0,1,1]]) #作為索引矩陣 # dim=0時,按列進行索引 print (torch.gather(input,dim=0,index=index1)) # dim=1時,按行進行索引 print (torch.gather(input,dim=1,index=index1))
結(jié)果如下圖所示:
# 按列進行索引
tensor([[1, 5, 6],
[4, 2, 6]])
# 按行進行索引
tensor([[1, 2, 2],
[5, 4, 5]])
畫圖說明


官方文檔
def gather(self, input, dim, index, *args, **kwargs):
For a 3-D tensor the output is specified by::
out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0
out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1
out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2
Args:
input (Tensor): the source tensor
dim (int): the axis along which to index
index (LongTensor): the indices of elements to gather
Example::
>>> t = torch.tensor([[1, 2], [3, 4]])
>>> torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]]))
tensor([[ 1, 1],
[ 4, 3]])
到此這篇關(guān)于Pytorch中的torch.gather()函數(shù)的文章就介紹到這了,更多相關(guān)Pytorch torch.gather()函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python標準庫之循環(huán)器(itertools)介紹
這篇文章主要介紹了Python標準庫之循環(huán)器(itertools)介紹,本文講解了無窮循環(huán)器、函數(shù)式工具、組合工具、groupby()、其它工具等內(nèi)容,需要的朋友可以參考下2014-11-11
使用Scrapy框架爬取網(wǎng)頁并保存到Mysql的實現(xiàn)
本文主要介紹了使用Scrapy框架爬取網(wǎng)頁并保存到Mysql的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07
python猜數(shù)字小游戲?qū)崿F(xiàn)代碼
大家好,本篇文章主要講的是python猜數(shù)字小游戲?qū)崿F(xiàn)代碼,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽2022-01-01

