torch.garther函数的numpy形式

torch.garther函数

torch.garther函数的具体原理可参见这里
以二维数组为例,

  1. 下述代码是行索引的例子;
tensor_0 = tensor([[ 3,  4,  5],
                   [ 6,  7,  8],
                   [ 9, 10, 11]]),
index = torch.tensor([[2, 1, 0]])
tensor_1 = tensor_0.gather(axis=0, index)
output: tensor([[9, 7, 5]])
  1. 下述代码是列索引的例子;
tensor_0 = tensor([[ 3,  4,  5],
                   [ 6,  7,  8],
                   [ 9, 10, 11]]),
index = torch.tensor([[2, 1, 0]])
tensor_1 = tensor_0.gather(axis=1, index)
output: tensor([[5, 7, 9]])

经过探索后发现,此种索引方式似乎只支持torch.tensor数据,而在numpy数组中,也需要类似的索引方式。然而,使用list列表迭代方式寻找则过于繁琐,这里根据torch.gather()内置函数的原理,设计适合numpy数组的索引方法。

torch.garther函数的numpy形式

  1. 下述代码是行索引的例子;
tensor_0 = np.array([[ 3,  4,  5],
                   [ 6,  7,  8],
                   [ 9, 10, 11]]),
index = np.array([[2, 1, 0]]).squeeze()
arg = np.arange(0, tensor_0.shape[1])   # 行采用index索引,列采用自然升序索引
tensor_1 = tensor_0[index, arg]
output: tensor([[9, 7, 5]])
  1. 下述代码是列索引的例子;
tensor_0 = tensor([[ 3,  4,  5],
                   [ 6,  7,  8],
                   [ 9, 10, 11]]),
index = torch.tensor([[2, 1, 0]]).squeeze()
arg = np.arange(0, tensor_0.shape[0])   # 行采用自然升序索引,列采用index索引
tensor_1 = tensor_0[arg, index]
output: tensor([[5, 7, 9]])
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值