Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mutate value of a tensor in Tensorflow.js?

How do I mutate value of a tensor in Tensorflow.js? For example if I have a tensor created like this: const a = tf.tensor1d([1,2,3,4])

How do I change the value of the third element of the tensor? I know that tensors are immutable and variables are mutable.

Doing this: const a = tf.variable(tf.tensor1d([1,2,3,4])) doesn't seem to solve the problem. I cannot do:

const a = a[0].assign(5)

I am able to do this in python tensorflow like this:

a = tf.Variable([1,2,3,4]) a = a[0].assign(100) with tf.Session() as sess: sess.run(tf.global_variables_iniliazer()) print sess.run(a)

This outputs [100, 2,3,4]

like image 520
Pranay Aryal Avatar asked Apr 12 '18 17:04

Pranay Aryal


2 Answers

Does tf.buffer work for you?

// Create a buffer and set values at particular indices.
const a = tf.tensor1d([1, 2, 3, 4]);
const buffer = tf.buffer(a.shape, a.dtype, a.dataSync());
buffer.set(5, 0);
const b = buffer.toTensor();
// Convert the buffer back to a tensor.
b.print();

Tensor
    [5, 2, 3, 4]
like image 150
BlessedKey Avatar answered Oct 13 '22 10:10

BlessedKey


I had to do this using mulStrict and addStrict which do element-wise multiplication and addition.

const a = tf.tensor1d([1,2,3,4]);
tf.mulStrict(a, tf.tensor1d([0,1,1,1]))
  .addStrict(tf.tensor1d([100, 0, 0, 0]);

This was based on asnwer here

like image 38
Pranay Aryal Avatar answered Oct 13 '22 11:10

Pranay Aryal