Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Tensorflow.js tf.LayersModel class .getLayer() Method

  • Last Updated : 04 Aug, 2021

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 .getLayer() function is used to fetch a layer that is based upon either its name (which must be unique) or else an index. Where, indices are relying on the order of the horizontal graph traversal in bottom-up fashion. Moreover, in case both name as well as index are given, then the index will take priority.

Syntax:

getLayer(name?, index?)

Parameters:

  • name: It is the stated name of the layer. It is optional and is of type string.
  • index: It is the stated index of the layer. It is optional and is of type number.

Return Value: It returns  tf.layers.Layer.

Example 1:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining model
const model = tf.sequential();
  
// Adding a layer
model.add(tf.layers.dense({units: 4, inputShape: [1]}));
  
// Calling getLayer() method
const layer_0 = model.getLayer(null, 0);
  
// Printing weights of the layer_0
// using getWeights() method
layer_0.getWeights()[0].print();

Output:

Tensor
     [[-0.0678914, 0.6647689, -0.3708572, -0.1764591],]

Example 2:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining model
const model = tf.sequential();
  
// Adding layers
model.add(tf.layers.dense({units: 4, inputShape: [1]}));
model.add(tf.layers.dense({units: 2, inputShape: [3], activation: 'relu6'}));
model.add(tf.layers.dense({units: 3, inputShape: [5], activation: 'sigmoid'}));
  
// Calling getLayer() method
const layer_0 = model.getLayer(NaN, 0);
const layer_1 = model.getLayer('denselayer', 1);
const layer_2 = model.getLayer(undefined, 2);
  
// Printing number of numbers in the weights
// of the layer_0, layer_1, and layer_2 
// using countParams() method
console.log(layer_0.countParams());
console.log(layer_1.countParams());
console.log(layer_2.countParams());

Output:

8
10
9

Reference: https://js.tensorflow.org/api/latest/#tf.LayersModel.getLayer

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!