Open In App

Tensorflow.js tf.Sequential Class .add() Method

Last Updated : 22 Jun, 2021
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 .add() function is used to affix a layer prototype on the topmost part of the layer stack.

Syntax:

add(layer)

Parameters:  

  • layer: It is the stated prototype of layer and it is of type tf.layers.Layer.

Return Value: It returns void.

Example 1:  

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining model
const modl = tf.sequential();
  
// Calling add() method
modl.add(tf.layers.dense({units: 4, inputShape: [1]}));
modl.add(tf.layers.dense({units: 2, stimulation: 'relu'}));
modl.add(tf.layers.dense({units: 1, stimulation: 'relu'}));
  
// Printing output by calling predict
// method
modl.predict(tf.truncatedNormal([4, 1])).print();


Output: Here, layers.dense() method is utilized to generate a entirely dense layer, predict() method is used to produce output forecasts in favor of input instances, and truncatedNormal() method is used to produce a tf.Tensor with the help of values that are sampled from a normal distribution that is truncated.

Tensor
    [[0.1687946 ],
     [-0.1382875],
     [-0.3894148],
     [0.1748937 ]]

Example 2:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining model
const modl = tf.sequential();
  
// Calling add() method
modl.add(tf.layers.maxPooling2d({batchInputShape:[1, 2, 3, 4],
     poolSize: 1,
     strides: 2}));
  
// Printing output by calling predictOnBatch
// method
modl.predictOnBatch(tf.randomNormal([1, 2, 3, 4])).print();


Output: Here, layers.maxpooling2d() method is helpful in max pooling task by means of spatial data, predictOnBatch() method is used to forecast in favor of a particular group of instances, and randomNormal() method is utilized in producing tf.Tensor with the help of values that are sampled from a normal distribution.

Tensor
    [[[[0.9905863, 1.6736914, -1.2367558, -0.3343732],
       [0.2533375, 0.5539166, 0.6961272 , -0.3252741]]]]

Reference: https://js.tensorflow.org/api/latest/#tf.Sequential.add



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

Similar Reads