šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

TensorflowJs sequential model – using the tf.sequential() function

The most used model type in TensorflowJs is sequential:

const myModel = tf.sequential()

A TensorflowJs sequential model is a model where the outputs of one layer are the inputs to the next layer, We just 'stack' the network layers, with no branching or skipping. You can check here its API.

For example, this is the architecture of a TensorflosJs sequential model:

TensorflowJs sequential model

In comparison. you can see here an example of a non-sequential model (also named a functional model). These are branching TensorflowJs models with multiple outputs.

How to create a sequential model in TensorflowJs?

Let's try to implement the architecture from the above picture in TensorflowJs.

So, we will need to implement a network with:

  • 3 inputs
  • 2 hidden layers each with 4 neurons
  • 1 output

The below code will implement this sequential model in TensorflowJs:

const myModel = tf.sequential()

// first hidden layer (and also the input layer)
myModel.add(
    tf.layers.dense({
        inputShape: [3],
        units: 4
    })
);
// second hidden layer
myModel.add(
    tf.layers.dense({
        units: 4
    })
);
// output layer
myModel.add(
    tf.layers.dense({
        units: 1
    })
);

The first layer that we add to myModel is a dense (meaning fully-connected) layer with 4 neurons. The units arguments specified how many neurons are in that layer.

Note that the first layer added in a sequential model is not the input layer, it is our first hidden layer instead.

The input layer is defined using the inputShape argument. In this case, we have inputShape: [3] meaning we have 3 input parameters.

You can check out if the architecture of your TensorflowJs model is correctly implemented using the model.summary() method.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *