Skip to content
Related Articles
Open in App
Not now

Related Articles

Tensorflow.js tf.Variable class

Improve Article
Save Article
  • Last Updated : 10 May, 2021
Improve Article
Save Article

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 value
initialValue = tf.tensor([[1, 2, 3]])
  
// Defining tf.Variable object 
const x = new tf.Variable(initialValue);
  
// Checking variables dtype
console.log("dtype:", x.dtype)
  
// Checking variable shape
console.log("shape:", x.shape)
  
// Printing the tf.Variable object
x.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 value
initialValue = tf.tensor([[1, 2, 3]])
  
// Defining tf.Variable object 
const x = new tf.Variable(initialValue,
    false, 'example_varaible', 'int32');
  
// Checking if variable is trainable
console.log("Is trainable:", x.trainable)
  
// Checking variables dtype
console.log("dtype:", x.dtype)
  
// Checking variable shape
console.log("shape:", x.shape)
  
// Checking variable name
console.log("Name:", x.name)
  
// Printing the tf.Variable object
x.print()


Output:

Is trainable: false
dtype: int32
shape: 1,3
Name: example_varaible
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 value
initialValue = tf.tensor([[1, 2, 3]])
  
// Defining tf.Variable object 
const x = new tf.Variable(initialValue);
  
// Printing the tf.Variable object
x.print()
  
// Adding initial value Tensor to Variable
result = x.add(initialValue)
  
// Printing result
result.print()


Output:

Tensor
     [[1, 2, 3],]
Tensor
     [[2, 4, 6],]

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!