Sort a Tensor from Smallest to Largest in TensorFlow – TensorFlow Example

By | May 27, 2019

tf.nn.top_k can help us to sort elements in tensor from largest to smallest, however, how to sort it from smallest to largest?

In this tutorial, we edit sort example code previous tutorial and enhance this sort functionality.

Here is example code:

import tensorflow as tf;
import numpy as np;
#create a tensor
data=tf.Variable(tf.random_uniform([10,7], -0.1, 0.1))

#define a function to sort a tensor 
#reverse = False, from largest to smallest
#reverse = True, from smallest to largest
def sort(tensor, reverse = False):
    shape = tf.shape(tensor)
    rank = tf.rank(tensor)
    k_n = shape[rank-1]
    t_v, t_i = tf.nn.top_k(tensor,k=k_n,sorted=True,name=None)
    if reverse:
        rank = tf.rank(t_v)
        t_v = tf.reverse(t_v, axis=[rank-1])
    return t_v

sort_data = sort(data,True)

init = tf.global_variables_initializer() 
init_local = tf.local_variables_initializer()
with tf.Session() as sess:[init, init_local])
    np.set_printoptions(precision=4, suppress=True)
    s= ([sort_data]))
    print s

The result is:

How to use this code?

sort_data = sort(data,True)
sort_data_2 = sort(data)

Leave a Reply

Your email address will not be published. Required fields are marked *