What if your model could watch itself and decide when to stop training or save progress automatically?
Why Custom callbacks in TensorFlow? - Purpose & Use Cases
Imagine you are training a machine learning model and want to stop training early if the model stops improving, save the model at certain points, or print custom messages during training.
Doing all this manually means watching the training closely, pausing it, saving files yourself, and repeating this over and over.
Manually monitoring training is slow and tiring. You might miss the best moment to stop or save your model.
It's easy to make mistakes, like forgetting to save the model or wasting time training too long.
This manual approach is error-prone and not practical for large or long training sessions.
Custom callbacks let you automate these tasks during training.
You write small pieces of code that run at key moments, like after each training step or epoch.
This way, you can stop training early, save models, or log info automatically without watching the process.
for epoch in range(100): train_one_epoch() if validation_loss_not_improving(): break save_model_if_needed()
class MyCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs=None): if logs['val_loss'] > threshold: self.model.stop_training = True save_model() model.fit(..., callbacks=[MyCallback()])
Custom callbacks let your training run smarter and hands-free, adapting automatically to your needs.
In a real project, you can stop training when the model stops improving to save time and resources, or save the best model automatically without interrupting training.
Manual training monitoring is slow and error-prone.
Custom callbacks automate tasks during training.
This makes training efficient, reliable, and easier to manage.
Practice
Solution
Step 1: Understand what callbacks do
Callbacks let you add custom actions during training, like logging or stopping early.Step 2: Identify the role of custom callbacks
Custom callbacks let you run your own code at points like start/end of epochs or batches.Final Answer:
To run your own code at specific points during model training -> Option AQuick Check:
Custom callbacks = run code during training [OK]
- Thinking callbacks change model structure
- Confusing callbacks with data augmentation
- Assuming callbacks convert model formats
Solution
Step 1: Recall callback method names
Common callback methods include on_train_begin, on_epoch_end, on_batch_begin, on_train_end.Step 2: Match method to event
on_epoch_end runs code after each epoch finishes, which is what the question asks.Final Answer:
on_epoch_end -> Option BQuick Check:
End of epoch method = on_epoch_end [OK]
- Using on_train_begin for epoch end
- Confusing batch and epoch methods
- Overriding on_train_end instead
import tensorflow as tf
class MyCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs=None):
print(f"Epoch {epoch+1} ended with loss {logs['loss']:.2f}")
model = tf.keras.Sequential([tf.keras.layers.Dense(1)])
model.compile(optimizer='sgd', loss='mse')
model.fit([[1.0]], [[2.0]], epochs=2, callbacks=[MyCallback()])Solution
Step 1: Understand on_epoch_end behavior
The method prints epoch number +1 and loss from logs after each epoch.Step 2: Check training epochs and output
Training runs 2 epochs, so prints for epoch 1 and 2 with loss values (numbers).Final Answer:
Epoch 1 ended with loss X\nEpoch 2 ended with loss Y (X and Y are numbers) -> Option DQuick Check:
Prints after each epoch with loss [OK]
- Assuming epoch numbering starts at 1 internally
- Expecting no print output
- Thinking logs is None causing error
class StopCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs=None):
if logs['loss'] < 0.1:
self.model.stop_training = True
model.fit(x_train, y_train, epochs=10, callbacks=[StopCallback()])Solution
Step 1: Check logs usage
logs can be None if no metrics are passed, so logs['loss'] may cause KeyError.Step 2: Confirm correct way to stop training
Setting self.model.stop_training = True is correct; no method call needed.Final Answer:
logs dictionary might be None causing KeyError -> Option CQuick Check:
Check logs is not None before accessing [OK]
- Calling stop_training as a method
- Expecting on_epoch_end to return a value
- Inheriting from wrong base class
Solution
Step 1: Identify when to check validation accuracy
Validation accuracy is updated at epoch end, so on_epoch_end is the right method.Step 2: Implement logic to save weights only if val_accuracy improves
Inside on_epoch_end, compare current val_accuracy with previous best and save if better.Final Answer:
Override on_epoch_end, check logs['val_accuracy'], save weights if improved -> Option AQuick Check:
Save on epoch end if val_accuracy improves [OK]
- Saving weights too often (every batch)
- Saving only before or after all training
- Not checking if accuracy improved before saving
Ready to prove it?
Pass the test and this pattern moves unknown
