When you want to create a model which does not have multiple input and output and it will be developed layer by layer then we will go for a sequential model of deep learning. Basically there two types of models functional and sequential model. So in this article, we are going to see the Sequential model with tf.sequential() in Tensorflow.js.
The tf.sequential() function creates a model in which one output of one layer is the input of the next layer. in simple words, we can say it is a linear stack of layers with no branching and skipping.
Syntax:
tf.sequential( layers, name )
Parameters:
- layers: It is a list of the layer which we want to add into the model.
- name: Name of the model.
Example 1: In this example, we are going to create a sequential model with 2 dense layers of input shape 3 and making some predictions with the model.
In the inputShape :[null,3] the first parameter is the undetermined batch dimension and the second is the output size of the last layer of the model. You can pass either inputShape : [null, 3] orinputShape : [3]
Javascript
// Import Tensorflow.js import * as tf from "@tensorflow/tfjs" // Create model tf.sequential() method // Here you need to specify the input // shape for first layer manually and // for the second layer it will // automatilly update var model = tf.sequential({ layers: [tf.layers.dense({units:1,inputShape:[3]}), tf.layers.dense({units:4})] }); // Prediction with model console.log( 'Lets Predict Something:' ); model.predict(tf.ones([1,3])).print(); |
Output:
Lets Predict Something: Tensor [[-1.1379941, 0.945751, -0.1970642, -0.5935861],]
Example 2: In this example, we are going to create a model with 2 dense layers of input shape 16 using the model.add() function to add a dense layer into the model.
Javascript
// Import Tensorflow.js import * as tf from "@tensorflow/tfjs" // Create sequantial model var model = tf.sequential(); // Add dense layer using model.add() model.add(tf.layers.dense({units:8, inputShape: [16]})); model.add(tf.layers.dense({units:4})); // Predict something console.log( 'Lets predict something:' ); model.predict(tf.ones([8,16])).print(); |
Output : Lets predict something: Tensor [[0.9305074, -0.7196146, 0.5809593, -0.08824], [0.9305074, -0.7196146, 0.5809593, -0.08824], [0.9305074, -0.7196146, 0.5809593, -0.08824], [0.9305074, -0.7196146, 0.5809593, -0.08824], [0.9305074, -0.7196146, 0.5809593, -0.08824], [0.9305074, -0.7196146, 0.5809593, -0.08824], [0.9305074, -0.7196146, 0.5809593, -0.08824], [0.9305074, -0.7196146, 0.5809593, -0.08824]]
References: https://js.tensorflow.org/api/latest/#sequential