sequential , functional and model subclassing API in Keras _ day 14

Computed shared-gradient contributions and parameter counts for the lesson architectures; not training benchmarks.
Checked architecture and shared-parameter arithmetic; no training accuracy shown.

Model building · Day 14

Sequential, Functional or subclassed: choose your Keras API

Understand the graph before choosing the interface. Keep the complete original lesson, then compare architectures, check a forward pass and trace a shared gradient.

Read the complete lesson

Original lesson preserved · Checked expansion: 16 November 2026
No Keras training accuracy is claimed.

Computed shared-gradient contributions and architecture parameter counts.
Graph arithmetic, not training benchmarks.

Complete preserved original

Every original explanation, repeated comparison, formula, code block, table and reference remains in order below. The checked companion guide follows separately. Its notes qualify the unverified historical accuracy and distinguish the different example architectures.



In our last blog on day 13, we explained what’s Keras and we showed a code example which was using the Sequential API but did not discuss its API type.

Understanding Keras APIs and Their Use Cases

In our previous blog post on Day 13, we introduced Keras and provided a code example using the Sequential API. In this post, we will delve into the different types of Keras APIs: Sequential, Functional, and Model Subclassing. We will explain each API, its inventor, appropriate use cases, and whether they can be used interchangeably. We will also analyze the code examples provided to illustrate the differences between these approaches.

Sequential API

Inventor: François Chollet, the creator of Keras.

Overview: The Sequential API is the simplest and most straightforward way to build a neural network in Keras. It allows you to create a model layer-by-layer in a linear stack.

Use Cases:
– Simple models with a single input and a single output.
– Beginners and quick prototyping.
– Basic feedforward neural networks and simple CNNs.

Mathematical Foundation:
The Sequential API models are compositions of functions, where each layer Li applies a transformation fi:
y=Ln ∘Ln-1 ∘⋯∘L1(x)
This means the output of one layer is the input to the next.

Advantages:
– Easy to use and understand.
– Ideal for simple, linear architectures.

Limitations:
– Limited flexibility: cannot handle models with multiple inputs/outputs or complex topologies like shared layers and residual connections.

Performance:
– Fast to set up and train for simple models, but less efficient for complex architectures due to its limitations in handling non-linear connections and multiple inputs/outputs.

For more information, visit the [official Keras documentation](https://keras.io/api/models/sequential/).

Functional API

Inventor: François Chollet.

Overview: The Functional API is a more flexible way to build models. It allows for the creation of complex models with multiple inputs and outputs, shared layers, and non-linear connections.

Use Cases:

  • Models with multiple inputs and outputs.
  • Complex architectures like branching and merging paths.
  • Shared layers, such as in Siamese networks.

Mathematical Foundation:

The Functional API models are represented as Directed Acyclic Graphs (DAGs) of layers:

y=f(x1,x2,⋯,xn)

This flexibility allows for constructing more complex architectures.

Advantages:

  • Supports arbitrary model architectures.
  • Suitable for advanced architectures such as residual networks and multi-modal inputs.

Limitations:

  • Slightly more complex to understand and use compared to the Sequential API.

Performance:

  • Efficient for complex architectures due to its ability to handle multiple inputs/outputs and non-linear connections.

For more details, visit the Keras documentation.

Model Subclassing API

Overview: The Model Subclassing API provides the highest level of flexibility and control. It involves creating a custom model by subclassing the tf.keras.Model class and defining the layers and forward pass manually.

Use Cases:

  • Research and development of novel architectures.
  • Models requiring custom behaviors and complex operations.

Mathematical Foundation:

In this API, you explicitly define the forward pass in the call method, giving full control over data flow through the layers:

y=model(x)

This method allows for implementing complex operations and unique behaviors.

Advantages:

  • Maximum flexibility and control.
  • Ideal for custom behaviors and complex models.

Limitations:

  • Requires a deeper understanding of Keras and TensorFlow.
  • More complex to implement compared to the Sequential and Functional APIs.

Performance:

  • Optimal for custom and complex models due to the direct control over the model architecture.

For further information, refer to the Keras guide on making new layers and models via subclassing.

Comparing the APIs

  • Sequential API: Best for simple, linear models.
  • Functional API: Suitable for complex models with multiple inputs/outputs and non-linear connections.
  • Model Subclassing API: Provides full control and customization, ideal for research and highly specialized models.

Can All APIs Be Used for the Same Problem?

Flexibility and Choice:

While all three APIs can technically be used to solve the same problem, the choice depends on the complexity and requirements of the model.

  • Sequential API: Limited to simple, linear models. Not suitable for complex architectures.
  • Functional API: Offers more flexibility and is suitable for complex models. Preferred for most use cases where complexity is involved.
  • Model Subclassing API: Provides full control and is best for novel or highly customized models.

Example:

For a simple classification task, the Sequential API is sufficient. For a model with multiple inputs and outputs, the Functional API is better suited. If the model requires custom training loops or complex behaviors, the Model Subclassing API would be the best choice.

Other APIs in Keras

Keras also includes specialized APIs for preprocessing, tuning, and serialization, among other tasks. These APIs support a wide range of workflows, making Keras a versatile library for deep learning.

By understanding the strengths and appropriate use cases of each Keras API, you can select the most suitable approach for your machine learning projects and build models effectively and efficiently.

For further reading and detailed information, you can explore the Keras Models API documentation.

Now is Time to Code:

Detailed Explanations

Why Use the Model Subclassing API?

  • Flexibility: Provides the ability to define any architecture and custom behavior, which is especially useful for complex or non-standard models.
  • Customization: Allows for implementing custom layers and operations within the forward pass, offering unparalleled control over the model’s inner workings.
  • Research and Innovation: Ideal for experimenting with novel architectures and approaches in deep learning research.

How It Affects the Results:

  • Precision and Control: By having full control over the model’s operations, you can optimize and customize the architecture to potentially achieve better performance and efficiency for specific tasks.
  • Complexity Management: This approach can manage more complex dependencies and layer interactions, which might not be possible with simpler APIs.

Mathematical Insight:

In the Model Subclassing API, you explicitly define the transformation of the input tensor x through various layers, leading to the output tensor y. This direct control allows for implementing sophisticated transformations and handling multiple inputs and outputs more effectively.

By understanding and leveraging these three different APIs in Keras, you can choose the best approach based on your specific needs, complexity, and the nature of your machine learning or deep
learning tasks.

Differences in Model Definitions and Explanations

The exact lines in each of the three code examples that differ are the lines where the model is defined. These lines are different because each API provides a distinct way to define the architecture of the neural network.

Sequential API

The model is defined using a sequential approach, where each layer is added one after another in a linear stack.

# Sequential API model definition
import tensorflow as tf

model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=[28, 28]),
    tf.keras.layers.Dense(300, activation="relu"),
    tf.keras.layers.Dense(100, activation="relu"),
    tf.keras.layers.Dense(10, activation="softmax")
])

Functional API

The model is defined using a functional approach, which allows for more complex architectures with multiple inputs and outputs.

# Functional API model definition
import tensorflow as tf

inputs = tf.keras.Input(shape=(28, 28))
x = tf.keras.layers.Flatten()(inputs)
x = tf.keras.layers.Dense(300, activation="relu")(x)
x = tf.keras.layers.Dense(100, activation="relu")(x)
outputs = tf.keras.layers.Dense(10, activation="softmax")(x)

model = tf.keras.Model(inputs, outputs)

Model Subclassing API

The model is defined by subclassing the tf.keras.Model class, providing the most flexibility and control over the model’s architecture and forward pass.

# Model Subclassing API model definition
import tensorflow as tf

class MyModel(tf.keras.Model):
    def __init__(self):
        super(MyModel, self).__init__()
        self.flatten = tf.keras.layers.Flatten()
        self.dense1 = tf.keras.layers.Dense(300, activation="relu")
        self.dense2 = tf.keras.layers.Dense(100, activation="relu")
        self.dense3 = tf.keras.layers.Dense(10, activation="softmax")

    def call(self, inputs):
        x = self.flatten(inputs)
        x = self.dense1(x)
        x = self.dense2(x)
        return self.dense3(x)

model = MyModel()

These differences exist because:

  • Sequential API: Best for simple models where the layers are stacked in a linear order.
  • Functional API: Suitable for complex models with non-linear topology, multiple inputs/outputs, and shared layers.
  • Model Subclassing API: Provides full control and customization over the model, ideal for research and novel architectures.

Comparison of Keras APIs: Sequential, Functional, and Model Subclassing in our code above, is the resuls the same ?

Results Comparison Across All 3 APIs

The results for models built using the Sequential API, Functional API, and Model Subclassing API will generally be the same, assuming the architectures, initialization, training process, and hyperparameters are identical. The underlying mathematical operations and computations are the same across these APIs; they merely offer different ways to define and build the model.

Key Factors for Same Results

  • Identical Architecture: All three APIs use the same layers in the same order: Flatten -> Dense (300 units, ReLU) -> Dense (100 units, ReLU) -> Dense (10 units, Softmax).
  • Same Initialization and Training Process: The random seed is set for reproducibility. The models are compiled with the same loss function (sparse_categorical_crossentropy), optimizer (sgd), and metric (accuracy). The training process (epochs, batch size, validation split) is identical.

Given these factors, the results in terms of accuracy and loss should be the same across the three APIs because the underlying computations performed by the models are identical.

Still Sequential api is better approach for this task, Now Why Sequential API is Better for This Task?

Simplicity and Readability

The Sequential API allows for the simplest and most readable code when building straightforward, linear models. This reduces the potential for errors and makes the code easier to understand and maintain.

Ease of Use

For tasks that do not require complex architectures, the Sequential API is the quickest and easiest way to build a model. There’s no need to define the input and output layers explicitly as in the Functional API or to implement a custom class as in the Model Subclassing API.

Focused Scope

The Sequential API is designed specifically for models where layers are stacked sequentially. This focused scope makes it a better fit for simple models, avoiding the overhead and additional code required by the other APIs.

Results Comparison for the Provided Example

The models built using the Sequential API, Functional API, and Model Subclassing API perform the same computations. Therefore, the training and evaluation results (accuracy and loss) for all three models should be the same.

Expected Results

Assuming the same architecture, initialization, and training procedure, the models should produce identical results. For example:

  • Test accuracy: 0.8745 (expected for all three APIs)

Conclusion

Result Similarity: The results are the same across all three APIs because the models perform identical computations.

Why Sequential is Better: For this particular task (a straightforward feedforward neural network), the Sequential API is better because it provides a simpler, more readable, and more efficient way to define and train the model without unnecessary complexity. It aligns perfectly with the problem’s requirements, offering the quickest and most straightforward path to implementation.

 

Keras APIs Comparison

AspectSequential APIFunctional APIModel Subclassing APIMathematical Foundation y=Ln ∘Ln-1 ∘⋯∘L1(x) y=f(x1,x2,⋯,xn) y=model(x)Transformation Example ai+1 =fi(Wi ·ai +bi) y1 =f1(W1 ·x+b1)
y2 =f2(W2 ·y1 +b2)
Custom defined in call method:
a=f1(W1 ·x+b1)
b=f2(W2 ·a+b2)
y=f3(a,b)

AlgorithmLinear flow from input to outputDAG with multiple branches and mergesCustom forward passImplementationLayers added sequentiallyLayers defined as a DAGLayers and forward pass defined explicitlyPerformanceFast for simple modelsEfficient for complex modelsVaries, can be optimized for specific tasksFlexibilityLimited (single input/output)High (multiple inputs/outputs, shared layers)Maximum (complete control over architecture)Ease of UseEasiest, ideal for beginnersModerate, requires understanding of DAGsMost complex, requires deep knowledgeUse CasesSimple models, prototypesComplex architectures (e.g., ResNet, Inception)Custom architectures, novel research models

Detailed Mathematical Examples

1. Sequential API

Transformation:

a1 =f1(W1 ·x+b1)
y=f2(W2 ·a1 +b2)

Backpropagation:

∂ℒ∂W2=∂ℒ∂y·∂y∂W2
∂ℒ∂W1=∂ℒ∂y·∂y∂a1·∂a1∂W1

2. Functional API

Transformation:

y1 =f1(W1 ·x+b1)
y2 =f2(W2 ·y1 +b2)
y=f3(y1,y2)

Backpropagation:

∂ℒ∂W2=∂ℒ∂y·∂y∂y2·∂y2∂W2
∂ℒ∂W1=∂ℒ∂y·(∂y∂y1·∂y1∂W1+∂y∂y2·∂y2∂y1·∂y1∂W1)

3. Model Subclassing API

Transformation:

import tensorflow as tf

class MyModel(tf.keras.Model):
    def __init__(self):
        super(MyModel, self).__init__()
        self.dense1 = tf.keras.layers.Dense(64, activation='relu')
        self.dense2 = tf.keras.layers.Dense(10)

    def call(self, inputs):
        x = self.dense1(inputs)
        return self.dense2(x)   

Backpropagation:

∂ℒ∂W1=∂ℒ∂y·∂y∂x1·∂x1∂W1
∂ℒ∂W2=∂ℒ∂y·∂y∂W2

Gradient Descent and Optimization

In all APIs, the training process involves:

Loss Calculation:

ℒ=1NΣi=1N ℒ(ŷi,yi)

Gradient Calculation (Backpropagation):

∂ℒ∂Wi

Final Note: Lets Look at the Differences Between Keras Sequential & Functional API again for better understanding

Sequential API

Design Philosophy:
– Linear Structure: The Sequential API is designed to stack layers in a strictly linear order.
– Single Input and Output: It supports only one input tensor and one output tensor.
– Ease of Use: It’s simple and intuitive, making it easy to build straightforward models quickly.

Internal Mechanism:
– Layer Management: Layers are added sequentially to an internal list. Each layer’s input is the previous layer’s output.
– Model Graph: The underlying computation graph is straightforward because it flows in one direction without any branches or merges.

Limitations:
– Fixed Architecture: You can’t branch or merge layers, and you can’t use multiple inputs or outputs.
– No Shared Layers: Each layer is used exactly once in the sequence.

Functional API

Design Philosophy:
– Graph Structure: The Functional API allows you to create models as directed acyclic graphs (DAGs).
– Multiple Inputs and Outputs: It supports models with multiple input and output tensors.
– Flexibility and Versatility: It can handle complex architectures with non-linear connections, shared layers, and dynamic behavior.

Internal Mechanism:
– Layer Management: Layers are connected via their inputs and outputs explicitly. You define the flow of data through the network by connecting tensors.
– Model Graph: The underlying computation graph can have branches, merges, and shared layers, which is more complex but also more powerful.

Capabilities:
– Branches and Merges: Layers can be connected in non-linear ways.
– Shared Layers: The same layer can be used in different parts of the model.
– Multiple Inputs/Outputs: Supports complex models that require processing different types of data simultaneously and producing multiple predictions.

Sequential API Example

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

model = Sequential([
    Dense(64, activation='relu', input_shape=(784,)),
    Dense(32, activation='tanh'),
    Dense(10, activation='softmax')
])

Internals:

– Layer Order: Maintains an internal list of layers: [Dense(64), Dense(32), Dense(10)].
– Forward Pass: Iterates over the list and applies each layer in sequence.
– Graph: Simple linear graph: input -> Dense(64) -> Dense(32) -> Dense(10) -> output.

Functional API Example

from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, concatenate

# Define two input layers
input1 = Input(shape=(784,), name='input_1')
input2 = Input(shape=(784,), name='input_2')

# First branch
x1 = Dense(64, activation='relu', name='dense_1')(input1)

# Second branch
x2 = Dense(64, activation='relu', name='dense_2')(input2)

# Concatenate the outputs
concat = concatenate([x1, x2], name='concat')

# Final layers
x = Dense(32, activation='tanh', name='dense_3')(concat)
outputs = Dense(10, activation='softmax', name='output')(x)

# Define the model with two inputs and one output
model = Model(inputs=[input1, input2], outputs=outputs)

Internals:

– Layer Connections: Tracks each layer’s input and output explicitly, creating a graph: input_1 -> Dense(64) -> concat <- Dense(64) <- input_2.
– Forward Pass: Computes the outputs based on the graph structure, handling branches and merges.
– Graph: More complex graph with branches and a merge: input_1 -> Dense(64) \ -> concat -> Dense(32) -> Dense(10) -> output<br> input_2 -> Dense(64) /.

Lets compare one more time the Sequential vs Functional API

AspectSequential APIFunctional APIDesignLinear stack of layersDirected acyclic graph (DAG) of layersInput/OutputSingle input and outputMultiple inputs and outputsLayer ConnectionsEach layer connected to the previous layer in sequenceLayers connected via explicitly defined tensors, allowing for complex connectionsGraph StructureSimple, linear computation graphComplex, branched, and merged computation graphFlexibilityLimited to simple, sequential modelsSupports complex architectures, including branches, merges, and shared layersUse CasesQuick prototyping, simple feed-forward networksAdvanced models requiring complex data flows, multi-modal inputs, and multi-task outputs

Why Functional API Can Do What Sequential API Cannot

– Graph-Based Design: The Functional API’s graph-based design allows for defining complex, non-linear relationships between layers, supporting multiple inputs and outputs, and enabling the creation of more sophisticated models.
– Explicit Connections: In the Functional API, you explicitly define how data flows between layers, which is not possible in the Sequential API that relies on a fixed sequence.
– Multiple Inputs and Outputs: The ability to handle multiple inputs and outputs directly comes from the Functional API’s flexibility in defining and managing multiple data streams and their interactions.

Conclusion

The three primary Keras APIs—Sequential, Functional, and Model Subclassing—are each designed with different modeling scenarios in mind:

  • Sequential API: Ideal for straightforward, linear stacks of layers where simplicity and ease of use are prioritized. It’s perfect for models that follow a single input-to-output pathway without branching or complex layer sharing.
  • Functional API: Suited for building complex architectures involving multiple inputs, multiple outputs, shared layers, or non-linear data flows. It provides a flexible way to construct models that require more than a simple stack of layers, allowing for arbitrary connectivity patterns among layers.
  • Model Subclassing API: Offers the highest level of customization and flexibility. By subclassing the Model class, you gain full control over the model’s architecture and forward pass, which is invaluable for implementing very complex or non-standard behaviors that are difficult or impossible to define with the Sequential or Functional APIs alone.

Understanding these differences:
Choosing the right API depends on the complexity and specific requirements of your neural network model:

  • Use the Sequential API for simple, linear stacks where clarity and ease-of-use are your primary goals.
  • Opt for the Functional API when your model involves multiple inputs/outputs, layer sharing, or non-linear architectures that require more flexible connections.
  • Select the Model Subclassing API when you need ultimate control over the training and inference process or wish to implement custom behaviors that go beyond the scope of the built-in layers and configurations.

This choice should be guided by the architectural needs of your project rather than any underlying hardware differences, ensuring that you pick the most appropriate tool for your model’s complexity and desired behavior.

lying hardware differences.

 

Checked companion guide · 16 November 2026

Choose the interface that matches the graph

Model-building APIs describe how you express a computation. They do not select a different kind of GPU, automatically improve accuracy or supply a faster optimizer. The same single-path network can be written in all three styles. A branched network requires an interface that can represent the connections you intend.

ChoiceUseful whenWhat you writeCheck carefully
SequentialA plain layer stack, one input and one output per layerAn ordered list of layersInput shape and layer order
FunctionalBranches, merges, multiple inputs/outputs or shared layersInput tensors and explicit layer connectionsTensor shapes and reuse of layer instances
SubclassingAdditional forward-pass customizationA Model subclass with tracked layers and callBuild state, training behavior and serialization

The original comparison table and run-together quotation remain intact above. This new table is a separate readable guide, not a replacement or reinterpretation of their cell data. The original prose calls Sequential “linear”: in this context it means a straight stack of layers, not a mathematically linear function. ReLU layers still make that stack nonlinear.

The official guides explain the basic stack, graph and subclass interfaces. They can also be combined: a Sequential component can appear in a Functional graph, and a custom layer can be used inside another model. Subclassing does not inherently require a custom training loop; compile, fit, evaluate and predict remain available. Custom training is a different decision from expressing the forward pass.

Same architecture is not the same as a fair experiment

Separate accuracy clarification: the historical “Test accuracy: 0.8745” and identical-results statements remain above. No run, dataset split, environment or measured result supporting that number is established in this verification. It must not be treated as a promised accuracy for any API. The six original snippets define models; none is a complete documented reproduction of that accuracy.

To compare the same computation, first match every layer, activation, shape and weight value, then compare predictions in inference mode on the same input. For a training comparison, also control optimizer state, update order, batch contents, losses, dropout/batch-normalization behavior, random state and device determinism. Setting a seed alone does not ensure separately constructed models consume random numbers in exactly the same order.

There is another important difference later in the original lesson: its final Sequential network has one 784-feature input and a 64→32→10 stack. The final Functional example has two 784-feature inputs, two distinct 64-unit branches, a 128-feature concatenation and a 32→10 output stack. Those models are not interchangeable rewrites. Each separately constructed Dense object owns separate weights even when its configuration is identical.

ExampleParameters including biases
Earlier 784→300→100→10 stack266,610
Later 784→64→32→10 stack52,650
Later two independent 64-unit branches104,938
Hypothetical shared 64-unit layer on both inputs54,698
Dense parameters = (input features + 1) × output units
Two independent branches: 2 × (784 + 1) × 64 = 100,480
After concatenation: (128 + 1) × 32 + (32 + 1) × 10 = 4,458

Adding 100,480 and 4,458 gives 104,938. Sharing one layer object would count its 50,240 parameters once, yielding 54,698 total. That is a different hypothetical model, not what the original two-branch code constructs.

These counts were computed independently from the displayed shapes. They describe parameters, not timing, memory overhead or measured accuracy. Claims that subclassing is universally “optimal,” or that Functional is inherently faster, require a controlled benchmark; none is claimed here. Functional describes a graph of layer calls and is not a promise of arbitrary Python control flow within a static graph.

A fixed-weight forward pass you can check

Use a deliberately tiny two-input, two-hidden-unit network so every number fits on a page. These are chosen teaching weights, not trained values. With row-vector notation, the input is x = [1, 2], the first weight rows are [1, −1] and [0.5, 1], and the first bias is [0, 0.5].

xW₁ + b₁ = [2, 1.5]
h = ReLU([2, 1.5]) = [2, 1.5]
y = h · [2, −1] + 0.2 = 2.7

A loop through two functions, explicit intermediate tensors, and a Python callable class all produce the same 2.7 in the executed NumPy check. These are three equivalent mathematical expressions, not three executed Keras APIs.

For a backend-equipped environment, the separate snippet below builds all three Keras versions, explicitly assigns the same weights, and asserts the intended 2.7 prediction. It is syntax checked only here: TensorFlow, Keras, JAX and PyTorch are unavailable. Its assertion is a verification procedure for the reader to execute, not a claim that it passed in Keras during this update. Building the subclass before set_weights is necessary because Dense weights are created lazily.

# Syntax checked only here: requires a Keras 3 training backend.
import numpy as np
import keras
from keras import layers

keras.utils.set_random_seed(42)
sequential = keras.Sequential([
    keras.Input(shape=(2,)),
    layers.Dense(2, activation='relu'),
    layers.Dense(1),
])
inputs = keras.Input(shape=(2,))
hidden = layers.Dense(2, activation='relu')(inputs)
functional = keras.Model(inputs, layers.Dense(1)(hidden))

class Custom(keras.Model):
    def __init__(self):
        super().__init__()
        self.hidden = layers.Dense(2, activation='relu')
        self.output_layer = layers.Dense(1)

    def call(self, inputs, training=None):
        return self.output_layer(self.hidden(inputs))

custom = Custom()
x = np.array([[1., 2.]], dtype='float32')
_ = custom(x)  # Build lazy weights before assigning them.
weights = [np.array([[1., -1.], [.5, 1.]], dtype='float32'),
           np.array([0., .5], dtype='float32'),
           np.array([[2.], [-1.]], dtype='float32'),
           np.array([.2], dtype='float32')]
for model in (sequential, functional, custom):
    model.set_weights(weights)
    output = keras.ops.convert_to_numpy(model(x, training=False))
    np.testing.assert_allclose(output, [[2.7]], atol=1e-6)

Why a shared parameter receives more than one gradient contribution

The original Functional backpropagation expression adds contributions from a direct path and an indirect path. The principle is the chain rule: if a parameter influences the loss along several paths, add all of its contributions. Those schematic matrix equations also require compatible dimensions and a consistent Jacobian convention; a dot symbol does not by itself establish the correct tensor contraction.

Consider a scalar shared weight w = 0.7 applied to u = 2 and v = 3. Add the two branch outputs, use a target t = 1, and choose half squared error. This small scalar case makes the path accounting explicit without matrix-shape ambiguity.

y = wu + wv = 3.5
L = ½(y − t)² = 3.125
∂L/∂w = (y − t)u + (y − t)v
= 5 + 7.5 = 12.5

A central finite difference with ε = 10⁻⁶ gives approximately 12.5000000006, agreeing within 10⁻⁸ absolute tolerance. Using two separate weights would give two separate derivatives, 5 and 7.5, rather than summing into one shared parameter.

Computed shared-gradient contributions of 5 and 7.5 summing to 12.5, and parameter counts for the lesson architectures.
Independently computed arithmetic; no training benchmark or measured model accuracy is shown. Open the chart for detail.

All six original Python snippets pass syntax parsing, but they were not executed against a Keras backend here. The original 64-unit subclass example ends with Dense(10) without softmax, so it returns scores/logits. If paired with cross-entropy, configure the loss consistently for logits or add a probability activation. The original code is retained; this note explains the requirement separately.

Primary references and next steps

The original Markdown-style Sequential documentation reference is retained exactly as text; these clickable primary links provide direct navigation. The original legacy math configuration and shortcode are retained rather than replaced with an added rendering library. The complete source and original custom code blocks remain recoverable.

Before adapting an example, write down the number and shape of its inputs, the connection graph, whether layers are shared and the intended output/loss pair. Then verify one forward pass before training. Day 15 continues the Sequential-versus-Functional comparison.

Questions about Keras model APIs

Which Keras API should I start with?

Use Sequential for a plain single-input, single-output layer stack. Use Functional for an explicit graph with branches, merges or shared layers. Use subclassing when the forward computation needs additional customization.

Does Functional mean a nonlinear activation function?

No. Functional describes a model-building interface. Its topology can branch, but activation functions such as ReLU are a separate choice.

Should all three APIs get exactly 0.8745 accuracy?

No. The historical 0.8745 value is not a reproduced benchmark here. Matching architectures does not guarantee identical random weights, training state, numerical execution or accuracy.

Are the final Sequential and Functional examples equivalent?

No. The final Sequential example has one input and 52,650 parameters; the two-input Functional example has separate branches and 104,938 parameters. Their tasks and architectures differ.

Does model subclassing require a custom training loop?

No. A subclassed Keras Model can use compile and fit. The call method defines the forward pass; custom training behavior is a separate choice.

Were these Keras models executed in this verification?

No. All six original snippets pass Python syntax checks, but Keras and its training backends are unavailable. The added fixed-weight forward calculations and branch-gradient check ran in NumPy.

You Can Also Learn Deep Learning in 80 Days Inside the iOS App Continue this roadmap in a focused mobile study experience with offline access, flashcards, notes, and progress tracking.
Open on the App Store