【问题标题】:Add values to a tensor element based on its position in pytorch根据张量元素在 pytorch 中的位置向张量元素添加值
【发布时间】:2020-10-04 08:10:01
【问题描述】:

在 pytorch 中,我想根据元素的位置向张量中的元素添加值。例如考虑,

Input = torch.tensor([1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0])

在Input数组的几个偏移量之间,Offsets = [0,5,10,15,20],我想添加不同的值,ValuesToAdd = [10,100,1000,10000]

我希望输出是

Output = torch.tensor([11,12,13,14,15,106,107,108,109,100,1001,1002,1003,1004,1005,10006,10007,10008,10009,10000])

这里,在输入数组中的索引Offsets[i]Offsets[i+1] 之间,添加了ValuesToAdd[i]。例如,对于输入数组中的索引10,11,12,1314Offsets[2] = 10Offsets[3]=15),添加了1000ValuesToAdd[2])。

我怎样才能做到这一点?我正在寻找一种更有效的方法,而不是遍历 Offsets 数组。

【问题讨论】:

    标签: python numpy pytorch add tensor


    【解决方案1】:

    您可以使用torch.repeat_interleave

    Offsets = torch.tensor(Offsets)
    shifts = Offsets[1:] - Offsets[:-1]
    output = Input.clone()
    output[Offsets[0]:Offsets[-1]] += torch.tensor(ValuesToAdd).repeat_interleave(shifts)
    print(torch.all(output == Output))
    # True
    

    【讨论】:

      猜你喜欢
      • 2022-08-09
      • 1970-01-01
      • 2019-04-21
      • 2021-09-14
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 2021-07-30
      • 2020-10-18
      相关资源
      最近更新 更多