Save the Best Keras Model and Halt Training Early
Use EarlyStopping and ModelCheckpoint together to save the best Keras weights and stop training when validation loss stalls.
01 Sept 2025, 18:03 UTC

Keep the best epoch, not the final epoch
Deep learning training often continues past the point where the model stops improving. If you save only the final weights, you may keep a version that overfits or performs worse than an earlier checkpoint. The useful takeaway is to pair two Keras callbacks: EarlyStopping to halt training when validation loss stops improving, and ModelCheckpoint to persist the weights from the best epoch.
Prerequisites
- TensorFlow with Keras 3 installed, or tf.keras from TensorFlow 2.x.
- A compiled
tf.keras.Model. - Training data and a separate validation dataset.
- A writable directory for checkpoint files.
A callback is a hook Keras runs at specific points during training, such as the end of each epoch. Validation loss (val_loss) measures error on data the model did not see during parameter updates.
Create and register the callbacks
Run this code in a Python script or notebook where your model and datasets are defined. The process needs write access to the checkpoint directory; no special system permissions are otherwise required.
import os
import tensorflow as tf
from tensorflow import keras
# 1. Ensure the target directory exists before training starts.
checkpoint_dir = './checkpoints'
os.makedirs(checkpoint_dir, exist_ok=True)
checkpoint_path = os.path.join(checkpoint_dir, 'best_model.keras')
# 2. Stop when validation loss does not improve for five consecutive epochs.
early_stopping = keras.callbacks.EarlyStopping(
monitor='val_loss',
patience=5,
restore_best_weights=True,
verbose=1,
)
# 3. Save only the epoch with the lowest validation loss.
model_checkpoint = keras.callbacks.ModelCheckpoint(
filepath=checkpoint_path,
monitor='val_loss',
save_best_only=True,
save_weights_only=False,
verbose=1,
)
# 4. Pass both callbacks to fit. validation_data is required for val_loss.
history = model.fit(
train_dataset,
validation_data=val_dataset,
epochs=50,
callbacks=[early_stopping, model_checkpoint],
)
patience=5 means Keras waits five epochs with no improvement before stopping. restore_best_weights=True replaces the model's current weights with the best-epoch weights when early stopping triggers. save_best_only=True overwrites the checkpoint file only when a new best epoch appears, so the directory retains one file rather than a copy of every epoch.
Where to run and required permissions
Run the training code on the host or container that owns the data and model objects. The process needs write permission for ./checkpoints, or your chosen path. If you train on a remote machine or cluster, confirm the mount path is writable before starting; otherwise the callback raises an error when it tries to write the first checkpoint.
Expected checks after training
- Confirm the checkpoint file exists:
import os
print(os.path.exists('./checkpoints/best_model.keras'))
- Inspect the training history to verify the lowest validation loss matches an early epoch, not necessarily the final epoch:
val_loss = history.history['val_loss']
best_epoch = int(val_loss.index(min(val_loss))) + 1
print(f'Best epoch by validation loss: {best_epoch}')
print(f'Total epochs run: {len(val_loss)}')
- Load the saved model and run predictions on held-out data:
restored_model = tf.keras.models.load_model('./checkpoints/best_model.keras')
predictions = restored_model.predict(held_out_dataset)
Limitations and recovery options
restore_best_weights=Truehas no effect if EarlyStopping never triggers; training ends with the final epoch weights.save_best_only=Truekeeps only one checkpoint file. Earlier best epochs are overwritten.- Validation data must be supplied to
model.fit; without it,val_lossis unavailable and the callbacks cannot monitor it. - Custom layers or loss functions require the
custom_objectsargument when loading:
restored_model = tf.keras.models.load_model(
'./checkpoints/best_model.keras',
custom_objects={'MyLayer': MyLayer},
)
If the checkpoint is missing or unreadable, fall back to the final weights in memory or retrain. Only the single best file is retained, so there is no automatic rollback to an earlier epoch.
Version behavior: .keras versus .h5
Keras 3 prefers the native .keras format used in the example. TensorFlow 2.x with tf.keras also supports HDF5 .h5 files, but .keras is the recommended default for new training runs. If you load a model saved under a different Keras version, verify architecture compatibility before resuming training or deploying predictions.
To verify the setup end to end, run a short fit with synthetic data, patience=1, and confirm training stops before the maximum epoch count and that best_model.keras is created. Do not assume the callback worked solely because training completed.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.