{"id":47537,"date":"2026-11-23T22:06:03","date_gmt":"2026-11-23T22:06:03","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=47537"},"modified":"2026-11-23T22:06:03","modified_gmt":"2026-11-23T22:06:03","slug":"tensorsflow-lab9-tensorsflow-modelsubclassing","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/tensorsflow-lab9-tensorsflow-modelsubclassing\/","title":{"rendered":"Tensorsflow Lab9 &#8211; Tensorsflow ModelSubclassing"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">This lab builds a neural network classifier by subclassing <code>tf.keras.Model<\/code> 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.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/05c5cbeab120e204548e798f399ee366.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What model subclassing is and when to use it<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Keras gives you three ways to define a model. With <strong>model subclassing<\/strong> you write a Python class that inherits from <code>keras.Model<\/code>. You create the layers in <code>__init__()<\/code> and write the forward pass in <code>call()<\/code>. Because <code>call()<\/code> is ordinary Python, you can use loops, conditionals, several inputs or custom logic that the other APIs can&#039;t express easily.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>API<\/th><th>Best for<\/th><th>Trade-off<\/th><\/tr><\/thead><tbody><tr><td>Sequential<\/td><td>A plain stack of layers<\/td><td>No branching, no multiple inputs or outputs<\/td><\/tr><tr><td>Functional<\/td><td>Graphs of layers, shared layers, multiple inputs or outputs<\/td><td>The structure must be a static graph<\/td><\/tr><tr><td>Subclassing<\/td><td>Dynamic or custom forward passes, research code<\/td><td>Keras can&#039;t inspect the structure until the model is called, and saving and serialization need more work<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">A small tabular dataset like Wine doesn&#039;t need subclassing. This lab uses it because the data is simple, so you can focus on the pattern itself.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites and setup<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Install the libraries the notebook imports. Run this in a virtual environment so the TensorFlow version doesn&#039;t conflict with other projects.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">python -m venv tf-lab\nsource tf-lab\/bin\/activate\npip install tensorflow scikit-learn pandas numpy seaborn matplotlib jupyter\npython -c <span class=\"hljs-string\">\"import tensorflow as tf; print(tf.__version__)\"<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> The <code>DESCR<\/code> text printed in the notebook says the dataset has &quot;50 in each of three classes&quot;. The real distribution is 59, 71 and 48, as the <code>value_counts()<\/code> cell and the <code>Class Distribution<\/code> line show. The classes are slightly imbalanced, so use a stratified split.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Complete working example<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">import numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import accuracy_score, classification_report\n\ntf.random.set_seed(42)\n\n# 1. Data\nX, y = datasets.load_wine(return_X_y=True)\nX_train, X_test, y_train, y_test = train_test_split(\n    X, y, test_size=0.2, stratify=y, random_state=42)\n\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)   # fit on training data only\nX_test = scaler.transform(X_test)\n\ny_train_cat = keras.utils.to_categorical(y_train, num_classes=3)\ny_test_cat = keras.utils.to_categorical(y_test, num_classes=3)\n\n# 2. Model\n@keras.saving.register_keras_serializable(package=\"lab9\")\nclass WineClassifier(keras.Model):\n    def __init__(self, num_classes=3, hidden_units=32, dropout_rate=0.2, **kwargs):\n        super().__init__(**kwargs)\n        self.num_classes = num_classes\n        self.hidden_units = hidden_units\n        self.dropout_rate = dropout_rate\n        self.dense1 = layers.Dense(hidden_units, activation=\"relu\")\n        self.dropout = layers.Dropout(dropout_rate)\n        self.dense2 = layers.Dense(hidden_units \/\/ 2, activation=\"relu\")\n        self.classifier = layers.Dense(num_classes, activation=\"softmax\")\n\n    def call(self, inputs, training=False):\n        x = self.dense1(inputs)\n        x = self.dropout(x, training=training)\n        x = self.dense2(x)\n        return self.classifier(x)\n\n    def get_config(self):\n        config = super().get_config()\n        config.update({\"num_classes\": self.num_classes,\n                       \"hidden_units\": self.hidden_units,\n                       \"dropout_rate\": self.dropout_rate})\n        return config\n\nmodel = WineClassifier()\nmodel(X_train&#91;:1])   # build the weights so summary() works\nmodel.summary()\n\n# 3. Train\nmodel.compile(optimizer=keras.optimizers.Adam(learning_rate=1e-3),\n              loss=\"categorical_crossentropy\",\n              metrics=&#91;\"accuracy\"])\n\nhistory = model.fit(X_train, y_train_cat,\n                    validation_split=0.2,\n                    epochs=100, batch_size=16,\n                    callbacks=&#91;keras.callbacks.EarlyStopping(\n                        patience=10, restore_best_weights=True)],\n                    verbose=0)\n\n# 4. Evaluate\nloss, acc = model.evaluate(X_test, y_test_cat, verbose=0)\ny_pred = np.argmax(model.predict(X_test, verbose=0), axis=1)\nprint(f\"Keras test accuracy:   {acc:.3f}\")\nprint(f\"sklearn accuracy_score: {accuracy_score(y_test, y_pred):.3f}\")\nprint(classification_report(y_test, y_pred))<\/code><\/span><\/pre>\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>super().__init__(<\/strong>kwargs)<\/code>** must come first. It sets up Keras&#039;s tracking of layers and weights, and it passes <code>name<\/code> and other standard arguments through.<\/li>\n\n\n<li><strong>Layers belong in <code>__init__()<\/code><\/strong>, not in <code>call()<\/code>. Keras tracks layers assigned to <code>self<\/code>, so their weights appear in <code>model.trainable_weights<\/code> and get updated during training.<\/li>\n\n\n<li><strong>The <code>training<\/code> argument<\/strong> tells <code>Dropout<\/code> (and <code>BatchNormalization<\/code>, if you add it) whether you are training or predicting. <code>fit()<\/code> passes <code>training=True<\/code>. <code>predict()<\/code> and <code>evaluate()<\/code> pass <code>False<\/code>.<\/li>\n\n\n<li><strong><code>model(X_train[:1])<\/code><\/strong> builds the model. Until a subclassed model sees data, Keras doesn&#039;t know the input shape, and <code>summary()<\/code> fails.<\/li>\n\n\n<li><strong><code>get_config()<\/code> and <code>register_keras_serializable<\/code><\/strong> are needed only if you want to save the whole model to a <code>.keras<\/code> file and load it back.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Expected results<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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&#039;t expect identical numbers between runs or machines. The two accuracy lines should match: <code>evaluate()<\/code> and <code>accuracy_score<\/code> measure the same thing in different ways.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">import<\/span> matplotlib.pyplot <span class=\"hljs-keyword\">as<\/span> plt\n\nplt.plot(history.history&#91;<span class=\"hljs-string\">\"loss\"<\/span>], label=<span class=\"hljs-string\">\"train loss\"<\/span>)\nplt.plot(history.history&#91;<span class=\"hljs-string\">\"val_loss\"<\/span>], label=<span class=\"hljs-string\">\"val loss\"<\/span>)\nplt.xlabel(<span class=\"hljs-string\">\"epoch\"<\/span>); plt.ylabel(<span class=\"hljs-string\">\"loss\"<\/span>); plt.legend(); plt.show()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Saving and reloading a subclassed model<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>.weights.h5<\/code>.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\"># Weights only<\/span>\nmodel.save_weights(<span class=\"hljs-string\">\"wine.weights.h5\"<\/span>)\nrestored = WineClassifier()\nrestored(X_test&#91;:<span class=\"hljs-number\">1<\/span>])\nrestored.load_weights(<span class=\"hljs-string\">\"wine.weights.h5\"<\/span>)\n\n<span class=\"hljs-comment\"># Full model (architecture + weights + optimizer), relies on get_config()<\/span>\nmodel.save(<span class=\"hljs-string\">\"wine_classifier.keras\"<\/span>)\nreloaded = keras.models.load_model(<span class=\"hljs-string\">\"wine_classifier.keras\"<\/span>)\n<span class=\"hljs-keyword\">print<\/span>(np.allclose(model.predict(X_test, verbose=<span class=\"hljs-number\">0<\/span>),\n                  reloaded.predict(X_test, verbose=<span class=\"hljs-number\">0<\/span>)))<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> Also save the fitted <code>StandardScaler<\/code>, for example with <code>joblib.dump(scaler, &quot;scaler.joblib&quot;)<\/code>. The model only gives correct predictions on data scaled exactly as the training data was.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common errors and fixes<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Symptom<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>summary()<\/code> says the model has not yet been built<\/td><td>A subclassed model has no input shape until it sees data<\/td><td>Call <code>model(sample_batch)<\/code> or <code>model.build((None, 13))<\/code> first<\/td><\/tr><tr><td>Error that you forgot to call <code>super().__init__()<\/code><\/td><td>Layers were assigned to <code>self<\/code> before the parent constructor ran<\/td><td>Make <code>super().__init__(**kwargs)<\/code> the first line of <code>__init__()<\/code><\/td><\/tr><tr><td>Shape mismatch between labels and output<\/td><td>One-hot labels with <code>sparse_categorical_crossentropy<\/code>, or integer labels with <code>categorical_crossentropy<\/code><\/td><td>Match the loss to the label format, or skip <code>to_categorical<\/code> and use the sparse loss<\/td><\/tr><tr><td>Model never improves, or variable-creation errors inside <code>tf.function<\/code><\/td><td>Layers created inside <code>call()<\/code>, so new weights are made on every call<\/td><td>Create every layer in <code>__init__()<\/code><\/td><\/tr><tr><td><code>load_model<\/code> cannot find the class<\/td><td>The custom class is not registered, or it is not imported in the loading script<\/td><td>Use <code>@keras.saving.register_keras_serializable()<\/code> and import the class before loading<\/td><\/tr><tr><td>Accuracy around 0.4 and loss stuck<\/td><td>Features were not scaled (<code>proline<\/code> reaches values in the thousands)<\/td><td>Apply <code>StandardScaler<\/code> fitted on the training split<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Best practices<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Fit the scaler on the training split only. Fitting it on all the data leaks test-set statistics into training.<\/li>\n\n\n<li>Pass <code>stratify=y<\/code> to <code>train_test_split<\/code> so each split keeps the same class proportions.<\/li>\n\n\n<li>Always pass <code>training<\/code> through to <code>Dropout<\/code> and <code>BatchNormalization<\/code> inside <code>call()<\/code>.<\/li>\n\n\n<li>Keep hyperparameters as constructor arguments and return them from <code>get_config()<\/code>. The class then becomes reusable and serializable.<\/li>\n\n\n<li>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.<\/li>\n\n\n<li>Set <code>tf.random.set_seed()<\/code> and <code>random_state<\/code> so classroom results can be reproduced.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Corrections to the original<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The notebook above runs, but a few points need correcting or clarifying:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The title spells the library &quot;Tensorsflow&quot;. The correct name is <strong>TensorFlow<\/strong>.<\/li>\n\n\n<li>The dataset description&#039;s &quot;50 in each of three classes&quot; is inaccurate. The real counts are 59, 71 and 48.<\/li>\n\n\n<li>Saved outputs such as <code>matplotlib.axes._subplots.AxesSubplot<\/code> and <code>Name: target, dtype: int64<\/code> come from older library versions. Recent pandas and matplotlib show slightly different text, for example <code>Name: count<\/code> for <code>value_counts()<\/code>. The code is still valid.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is model subclassing in TensorFlow?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It means defining a model as a Python class that inherits from <code>tf.keras.Model<\/code>. You create the layers in <code>__init__()<\/code> and write the forward pass in <code>call()<\/code>. The model still uses the normal <code>compile()<\/code>, <code>fit()<\/code>, <code>evaluate()<\/code> and <code>predict()<\/code> workflow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why does model.summary() fail on my subclassed model?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A subclassed model doesn&#039;t know its input shape until it is called, so it has no weights yet. Call it on a sample batch or run <code>model.build((None, num_features))<\/code> before calling <code>summary()<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the training argument in call() used for?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It tells layers such as <code>Dropout<\/code> and <code>BatchNormalization<\/code> whether you are training or running inference. Keras sets it to True inside <code>fit()<\/code> and to False in <code>evaluate()<\/code> and <code>predict()<\/code>, as long as you pass it on to those layers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I save a subclassed Keras model?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The simplest way is <code>model.save_weights(&quot;name.weights.h5&quot;)<\/code> and then loading the weights into a new instance. To save the whole model as a <code>.keras<\/code> file, implement <code>get_config()<\/code> and register the class with <code>keras.saving.register_keras_serializable()<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should I use subclassing or the Functional API?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/artificial-intelligence\/machine-learning\/\">More Machine Learning tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/lead-machine-learning-engineer-role-blueprint-responsibilities-skills-kpis-and-career-path\/\">Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/staff-mlops-engineer-role-blueprint-responsibilities-skills-kpis-and-career-path\/\">Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>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&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[6512],"tags":[7380],"class_list":["post-47537","post","type-post","status-publish","format-standard","hentry","category-machine-learning","tag-tensorflow"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47537","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=47537"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47537\/revisions"}],"predecessor-version":[{"id":80164,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47537\/revisions\/80164"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=47537"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=47537"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=47537"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}