π οΈ Object-Oriented Deep Learning via Model Subclassing
While the Sequential and Functional APIs cover the vast majority of deep learning use cases, certain advanced research models require imperative, dynamic control over the forward passβsuch as conditional routing, dynamic loops, or custom gradient handling. By inheriting from `tf.keras.Model`, developers gain object-oriented freedom to write custom neural network architectures and forward logic from scratch.
1. The Subclassing Anatomy (`__init__` vs. `call`)
Understanding the two essential methods of a subclassed Keras model: `__init__` for defining layers and `call` for executing the forward pass.
Subclassing Anatomy Matrix
SUBCLASSING METHODS BREAKDOWN:
ββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββ
β METHOD β PURPOSE β IMPLEMENTATION RESPONSIBILITY β
ββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββ€
β `__init__(self, ...)` β Layer Initialization β Instantiate layers (Dense, Conv2D, etc.) β
β β β and store them as class attributes. β
ββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββ€
β `call(self, inputs)` β Forward Pass Execution β Define how tensors flow through layers β
β β β including activation and conditional logicβ
ββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββ
Architectural Definition: Subclassing converts your neural network into a standard Python class, empowering you to use Python control flow (`if`, `for`, `while`) directly inside the `call` method.
2. Comparing API Paradigm Flexibility
Evaluating when to use Sequential, Functional, or Subclassed model APIs based on project complexity.
API Selection Matrix
API PARADIGM SELECTION GUIDE:
ββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββ
β API PARADIGM β ARCHITECTURAL FLEXIBILITY β RECOMMENDED USE CASE β
ββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββ€
β Sequential API β Low (Strict linear stack) β Simple feedforward / CNN networks β
ββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββ€
β Functional API β High (Directed Acyclic Graphs) β Multi-input, multi-output, & residual netsβ
ββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββ€
β Model Subclassing β Maximum (Imperative Python code) β Custom research architectures & dynamic β
β β β control flow (e.g., custom RNN cells) β
ββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββ
Engineering Insight: While model subclassing offers maximum flexibility, it sacrifices static graph inspection (`model.summary()` requires calling the model on sample inputs first).
3. Python Code Example: Subclassing `tf.keras.Model`
A production Python script demonstrating how to subclass `tf.keras.Model`, define layers in `__init__`, and execute custom forward pass logic in `call`.
Python (subclassed_model_demo.py)
import tensorflow as tf
from tensorflow.keras import layers, Model
class CustomMLP(Model):
def __init__(self, num_classes=2, name="custom_mlp", **kwargs):
super(CustomMLP, self).__init__(name=name, **kwargs)
# Define layers in constructor
self.dense_1 = layers.Dense(64, activation='relu', name='hidden_1')
self.dropout = layers.Dropout(0.3, name='dropout_layer')
self.dense_2 = layers.Dense(32, activation='relu', name='hidden_2')
self.output_layer = layers.Dense(num_classes, activation='softmax', name='output_layer')
def call(self, inputs, training=False):
# Define forward pass with optional training flag for dropout
x = self.dense_1(inputs)
x = self.dropout(x, training=training)
x = self.dense_2(x)
return self.output_layer(x)
def instantiate_and_test_subclassed_model():
# 1. Instantiate subclassed model
model = CustomMLP(num_classes=3)
# 2. Compile model
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# 3. Generate dummy training data
X_train = tf.random.normal(shape=(100, 10))
y_train = tf.random.uniform(shape=(100,), minval=0, maxval=3, dtype=tf.int32)
# 4. Train model via standard model.fit()
print("[+] Training subclassed model...")
history = model.fit(X_train, y_train, epochs=2, batch_size=16, verbose=1)
print("[+] Subclassed model training complete!")
if __name__ == "__main__":
instantiate_and_test_subclassed_model()
Execution Output:
[+] Training subclassed model...
Epoch 1/2
7/7 [==============================] - 1s 5ms/step - loss: 1.1524 - accuracy: 0.3200
Epoch 2/2
7/7 [==============================] - 0s 2ms/step - loss: 1.0912 - accuracy: 0.3400
[+] Subclassed model training complete!
4. Customizing the Training Step (`model.train_step`)
Overriding `model.train_step` inside subclassed models to implement custom training logic, gradient clipping, or Generative Adversarial Network (GAN) loops.
Custom train_step Pattern
OVERRIDING train_step():
class CustomTrainingModel(tf.keras.Model):
def train_step(self, data):
x, y = data
with tf.GradientTape() as tape:
y_pred = self(x, training=True)
loss = self.compiled_loss(y, y_pred)
# Compute gradients & update weights
gradients = tape.gradient(loss, self.trainable_variables)
self.optimizer.apply_gradients(zip(gradients, self.trainable_variables))
# Update metrics
self.compiled_metrics.update_state(y, y_pred)
return {m.name: m.result() for m in self.metrics}
Strategic Insight: Overriding `train_step` allows you to maintain the convenience of `model.fit()` while completely customizing how gradient updates and loss computations are performed.
5. Best Practices for Model Subclassing
Software engineering standards for structuring subclassed models and ensuring serialization compatibility.
Subclassing Best Practices Checklist
MODEL SUBCLASSING CHECKLIST:
ββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β BEST PRACTICE β IMPLEMENTATION & OBJECTIVE β
ββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Pass `**kwargs` β Always accept and pass `**kwargs` (`super().__init__(**kwargs)`) in your β
β β subclass constructor to support Keras model serialization and naming. β
ββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Use Functional When β Prefer the Functional API over Subclassing unless you genuinely need dynamic β
β Possible β control flow or custom training steps. β
ββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Handle `training` Flag β Pass the `training` boolean explicitly to layers like Dropout or BatchNorm β
β β inside your `call()` method. β
ββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Masterclass Rule: Always handle the `training` flag in your `call()` method to ensure layers like Dropout behave correctly during training versus inference.
6. Chapter Summary & Module Transition
Reviewing model subclassing and previewing Module 4 computer vision specializations.
Chapter Review Checklist
CHAPTER REVIEW CHECKLIST:
1. Subclassing `tf.keras.Model` enables object-oriented, custom neural network architectures.
2. Define layers in `__init__` and execute forward pass operations in `call()`.
3. Overriding `train_step` customizes gradient updates while preserving `model.fit()` convenience.
4. Next Module: We transition to Module 4, starting with Chapter 15 ("Computer Vision: Convolutional Neural Networks & Pooling").
Next Module Preview: In Module 4, we explore deep learning specializations, starting with Convolutional Neural Networks (CNNs) for computer vision in Chapter 15.