PyTorch中gather的理解

2维tensor的gather操作理解
考虑2维tensor a

a = t.arange(0, 16).view(4, 4)
print(a)

output:

tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11],
        [12, 13, 14, 15]])

index与[[2,2,0,1]]的维度相同,即(1,4).
dim=0,按列查看,第一个2处于该张量的第0列 ,所以第一个元素取a中第0列的索引为2的元素8;
dim=1,按行查看,第一个2处于第0行,所以第一个元素取a中第0行的索引为2的元素, 由于index只有第0行,所以对应的返回为a中第0行的索引为2,2,0,1的元素,即[[2,2,0,1]].

index = t.LongTensor([[2,2,0,1]])
print('dim=0:',a.gather(0, index))
print('dim=1:',a.gather(1, index))

output:

dim=0: tensor([[8, 9, 2, 7]])
dim=1: tensor([[2, 2, 0, 1]])

dim=0,数字i在第x列就选取原张量的第x列索引为i的元素.
举例, 0表示第0列索引为0(0),3表示第1列索引为3(13)
dim=1,数字在第x行就选取原张量的第x行索引为i的元素.
举例, 0表示第0行索引为0的数(0),3表示第2行索引为3的元素(11)

index = t.LongTensor([[0,2],
                      [1,2],
                      [1,3]])
print('dim=0:\n',a.gather(0, index))
print('dim=1:\n',a.gather(1, index))

output:

dim=0:
 tensor([[ 0,  9],
        [ 4,  9],
        [ 4, 13]])
dim=1:
 tensor([[ 0,  2],
        [ 5,  6],
        [ 9, 11]])

自用笔记,记录备查

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值