tensorflow argsort confusion in sort?

Viewed 185

I must be missing something rather obvious, however argsort() seems to behave inconsistently.

here is a simple example of 5 float numbers, where the first example shows expected results, however the second example seems mixed up...

##- Example 1 : Should return [4, 1, 2, 3, 0]
a = [1.0, 0.25, 0.5, 0.75, 0.0]
b = tf.argsort(a,axis=-1,direction='ASCENDING',stable=True,name=None)
c = tf.keras.backend.eval(b)
tf.print(f'expected: {c}')

##- Example 2 : Should return [3, 2, 0, 4, 1] (I think)
a = [0.75, 0.5, 0.0, 1.0, 0.25]
b = tf.argsort(a,axis=-1,direction='ASCENDING',stable=True,name=None)
c = tf.keras.backend.eval(b)
tf.print(f'confused: {c}')

This yields...

expected: [4 1 2 3 0]
confused: [2 4 1 0 3]

where I would expect:

[4, 1, 2, 3, 0]
[3, 2, 0, 4, 1]

Could someone explain this behavior?

1 Answers

I think you're getting confused by what argsort is supposed to return. The way to interpret the output is to think that if you were to use these indices to index into the original array, you would end up pulling out all the elements in sorted order.

  • It DOES tell you in what order to select elements from the array to get a sorted result

  • It DOES NOT tell you what position the number at index i should be in.

It just so happened that these two are the same in the first example, so that must've thrown you off.


This is how argsort is supposed to be used:

arr = np.array([0.75, 0.5, 0.0, 1.0, 0.25])

np.argsort(arr)
# array([2, 4, 1, 0, 3])

arr[np.argsort(arr)]
# array([0.  , 0.25, 0.5 , 0.75, 1.  ])

Except, typically you're sorting something else instead of arr.

Related