Shuffle Two PyTorch Tensors the Same Way
At times in Pytorch it might be useful to shuffle two separate tensors in the same way, with the result that the shuffled elements create two new tensors which maintain the pairing of elements between the tensors. An example might be to shuffle a dataset and ensure the labels are still matched correctly after the shuffling.
import torch
x = torch.arange(10)
y = torch.arange(9, -1, -1)
print(x)
print(y)
These new tensor elements are tensors, and are paired as follows, the next steps will shuffle the position of these elements while maintaining their pairing.
0->9, 1->8, 2->7, 3->6, 4->5, 5->4, 6->3, 7->2, 8->1, 9->0
shuffle_index = torch.randperm(x.shape[0])
shuffle_index
x_new = x[shuffle_index]
y_new = y[shuffle_index]
print(x_new)
print(y_new)