将 TensorFlow 中张量的值转换为常规 Javascript 数组

Isa*_*aac 7 javascript arrays vector-multiplication tensorflow.js

我在两个一维数组 (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);
Run Code Online (Sandbox Code Playgroud)

控制台日志(数组1);

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

edk*_*ked 6

版本 < 15

tf.dataor的结果tf.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)
})
Run Code Online (Sandbox Code Playgroud)
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.14.1"> </script>
  </head>

  <body>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

从 0.15 版开始

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