Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a index selected tensor to another tensor with overlapping indices in pytorch

Tags:

numpy

pytorch

This is a follow up question to this question. I want to do the exactly same thing in pytorch. Is it possible to do this? If yes, how?

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)

I need something like torch.add.at(warped_image, (iy, ix), image) that gives the output as

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

Note that the indices at (0,1) and (1,1) point to the same location (0,2). So, I want warped_image[0,2] = image[0,1] + image[1,1] = 51.

like image 380
Nagabhushan S N Avatar asked Oct 14 '22 22:10

Nagabhushan S N


1 Answers

What you are looking for is torch.Tensor.index_put_ with the accumulate argument set to 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]])

Or, using the out-place version 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]])
like image 154
Ivan Avatar answered Oct 18 '22 13:10

Ivan