Sorting a matrix by column

Issue

I have a matrix which looks like this:

[[5,2],
[4,3],
[3,4]]

Using the command

tf.tensor([...])

And I would like to the matrix by the column with index 0, so that it will look like this:

[[3,4],
[4,3],
[5,2]]

How would I do that using Tensorflow.js?

Solution

Looking at the example, the tensor is sorted over the first axis.

Currently, there is no yet tf.sort in tensorflow.js. But to achieve the same thing, we can slice the tensor over its first axis, then sort it and get the indices. With the later, we can sort the initial tensor using tf.gather

a = tf.tensor2d([[3,4], [4,3],[5,2]])
firstAxis = a.gather([0], 1).reshape([-1]);
ind = tf.topk(firstAxis, a.shape[0]).indices
a.gather(ind.reverse(), 0).print()

Answered By – edkeveked

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published