Keras model building · Day 15
Two Keras APIs.
One simple computation.
Follow the same input through Sequential and Functional models. See why connections and operation order matter, then check every output by hand.
Read the complete lesson
Complete preserved original
All original explanations, repeated objectives, equations, code and the comparison image with its full caption follow in their original order. A separate companion guide below adds checked examples and clarifications.
Keras API Example
Let’s continue from day 14 which we explained the 3 Keras API types and compare them
Lets focus on Understanding Sequential vs. Functional API in Keras with a Simple Example
Understanding Sequential vs. Functional API in Keras with a Simple Example
When building neural networks in Keras, there are two main ways to define models: the Sequential API and the Functional API. In this post, we’ll explore the differences between these two approaches using a simple mathematical example.
Sequential API
The Sequential API in Keras is a linear stack of layers. It’s easy to use but limited to single-input, single-output stacks of layers. Here’s a simple example to illustrate how it works.
Objective:
- Multiply the input x by 2.
- Add 3 to the result.
Let’s implement this using the Sequential API:
from keras.models import Sequential
from keras.layers import Lambda
# Define a simple sequential model
model = Sequential()
model.add(Lambda(lambda x: 2 * x, input_shape=(1,)))
model.add(Lambda(lambda x: x + 3))
model.summary()
Functional API
The Functional API in Keras is more flexible and allows for the creation of complex models with multiple inputs and outputs. We’ll use the same mathematical operations to illustrate how it works.
Objective:
- Multiply the input x by 2.
- Add 3 to the result.
Mathematical Operations:
y1 = 2 · x
y2 = y1 + 3
Let’s implement this using the Functional API:
from keras.models import Model
from keras.layers import Input, Lambda
# Define the input
input_ = Input(shape=(1,))
# Define the operations
y1 = Lambda(lambda x: 2 * x)(input_)
y2 = Lambda(lambda x: x + 3)(y1)
# Create the model
model = Model(inputs=input_, outputs=y2)
model.summary()
Summary
Both the Sequential and Functional APIs can achieve the same result in this simple example. However, the Sequential API is limited to linear stacks of layers, while the Functional API allows for more complex architectures.
Let’s even compare them in an image

• Diagram: Shows a simple linear stack of layers. • Input Layer: Receives input features (e.g., x1, x2, x3). • 1st Hidden Layer: Processes the input layer. • 2nd Hidden Layer: Processes the output from the 1st hidden layer. • Output Layer: Produces the final prediction (y). • Explanation: • Sequential API: Simple linear stack of layers, suitable for straightforward models.Functional API:
• Diagram: Demonstrates a more complex model with branching. • Input Layer: Receives input features (e.g., x1, x2, x3). • 1st Hidden Layer: Processes the input layer. • 2nd Hidden Layer: Processes the output from the 1st hidden layer. • Branched Hidden Layer: Creates a branch for more complex processing. • 1st Output Layer: Produces the first output (y1). • 2nd Output Layer: Produces the second output (y2). • Explanation: • Functional API: Allows complex architectures with multiple inputs, outputs, and shared layers.This diagram and the accompanying explanations should help illustrate the specific features and use cases of each API more effectively.
Checked companion guide · 16 November 2026
Follow five inputs through the same chain
The first layer receives x and produces 2x. The second layer receives that result, not the original x, and adds 3. In the Functional version, the argument (y1) explicitly makes that connection. In the Sequential version, the layer order makes it for you.
g(f(x)) = 2x + 3
At x = 2: 2 × 2 = 4, then 4 + 3 = 7
The variable u names the input to g. It makes clear that g receives the output of f. The two APIs express the same composition, so changing the API alone does not change these outputs.
| Input x | First layer: 2x | Second layer: 2x + 3 | Reverse: 2x + 6 | Parallel sum: 3x + 3 |
|---|---|---|---|---|
| -2 | -4 | -1 | 2 | -3 |
| -1 | -2 | 1 | 4 | 0 |
| 0 | 0 | 3 | 6 | 3 |
| 1 | 2 | 5 | 8 | 6 |
| 2 | 4 | 7 | 10 | 9 |
Every table value was computed in NumPy and independently checked against these expanded formulas. This is deterministic arithmetic, not a fitted model or an accuracy benchmark. At x = 0 the original chain and the parallel example both output 3; agreement at one input does not establish that two functions are equivalent.
Shape clarification: Input(shape=(1,)) means one feature per sample. Five scalar samples should be supplied as a two-dimensional array with shape (5, 1). The unspecified batch dimension is separate from the feature dimension.
Order and connections are different decisions
“Linear stack” describes the connection pattern: one layer after another. It does not mean that every Sequential network computes a mathematically linear function. In this example, 2x + 3 is an affine function because of the constant offset. Adding a nonlinear activation could make a single-path stack nonlinear as a function too.
Add two parallel branches: f(x) + g(x) = 2x + (x + 3) = 3x + 3
Reversing layers and changing the graph both alter the computation. Neither change is implied just by using the Functional API. A Functional graph can be a simple chain.
For an explicit parallel graph, apply both operations to inputs, then merge their outputs with layers.Add()([branch1, branch2]). That would represent the new 3x + 3 example above. The original code instead applies the second layer to y1, so it represents 2x + 3. If branches are kept as two outputs rather than added, the model would return two separate tensors instead of their sum.

Original illustration clarification: the retained image and full caption show a general Sequential stack and a more complex branched Functional architecture. That illustration is a broad API comparison, not the exact graph of the two original Lambda snippets. Both original snippets have just the same single path.
The derivative of the original chain is 2: the derivative of “multiply by 2” is 2 and the derivative of “add 3” is 1, so the chain rule gives 1 × 2. A central finite difference with ε = 10−6 agreed with 2 at all five test inputs within an absolute tolerance of 10−8. This checks a scalar mathematical derivative, not Keras automatic differentiation.
Verify the rule before training anything
The original model.summary() calls describe architecture; they do not calculate a prediction table. These two Lambda operations have no trainable weights: 2 and 3 are constants in Python expressions, not parameters learned from examples. There is no need to compile or train the models to evaluate this fixed rule.
The following complete NumPy example was executed with NumPy 2.3.5. All three assertions passed. It checks the intended chain, a deliberately reversed chain and a deliberately different parallel sum.
import numpy as np
x = np.array([-2., -1., 0., 1., 2.])
multiply = lambda value: 2 * value
add = lambda value: value + 3
chain = add(multiply(x))
reverse = multiply(add(x))
parallel = multiply(x) + add(x)
np.testing.assert_array_equal(chain, [-1, 1, 3, 5, 7])
np.testing.assert_array_equal(reverse, [2, 4, 6, 8, 10])
np.testing.assert_array_equal(parallel, [-3, 0, 3, 6, 9])
A separate Keras inference procedure
This addition uses an explicit keras.Input in the Sequential model and tests both models on the same batch. Syntax checked only here: Keras, TensorFlow, JAX and PyTorch are not installed in the verification environment, so the assertions below were not executed against a Keras backend. Install and configure a supported backend in your own environment before running it; no training or timing result is claimed.
import numpy as np
import keras
from keras import layers
x = np.array([[-2.], [-1.], [0.], [1.], [2.]], dtype="float32")
sequential = keras.Sequential([
keras.Input(shape=(1,)),
layers.Lambda(lambda t: 2 * t),
layers.Lambda(lambda t: t + 3),
])
inputs = keras.Input(shape=(1,))
y1 = layers.Lambda(lambda t: 2 * t)(inputs)
y2 = layers.Lambda(lambda t: t + 3)(y1)
functional = keras.Model(inputs, y2)
expected = 2 * x + 3
for model in (sequential, functional):
actual = keras.ops.convert_to_numpy(model(x, training=False))
np.testing.assert_allclose(actual, expected)
assert model.count_params() == 0
Historical-code note: the original Sequential snippet supplies input_shape directly to its first Lambda layer. It remains verbatim above. The added procedure follows the current guide’s explicit Input pattern, which makes the input specification clear without rewriting the historical example.
Saving note: Lambda is useful for these short teaching operations. Its Python-bytecode serialization has portability and safety limitations. For reusable layers that need reliable saving and inspection, follow the official guidance on subclassing Layer and implementing configuration. This lesson does not demonstrate or verify model saving/loading.
Read the primary references
- Keras: the Sequential model — plain layer stacks and explicit inputs.
- Keras: the Functional API — layer graphs, shared layers, multiple inputs and outputs.
- Keras: Lambda layer — simple expressions and serialization limitations.
Sources checked on 16 November 2026. New equations are selectable HTML. The four original TeX strings remain recoverable alongside their readable mathematical displays; the original script and stylesheet strings are retained. No additional rendering library was installed. The original source document label “Keras API Example” is visible above, and its malformed introductory markup has been repaired visibly without losing its source record.
Questions about Sequential and Functional models
Do Sequential and Functional give the same answer here?
Yes, the two original snippets express the same operations in the same order: multiply by 2, then add 3. Both describe 2x + 3. Their NumPy arithmetic was checked; the Keras models were not executed here.
Does Functional always mean a branched network?
No. A Functional model can represent the same single path as a Sequential stack. Branches, shared layers and multiple inputs or outputs are additional possibilities.
What does Input(shape=(1,)) mean?
Each sample contains one feature. A batch of five scalar samples has shape (5, 1); the batch dimension is not included in shape=(1,).
Do these Lambda layers learn the numbers 2 and 3?
No. The two original Lambda expressions contain fixed constants and create no trainable weights. Defining these models does not fit data or learn a rule.
Does model.summary() calculate predictions?
No. It describes the model structure and parameters. Call the model on an input tensor or array to calculate outputs; the added Keras procedure shows how to compare them.
Were the original Keras examples executed?
No. Both original snippets and the new Keras procedure pass Python syntax parsing. Keras, TensorFlow, JAX and PyTorch are unavailable here. The NumPy examples, output table, plot and finite-difference check were executed.
