Sunday, December 29, 2024
Google search engine
HomeLanguagesJavascriptTensorflow.js tf.tidy() Function

Tensorflow.js tf.tidy() Function

Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment.

The .tidy() function is used to execute the given function i.e. fn and once its terminated it clears up all the equidistant tensors that are allotted by the stated function fn excluding the ones that are returned by fn. Here, fn should not yield a promise. However, the returned output might be a complex object.

Note:

  • This method favors in preventing memory leaks. Generally, wrap calls to the processes in tf.tidy() function in order to cleanup the memory automatically.
  • However, the variables are not cleared within the tidy() function. In case, variables are to be disposed, then we can make use of tf.disposeVariables() or else invoke dispose() method instantly on the variables.

Syntax:

tf.tidy(nameOrFn, fn?)

 

Parameters:  

  • nameOrFn: The stated designation of the stopper, or else the function which is to be executed. In case, a designation is given, then the second argument must be a function. And if the debug mode is on, then the scheduling as well as the memory utilization of the stated function will be pursued and showed on the console utilizing the given designation. It can be of type string or function.
  • fn: The stated function which is to be executed. It is optional and is of type function.

Return Value: It returns void, number, string, TypedArray, tf.Tensor, tf.Tensor[], or {[key: string]:tf.Tensor, number, or string}.

Example 1:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Calling tidy() method
const res = tf.tidy(() => {
    
   // Calling scalar() method
   const x = tf.scalar(3);
    
   // Calling sqrt() function
   const y = tf.sqrt(5);
    
   // Calling square() method
   const z = y.square();
  
  // Calling sub() method 
  return z.sub(x);
});
  
// Printing output
res.print();


Output:

Tensor
    2

Example 2: 

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Calling tidy() method
const res = tf.tidy(() => {
    
   // Calling sin() method
   const op = tf.sin(45);
    
   // Printing number of tensors inside tidy
   // Using memory() method
   console.log('number of tensors inside tidy: '
      + tf.memory().numTensors);
  
  // Calling sqrt() method 
  return op.sqrt();
});
  
   // Printing number of tensors outside tidy
   // Using memory() method
   console.log('number of tensors outside tidy: '
      + tf.memory().numTensors);
  
// Printing output
res.print();


Output:

number of tensors inside tidy: 1
number of tensors outside tidy: 1
Tensor
    0.9224448204040527

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

RELATED ARTICLES

Most Popular

Recent Comments