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

By | May 27, 2019

TensorFlow function  tf.nn.top_k can help us to sort elements in tensor. In this page, we write an example on how to sort a tensor from largest to smallest.

Here is example code:

import tensorflow as tf;
import numpy as np;

#create a tensor
data=tf.Variable(tf.random_uniform([10,5], -0.1, 0.1))

#define a function to sort a tensor from largest to smallest
def sort(tensor):
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)
return t_v

sort_data = sort(data)

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

s= (sess.run([sort_data]))
print s

The result is:

You can practise this function by editing our example code.