I used the outerProduct function in the TensorFlow.js framework on two 1D arrays (a,b), but I am finding it difficult to get the values of the resulting tensor in the regular javascript format.
Even after using .dataSync and Array.from(), I am still unable to get the expected output format. The resulting outer product between the two 1D arrays should give one 2D array, but I am getting 1D array instead.
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);
The expected result is array1 = [ [ 3, 6 ] , [ 4, 8 ] ], but I am getting array1 = [ 3, 6, 4, 8 ]
Version < 15
The result of tf.data
or tf.dataSync
is always a flatten array. But one can use the shape of the tensor to get a multi-dimensional array using map and reduce.
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>
From version 0.15
One can use tensor.array() or tensor.arraySync()