18

How do I get the value out of a tensor in Tensorflow.js after specifying the index?

Pranay Aryal
  • 5,208
  • 4
  • 30
  • 41

5 Answers5

21

You can use datasync for this.

const newTensor = tf.tensor2d([[2,4],[5,6]]);
const tensorData = newTensor.dataSync();
console.log("data[0] is " + tensorData[0]);
console.log("data[3] is " + tensorData[3]);

https://codepen.io/anon/pen/NMKgeO?editors=1011

BlessedKey
  • 1,615
  • 1
  • 10
  • 16
3

You can use the following more powerful method

tensor.buffer().get(0, 0);

This will allow you index into logical coordinates of the tensor (the 2d coordinates as opposed to the flattened 1d coordinate). See the link

Raza
  • 189
  • 1
  • 7
2
const newTensor = tf.tensor2d([[2,4], [5,6]])
newTensor.get([0]) ##returns 2
newTensor.get([3]) ##returns 6

Thankfully, all this returns a number and not a tensor.

vcucu
  • 184
  • 3
  • 12
Pranay Aryal
  • 5,208
  • 4
  • 30
  • 41
1

tf.Tensor.dataSync() does not retain the original shape. If you would like to preserve the shape, you can use tf.Tensor.arraySync().

eaksan
  • 535
  • 5
  • 11
1

Alternatively you can also use slice to get the value:

let value = tensor.slice([i,j], [1, 1]);

or

let value = tensor.slice([i,j], [1, 1]).arraySync()[0][0];
vcucu
  • 184
  • 3
  • 12