Skip to content
Related Articles

Related Articles

Improve Article

Tensorflow.js tf.variable() Function

  • Last Updated : 07 Jul, 2021

Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. It helps developers to develop ML models in JavaScript, and use ML directly in the browser or in Node.js.

The tf.variable() function is used to create a new variable with the provided initial value.

Syntax:

tf.variable(initialValue, trainable, name, dtype)

Parameters:

  • initialValue: The initial value of the tensor from which the new variable will be initialized.
  • trainable: It is an optional parameter. It is of boolean type if true optimizers are allowed to update the variable and if false optimizers are not allowed to update it.
  • name: It is also an optional parameter. It is of string type. It is used for the name of the variable used as a unique ID.
  • dtype: It is also an optional parameter. If it is passed as the argument the intialValue will be changed to the specified dtype.

Return Value: This function returns tf.variable.



Example 1:

Javascript




// Creating and initializing a new variable
var val = tf.variable(tf.tensor2d(
    [8, 2, 5, 6],
    [2, 2]
));
 
// Printing the tensor
val.print()

Output:

Tensor
   [[8, 2],
    [5, 6]]

Example 2:

Javascript




// Creating and initializing a new variable
var val = tf.variable(tf.tensor([1, 2, 5, 6]));
 
// Printing the tensor
val.print()

Output:

Tensor
   [1, 2, 5, 6]

Example 3:

Javascript




// Creating and initializing a new variable
const x = tf.variable(tf.tensor([1, 2, 3]),
    true,"gfg",'complex64');
 
// Printing the tensor
x.print();

Output:

Tensor
   [1 + 0j, 2 + 0j, 3 + 0j]

Reference: https://js.tensorflow.org/api/latest/#variable




My Personal Notes arrow_drop_up
Recommended Articles
Page :