PyTorch transferring index to 1-0
How to quickly set the elements in the given index list to 1 and others to 0?

For example,I have an ID pool like:
torch.arange(10),
for a given input index tensor([1,5,7,9,2]) wanna return tensor([0,1,1,0,0,1,0,1,0,1])

Easiest is to start with zeros and fill with ones using fancy indexing like this:

import torch

tensor = torch.zeros(10)
tensor[[1, 5, 7, 9, 2]] = 1


If your IDs are predefined (e.g. torch.arange(10)) and you want to get only those elements which are not zero you can do this:

import torch

ids = torch.arange(10)

mask = torch.zeros_like(ids).bool() # it has to be bool
mask[[1, 5, 7, 9, 2]] = True

torch.masked_select(ids, mask)


Which would give you:

tensor([1, 2, 5, 7, 9])

