Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Argsort in Tensorflow?

How can I argsort a 25 x 5 x 5 matrix (tensor) along the 2nd axis? Essentially, I am looking for tensorflow's equivalent (function or methodology) to numpy's argsort, e.g. np.argsort(matrix, 2).

like image 978
Ari Avatar asked Feb 01 '17 16:02

Ari


2 Answers

In your case you could probably use top_k which returns the highest k values. k can be a 1D vector defining how many values to 'top' per dimensions. In your case, if you want the second axis set k=[0, 5, 0] might do it.

tf.nn.top_k(matrix, k=[0,5,0], sorted=True)

I didn't run it tho. Hope this helps

like image 142
pltrdy Avatar answered Oct 10 '22 12:10

pltrdy


For reference, tf.argsort is now supported in Tensorflow.

Example:

import tensorflow as tf


tensor = tf.constant(
    [
        [8, 7, 11],
        [5, 3, 4],
        [17, 33, 23],
    ]
)

arg_sort_op = tf.argsort(tensor, axis=-1)

with tf.Session() as sess:
    out = sess.run(arg_sort_op)

print(out)

#  [[1 0 2]
#   [1 2 0]
#   [0 2 1]]
like image 28
o-90 Avatar answered Oct 10 '22 13:10

o-90