【问题标题】:Convert values of a tensor in TensorFlow to regular Javascript array将 TensorFlow 中张量的值转换为常规 Javascript 数组
【发布时间】:2019-02-07 20:57:36
【问题描述】:

我在两个一维数组 (a,b) 上使用了 TensorFlow.js 框架中的 outerProduct 函数,但我发现很难以常规 javascript 格式获取结果张量的值。

即使在使用 .dataSync 和 Array.from() 之后,我仍然无法获得预期的输出格式。两个一维数组之间的结果外积应该给出一个二维数组,但我得到的是一维数组。

const a = tf.tensor1d([1, 2]);
const b = tf.tensor1d([3, 4]);
const tensor = tf.outerProduct(b, a);
const values = tensor.dataSync();
const array1 = Array.from(values);

console.log(array1);

预期结果是 array1 = [ [ 3, 6 ] , [ 4, 8 ] ],但我得到 array1 = [ 3, 6, 4, 8 ]

【问题讨论】:

    标签: javascript arrays tensorflow.js vector-multiplication


    【解决方案1】:

    版本

    tf.datatf.dataSync 的结果始终是展平数组。但是可以使用张量的形状来获得一个使用mapreduce 的多维数组。

    const x = tf.tensor3d([1, 2 , 3, 4 , 5, 6, 7, 8], [2, 4, 1]);
    
    x.print()
    
    // flatten array
    let arr = x.dataSync()
    
    //convert to multiple dimensional array
    shape = x.shape
    shape.reverse().map(a => {
      arr = arr.reduce((b, c) => {
      latest = b[b.length - 1]
      latest.length < a ? latest.push(c) : b.push([c])
      return b
    }, [[]])
    console.log(arr)
    })
    <html>
      <head>
        <!-- Load TensorFlow.js -->
        <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.14.1"> </script>
      </head>
    
      <body>
      </body>
    </html>

    从 0.15 版开始

    可以使用tensor.array()tensor.arraySync()

    【讨论】:

      【解决方案2】:

      从 tfjs 版本 0.15.1 开始,您可以使用 await tensor.array() 获取嵌套数组。

      【讨论】:

        【解决方案3】:

        你可以用你的values 做类似的事情

        const values = [3, 6, 4, 8];
        
        let array1 = []
        
        for (var i = 0; i < values.length; i += 2) {
          array1.push([values[i], values[i + 1]])
        }
        
        console.log(array1)

        【讨论】:

        • 谢谢。我试图将您的建议概括为 a 中的 n 元素和 b 数组中的 m 元素,这将给出一个 n x m 的二维数组。我发现 2 的增量是列数,在这种情况下,它将是 a 中的元素数;但必须添加 array1(i+m-1) 次,这不会使代码动态化。你知道如何让它更有活力吗?例如,考虑对上述代码的修改: const a = tf.tensor1d([1, 2, 3]);常量 b = tf.tensor1d([3, 4]); const tensor = tf.outerProduct(b, a).
        • for 循环变为: for (var i = 0; i
        • 你可以只做一个动态增量而不是 2 :)
        • 如果我调整增量,我仍然需要添加更多参数来手动推送 =>([array1[i], array1[i + 1], array1[i + 2], array1[ i+3]...,array1[i+m-2],array1[i+m-1]])。这就是问题所在。
        猜你喜欢
        • 1970-01-01
        • 2016-10-15
        • 2021-11-12
        • 2020-12-31
        • 2016-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-28
        相关资源
        最近更新 更多