Open In App

Tensorflow.js tf.layers dispose() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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 dispose() function is used to dispose the weights of the layers stated. Moreover, it decrease the stated layer object’s reference count via one.

Note:

  • Here, a layer is reference counted. Where, its reference number is raised via one for the first time its apply() method is invoked as well as when it becomes a segment of a new Node by invoking the apply() method on a tf.SymbolicTensor.
  • Here, when a layer’s reference number becomes zero then its every single weights will be disposed and the basic memory i.e. the textures assigned in WebGL will also be cleared.
  • When the reference count of a layer is greater than zero following the deduction then the Layer weights will not be disposed.
  • Finally, when a Layer is disposed, it cannot be utilized in the invokes like apply(), getWeights() or setWeights() any longer.

Syntax:

dispose()

Parameters:

This method has no parameters.

Return Value: It returns DisposeResult.

Example 1:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Creating a model
const model = tf.sequential();
  
// Adding a layer
model.add(tf.layers.dense({units: 1, inputShape: [3]}));
  
// Calling dispose method
const val = model.layers[0].dispose();
  
// Printing output
console.log(val);


Output:

{
  "refCountAfterDispose": 0,
  "numDisposedVariables": 2
}

Example 2:

Javascript




// Importing the tensorflow.js library
//import * as tf from "@tensorflow/tfjs"
  
// Creating a model
const model = tf.sequential();
  
// Adding layers
model.add(tf.layers.dense({units: 1, inputShape: [5, 1]}));
model.add(tf.layers.dense({units: 4}));
model.add(tf.layers.dense({units: 2, inputShape: [6], batchSize: 5}));
  
// Calling dispose() method
const val1 = model.layers[0].dispose();
const val2 = model.layers[1].dispose();
const val3 = model.layers[2].dispose();
  
// Printing output
console.log(val1);
console.log(val2);
console.log(val3);


Output:

{
  "refCountAfterDispose": 0,
  "numDisposedVariables": 2
}
{
  "refCountAfterDispose": 0,
  "numDisposedVariables": 2
}
{
  "refCountAfterDispose": 0,
  "numDisposedVariables": 2
}

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



Last Updated : 27 Jul, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads