Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert values of a tensor in TensorFlow to regular Javascript array

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 ]

like image 662
Isaac Avatar asked Feb 07 '19 20:02

Isaac


2 Answers

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/[email protected]"> </script>
  </head>

  <body>
  </body>
</html>

From version 0.15

One can use tensor.array() or tensor.arraySync()

like image 158
edkeveked Avatar answered Sep 18 '22 13:09

edkeveked


As of tfjs version 0.15.1 you can use await tensor.array() to get the nested array.

like image 26
Nikhil Avatar answered Sep 22 '22 13:09

Nikhil