How to select 5% of total values from a tensor randomly?

a = torch.rand(2,5,10)
I want to select at most 5% of values from tensor a randomly and then multiply those values with -1? How to do that? kindly, give a generic solution as the shape of the tensor is not fixed

@albanD any suggestions?

Hi,

I guess you can do out = (torch.rand_like(a) - 0.05).sign().type_as(a) * a assuming a is a floating point number. This should select around 5% (the bigger the Tensor, the more precise it will be).

1 Like