Tensorflow.js tf.Variable class .assign() method
TensorFlow.js is an open-source JavaScript library designed by Google to develop Machine Learning models and deep learning neural networks. tf.Variable class is used to create, track and manage variables in Tensorflow. Tensorflow variables represent the tensors whose values can be changed by running operations on them.
The assign() is the method available in the Variable class which is used to assign the new tf.Tensor to the variable. The new value must have the same shape and dtype as the old Variable value.
Syntax:
assign(newValue)
Parameters:
- newValue: It’s an object of type tf.Tensor. This new value gets assigned to the variable.
Return Value: It returns void.
Example 1: This example first creates a new tf.Variable object with initial value then assign this variable a new value with same shape and dtype as an initial value.
Javascript
initialValue = tf.tensor([[1, 2, 3]])
let x = new tf.Variable(initialValue);
console.log( "dtype:" ,x.dtype)
console.log( "shape:" ,x.shape)
x.print()
newValue = tf.tensor([[5, 8, 10]])
x.assign(newValue)
x.print()
|
Output:
dtype: float32
shape: 1,3
Tensor
[[1, 2, 3],]
Tensor
[[5, 8, 10],]
Example 2: This example first creates a new tf.Variable object with initial value then it tries to assign this variable a new value with different shape as the initial value. This will give an error.
Javascript
initialValue = tf.tensor([[1, 2],[3, 4]])
let x = new tf.Variable(initialValue);
console.log( "dtype:" ,x.dtype)
console.log( "shape:" ,x.shape)
x.print()
newValue = tf.tensor([[5, 6],[10, 11]])
x.assign(newValue)
x.print()
|
Output:
dtype: float32
shape: 2,2
Tensor
[[1, 2],
[3, 4]]
Tensor
[[5 , 6 ],
[10, 11]]
Reference: https://js.tensorflow.org/api/latest/#tf.Variable.assign
Last Updated :
22 Apr, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...