【问题标题】:Add a index selected tensor to another tensor with overlapping indices in pytorch在pytorch中将索引选择的张量添加到另一个具有重叠索引的张量
【发布时间】:2021-04-11 12:34:51
【问题描述】:

这是this question 的后续问题。我想在 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)

我需要像 torch.add.at(warped_image, (iy, ix), image) 这样的东西,输出为

[[  0.   0.  51.]
 [246. 116.   0.]
 [300. 211.  64.]]

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

【问题讨论】:

    标签: numpy pytorch


    【解决方案1】:

    您要查找的是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]])
    

    或者,使用替换版本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]])
    

    【讨论】:

    • 哇!太感谢了!我希望这能让渐变流动。
    • 是的!如果你在image 上将requires_grad 设置为True,那么warped_image 将变成grad_fn(用于反向传播)设置为<IndexPutBackward>
    • 我也需要渐变流过索引,但我得到了一个错误。知道如何解决它或任何解决方法吗?我问了一个单独的question
    • @NagabhushanSN 我认为你不能通过索引传递梯度,因为它们是离散且不可微的
    • 是的,我想到了。事实证明,这毕竟是不需要的。
    猜你喜欢
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 2020-03-28
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多