Recommended way to replace a partcular value in a tensor

What is the recommend way to replace a particular value in a tensor with something else?
is torch.where() the most efficient solution?

q =[[0,1,2],[3,0,4],[5,6,0]]
tense_tensor = torch.tensor(q)
print(torch.where(tense_tensor==0,torch.tensor(-1),tense_tensor))

What about

tensor[tensor==4] = 16

Assuming you want to replace for example each 4 with a 16.

Edit: you could also do this with a tensor, but you would need to do it like tensor[tensor==4] = sixteens_tensor.clone() if you want to do it in autograd on a leaf variable. Also the sixteens_tensor must contain exactly as many values as there are 4s in tensor

4 Likes

This definitely looks cleaner! But I don’t have a sense of how much more efficient it is. It looks like it though.
Also I dont want to modify the original tensor. So will need to make a clone() first.

I don’t think you will see much differences there regarding the performance.

Note: if you want to replace the 4s by arbitrary values defined in a tensor, I would recommend masked_scatter_ instead of looping over tensors yourself. This approach should also work with a tensor of always the same value (e.g. always 16). However, this function will also modify the original tensor. If you don’t want this behavior, you would also need to clone it before.

1 Like

@justusschock Thanks.
Is there a batch way to replace several particular values? for example, old_new_value = [[2,22],[3,33]], which means 2 should be replaced by 22, and 3 should be replaced by 33.
Can I have a efficient way to achieve this ? Thank you.