1
votes

What is this ? Im learning tensorflow.js with youtube video "6.3: TensorFlow.js: Variables & Operations - Intelligence and Learning".

Everything works well until i try this get().

const getRandomInt = (max) => {
return Math.floor(Math.random() * Math.floor(max));
};

   const values = [];
  for (let i = 0; i< 30; i++) {
    values[i] = getRandomInt(10);
  }

const shape = [2, 5, 3];

const matriisi = tf.tensor3d(values, shape, 'int32');

console.log(matriisi.get(3));

And web console says:

"Error: Number of coordinates in get() must match the rank of the tensor"

1

1 Answers

0
votes

The number of parameters to the get function should match the rank of your tensor. Your tensor is or rank 3 which means that get should have 3 parameters. The third element in your tensor has the following coordinates: [0, 1, 0]. You rather need to use matriisi.get(0, 1, 0).

Another way to get an element by its index is to use dataSync() or data() in order to get an array-like element that you can access by index.

const a = tf.randomNormal([2, 5, 3], undefined, undefined, undefined, 3);

const indexToCoords = (index, shape) => {
  const pseudoShape = shape.map((a, b, c) => c.slice(b + 1).reduce((a, b) => a * b, 1));
  let coords = [];
  let ind = index;
  for (let i = 0; i < shape.length; i++) {
    coords.push(Math.floor(ind / pseudoShape[i]));
    ind = ind % pseudoShape[i];
  }
  return coords
}
const coords = indexToCoords(3, [2, 5, 3]);
// get the element of index 3
console.log(a.get(...coords));

// only dataSync will do the trick 
console.log(a.dataSync()[3])
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]"> </script>
  </head>

  <body>
  </body>
</html>