Open In App

Tensorflow.js tf.dispose() Function

Last Updated : 22 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads