新闻动态

解析Pytorch中的torch.gather()函数

发布日期:2021-12-11 08:56 | 文章来源:源码中国

参数说明

以官方说明为例,gather()函数需要三个参数,输入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))

结果如下图所示:

# 按列进行索引
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]])

到此这篇关于Pytorch中的torch.gather()函数的文章就介绍到这了,更多相关Pytorch torch.gather()函数内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

版权声明:本站文章来源标注为YINGSOO的内容版权均为本站所有,欢迎引用、转载,请保持原文完整并注明来源及原文链接。禁止复制或仿造本网站,禁止在非www.yingsoo.com所属的服务器上建立镜像,否则将依法追究法律责任。本站部分内容来源于网友推荐、互联网收集整理而来,仅供学习参考,不代表本站立场,如有内容涉嫌侵权,请联系alex-e#qq.com处理。

相关文章

实时开通

自选配置、实时开通

免备案

全球线路精选!

全天候客户服务

7x24全年不间断在线

专属顾问服务

1对1客户咨询顾问

在线
客服

在线客服:7*24小时在线

客服
热线

400-630-3752
7*24小时客服服务热线

关注
微信

关注官方微信
顶部