Is it possible to shuffle two 2D tensors in PyTorch by their rows, but maintain the same order for both? I know you can shuffle a 2D tensor by rows with the following code:
JavaScript
x
2
1
a=a[torch.randperm(a.size()[0])]
2
To elaborate: If I had 2 tensors
JavaScript
1
8
1
a = torch.tensor([[1, 1, 1, 1, 1],
2
[2, 2, 2, 2, 2],
3
[3, 3, 3, 3, 3]])
4
5
b = torch.tensor([[4, 4, 4, 4, 4],
6
[5, 5, 5, 5, 5],
7
[6, 6, 6, 6, 6]])
8
And ran them through some function/block of code to shuffle randomly but maintain correlation and produce something like the following
JavaScript
1
8
1
a = torch.tensor([[2, 2, 2, 2, 2],
2
[1, 1, 1, 1, 1],
3
[3, 3, 3, 3, 3]])
4
5
b = torch.tensor([[5, 5, 5, 5, 5],
6
[4, 4, 4, 4, 4],
7
[6, 6, 6, 6, 6]])
8
My current solution is converting to a list, using the random.shuffle() function like below.
JavaScript
1
11
11
1
a_list = a.tolist()
2
b_list = b.tolist()
3
temp_list = list(zip(a_list , b_list ))
4
random.shuffle(temp_list) # Shuffle
5
a_temp, b_temp = zip(*temp_list)
6
a_list, b_list = list(a_temp), list(b_temp)
7
8
# Convert back to tensors
9
a = torch.tensor(a_list)
10
b = torch.tensor(b_list)
11
This takes quite a while and was wondering if there is a better way.
Advertisement
Answer
You mean
JavaScript
1
4
1
indices = torch.randperm(a.size()[0])
2
a=a[indices]
3
b=b[indices]
4
?