Intermediate 9 min · March 15, 2026

Keras Sequential vs Functional — Avoid ResNet ValueError

Residual connection in Keras Sequential causes ValueError; Functional API required for branching like ResNet.

N
Naren · Founder
Plain-English first. Then code. Then the interview question.
About
Quick Answer
  • Sequential API builds models as a linear stack — one input, one output, no branches, no exceptions
  • Functional API builds any directed acyclic graph — multi-input, multi-output, skip connections, shared layers, intermediate sub-models
  • Both produce identical computation graphs — there is zero runtime performance difference between them
  • Sequential cannot express residual connections, weight sharing, or multiple output heads — the moment you need any of these, it is the wrong tool
  • Any Sequential model can be rewritten as Functional with the same layers, same weights, and identical outputs
  • In Keras 3, both APIs work identically across TensorFlow, JAX, and PyTorch backends — the API choice is purely about architecture expressiveness

Keras provides two primary ways to build neural networks: the Sequential API and the Functional API. Both create the same underlying computation graphs — TensorFlow, JAX, or PyTorch depending on your Keras 3 backend — but they differ fundamentally in what architectures they can express. Sequential handles linear stacks of layers and nothing else. The Functional API handles any directed acyclic graph of layers: multi-input models, multi-output models, shared layers, and residual connections.

The choice matters more at design time than at runtime. Both APIs produce identical computation graphs. There is no speed difference, no memory difference, no training difference. The difference is entirely in what architectures you can express and how clearly the code communicates the intended structure to the next engineer who reads it.

In 2026 with Keras 3 supporting multiple backends, the choice of API is completely independent of whether you're running on TensorFlow, JAX, or PyTorch. I've used both in production — from simple image classifiers to multi-task systems with shared encoders and task-specific heads, to ResNet-style backbones with residual connections. Here is the practical decision framework I actually use, grounded in what goes wrong when teams make the wrong choice.

What is the Keras Sequential API?

The Sequential API builds models as a linear stack of layers, where each layer has exactly one input tensor and one output tensor. Data flows in one direction: from the first layer to the last, with no branching, no merging, and no skipping. The model is defined either by passing a list of layers to the constructor or by calling model.add() in sequence.

The Sequential API is deliberately simple — and that simplicity is its actual value. When your architecture is genuinely a straight line, Sequential communicates that intent clearly. You do not need to manage tensor variables, there are no wiring mistakes possible, and the code reads in the same order that data flows through the network. For standard feedforward networks, simple CNNs, vanilla RNNs, and baseline experiments, it is the right tool.

The limitations are structural, not a list of features that might be added later. A Sequential model cannot have multiple input branches, multiple output heads, layers that share weights with other layers, or residual connections where a later layer receives input from an earlier one. If your architecture needs any of these — and most production architectures eventually do — Sequential cannot express it and there is no workaround within the API itself.

One practical note: always include an explicit layers.Input(shape=(...)) as the first element. Without it, Keras cannot infer shapes until the first call to fit() or predict(), which means model.summary() shows None everywhere and shape errors are harder to catch before training starts.

What is the Keras Functional API?

The Functional API builds models by defining the computation graph explicitly. You create Input() tensors, pass them through layer objects by calling those objects, and Keras tracks the connections. The model is then defined by passing the input and output tensors to keras.Model().

This explicit tensor-passing style requires more code than Sequential for simple architectures, but it removes every architectural constraint that Sequential imposes. You can split a tensor into multiple branches by passing the same tensor to multiple layer calls. You can merge tensors from different branches using Add(), Concatenate(), or Multiply(). You can reuse the same layer object on different inputs — weight sharing — by calling it multiple times. And you can create multiple output tensors from a single backbone and return all of them from the model.

The Functional API is the standard for any non-trivial production architecture. ResNet uses residual connections. Inception uses parallel convolution branches with different filter sizes. Siamese networks use shared layers called on two separate inputs. Multi-task learning models use a shared encoder with independent task-specific heads. None of these are expressible with Sequential. All of them are straightforward with Functional.

One mental model that helps: think of the Functional API as plumbing. Input() is the water source. Each layer call is a pipe fitting. Add() and Concatenate() are junction pieces. keras.Model() defines which pipes are the output taps. The layer objects are reusable fittings — you can connect the same fitting into multiple places in the plumbing system, and water flows through the same physical component in each path.

Model Subclassing API — The Third Option

Keras also offers a third approach: Model Subclassing. You inherit from keras.Model, define your layers in __init__, and implement the actual forward pass in the call() method. This gives you full imperative control flow inside the forward pass — if statements that change which layers execute, for loops that iterate over a dynamic number of steps, conditional branching based on the values of tensors rather than just their shapes.

I reach for Subclassing only in specific situations. Research prototypes where the computation graph changes during training. Reinforcement learning agents where the action space or episode structure affects the forward pass. Recursive architectures where the number of steps is input-dependent. Tree-structured models. Anything where the graph topology is not fixed at definition time.

For everything else — including quite complex static architectures — I use Functional. The reason is tooling. Functional models produce complete, accurate model.summary() output with correct shapes at every layer. keras.utils.plot_model() generates a full visual graph. Serialisation with model.save() works completely and portably across backend switches. Subclassing models have more limited tooling support in all three areas, and the dynamic graph means that shape errors can surface at runtime during training rather than at graph construction time.

The practical rule: if you can draw the architecture as a fixed DAG on a whiteboard and have it not change during training, use Functional. If the graph topology is genuinely dynamic — if what you're drawing on the whiteboard would need to include conditional branches based on tensor values — use Subclassing.

Transfer Learning and Fine-Tuning — The Most Common Production Use Case

Transfer learning is one of the most common reasons teams encounter the Functional API in production, even when they started with Sequential for their own layers. Almost all pretrained models in keras.applications are built with the Functional API — ResNet50, EfficientNet, MobileNetV3, VGG16. When you load one of these and add custom layers on top, you are working with Functional models whether you explicitly chose the API or not.

The standard two-phase fine-tuning pattern I use in production is worth understanding in detail, because the ordering matters and getting it wrong in either direction has concrete consequences.

Phase 1 — train the new head on frozen backbone: set base_model.trainable = False before compiling. This ensures the randomly initialised head layers do not immediately destroy the pretrained features in the backbone through large gradient updates. The learning rate can be normal during this phase since only the head weights are updating. Run for enough epochs that the head has learned a reasonable mapping from backbone features to your task.

Phase 2 — fine-tune the top layers of the backbone: set base_model.trainable = True, then selectively freeze the bottom layers. Use a learning rate that is one to two orders of magnitude lower than Phase 1 — typically 1e-5 or lower. The lower rate is essential: the backbone features are already good, and you want to nudge them toward your domain without destroying the general representations. Recompile the model after changing trainable flags — this is not optional, the optimiser state needs to reflect the new trainable parameter set.

Decision Framework — Which API Should You Choose?

Here is the practical decision tree I actually use in production when starting a new model.

Is the architecture a strict linear chain with one input and one output? Use Sequential. Is the architecture anything other than a strict linear chain — multiple inputs, multiple outputs, residual connections, parallel branches, shared layers, intermediate sub-model extraction? Use Functional. Does the forward pass require imperative control flow — if statements or for loops over a dynamic number of steps that depend on tensor values, not just shapes? Use Subclassing, or Subclass individual blocks and wire them with Functional at the model level.

The decision is purely about architectural expressiveness. There is no runtime performance difference between Sequential and Functional — both produce the same type of Keras Model object with the same computation graph. The weights are identical, training is identical, inference is identical. You are choosing between two syntaxes for describing the same underlying graph.

One rule of thumb that has saved multiple teams I've worked with: if you are not certain the architecture will remain a linear stack for the entire project lifetime, start with Functional. Migrating from Functional to Sequential is pointless since Sequential is strictly less expressive. Migrating from Sequential to Functional when you hit the first skip connection at week six of a project is a frustrating and avoidable interruption.

Debugging Common Architecture Errors

The Functional API is more powerful than Sequential, but it surfaces errors in ways that can be cryptic until you understand the pattern behind them. Almost every Functional API error I've seen in production falls into one of four categories, and each has a clear diagnostic approach.

The graph disconnected error is the most common. It means you're trying to include a tensor in your model's computation graph that traces back to an Input() layer not listed in the keras.Model(inputs=[...]) constructor. The fix is always the same: check which Input() layers your tensors come from and make sure all of them are listed.

The None dimensions error typically means a Sequential model is missing an explicit Input() layer, or you are calling model.summary() before the model has processed any data. Adding Input() as the first layer is almost always the fix.

Weight sharing bugs are usually discovered through the parameter count: if your Siamese network has double the expected parameters, you created two separate layer objects instead of calling one shared object twice.

Shape errors during training are best diagnosed visually. plot_model() with show_shapes=True prints the tensor shape at every layer. Reading model.summary() works but is slower for complex graphs — the visual is much faster for identifying where a dimension mismatch occurs.

Autoencoders — A Natural Functional API Pattern

Autoencoders are worth covering explicitly because they demonstrate two Functional API capabilities that Sequential fundamentally cannot support, and they're a common architecture for dimensionality reduction, anomaly detection, generative modelling, and representation learning.

The first capability: sub-model extraction. With the Functional API, you can create multiple Keras Model objects from the same computation graph. The encoder model and the autoencoder model share the same layer objects and the same weights — training the autoencoder updates the encoder's weights, and the encoder model immediately reflects those updated weights. No copying, no re-training, no synchronisation code.

The second capability: conditional graph reuse. You can attach different decoders to the same encoder for experiments — one decoder for image reconstruction, another for masked patch prediction, another for contrastive learning objectives — and all of them share the encoder's weights while each has its own loss function and training data.

This pattern extends directly to any architecture with reusable intermediate representations: vision-language models where the image and text encoders feed different downstream heads, multi-task models where a shared feature extractor drives separate classification and regression heads, and distillation setups where a student encoder is trained to match a teacher encoder's representations.

Sequential vs Functional vs Subclassing
FeatureSequential APIFunctional APIModel Subclassing
Architecture typeLinear stack only — one input, one output, no exceptionsAny directed acyclic graph — branching, merging, skippingAny graph plus dynamic control flow in the forward pass
Multi-input modelsNo — impossible by definitionYes — pass a list of Input() tensors to keras.Model()Yes — handled in call() with multiple arguments
Multi-output modelsNo — impossible by definitionYes — return a list of output tensors from keras.Model()Yes — return a tuple or dict from call()
Shared layers (weight reuse)No — each layer position is called exactly onceYes — assign layer to variable, call it on multiple tensorsYes — call self.layer on multiple inputs in call()
Residual / skip connectionsNo — a layer can only receive the immediately preceding layer's outputYes — Add()([current_output, earlier_tensor]) is straightforwardYes — handled imperatively in call()
Intermediate sub-model extractionAwkward — requires layer indexing hacksNatural — create keras.Model(input, intermediate_tensor) from any tensorNot supported — graph is not static
model.summary() qualityGood for linear stacks — shows concrete shapes when Input() is presentExcellent — shows full graph with shapes at every layerPartial — shapes not always resolvable without running data through
plot_model() readabilityLow value for complex linear stacksHigh — shows the full DAG visually with tensor shapesLimited — dynamic graph may not render completely
Debugging difficultyEasiest — errors surface immediately at add() or compile()Medium — graph disconnected and shape errors are common but diagnosableHardest — errors often surface at runtime during training
Transfer learningAwkward — requires accessing pretrained model layers by indexNatural — use base_model.input and base_model.output directlyNatural — call base_model in call() as a layer
Keras 3 backend supportYes — TensorFlow, JAX, PyTorchYes — TensorFlow, JAX, PyTorchYes — TensorFlow, JAX, PyTorch
Best used forSimple baselines, genuinely linear architectures, teaching examplesMost real production architectures — any non-trivial modelResearch prototypes, RL agents, genuinely dynamic architectures

Key Takeaways

  • Sequential API builds linear stacks — one input, one output, no exceptions. Functional API builds any directed acyclic graph. Both produce the same underlying Keras Model with identical computation graphs and zero runtime performance difference.
  • Use Sequential for simple baselines and genuinely linear architectures. Switch to Functional the moment you need multi-input, multi-output, skip connections, or weight sharing — and start with Functional if there is any chance of needing these later.
  • Weight sharing in Functional API: create one layer object and call it on multiple tensors. Both calls use and update the same weights. Creating new layer objects instead is the most common weight sharing mistake and shows immediately as a doubled parameter count.
  • Multi-input and multi-output models require the Functional API — pass a list of Input() tensors to keras.Model(inputs=[...]) and return a list of output tensors from keras.Model(outputs=[...]).
  • Any Sequential model can be rewritten as a Functional model with the same layers, same weights, and identical outputs. The reverse is not always possible — Functional models with branching cannot be converted to Sequential.
  • Transfer learning requires the Functional API — all pretrained models in keras.applications are Functional. Freeze the backbone before Phase 1, recompile after changing trainable flags, and use a learning rate of 1e-5 or lower for Phase 2 fine-tuning.
  • In Keras 3, both APIs work identically across TensorFlow, JAX, and PyTorch backends. The API choice is purely about architecture expressiveness, not backend or performance.
  • Model Subclassing is for genuinely dynamic architectures — use it at the block level for components with internal logic, and wire those blocks together with the Functional API at the model level.

Common Mistakes to Avoid

  • Using Sequential when the architecture needs a skip connection or any form of branching
    Symptom: ValueError about incompatible shapes when trying to add a merge layer. Model summary shows unexpected None dimensions. Training never starts despite the architecture looking correct in diagrams. Engineers spend time on reshape workarounds that do not resolve the underlying problem.
    Fix: Switch to the Functional API. Use layers.Add()([current_output, shortcut]) for residual connections — it is three lines to express what Sequential structurally cannot. Sequential cannot model any architecture where a layer receives input from more than the immediately preceding layer, and no amount of reshaping changes that.
  • Not specifying input shape in Sequential models
    Symptom: model.summary() shows (None, None) in the Output Shape column throughout the network — parameter counts show as 0. model.predict() fails with shape mismatch errors. The model appears to build successfully but cannot be used.
    Fix: Add layers.Input(shape=(...)) as the first element in the Sequential layer list. Without it, Keras defers shape inference until the first call to fit() or predict(), which means summary() cannot show concrete shapes and shape errors are caught much later than they should be.
  • Creating new layer objects instead of reusing one object for weight sharing
    Symptom: Siamese network has double the expected parameter count. Two branches produce different embeddings for identical inputs because they have independently initialised weights. Model accuracy is lower than expected because both branches need to learn separately what one shared encoder should learn jointly.
    Fix: Assign the layer to a variable first, then call it on each input: shared_encoder = layers.Dense(64); output_a = shared_encoder(input_a); output_b = shared_encoder(input_b). Each call to layers.Dense(64) without assignment creates a separate layer with separate weights — that is two independent layers, not weight sharing.
  • Missing one or more Input() layers from the keras.Model(inputs=[...]) constructor
    Symptom: Graph disconnected error when building the model. The error message names the tensor it cannot trace back to a listed input. Occurs in any Functional model with multiple input branches or complex graph topology.
    Fix: Every Input() tensor that appears anywhere in the computation graph must be explicitly listed in the keras.Model(inputs=[...]) call. If you have two input branches, both must be listed. Trace the error tensor back to its originating Input() layer and add it to the list.
  • Forgetting to freeze pretrained layers before Phase 1 of transfer learning
    Symptom: Model accuracy drops dramatically in the first few training epochs. Loss decreases erratically rather than smoothly. Pretrained features are destroyed by large gradient updates from the randomly initialised head, which treats the backbone weights as equally uncertain as the head weights.
    Fix: Set base_model.trainable = False before compiling and before any Phase 1 training. After the head has been trained with the backbone frozen, set base_model.trainable = True, freeze all but the top N layers, then recompile with a learning rate of 1e-5 or lower before Phase 2.
  • Treating Functional and Subclassing as interchangeable for static architectures
    Symptom: plot_model() produces incomplete or empty diagrams for Subclassing models. model.summary() shows less shape information. Shape errors surface at training time rather than at graph construction time, making the feedback loop slower. Serialisation with model.save() behaves differently and may not round-trip cleanly across backend switches.
    Fix: Use Functional for any architecture where the computation graph is fixed at definition time — this covers the vast majority of production models. Use Subclassing only for architectures with genuinely dynamic graph topology (control flow that depends on tensor values, not shapes). For reusable building blocks with internal logic, subclass keras.Model for the block and wire blocks together with Functional at the model level.

Interview Questions on This Topic

  • QWhat is the difference between the Keras Sequential and Functional API?JuniorReveal
    The Sequential API builds models as a linear stack of layers — each layer has exactly one input and one output, and each layer receives the output of the immediately preceding layer. The Functional API builds models by explicitly calling layer objects on tensors and connecting them into any directed acyclic graph. Use Sequential for genuinely linear architectures where the model is a strict straight-line stack. Use Functional for multi-input models, multi-output models, residual connections, parallel branches, and shared layers — any architecture that is not a strict linear chain. Both APIs produce identical computation graphs with no runtime performance difference. The choice is purely about what architectures you can express.
  • QWhen would you use the Functional API over Sequential, and can you give a concrete example?JuniorReveal
    Use the Functional API whenever the architecture is not a strict linear stack. Concrete examples: ResNet uses residual connections where a layer adds its output to an earlier layer's output — the Add() layer receives two tensors, which Sequential cannot express. Siamese networks use a shared encoder called on two separate inputs — one layer object called twice, which Sequential cannot express. Multi-task models produce multiple output tensors from one backbone — multiple outputs, which Sequential cannot express. Any time you see a model diagram with a node that has more than one incoming edge or more than one outgoing edge, you need the Functional API. If a single Dense-ReLU-Dense-Softmax stack is sufficient, Sequential is fine. In my experience, most non-trivial production models need Functional.
  • QHow does weight sharing work in the Keras Functional API, and how would you verify it is working correctly?Mid-levelReveal
    Create a single layer object and call it on multiple tensors. The layer object holds the weights. Each call on a different tensor uses the same weights and accumulates gradients from all calls during backpropagation. For a Siamese network: shared_encoder = layers.Dense(64); output_a = shared_encoder(input_a); output_b = shared_encoder(input_b). Both calls use and update the same 64-unit Dense weight matrix. To verify: check model.count_params() — a correctly shared two-branch model has the same parameter count as a single-branch model. If you see double the expected parameters, you created two separate layer objects. Also verify by passing identical inputs through both branches and confirming identical outputs: np.allclose(model.predict([x, x])[0], model.predict([x, x])[1]) should be True.
  • QCan you convert a Sequential model to a Functional model? Is the reverse always possible?Mid-levelReveal
    Yes, any Sequential model can be rewritten as a Functional model. Create an Input() tensor with the same shape, pass it through the same layers in the same order, and wrap with keras.Model(inputs, outputs). The resulting model has identical weights, identical forward pass, and identical output for any given input. The reverse is not always possible — Functional models with any branching, multiple inputs, multiple outputs, or shared layers cannot be expressed as Sequential models because Sequential is structurally limited to linear chains. The migration from Sequential to Functional is always safe and mechanical. The migration in the other direction is sometimes impossible by design.
  • QWhat is a multi-output model in Keras and when would you build one?Mid-levelReveal
    A multi-output model produces multiple prediction tensors from one forward pass. Built with the Functional API by creating multiple output tensors from the same backbone and passing them as a list to keras.Model(inputs, outputs=[out1, out2]). The most common production use case is multi-task learning: a single image encoder producing both a classification output and a bounding box regression output, each with its own loss function. The total loss is a weighted sum of individual losses. This is more parameter-efficient than training separate models for each task, and tasks often benefit from shared feature representations when the underlying data is related. You can also assign different loss weights to tasks if one matters more to the business objective.
  • QWhen would you choose Model Subclassing over the Functional API for a production model?SeniorReveal
    I choose Subclassing only when the computation graph is genuinely dynamic — when the topology changes based on tensor values during the forward pass, not just on shapes. Reinforcement learning agents where the number of action steps varies per episode. Recursive tree-structured models where depth depends on input. Research architectures where different branches activate based on routing decisions made during inference. For almost everything else — including quite complex architectures with many layers, branches, and shared weights — I use Functional. The reason is tooling: Functional models produce complete model.summary() output with concrete shapes, plot_model() generates useful visual graphs, and serialisation is reliable across backend switches. With Subclassing, all three are degraded. A pragmatic middle ground: subclass keras.Model for reusable blocks that encapsulate internal logic, then wire those blocks together using the Functional API at the full model level.

Frequently Asked Questions

What is the Keras Sequential API?

The Keras Sequential API builds neural networks as a linear stack of layers. You add layers in order with model.add() or pass them as a list to keras.Sequential(). Data flows from the first layer to the last in one straight path with no branching and no skip connections. It is the simplest Keras API, appropriate for feedforward networks, simple CNNs, and linear RNNs where the architecture has no branches. Always include an explicit Input() layer as the first element to enable shape propagation from the start.

What is the Keras Functional API?

The Keras Functional API builds models by explicitly calling layer objects on tensors and connecting them into a computation graph. You create Input() tensors, call layers on them to produce output tensors, and define the model with keras.Model(inputs, outputs). It supports any architecture expressible as a directed acyclic graph: multi-input, multi-output, residual connections, parallel branches, shared layers, and intermediate sub-model extraction. It is the standard API for non-trivial production architectures and all models in keras.applications.

Which Keras API should I use for most projects?

Default to the Functional API for production work. It supports everything Sequential supports and everything Sequential cannot express. The code is slightly more verbose for simple architectures but that verbosity is constant — it does not grow with complexity the way Sequential workarounds do. Use Sequential only when you are certain the architecture is and will remain a strict linear stack with no branching. Use Model Subclassing only for architectures with genuinely dynamic computation graphs.

What is a residual connection and how do you build one with Keras?

A residual connection adds a layer's input directly to its output: output = F(x) + x. Introduced in ResNet to enable training of very deep networks by giving gradients a shortcut path during backpropagation. In Keras Functional API: shortcut = x; x = layers.Dense(64, activation='relu')(x); x = layers.Dense(64)(x); x = layers.Add()([x, shortcut]); x = layers.Activation('relu')(x). The Add() layer receives two input tensors — one from the current path, one from the shortcut — which is why residual connections require the Functional API and cannot be expressed with Sequential.

Can Keras Functional models be saved and loaded?

Yes. Both Sequential and Functional models use the same serialisation API. Save with model.save('model.keras') (the recommended Keras native format) or model.save('model_dir', save_format='tf') for TensorFlow SavedModel format. Load with keras.models.load_model('model.keras'). The save format is independent of which Keras API you used to build the model. In Keras 3, model.save() uses the .keras format by default, which is portable across backends.

🔥

That's TensorFlow & Keras. Mark it forged?

9 min read · try the examples if you haven't

Previous
Building Your First Neural Network with Keras
5 / 10 · TensorFlow & Keras
Next
Image Classification with TensorFlow and Keras