Sequential is the quickest way to define the many models that are a plain stack of layers.
keras.Sequential builds a model from a list of layers, each feeding the next. Start the list with keras.Input(shape=...), which declares the shape of one sample (without the batch dimension), so the model can create its weights right away.
Once built you can:
model.summary()to print each layer's output shape and parameter count.model.count_params(),model.layers,model.weights,model.output_shape.- Call
model(x)on a batch to get predictions as backend tensors.
Without an Input, the model is built lazily the first time it sees data, and summary() is unavailable until then.
The batch dimension appears as None in shapes because any batch size works. A Dense(units) layer has inputs * units + units parameters: weights plus biases.
Sequential is right when there is exactly one input, one output and no branching. For multiple inputs or outputs, skip connections or shared layers, use the functional API; for arbitrary Python logic, subclass keras.Model. You can also model.add(layer) and model.pop() to edit a Sequential model incrementally.
Example
import keras
from keras import layers
model = keras.Sequential([
keras.Input(shape=(784,)), # one sample = 784 features
layers.Dense(128, activation="relu"),
layers.Dropout(0.2),
layers.Dense(10, activation="softmax"),
], name="mnist_mlp")
model.summary() # layers, output shapes, parameter counts
print(model.count_params()) # 101770 (784*128+128 + 128*10+10)
print(model.output_shape) # (None, 10)
print(len(model.layers)) # 3
print(tuple(model.layers[0].kernel.shape)) # (784, 128)Remember
- Start with
keras.Input(shape=...)for one sample's shape summary()shows shapes and parameter counts- Sequential = one input, one output, no branches
Watch out for
- Including the batch size in
keras.Input(shape=...).