Randomly selecting n percentage of elements from a tensor and updating them

I have a tensor of some shape. I would like to select only n percentage of the elements in that tensor and add a number to them. For example, say I have a tensor like torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]) and I want to select n=.2 or 20% of the elements randomly then add 10. Then some possible results could be torch.tensor([10.0, 2.0, 3.0, 4.0, 15.0, 6.0, 7.0, 8.0, 9.0, 10.0]) 1st and 5th position chosen, or torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 16.0, 7.0, 8.0, 9.0, 20.0]) 6th and 10th position chosen.

How can I do this for a tensor of an arbitrary shape? Then tensor is quite small and speed is not necessarily a top concern. Just want it to work. Thanks!

You could use torch.randperm to permute the indices and then select the desired percentage of them to manipulate your tensor:

x = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0])
p = 0.2
idx = torch.randperm(x.size(0))[:int(x.size(0)*p)]
x[idx] += 10.
print(idx, x)
2 Likes