按列对矩阵进行排序

时间:2021-03-20 05:41:50

标签: javascript tensorflow matrix tensorflow.js

我有一个看起来像这样的矩阵:

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

使用命令

tf.tensor([...])

我想通过索引为 0 的列来矩阵,使其看起来像这样:

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

我将如何使用 Tensorflow.js 做到这一点?

2 个答案:

答案 0 :(得分:2)

看这个例子,张量在第一个轴上排序。

目前,tensorflow.js 中还没有 tf.sort。但是为了达到同样的目的,我们可以在它的第一个轴上对张量进行切片,然后对其进行排序并获得索引。对于后者,我们可以使用 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()

答案 1 :(得分:0)

您可以使用简单的 javaScript 来实现:

let arr = [[5,2], [4,3], [3,4]];

let result = arr.sort((a, b) => a[0] - b[0]);
console.log(result);