When same elements are encountered, torch.sort and argsort sort the tensor in random manner. This is not the case in numpy. I have a list of elements already sorted according to the second column and now i want to sort it using the first column but preserve the earlier sort in case of tie in the new sorting.
import torch
a = torch.tensor(
[[ 0., 3.],
[ 2., 3.],
[ 2., 2.],
[10., 2.],
[ 0., 2.],
[ 6., 2.],
[10., 1.],
[ 2., 1.],
[ 0., 1.],
[ 6., 1.],
[10., 0.],
[12., 0.]]
)
print(a[torch.argsort(a[:, 0])])
Output:
tensor([[ 0., 3.],
[ 0., 2.],
[ 0., 1.],
[ 2., 1.],
[ 2., 2.],
[ 2., 3.],
[ 6., 1.],
[ 6., 2.],
[10., 1.],
[10., 2.],
[10., 0.],
[12., 0.]])
Numpy:
import numpy as np
a = np.array(
[[ 0., 3.],
[ 2., 3.],
[ 2., 2.],
[10., 2.],
[ 0., 2.],
[ 6., 2.],
[10., 1.],
[ 2., 1.],
[ 0., 1.],
[ 6., 1.],
[10., 0.],
[12., 0.]]
)
print(a[np.argsort(a[:, 0])])
Output:
[[ 0. 3.]
[ 0. 2.]
[ 0. 1.]
[ 2. 3.]
[ 2. 2.]
[ 2. 1.]
[ 6. 2.]
[ 6. 1.]
[10. 2.]
[10. 1.]
[10. 0.]
[12. 0.]]
What could be the reason for this? And what can I do to avoid it?