Search code examples
javascripttensorflowtensorflow.js

TensorflowJS: How can I read and write to a row at a specific index of a Tensor?


In Tensorflow JS, how can I read and write to a row at a specific index of a Tensor? I want to do something like this:

let a = tf.tensor([[1, 2], [3, 4]]);
let b = tf.tensor([[5, 6], [7, 8]]);
a[0] -= b[1]
a.print()
b.print()

This should print:

[[-4, -4],
[3, 4]]

[[5, 6]
[7, 8]]

Also, where can I find out how to do other basic operations on javascript Tensors? (I only found this so far: https://js.tensorflow.org/api/0.6.1/#class:Tensor)

EDIT: This answers the read part of my question: How can I get specific rows of a tensor in TensorFlow?


Solution

  • A tensor is immutable, so it is not possible to change its value after it has been created. What can be done is to create a new tensor and give to it the values of tensor a and b.

    let a = tf.tensor([[1, 2], [3, 4]]);
    let b = tf.tensor([[5, 6], [7, 8]]);
    
    tf.concat([a.sub(b).slice(1, 1), a.slice(1,1)]).print()
    
    // or
    
    const cond = tf.tensor1d([false, true], 'bool');
    
    a.sub(b).where(cond, a).print()