Suppose I have a tensor of size (3,5). I need to shuffle each of the three 5 elements row independently. All the solutions that I found shuffle all the rows with the same shuffling order (eg. using torch.randperm). Is there a way to shuffle each row with independant random shuffling order, without using a for loop to shuffle each of the row one by one?
import torch x = torch.rand(3, 5) indices = torch.argsort(torch.rand(*x.shape), dim=-1) result = x[torch.arange(x.shape).unsqueeze(-1), indices]
Instead of indexing by hand, one can use the
import torch x = torch.rand(3, 5) indices = torch.argsort(torch.rand_like(x), dim=-1) result = torch.gather(x, dim=-1, index=indices)