Observe · checkpoint · recover
TensorBoard, callbacks
and saving in Keras
Understand what training logs tell you, which epoch a checkpoint keeps, and how to test a saved model before relying on it.
Three outputs, three different purposes
Use TensorBoard to inspect what happened during training, callbacks to react while training runs, and saved models to recover a usable model afterwards. Keeping these jobs separate prevents a common mistake: assuming that a log directory is a trained model backup.
This expanded Day 16 reader keeps every original passage, repeated explanation, code string and all three screenshots below. Current Keras guidance is added separately so you can compare it with the historical instructions. The original author, publication date and stable lesson URL are retained.
| Artifact | Purpose | Important limit |
|---|---|---|
| TensorBoard events | Metric summaries across training and validation | Logs do not recreate a model |
| Native .keras file | Model configuration, weights, optimizer state if present | Custom objects may require registration |
| .weights.h5 file | Load weights into a compatible model | Not a replacement for architecture configuration |
| Checkpoint callback | Write model artifacts during fit | Default is not best-only |
Execution scope: the new synthetic regression smoke test below ran with TensorFlow 2.21.0 and Keras 3.15.1. It tests file round trips and callback output, not image classification accuracy. The original Fashion-MNIST training run remains unexecuted in this pass; retained screenshots are historical evidence, not newly reproduced results.
Read the historical code with these current notes
Saving, loading and exporting are separate workflows
The original save_format="tf" call belongs to an older API. In current Keras, use model.save("model.keras") and keras.models.load_model("model.keras") for the native whole-model round trip. The .keras archive includes configuration, model weights and optimizer state when an optimizer is present. It does not package your dataset, arbitrary Python environment or every external dependency.
For a deployment SavedModel, current guidance uses model.export. Keras 3 load_model does not reopen a SavedModel directory; the documented inference integration uses TFSMLayer. That export workflow is referenced here, not executed by this lesson’s smoke test. Load only model files you trust and follow the API’s safe-loading guidance.
The old my_weights.h5 string remains intact below. For current save_weights, choose a .weights.h5 suffix and first create a compatible architecture before loading. A weights file is not a whole-model architecture archive. Exact optimizer-state behavior depends on the saving API and compiled model; do not assume weights-only means a complete resumable training snapshot, or that no optimizer information can ever be present.
The last checkpoint and best in-memory weights can differ
The original checkpoint uses save_weights_only=True but leaves save_best_only=False. Its default epoch schedule writes the same file repeatedly. EarlyStopping separately monitors validation loss by default, and restore_best_weights=True restores selected model weights in memory. Those weights need not match the last overwritten checkpoint. The added example explicitly requests best-only full-model checkpoints and keeps checkpoints and event logs in different directories.
Restoring model weights does not establish that the optimizer has been rolled back to an exactly matching earlier training state. If you need to resume training, plan and test your recovery mechanism; if you only need inference, compare predictions after loading. Use a validation set to choose stopping and checkpoints, then reserve the test set for final evaluation rather than repeated tuning.
Architecture clarification: the retained closing prose refers to a Functional model, but the displayed full training script constructs tf.keras.Sequential. The historical screenshots are preserved without asserting that they reproduce this exact script.
Logging is not profiling, and a metric is not always between zero and one
The retained profiling range 100–200 is optional. The executed addition uses profile_batch=0 to disable profiling and logs epoch metrics. It verifies event files and tags programmatically; a TensorBoard browser dashboard and GPU profiler were not tested. Current callback documentation also notes limitations around graph writing, so a graph visualization is not promised merely because the callback was constructed.
The original !pip command is notebook shell syntax, not normal Python-file syntax. Install dependencies in an appropriate environment before running a .py file; do not paste that line unchanged into a Python script. The full historical script also plots loss and accuracy on a single 0–1 vertical range. Cross-entropy loss can exceed one, so that range can clip loss. Plot loss and accuracy on separate axes or allow a suitable loss-axis range.
The original log naming uses timestamps to the nearest second. Fast or concurrent runs could collide; use distinct directories when comparing experiments. The added smoke test uses a fresh temporary directory, so it does not overwrite earlier runs. Event files, checkpoints and model files are all created locally by the example, never inside the WordPress server.
Check the data and epoch arithmetic
Fashion-MNIST’s standard training partition contains 60,000 examples and its test partition contains 10,000. The preserved slicing takes the final 5,000 training examples for validation, leaving 55,000 for fitting. Splitting before learning preprocessing parameters avoids using validation or test information to choose training transformations.
The original fixed division rescales pixel intensities; it does not learn a mean or variance. For a dense layer with d inputs and u units, the count is d × u + u including biases. The preserved 784 → 300 → 100 → 10 network therefore has the following count:
That is a mathematical parameter count, not a measured accuracy or training-time claim. The synthetic one-input/one-output Dense smoke test has just two parameters: one weight and one bias.
A deliberately invented early-stopping trace
Consider validation losses 0.80, 0.60, 0.61, 0.62, with minimization, min_delta = 0 and patience = 2. Epoch 2 is the best. Epochs 3 and 4 do not improve it, so a stop is requested after epoch 4 and best-weight restoration selects epoch 2. This trace is hypothetical; it is not the output of the four-epoch synthetic fit, which improved throughout. The actual Keras callback was also driven with this explicit trace in a separate controlled check.

Executed: a small saving and logging smoke test
This complete procedure uses 24 scalar training samples and 8 validation samples, y = 2x + 1, over four epochs. It asserts that predictions match after both full-model and weights round trips, loads the best checkpoint, and reads TensorBoard event tags. It is designed to test the workflow with little data, not to prove generalization. Its two-parameter fit does not establish performance on Fashion-MNIST.
Run it from a writable working directory containing a day16 folder for the JSON report, with TensorFlow, Keras, NumPy and TensorBoard installed. Model artifacts use a new temporary directory. The assertions passed in the recorded environment; package and platform differences can still matter. EarlyStopping participated in fit but did not stop that improving trace. The independent controlled trace verifies its patience behavior separately.
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
os.environ['TF_NUM_INTEROP_THREADS']='1'
os.environ['TF_NUM_INTRAOP_THREADS']='1'
from pathlib import Path
import json, tempfile
import numpy as np
import tensorflow as tf
import keras
root=Path(tempfile.mkdtemp(prefix='day16-'))
keras.utils.set_random_seed(42)
x=np.linspace(-1,1,32,dtype='float32').reshape(-1,1)
y=2*x+1
options=tf.data.Options();options.threading.private_threadpool_size=1
train=tf.data.Dataset.from_tensor_slices((x[:24],y[:24])).batch(8).with_options(options)
valid=tf.data.Dataset.from_tensor_slices((x[24:],y[24:])).batch(8).with_options(options)
model=keras.Sequential([keras.Input(shape=(1,)),keras.layers.Dense(1)])
model.compile(optimizer=keras.optimizers.SGD(0.05),loss='mse')
(root/'checkpoints').mkdir()
callbacks=[keras.callbacks.ModelCheckpoint(root/'checkpoints'/'best.keras',monitor='val_loss',mode='min',save_best_only=True),keras.callbacks.EarlyStopping(monitor='val_loss',mode='min',patience=2,restore_best_weights=True),keras.callbacks.TensorBoard(log_dir=str(root/'logs'),profile_batch=0)]
history=model.fit(train,validation_data=valid,epochs=4,callbacks=callbacks,verbose=0)
before=model(x,training=False).numpy()
model.save(root/'final.keras')
loaded=keras.models.load_model(root/'final.keras')
np.testing.assert_allclose(before,loaded(x,training=False).numpy(),rtol=1e-6,atol=1e-6)
model.save_weights(root/'final.weights.h5')
clone=keras.models.clone_model(model);clone.load_weights(root/'final.weights.h5')
np.testing.assert_allclose(before,clone(x,training=False).numpy(),rtol=1e-6,atol=1e-6)
assert (root/'checkpoints'/'best.keras').is_file()
assert keras.models.load_model(root/'checkpoints'/'best.keras').count_params()==2
logs=list((root/'logs').rglob('events.out.tfevents.*'));assert logs
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
summary=[]
for p in logs:
a=EventAccumulator(str(p)).Reload();summary.append({'file':p.name,'tags':a.Tags()})
result={'tensorflow':tf.__version__,'keras':keras.__version__,'epochs':len(history.history['loss']),'loss':history.history['loss'],'val_loss':history.history['val_loss'],'full_model_roundtrip':True,'weights_roundtrip':True,'checkpoint_load':True,'parameters':model.count_params(),'event_files':summary,'scope':'Synthetic 24 train/8 validation scalar regression, 4 epochs. No Fashion-MNIST or TensorBoard browser UI tested. EarlyStopping constructed and invoked; patience stop not triggered in this improving fit.'}
Path('day16/runtime-result.json').write_text(json.dumps(result,indent=2));print(json.dumps(result,indent=2))
Practice: change the monitored metric only after inspecting the history keys. If you monitor a missing metric, best-model saving and early stopping cannot select the intended result. After changing architecture, confirm that a weights file still matches before relying on it. After changing log directories, launch TensorBoard against the actual parent log path rather than a model-file path.
Primary references and next steps
- Keras whole-model saving and loading
- Keras 3 migration and SavedModel differences
- ModelCheckpoint configuration
- EarlyStopping monitor, patience and restoration
- TensorBoard callback and profiling options
- Fashion-MNIST dataset shapes
References checked 16 November 2026. These additions explain version differences while leaving the historical lesson readable. Original screenshots and their order remain below; they have not been relabeled as current output.
Complete original lesson and screenshots
Every original explanation and code block follows, including older syntax and repeated paragraphs. Read the separate current-version notes above before running it. The historical full training script is not newly executed here, and its screenshots are retained without inventing their accuracy or provenance.
Mastering TensorFlow: Using TensorBoard, Callbacks, and Model Saving in Keras
Mastering TensorFlow: Using TensorBoard, Callbacks, and Model Saving in Keras
TensorFlow and Keras provide powerful tools for building, training, and evaluating deep learning models. In this blog post, we will explore three essential techniques:
- Using TensorBoard for visualization
- Utilizing callbacks to enhance model training
- Saving and restoring models
Using TensorBoard for Visualization
TensorBoard is an interactive visualization tool that helps you understand your model’s training dynamics. It allows you to view learning curves, compare metrics between multiple runs, and analyze training statistics.
Installation
!pip install -q -U tensorflow tensorboard-plugin-profile
Setting Up Logging Directory
We need a directory to save our logs. This directory will contain event files that TensorBoard reads to visualize the training process.
from pathlib import Path
from time import strftime
def get_run_logdir(root_logdir="my_logs"):
return Path(root_logdir) / strftime("run_%Y_%m_%d_%H_%M_%S")
run_logdir = get_run_logdir()
Saving and Restoring a Model
Keras allows you to save the entire model (architecture, weights, and training configuration) to a single file or a folder.
Saving a Model
model.save("my_keras_model", save_format="tf")
Loading a Model
model = tf.keras.models.load_model("my_keras_model")
Saving Weights Only
model.save_weights("my_weights.h5")
model.load_weights("my_weights.h5")
Using Callbacks
Callbacks in Keras allow you to perform actions at various stages of training (e.g., saving checkpoints, early stopping).
ModelCheckpoint
Save the model at regular intervals.
checkpoint_cb = tf.keras.callbacks.ModelCheckpoint("my_checkpoints.weights.h5", save_weights_only=True)
EarlyStopping
Stop training when a monitored metric has stopped improving.
early_stopping_cb = tf.keras.callbacks.EarlyStopping(patience=10, restore_best_weights=True)
TensorBoard Callback
Log data for TensorBoard.
tensorboard_cb = tf.keras.callbacks.TensorBoard(log_dir=run_logdir, profile_batch=(100, 200))
Full Code with Techniques Applied
Here is the full code incorporating all the techniques discussed:
# Install TensorFlow and TensorBoard plugin
!pip install -q -U tensorflow tensorboard-plugin-profile
# Import necessary libraries
import tensorflow as tf
import matplotlib.pyplot as plt
import pandas as pd
from pathlib import Path
from time import strftime
# Load Fashion MNIST dataset
fashion_mnist = tf.keras.datasets.fashion_mnist
(X_train_full, y_train_full), (X_test, y_test) = fashion_mnist.load_data()
# Split data into training, validation, and test sets
X_train, y_train = X_train_full[:-5000], y_train_full[:-5000]
X_valid, y_valid = X_train_full[-5000:], y_train_full[-5000:]
# Scale pixel values to the 0-1 range
X_train, X_valid, X_test = X_train / 255.0, X_valid / 255.0, X_test / 255.0
# Class names for Fashion MNIST
class_names = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat",
"Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]
# Display the first few images and labels
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5, 5, i + 1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(X_train[i], cmap=plt.cm.binary)
plt.xlabel(class_names[y_train[i]])
plt.show()
# Set random seed for reproducibility
tf.random.set_seed(42)
# Build the model
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")
])
# Compile the model
model.compile(loss="sparse_categorical_crossentropy",
optimizer="sgd",
metrics=["accuracy"])
# Define log directory for TensorBoard
def get_run_logdir(root_logdir="my_logs"):
return Path(root_logdir) / strftime("run_%Y_%m_%d_%H_%M_%S")
run_logdir = get_run_logdir()
# Define callbacks
checkpoint_cb = tf.keras.callbacks.ModelCheckpoint("my_checkpoints.weights.h5", save_weights_only=True)
early_stopping_cb = tf.keras.callbacks.EarlyStopping(patience=10, restore_best_weights=True)
tensorboard_cb = tf.keras.callbacks.TensorBoard(log_dir=run_logdir, profile_batch=(100, 200))
# Train the model with callbacks
history = model.fit(X_train, y_train, epochs=30,
validation_data=(X_valid, y_valid),
callbacks=[checkpoint_cb, early_stopping_cb, tensorboard_cb])
# Start TensorBoard (run these two lines in a Jupyter notebook or Colab cell)
# %load_ext tensorboard
# %tensorboard --logdir=./my_logs
# Evaluate the model on the test set
test_loss, test_acc = model.evaluate(X_test, y_test)
print(f"Test accuracy: {test_acc:.4f}")
# Plot training and validation accuracy and loss
def plot_learning_curves(history):
pd.DataFrame(history.history).plot(figsize=(8, 5))
plt.grid(True)
plt.gca().set_ylim(0, 1) # set the vertical range to [0-1]
plt.show()
plot_learning_curves(history)
# Make predictions
y_pred = model.predict(X_test)
# Plot the first 25 test images, their predicted labels, and the true labels.
# Color correct predictions in blue and incorrect predictions in red.
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5, 5, i + 1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(X_test[i], cmap=plt.cm.binary)
predicted_label = class_names[y_pred[i].argmax()]
true_label = class_names[y_test[i]]
color = 'blue' if predicted_label == true_label else 'red'
plt.xlabel(f"{predicted_label} ({true_label})", color=color)
plt.show()
This blog post covers the essential techniques of using TensorBoard, callbacks, and model saving/restoring in Keras with TensorFlow. These techniques will enhance your model training process and provide valuable insights into your model’s performance. Happy coding!
Check the results in the screenshots below:
Just run the code in Google Colab to see your model in action, but let’s see some images from the result of our given code which was a functional Keras model discussed in our previous post.
Check the results in the screenshots Bellow :
Just run the code in Google Colab to see your Self but let’s see some images from the result of our given code which was a functional Keras mode which we discussed in our previous days post



Questions about saving and callbacks
What is the difference between a model file and TensorBoard logs?
A .keras model file stores model configuration, weights and optimizer state when present. TensorBoard event files record summaries for inspection; they are not a substitute for a saved model.
Does the original checkpoint keep the best epoch?
No. Its save_best_only setting is left at the default False. It writes weights after each epoch to the same path. The separate EarlyStopping callback can restore a different, better epoch in memory.
How do I save a model with Keras 3?
For the native round trip, use model.save with a .keras filename and load it with keras.models.load_model. SavedModel export is a separate deployment workflow; Keras 3 load_model does not load a SavedModel directory.
Can I use my_weights.h5 for current weights-only saving?
Use a filename ending in .weights.h5 for current Keras weights saving. Recreate a compatible architecture before loading those weights. The original older filename remains preserved in the historical section.
Was the original Fashion-MNIST model retrained here?
No. The historical training code and screenshots are preserved, but its full training and test accuracy were not reproduced. A separate small synthetic TensorFlow example executed model saving, loading, weights, checkpoints and TensorBoard event logging.
Does a patience of two always mean stop after two epochs?
No. Patience counts consecutive monitored epochs without a qualifying improvement. In the added four-epoch synthetic fit the validation loss improved, so the early-stop condition did not trigger.
