【问题标题】:How do I reorder the dimensions of a rank 3 tensor in Tensorflow.js?如何在 Tensorflow.js 中重新排序 3 级张量的尺寸?
【发布时间】:2020-05-25 17:31:10
【问题描述】:

假设我有以下 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

【问题讨论】:

    标签: javascript tensor tensorflow.js


    【解决方案1】:

    两个张量可以沿轴-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>

    【讨论】:

    【解决方案2】:

    怎么样...

    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();
    

    希望这会有所帮助...

    【讨论】:

    • 感谢您的回答!这就像一个魅力,但不幸的是它比另一个答案慢,所以我将那个标记为解决方案。不过还是谢谢!
    猜你喜欢
    • 2019-08-26
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    相关资源
    最近更新 更多