Tensorflow.js tf.Variable class

TensorFlow is an open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks in the browser or node environment.
The tf.Variable class is used to make a new mutable tf.Tensor and is provided with an assign value that copies the tf.Tensor to this new variable containing the same shape and dtype.
tf.Variable class extends tf.Tensor class.
Syntax:
tensorflow.Variable(initialTensor)
Parameters:
- initialTensor: It is the initial tensor that is assigned to the Variable class object.
Return Value: It returns nothing (i.e. void).
Example 1: This example only uses the initial value to create tf.Variable object. No optional parameters are passed.
Javascript
// Defining tf.Tensor object for initial valueinitialValue = tf.tensor([[1, 2, 3]])// Defining tf.Variable object const x = new tf.Variable(initialValue);// Checking variables dtypeconsole.log("dtype:", x.dtype)// Checking variable shapeconsole.log("shape:", x.shape)// Printing the tf.Variable objectx.print() |
Output:
dtype: float32
shape: 1,3
Tensor
[[1, 2, 3],]
Example 2: This example uses optional parameters along with the initial value to create a Variable object.
Javascript
// Defining tf.Tensor object for initial valueinitialValue = tf.tensor([[1, 2, 3]])// Defining tf.Variable object const x = new tf.Variable(initialValue, false, 'example_variable', 'int32');// Checking if variable is trainableconsole.log("Is trainable:", x.trainable)// Checking variables dtypeconsole.log("dtype:", x.dtype)// Checking variable shapeconsole.log("shape:", x.shape)// Checking variable nameconsole.log("Name:", x.name)// Printing the tf.Variable objectx.print() |
Output:
Is trainable: false
dtype: int32
shape: 1,3
Name: example_variable
Tensor
[[1, 2, 3],]
Example 3: This example creates a tf.Variable object using initial value then again adds the initial value to the Variable.
Javascript
// Defining tf.Tensor object for initial valueinitialValue = tf.tensor([[1, 2, 3]])// Defining tf.Variable object const x = new tf.Variable(initialValue);// Printing the tf.Variable objectx.print()// Adding initial value Tensor to Variableresult = x.add(initialValue)// Printing resultresult.print() |
Output:
Tensor
[[1, 2, 3],]
Tensor
[[2, 4, 6],]



