如何在 Tensorflow.js 中重新排序 3 阶张量的维度?

How do I reorder the dimensions of a rank 3 tensor in Tensorflow.js?

假设我有以下 2 个张量:

var a = tf.tensor([[1,2],[3,4]]);
var b = tf.tensor([[5,6],[7,8]]);

我可以像这样把它们叠在一起:

var c = tf.stack([a, b]);

通过 c.print(),我可以看到 Tensorflow 如何堆叠 2 个张量:

Tensor
    [[[1, 2],
      [3, 4]],

     [[5, 6],
      [7, 8]]]

但是,我想像这样堆叠它们:

Tensor
    [[[1, 5],
      [2, 6]],
     [[3, 7],
      [4, 8]]]

换句话说,如果张量 c 的维度是 A, B, C,我怎样才能将维度重新排序为 B, C, A

我已经尝试阅读 Tensorflow.js API documentation,但据我所知,没有办法做到这一点(除非我错过了)。

我也尝试过使用普通 Javascript 数组来实现它,但我注意到这是非常低效和缓慢的(可根据要求提供此代码,我怀疑这是因为在处理多个数组时 ~3Kx2K 它在堆上分配了很多)。

如何将 A, B, C 的张量维度重新排序为 B, C, A

两个张量可以沿轴-1叠加

const a = tf.tensor([[1,2],[3,4]]);
const b = tf.tensor([[5,6],[7,8]]);
const c = tf.stack([a, b], axis=-1);
c.print()
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"> </script>
  </head>

  <body>
  </body>
</html>

要更改张量的顺序,可以使用 transpose 并且轴重新排序的方式可以作为参数给出

const a = tf.tensor([[1,2, 3],[3,4, 7]]);
const b = tf.tensor([[5,6, 20],[7,8, 10]]);
const c = tf.stack([a, b]); // default axis = 0
const d = c.transpose([1, 2, 0])
d.print()
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"> </script>
  </head>

  <body>
  </body>
</html>

怎么样...

var a = tf.tensor([[1,2],[3,4],[10,11]]);
var b = tf.tensor([[5,6],[7,8],[20,21]]);

x = a.transpose().stack(b.transpose()).transpose();
x.print();

希望这对您有所帮助...