How do I get the value out of a tensor in Tensorflow.js after specifying the index?
Asked
Active
Viewed 9,548 times
5 Answers
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]);

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
-
How would you do that in python Tensorflow Keras? – gustavz Jan 24 '19 at 15:27
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
-
It doesn't work: **Error: Number of coordinates in get() must match the rank of the tensor**. – JavaRunner Aug 12 '18 at 20:58
-
-
3
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