7

我在两个一维数组(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);

控制台.log(array1);

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

4

3 回答 3

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

于 2019-02-07T21:10:34.083 回答
2

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

于 2019-02-08T20:58:06.017 回答
0

你可以拿走你的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)

于 2019-02-07T21:12:59.340 回答