Linear layer stacks
Create a straightforward feed-forward neural network where each layer has one input and one output.
TensorFlow · Class
tf.keras.Sequential groups an ordered, linear stack of Keras layers into a Model. It is designed for straightforward one-input, one-output layer pipelines.
Sequential creates a Model from an ordered list of layers, passing each layer's output to the next layer's input. Define the input shape explicitly or let the model infer it on first use, then compile it before training or evaluation.
tf.keras.Sequential(layers=None, trainable=True, name=None)| Name | Type | Description |
|---|---|---|
layers | list of Layer objects or None | Optional list of layers forming the linear stack. |
trainable | bool | Whether the model is trainable. |
name | str or None | Optional model name. |
A tf.keras.Sequential model, which is a Model composed of the supplied linear stack of layers.
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.Input(shape=(4,)),
tf.keras.layers.Dense(8, activation="relu"),
tf.keras.layers.Dense(1),
])
model.compile(optimizer="sgd", loss="mse")
model.fit(tf.ones((8, 4)), tf.ones((8, 1)), epochs=1, verbose=0)
print(model(tf.ones((1, 4))).shape)Builds, compiles, trains, and calls a two-layer sequential model with an explicit input shape.
Create a straightforward feed-forward neural network where each layer has one input and one output.
Assemble a model incrementally while experimenting with architecture.
Train, evaluate, and run inference on a simple Keras model.
Sequential represents a linear stack of layers, with one layer feeding the next. It is suited to models where every layer has one input tensor and one output tensor.
Follow-up: When should it be replaced? Use the Functional API for multiple inputs or outputs, shared layers, or non-linear topologies.
Pass layers in a list to the constructor or create an empty model and append layers with add(). The resulting object is a Keras Model that supports compilation, training, evaluation, and inference.
Follow-up: How can the input shape be made explicit? Add tf.keras.Input as the first element or layer.
The model can infer its input shape when first called or trained. An explicit Input layer builds the model earlier and makes its structure available for methods such as summary().
Follow-up: Why might early building matter? It allows inspection and shape validation before data-dependent execution.
tf.keras.Modeltf.keras.Inputtf.keras.layers.Densetf.keras.models.clone_model