Tensorflow.Js Problem: "Error: Number of coordinates in get() must match the rank of the tensor"

Tensorflow.Js Problem: "Error: Number of coordinates in get() must match the rank of the tensor"

这是什么? 我正在学习 tensorflow.js YouTube 视频“6.3:TensorFlow.js:变量与运算 - 智能与学习”。

一切正常,直到我尝试这个 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));

Web 控制台显示:

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

get 函数的参数数量应与张量的等级相匹配。 你的张量是 or rank 3 这意味着 get 应该有 3 个参数。张量中的第三个元素具有以下坐标:[0, 1, 0]。您更需要使用 matriisi.get(0, 1, 0).

通过索引获取元素的另一种方法是使用 dataSync()data() 来获取可以通过索引访问的类似数组的元素。

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/tfjs@0.13.0"> </script>
  </head>

  <body>
  </body>
</html>