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]
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With