Raady
Raady

Reputation: 1726

sorting of 2d array min to max in tensorflow

I have an array

x1 = tf.Variable([[0.51, 0.52, 0.53, 0.94, 0.35],
             [0.32, 0.72, 0.83, 0.74, 0.55],
             [0.23, 0.72, 0.63, 0.64, 0.35],
             [0.11, 0.02, 0.03, 0.14, 0.15],
             [0.01, 0.72, 0.73, 0.04, 0.75]],tf.float32)

I want to sort the elements in each row from min to max. Is there any function for doing such ?

In the example here they are using tf.nn.top_k2d array,using this I can loop to create the max to min.

def sort(instance):
   sorted = []
   rows = tf.shape(instance)[0]
   col = tf.shape(instance)[1]
   for i in range(rows.eval()):
       matrix.append([tf.gather(instance[i], tf.nn.top_k(instance[i], k=col.eval()).indices)])
   return matrix

Is there any thing similar for finding the min to max or how to reverse the array in each row ?

Upvotes: 1

Views: 1290

Answers (1)

fabmilo
fabmilo

Reputation: 48330

As suggested by @Yaroslav you can just use the top_k values.

a = tf.Variable([[0.51, 0.52, 0.53, 0.94, 0.35],
             [0.32, 0.72, 0.83, 0.74, 0.55],
             [0.23, 0.72, 0.63, 0.64, 0.35],
             [0.11, 0.02, 0.03, 0.14, 0.15],
             [0.01, 0.72, 0.73, 0.04, 0.75]],tf.float32)

row_size = a.get_shape().as_list()[-1]
top_k = tf.nn.top_k(-a, k=row_size)
sess.run(-top_k.values)

this prints for me

array([[ 0.34999999,  0.50999999,  0.51999998,  0.52999997,  0.94      ],
       [ 0.31999999,  0.55000001,  0.72000003,  0.74000001,  0.82999998],
       [ 0.23      ,  0.34999999,  0.63      ,  0.63999999,  0.72000003],
       [ 0.02      ,  0.03      ,  0.11      ,  0.14      ,  0.15000001],
       [ 0.01      ,  0.04      ,  0.72000003,  0.73000002,  0.75      ]], dtype=float32)

Upvotes: 1

Related Questions