Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptTensorflow.js tf.dispose() Function

Tensorflow.js tf.dispose() Function

Tensorflow.js is an open-source library developed by Google brain team for running deep learning neural networks in the browser or node environment.

The .dispose() function is used to dispose a tensor to the memory.

Syntax:

tensor.dispose()

Parameters: this method don’t have any parameters

Return value: void

Example 1: In this example, we will dispose a tensor using tf.dispose function.

Javascript




// Importing the tensorflow.Js library
import * as tf from "@tensorflow/tfjs"
  
// Creating the tensor
var tr = tf.tensor([1, 2, 3, 4, 5, 6, 7]);
  
// Disposing the tensor
tr.dispose()
  
// Trying to print it now
tr.print()


  Output:

An error occurred 
  Tensor is disposed

Example 2: In this example, we will create a rank-2 tensor and try to print to before and after using tf.dispose function.

Javascript




// Importing the tensorflow.Js library
import * as tf from "@tensorflow/tfjs"
  
// Create a new tensor
var tr2d = tf.tensor2d([1, 2, 3, 4], [2, 2]);
  
// Print the tensor
tr2d.print()
  
// Dispose the tensor
tr2d.dispose()
  
// Try to print it again
tr2d.print()


 Output:

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

Example 3: In this example, we are creating a tensor with value, shape, and dataType. Then, we will dispose it using tf.dispose() function:

Javascript




// Importing the tensorflow.Js library
import * as tf from "@tensorflow/tfjs"
   
// Creating a value variable which
// stores the value
var value = ['1', '2', '3', '4', '5', '6']
   
// Creating a shape variable
// which stores the shape
var shape = [2, 3]
   
// Creating a d_Type variable
// which stores the data-type
var d_Type = 'string'
   
// Creating the tensor
var tr3d = tf.tensor(value, shape, d_Type)
   
// Printing the tensor
tr3d.print()


 Output: 

"Tensor
    [['1', '2', '3'],
     ['4', '5', '6']]" 

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments