I have a 2D tensor and I would like to sort by the first dimension like this example:
a = torch.FloatTensor(
[[5, 5],
[5, 3],
[3, 5],
[6, 4],
[3, 7]])
And I expected this result after sorting:
a = torch.FloatTensor(
[[3, 5],
[3, 7],
[5, 3],
[5, 5],
[6, 4]])
Is it possible to do this in pytorch? I know that is possible to do it in numpy, but I want do it in GPU using torch.
Sort by first column and use the indices to then sort the whole array:
a[a[:, 0].sort()[1]]
Output:
tensor([[3., 5.],
[3., 7.],
[5., 5.],
[5., 3.],
[6., 4.]])
And if you really need it interleaved:
b = a[a[:, 1].sort()[1]]
b[b[:, 0].sort()[1]]
Output:
tensor([[3., 5.],
[3., 7.],
[5., 3.],
[5., 5.],
[6., 4.]])
torch.stack(sorted(a, key=lambda a: a[0]))
Output will be:
tensor([[3., 5.],
[3., 7.],
[5., 5.],
[5., 3.],
[6., 4.]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With