ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Pytorch中的torch.gather()函数

2021-11-12 19:06:52  阅读:206  来源: 互联网

标签:dim gather tensor index torch Pytorch input


参数说明

以官方说明为例,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]])
      

标签:dim,gather,tensor,index,torch,Pytorch,input
来源: https://blog.csdn.net/xiaoliujun1999/article/details/121292061

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有