本篇文章小编给大家分享一下解析Pytorch中torch.gather()函数代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
参数说明
以官方说明为例,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]])
原神祈愿模拟器最新版
原神祈愿模拟器手机版是一款完整汉化的趣味原神抽卡模拟小游戏,
宝宝森林美食完整版
宝宝森林美食游戏最新版是一款十分有趣的休闲益智游戏,帮助宝宝
g沙盒仇恨官方英文版(gorebox)
G沙盒仇恨英文原版是一款最近非常火热的沙盒模拟类游戏,在这里
迷你世界测试服最新版2024
迷你世界测试服2021最新版,即迷你世界的先遣服版本,用户能
闪耀暖暖最新版2024
闪耀暖暖手游这是非常好玩的换装手游,游戏内容丰富有趣,游戏环