Consider the following list:
[[3], [1, 2], [4], [0], [2]]
And zeros tensor of size (5, 5)
I want to fill these indices according to their index in the list to the tensor with 1.
So, the expected output should be:
tensor([[0., 0., 0., 1., 0.],
[0., 1., 1., 0., 0.],
[0., 0., 0., 0., 1.],
[1., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.]])
What happened above is this:
at the index [0, 3]
put 1
(the case for the first element in my list).
A very similar case is achievable through using Tensor.scatter_
. However, since it takes a tensor as the argument (index
); you cannot create a tensor from a list if it contains a sub-list with a different size than the other elements, which is the case with [1, 2]
in my list (this is actually the problem).
The scatter
method could be used if the list is all of same size as the following:
tensor.scatter_(1, torch.tensor(index), 1)