Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting values of specific indices inside tensor?

I am following a tensorflow.js Udemy course and the teacher used a function get on a tensor object and passed in row and column indices to return the value at that position. I am unable to find this method in documentation and it also doesn't work inside nodejs, the function get() seems to not exist.

Here is his code, that he was running in browser in his custom console: 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

This is my code, the only way that I got it to work but looks really ugly:

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
})();

There has to be a better way to access the value at specific index. The data() method simply returns an array of all values from tensor and I am unable to find a way to access values by row, column syntax.

like image 947
miyagisan Avatar asked Nov 07 '22 17:11

miyagisan


1 Answers

get is deprecated since v0.15.0 and removed from v1.0.0. Therefore the only way of retrieving a value at a specific index is to use either

  • tf.slice which will return a tensor of the value at the specific index or

  • if you want to retrieve the value as a javascript number, then you can use either

    • tf.data and the index of the value or

    • tf.array and the coordinates

    • using 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()
})();
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"> </script>
  </head>

  <body>
  </body>
</html>
like image 84
edkeveked Avatar answered Nov 15 '22 12:11

edkeveked