MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Tensorsflow Lab9 – Tensorsflow ModelSubclassing

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.

APIBest forTrade-off
SequentialA plain stack of layersNo branching, no multiple inputs or outputs
FunctionalGraphs of layers, shared layers, multiple inputs or outputsThe structure must be a static graph
SubclassingDynamic or custom forward passes, research codeKeras 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 passes name and other standard arguments through.
  • Layers belong in __init__(), not in call(). Keras tracks layers assigned to self, so their weights appear in model.trainable_weights and get updated during training.
  • The training argument tells Dropout (and BatchNormalization, if you add it) whether you are training or predicting. fit() passes training=True. predict() and evaluate() pass False.
  • model(X_train[:1]) builds the model. Until a subclassed model sees data, Keras doesn't know the input shape, and summary() fails.
  • get_config() and register_keras_serializable are needed only if you want to save the whole model to a .keras file 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

SymptomCauseFix
summary() says the model has not yet been builtA subclassed model has no input shape until it sees dataCall 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 ranMake super().__init__(**kwargs) the first line of __init__()
Shape mismatch between labels and outputOne-hot labels with sparse_categorical_crossentropy, or integer labels with categorical_crossentropyMatch the loss to the label format, or skip to_categorical and use the sparse loss
Model never improves, or variable-creation errors inside tf.functionLayers created inside call(), so new weights are made on every callCreate every layer in __init__()
load_model cannot find the classThe custom class is not registered, or it is not imported in the loading scriptUse @keras.saving.register_keras_serializable() and import the class before loading
Accuracy around 0.4 and loss stuckFeatures 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=y to train_test_split so each split keeps the same class proportions.
  • Always pass training through to Dropout and BatchNormalization inside call().
  • 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() and random_state so 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.AxesSubplot and Name: target, dtype: int64 come from older library versions. Recent pandas and matplotlib show slightly different text, for example Name: count for value_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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

Tensorsflow Lab7 – Tensorsflow SequentialModel

This lab uses the WHO life expectancy dataset to build a regression model with the TensorFlow Keras Sequential API. The notebook above covers loading the data, inspecting…

Read More

Tensorsflow Lab8 – Tensorsflow FunctionalModel

This lab uses the UCI heart disease dataset (303 patients, 13 features, a binary target) to build a binary classifier with the Keras Functional API in TensorFlow….

Read More

Tensorsflow Lab6 – Tensorsflow SimpleLinearRegression

This lab builds simple linear regression (y = Wx + b) from scratch in TensorFlow 2. It creates the weight and bias with tf.Variable, computes gradients of…

Read More

Tensorsflow Lab5 – Tensorsflow GradientTape

tf.GradientTape is TensorFlow's automatic differentiation API. It records the operations you run inside a with block, then plays them back in reverse to compute gradients for training….

Read More

Tensorsflow Lab4 – Tensorsflow function

This lab shows how tf.function turns ordinary Python functions into TensorFlow graphs. It covers how AutoGraph converts if, for and while into graph ops, why Python side…

Read More

Tensorsflow Lab3 – Tensorsflow EagerExecution

In eager execution, TensorFlow runs each operation as soon as Python calls it and gives you a concrete value back, with no graph to build first. It…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x