Implementation:Tensorflow Tfjs Tf Sequential
| Knowledge Sources | |
|---|---|
| Domains | Deep_Learning, Neural_Networks |
| Last Updated | 2026-02-10 00:00 GMT |
Environment:Tensorflow_Tfjs_Browser_Runtime
Overview
Concrete API for defining neural network architecture using the sequential pattern in TensorFlow.js, via tf.sequential(), Sequential.add(), and layer factory functions such as tf.layers.dense().
Description
TensorFlow.js provides a Sequential model class that implements the linear layer-stacking pattern. A sequential model is created via the tf.sequential() factory function and layers are appended one at a time using the add() method.
The tf.sequential() factory creates an empty Sequential model instance (or optionally pre-populates it with an array of layers passed in the config). The Sequential class extends LayersModel and restricts the topology to a linear chain: each layer has exactly one input and one output, and layer is output shape becomes layer i+1s input shape.
The add(layer) method appends a layer to the sequential stack. Internally, add performs several critical operations:
- If this is the first layer and it lacks an
inputShape, it defers weight creation until the first call (lazy building). - If this is the first layer and
inputShapeis provided, it automatically inserts anInputLayerbefore the user's layer to define the model's entry point. - For subsequent layers, it verifies shape compatibility: the new layer's expected input shape must be consistent with the previous layer's output shape.
- It calls the layer's
build()method, which allocates and initializes all weight tensors for that layer.
The tf.layers.dense() factory creates a fully connected (dense) layer. The Dense class implements the transformation output = activation(dot(input, kernel) + bias), where kernel is the weight matrix and bias is the bias vector.
After all layers are added, the model is uncompiled — it has a defined architecture with initialized weights but no optimizer, loss function, or metrics. The model must be compiled before training.
Code Reference
Source
Repository: https://github.com/tensorflow/tfjs
| File | Key Locations |
|---|---|
tfjs-layers/src/exports.ts |
sequential factory function at L134–136
|
tfjs-layers/src/models.ts |
Sequential class at L397–555, add() method at L452–555
|
tfjs-layers/src/exports_layers.ts |
dense factory function at L519–521
|
tfjs-layers/src/layers/core.ts |
Dense class at L188–310
|
Signature
// Sequential model factory
export function sequential(config?: SequentialArgs): Sequential
// SequentialArgs: {
// layers?: Layer[], // optional array of layers to add immediately
// name?: string // optional model name
// }
// Add a layer to the sequential stack
add(layer: Layer): void
// Dense layer factory
export function dense(args: DenseLayerArgs): Dense
// DenseLayerArgs: {
// units: number, // number of output neurons (required)
// activation?: ActivationIdentifier, // e.g. 'relu', 'sigmoid', 'softmax'
// useBias?: boolean, // default true
// kernelInitializer?: InitializerIdentifier | Initializer, // default 'glorotUniform'
// biasInitializer?: InitializerIdentifier | Initializer, // default 'zeros'
// inputShape?: Shape, // required for first layer only
// inputDim?: number, // alternative to inputShape for 1D
// kernelConstraint?: ConstraintIdentifier | Constraint,
// biasConstraint?: ConstraintIdentifier | Constraint,
// kernelRegularizer?: RegularizerIdentifier | Regularizer,
// biasRegularizer?: RegularizerIdentifier | Regularizer,
// activityRegularizer?: RegularizerIdentifier | Regularizer
// }
Import
import * as tf from '@tensorflow/tfjs';
// Then use:
// tf.sequential()
// model.add(layer)
// tf.layers.dense({...})
External Dependencies
@tensorflow/tfjs-core— Provides the tensor computation engine, data types, and shape utilities used by all layers.@tensorflow/tfjs-layers— Contains theSequentialclass,Denselayer, and all layer base classes.
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| config | SequentialArgs |
No | Optional configuration with pre-built layers array and model name |
| layer | Layer |
Yes (for add) | A layer instance to append to the model stack |
| units | number |
Yes (for dense) | Number of output neurons in the dense layer |
| activation | string |
No | Activation function identifier (e.g., 'relu', 'softmax') |
| inputShape | number[] |
First layer only | Shape of input tensor excluding batch dimension (e.g., [784]) |
Outputs
| Name | Type | Description |
|---|---|---|
| model | Sequential |
Configured but uncompiled sequential model with initialized weights |
| add return | void |
Mutates the model in-place by appending the layer |
| dense return | Dense |
A Dense layer instance ready to be added to a model |
Usage Examples
Basic MLP for Classification
import * as tf from '@tensorflow/tfjs';
// Create empty sequential model
const model = tf.sequential();
// Add layers one by one
model.add(tf.layers.dense({units: 128, activation: 'relu', inputShape: [784]}));
model.add(tf.layers.dense({units: 64, activation: 'relu'}));
model.add(tf.layers.dense({units: 10, activation: 'softmax'}));
// Inspect the architecture
model.summary();
// Output:
// Layer (type) Output shape Param #
// =================================================================
// dense_Dense1 (Dense) [null,128] 100480
// dense_Dense2 (Dense) [null,64] 8256
// dense_Dense3 (Dense) [null,10] 650
// =================================================================
// Total params: 109386
// Trainable params: 109386
// Non-trainable params: 0
Pre-populating Layers via Config
import * as tf from '@tensorflow/tfjs';
// Pass layers array directly to the constructor
const model = tf.sequential({
layers: [
tf.layers.dense({units: 32, activation: 'relu', inputShape: [10]}),
tf.layers.dense({units: 1, activation: 'sigmoid'})
]
});
Binary Classification Network
import * as tf from '@tensorflow/tfjs';
const model = tf.sequential();
model.add(tf.layers.dense({
units: 64,
activation: 'relu',
inputShape: [20],
kernelInitializer: 'heNormal',
kernelRegularizer: tf.regularizers.l2({l2: 0.01})
}));
model.add(tf.layers.dense({units: 32, activation: 'relu'}));
model.add(tf.layers.dense({units: 1, activation: 'sigmoid'}));
XOR Problem (Minimal Network)
import * as tf from '@tensorflow/tfjs';
const model = tf.sequential();
model.add(tf.layers.dense({units: 8, activation: 'relu', inputShape: [2]}));
model.add(tf.layers.dense({units: 1, activation: 'sigmoid'}));
// Model is now defined but uncompiled — must call model.compile() before training
Related Pages
Implements Principle
Environments
- Environment:Tensorflow_Tfjs_Browser_Runtime -- Browser runtime (WebGL / WebGPU / WASM / CPU backends)