This lab builds a neural network classifier by subclassing tf.keras.Model instead of using the Sequential or Functional API. The notebook above loads the scikit-learn Wine dataset (178 samples, 13 numeric features, 3 classes) and explores it with pandas before training the model. The sections below explain how model subclassing works, give a complete script you can run, and cover saving the model and the errors you are most likely to hit.
What model subclassing is and when to use it
Keras gives you three ways to define a model. With model subclassing you write a Python class that inherits from keras.Model. You create the layers in __init__() and write the forward pass in call(). Because call() is ordinary Python, you can use loops, conditionals, several inputs or custom logic that the other APIs can't express easily.
| API | Best for | Trade-off |
|---|---|---|
| Sequential | A plain stack of layers | No branching, no multiple inputs or outputs |
| Functional | Graphs of layers, shared layers, multiple inputs or outputs | The structure must be a static graph |
| Subclassing | Dynamic or custom forward passes, research code | Keras can't inspect the structure until the model is called, and saving and serialization need more work |
A small tabular dataset like Wine doesn't need subclassing. This lab uses it because the data is simple, so you can focus on the pattern itself.
Prerequisites and setup
Install the libraries the notebook imports. Run this in a virtual environment so the TensorFlow version doesn't conflict with other projects.
python -m venv tf-lab
source tf-lab/bin/activate
pip install tensorflow scikit-learn pandas numpy seaborn matplotlib jupyter
python -c "import tensorflow as tf; print(tf.__version__)"Code language: JavaScript (javascript)
Note: The DESCR text printed in the notebook says the dataset has "50 in each of three classes". The real distribution is 59, 71 and 48, as the value_counts() cell and the Class Distribution line show. The classes are slightly imbalanced, so use a stratified split.
Complete working example
This script repeats the preparation from the notebook (split, scale, one-hot encode). It then defines, trains and evaluates a subclassed model. It runs on its own from start to finish.
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score, classification_report
tf.random.set_seed(42)
# 1. Data
X, y = datasets.load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train) # fit on training data only
X_test = scaler.transform(X_test)
y_train_cat = keras.utils.to_categorical(y_train, num_classes=3)
y_test_cat = keras.utils.to_categorical(y_test, num_classes=3)
# 2. Model
@keras.saving.register_keras_serializable(package="lab9")
class WineClassifier(keras.Model):
def __init__(self, num_classes=3, hidden_units=32, dropout_rate=0.2, **kwargs):
super().__init__(**kwargs)
self.num_classes = num_classes
self.hidden_units = hidden_units
self.dropout_rate = dropout_rate
self.dense1 = layers.Dense(hidden_units, activation="relu")
self.dropout = layers.Dropout(dropout_rate)
self.dense2 = layers.Dense(hidden_units // 2, activation="relu")
self.classifier = layers.Dense(num_classes, activation="softmax")
def call(self, inputs, training=False):
x = self.dense1(inputs)
x = self.dropout(x, training=training)
x = self.dense2(x)
return self.classifier(x)
def get_config(self):
config = super().get_config()
config.update({"num_classes": self.num_classes,
"hidden_units": self.hidden_units,
"dropout_rate": self.dropout_rate})
return config
model = WineClassifier()
model(X_train[:1]) # build the weights so summary() works
model.summary()
# 3. Train
model.compile(optimizer=keras.optimizers.Adam(learning_rate=1e-3),
loss="categorical_crossentropy",
metrics=["accuracy"])
history = model.fit(X_train, y_train_cat,
validation_split=0.2,
epochs=100, batch_size=16,
callbacks=[keras.callbacks.EarlyStopping(
patience=10, restore_best_weights=True)],
verbose=0)
# 4. Evaluate
loss, acc = model.evaluate(X_test, y_test_cat, verbose=0)
y_pred = np.argmax(model.predict(X_test, verbose=0), axis=1)
print(f"Keras test accuracy: {acc:.3f}")
print(f"sklearn accuracy_score: {accuracy_score(y_test, y_pred):.3f}")
print(classification_report(y_test, y_pred))
super().__init__(kwargs)** must come first. It sets up Keras's tracking of layers and weights, and it passesnameand other standard arguments through.- Layers belong in
__init__(), not incall(). Keras tracks layers assigned toself, so their weights appear inmodel.trainable_weightsand get updated during training. - The
trainingargument tellsDropout(andBatchNormalization, if you add it) whether you are training or predicting.fit()passestraining=True.predict()andevaluate()passFalse. model(X_train[:1])builds the model. Until a subclassed model sees data, Keras doesn't know the input shape, andsummary()fails.get_config()andregister_keras_serializableare needed only if you want to save the whole model to a.kerasfile and load it back.
Expected results
The Wine classes separate well once the features are scaled. A small network like this one usually reaches test accuracy above 0.9. The exact figures change with the split, the seed and the TensorFlow version, so don't expect identical numbers between runs or machines. The two accuracy lines should match: evaluate() and accuracy_score measure the same thing in different ways.
import matplotlib.pyplot as plt
plt.plot(history.history["loss"], label="train loss")
plt.plot(history.history["val_loss"], label="val loss")
plt.xlabel("epoch"); plt.ylabel("loss"); plt.legend(); plt.show()Code language: JavaScript (javascript)
If validation loss rises while training loss keeps falling, the model is overfitting. Early stopping handles this by restoring the weights from the best epoch.
Saving and reloading a subclassed model
Saving only the weights works the same way for any model. To reload them, build a new instance with the same constructor arguments and call it once before loading. Current Keras versions require weight files to end in .weights.h5.
# Weights only
model.save_weights("wine.weights.h5")
restored = WineClassifier()
restored(X_test[:1])
restored.load_weights("wine.weights.h5")
# Full model (architecture + weights + optimizer), relies on get_config()
model.save("wine_classifier.keras")
reloaded = keras.models.load_model("wine_classifier.keras")
print(np.allclose(model.predict(X_test, verbose=0),
reloaded.predict(X_test, verbose=0)))Code language: PHP (php)
Note: Also save the fitted StandardScaler, for example with joblib.dump(scaler, "scaler.joblib"). The model only gives correct predictions on data scaled exactly as the training data was.
Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
summary() says the model has not yet been built | A subclassed model has no input shape until it sees data | Call model(sample_batch) or model.build((None, 13)) first |
Error that you forgot to call super().__init__() | Layers were assigned to self before the parent constructor ran | Make super().__init__(**kwargs) the first line of __init__() |
| Shape mismatch between labels and output | One-hot labels with sparse_categorical_crossentropy, or integer labels with categorical_crossentropy | Match the loss to the label format, or skip to_categorical and use the sparse loss |
Model never improves, or variable-creation errors inside tf.function | Layers created inside call(), so new weights are made on every call | Create every layer in __init__() |
load_model cannot find the class | The custom class is not registered, or it is not imported in the loading script | Use @keras.saving.register_keras_serializable() and import the class before loading |
| Accuracy around 0.4 and loss stuck | Features were not scaled (proline reaches values in the thousands) | Apply StandardScaler fitted on the training split |
Best practices
- Fit the scaler on the training split only. Fitting it on all the data leaks test-set statistics into training.
- Pass
stratify=ytotrain_test_splitso each split keeps the same class proportions. - Always pass
trainingthrough toDropoutandBatchNormalizationinsidecall(). - Keep hyperparameters as constructor arguments and return them from
get_config(). The class then becomes reusable and serializable. - Use Sequential or Functional when they can express the model. Choose subclassing only when you need dynamic behaviour, because it makes saving and inspection harder.
- Set
tf.random.set_seed()andrandom_stateso classroom results can be reproduced.
Corrections to the original
The notebook above runs, but a few points need correcting or clarifying:
- The title spells the library "Tensorsflow". The correct name is TensorFlow.
- The dataset description's "50 in each of three classes" is inaccurate. The real counts are 59, 71 and 48.
- Saved outputs such as
matplotlib.axes._subplots.AxesSubplotandName: target, dtype: int64come from older library versions. Recent pandas and matplotlib show slightly different text, for exampleName: countforvalue_counts(). The code is still valid.
Frequently asked questions
What is model subclassing in TensorFlow?
It means defining a model as a Python class that inherits from tf.keras.Model. You create the layers in __init__() and write the forward pass in call(). The model still uses the normal compile(), fit(), evaluate() and predict() workflow.
Why does model.summary() fail on my subclassed model?
A subclassed model doesn't know its input shape until it is called, so it has no weights yet. Call it on a sample batch or run model.build((None, num_features)) before calling summary().
What is the training argument in call() used for?
It tells layers such as Dropout and BatchNormalization whether you are training or running inference. Keras sets it to True inside fit() and to False in evaluate() and predict(), as long as you pass it on to those layers.
How do I save a subclassed Keras model?
The simplest way is model.save_weights("name.weights.h5") and then loading the weights into a new instance. To save the whole model as a .keras file, implement get_config() and register the class with keras.saving.register_keras_serializable().
Should I use subclassing or the Functional API?
Use the Functional API when the model is a fixed graph of layers. It is easier to inspect, plot and serialize. Use subclassing when the forward pass needs Python control flow or custom logic.
Related tutorials
- More Machine Learning tutorials
- Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
- Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals