A Sequential model is the simplest way to build a Keras model — you pass it a list of layers, and data flows through them in order, each layer's output becoming the next layer's input. It only supports this simple linear topology; models with multiple inputs, multiple outputs, shared layers, or non-linear connections between layers, like a residual/skip connection, require the more flexible Functional API instead, built with tf.keras.Model().
1Understanding tf.keras.Sequential()
A Sequential model is the simplest way to build a Keras model — you pass it a list of layers, and data flows through them in order, each layer's output becoming the next layer's input. It only supports this simple linear topology; models with multiple inputs, multiple outputs, shared layers, or non-linear connections between layers, like a residual/skip connection, require the more flexible Functional API instead, built with tf.keras.Model().
Reach for Sequential() only when your architecture really is a single, unbranching stack of layers — the moment you need multiple inputs/outputs or a skip connection, switch to the Functional API with tf.keras.Model() instead of trying to force it into a Sequential model.
import tensorflow as tf
from tensorflow.keras import layers
model = tf.keras.Sequential([
layers.Dense(64, activation='relu', input_shape=(32,)),
layers.Dense(10, activation='softmax')
])
print(model.output_shape)2Practical Example
Here is a real-world application of tf.keras.Sequential() showing how it is used in production TensorFlow code.
import tensorflow as tf
from tensorflow.keras import layers
model = tf.keras.Sequential()
model.add(layers.Dense(64, activation='relu', input_shape=(32,)))
model.add(layers.Dense(10, activation='softmax'))
print(len(model.layers))3Best Practices
Follow these guidelines when working with tf.keras.Sequential():
1. Use Sequential() for simple, single-path architectures, and the Functional API for anything with multiple inputs, multiple outputs, or non-linear connections between layers
2. Specify an explicit input shape on the first layer, or via an Input layer, so the model can build its weights immediately, rather than waiting until the first call with real data
3. Add layers with model.add() incrementally when building a model conditionally or in a loop, instead of always passing the full list to the constructor at once
Tip: Reach for Sequential() only when your architecture really is a single, unbranching stack of layers — the moment you need multiple inputs/outputs or a skip connection, switch to the Functional API with tf.keras.Model() instead of trying to force it into a Sequential model.
import tensorflow as tf
from tensorflow.keras import layers
model = tf.keras.Sequential([
layers.Dense(64, activation='relu', input_shape=(32,)),
layers.Dense(10, activation='softmax')
])
print(model.output_shape)