Is there a way to use index_add
with the index
argument being more that 1-dimensional ?
More especially, if I have a 2d-array that I want to fill not row by row or column by column, but element by element by specifying the 2d coordinates in which to add the desired amount in the 2d-array.
Example:
>>> to_be_filled = torch.zeros((2, 7))
>>> to_be_filled
torch.tensor([
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]
])
>>> index = torch.tensor([
[0, 1], # adding 0.4
[0, 2], # adding -1.4
[0, 3], # adding -1.13
[0, 6], # adding -1
[1, 2], # adding 3
[0, 1] # adding 2
])
>>> values = torch.tensor([
0.4, # at coordinates (0, 1)
-1.4, # at coordinates (0, 2)
-1.13, # at coordinates (0, 3)
-1, # at coordinates (0, 6)
3, # at coordinates (1, 2)
2 # at coordinates (0, 1)
])
I would like to do this like the following, but I have an error:
>>> to_be_filled.index_add_(0, index, values)
IndexError: index_add_(): Index is supposed to be a vector
Expected result:
torch.tensor([
[0, 2.4, -1.4, -1.13, 0, 0, -1],
[0, 0, 3, 0, 0, 0, 0]
])
Is there a way to do this using pytorch operations?
Note: doing to_be_filled[index[:, 0], index[:, 1]] += values
yields the following result:
torch.tensor([
[0, 2, -1.4, -1.13, 0, 0, -1],
[0, 0, 3, 0, 0, 0, 0]
])
This approach does not accumulate when an index appear twice or more (notice that to_be_filled[0, 1] == 2
instead of 2.4
)