一看就懂的torch.gather()用法

官方文档中对此函数解释如下:
https://pytorch.org/docs/stable/generated/torch.gather.html?highlight=gather#torch.gather
其中Gathers values along an axis specified by dim.指出了gather函数本质是对一个张量进行取出其中元素的效果,类比于二维数组中通过index下标取出二维数组的元素,例如arr[1][2]=5

官方文档给出了计算式子,这里是实际计算的一个例子。
input:
[[1, 2],
[3, 4]]

index:
[[0, 0],
[1, 0]]

out的计算式如下:
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

torch.gather(input, 1, index)

out[i][j]=input[i][index[i][j]]
out[0][0]=input[0][index[0][0]]=input[0][0]=1
out[0][1]=input[0][index[0][1]]=input[0][0]=1
out[1][0]=input[1][index[1][0]]=input[1][1]=4
out[1][1]=input[1][index[1][1]]=input[1][0]=3

综上,该函数作用为Gathers values along an axis specified by dim,翻译过来也许你会看着迷糊。本质就是从完整数据中按索引取值,和二维数组一样

参考:https://zhuanlan.zhihu.com/p/352877584

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值