在pytorch中将索引选定张量添加到另一个具有重叠索引的张量

Nag*_*S N 5 numpy pytorch

这是这个问题的后续问题。我想在 pytorch 中做同样的事情。是否有可能做到这一点?如果是,如何?

import torch
image = torch.tensor([[246,  50, 101], [116,   1, 113], [187, 110,  64]])
iy = torch.tensor([[1, 0, 2], [1, 0, 2], [2, 2, 2]])
ix = torch.tensor([[0, 2, 1], [1, 2, 0], [0, 1, 2]])
warped_image = torch.zeros(size=image.shape)
Run Code Online (Sandbox Code Playgroud)

我需要类似的东西torch.add.at(warped_image, (iy, ix), image)给输出

[[  0.   0.  51.]
 [246. 116.   0.]
 [300. 211.  64.]]
Run Code Online (Sandbox Code Playgroud)

请注意,位于(0,1)和的索引(1,1)指向相同的位置(0,2)。所以,我想要warped_image[0,2] = image[0,1] + image[1,1] = 51.

Iva*_*van 6

您正在寻找的是torch.Tensor.index_put_参数accumulate设置为True

>>> warped_image = torch.zeros_like(image)

>>> warped_image.index_put_((iy, ix), image, accumulate=True)
tensor([[  0,   0,  51],
        [246, 116,   0],
        [300, 211,  64]])
Run Code Online (Sandbox Code Playgroud)

或者,使用异地版本torch.index_put

>>> torch.index_put(torch.zeros_like(image), (iy, ix), image, accumulate=True)
tensor([[  0,   0,  51],
        [246, 116,   0],
        [300, 211,  64]])
Run Code Online (Sandbox Code Playgroud)