获取张量内特定索引的值?

miy*_*san 5 javascript tensorflow.js

我正在学习 tensorflow.js Udemy 课程,老师get在张量对象上使用了一个函数,并传入行和列索引以返回该位置的值。我无法在文档中找到此方法,它在 nodejs 中也不起作用,函数 get() 似乎不存在。

这是他的代码,他在自定义控制台的浏览器中运行:https : //stephengrider.github.io/JSPlaygrounds/

    const data = tf.tensor([
        [10, 20, 30],
        [40, 50, 60]
    ]);
    data.get(1, 2);  // returns 60 in video, in browser
Run Code Online (Sandbox Code Playgroud)

这是我的代码,这是我让它工作的唯一方法,但看起来真的很难看:

const tf = require('@tensorflow/tfjs-node');

(async () => {
    const data = tf.tensor([
        [10, 20, 30],
        [40, 50, 60]
    ]);
    let lastIndex = (await data.data())[5];
    console.log(lastIndex) // returns 60
})();
Run Code Online (Sandbox Code Playgroud)

必须有更好的方法来访问特定索引处的值。该data()方法只是从张量返回一个包含所有值的数组,我无法找到按行、列语法访问值的方法。

edk*_*ked 1

get自v0.15.0起已弃用并从v1.0.0中删除。因此,检索特定索引处的值的唯一方法是使用

  • tf.slice这将返回特定索引处的值的张量或

  • 如果你想以 JavaScript 数字的形式检索该值,那么你可以使用

    • tf.data和值的索引或

    • tf.array和坐标

    • 使用tf.buffer

(async () => {
    const data = tf.tensor([
        [10, 20, 30],
        [40, 50, 60]
    ]);
    console.time()
    let lastIndex = (await data.data())[5];
    console.log(lastIndex) // returns 60
    console.timeEnd()
    
    // using slice
    console.time()
    data.slice([1, 2], [1, 1]).print()
    console.timeEnd()
    
    //using array and the coordinates
    console.time()
    const value = (await data.array())[1][2]
    console.log(value)
    console.timeEnd()
    
    // using buffer
    console.time()
    const buffer = await data.buffer()
    const value2 = buffer.get(1, 2)
    console.log(value2)
    console.timeEnd()
})();
Run Code Online (Sandbox Code Playgroud)
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"> </script>
  </head>

  <body>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)