Approach: compile a Keras model, use ModelCheckpoint to save only the best weights, EarlyStopping to stop on val_loss, and TensorBoard for logs. Show how to resume by loading weights and setting initial_epoch. Also show steps for reproducibility (seeds, PYTHONHASHSEED, deterministic ops where possible).python
import os
import random
import numpy as np
import tensorflow as tf
from tensorflow import keras
# Reproducibility (best-effort)
os.environ['PYTHONHASHSEED'] = '0'
random.seed(0)
np.random.seed(0)
tf.random.set_seed(0)
try:
tf.config.experimental.enable_op_determinism()
except Exception:
pass # not available on all TF builds
# Example model
def build_model(input_shape=(28,28,1), num_classes=10):
inputs = keras.Input(shape=input_shape)
x = keras.layers.Conv2D(32,3, activation='relu')(inputs)
x = keras.layers.Flatten()(x)
outputs = keras.layers.Dense(num_classes, activation='softmax')(x)
return keras.Model(inputs, outputs)
model = build_model()
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# Paths & callbacks
log_dir = "logs/fit"
ckpt_path = "checkpoints/best_weights.ckpt"
os.makedirs(os.path.dirname(ckpt_path), exist_ok=True)
tensorboard_cb = keras.callbacks.TensorBoard(log_dir=log_dir)
checkpoint_cb = keras.callbacks.ModelCheckpoint(
filepath=ckpt_path,
save_weights_only=True,
monitor='val_loss',
save_best_only=True,
verbose=1
)
earlystop_cb = keras.callbacks.EarlyStopping(
monitor='val_loss',
patience=5,
restore_best_weights=True,
verbose=1
)
# Example data (replace with real datasets)
(x_train, y_train), (x_val, y_val) = keras.datasets.mnist.load_data()
x_train = x_train[..., np.newaxis] / 255.0
x_val = x_val[..., np.newaxis] / 255.0
# Resume training if checkpoint exists
initial_epoch = 0
if os.path.exists(ckpt_path + '.index') or os.path.exists(ckpt_path):
try:
model.load_weights(ckpt_path)
# If you saved epoch in filename or a separate JSON, set initial_epoch accordingly.
print("Loaded weights from checkpoint; continuing training.")
except Exception as e:
print("Could not load weights:", e)
history = model.fit(
x_train, y_train,
validation_data=(x_val, y_val),
epochs=50,
batch_size=64,
callbacks=[tensorboard_cb, checkpoint_cb, earlystop_cb],
initial_epoch=initial_epoch
)
Key points / reasoning:- ModelCheckpoint with save_best_only=True+monitor='val_loss' ensures we keep the best weights.- EarlyStopping with restore_best_weights=True returns the model to best state after stopping.- TensorBoard callback writes scalars and graphs to log_dir for visualization.- To resume, load_weights before calling fit and set initial_epoch if you tracked epochs externally; otherwise fit will start from 0 but weights will be preloaded.- Reproducibility: set PYTHONHASHSEED, random, numpy, and tf seeds and enable TF deterministic ops where available. Note: full bitwise determinism on GPU may not be achievable for all ops—document and test in your environment.