Share on facebook
Share on twitter
Share on linkedin
Share on pinterest

Custom Callbacks in Keras

Keras comes with a long list of predefined callbacks that are ready to use. Keras callbacks are functions that are executed during the training process.

According to Keras Documentation, A callback is a set of functions to be applied at given stages of the training procedure. You can use callbacks to get a view on internal states and statistics of the model during training. You can pass a list of callbacks (as the keyword argument callbacks) to the .fit() method of the Sequential or Model classes. The appropriate methods of the callbacks will then be called at each stage of the training.

In this article, we’ll discuss how to create custom callbacks in Keras.


Along with various built-in callbacks that are ready to use, we can also create custom callbacks in Keras.

In Keras, we can create custom callbacks in two ways

  1. By creating a class that inherits from keras.callbacks.Callback
  2. By using the LambdaCallback


Now let’s see how to create a custom callback class that computes the ROC AUC at the end of every epoch.

To create a custom callback, we need to create a class that inherits from keras.callbacks.Callback and redefining the methods we need.

Since we are calculating ROC AUC at the end of each epoch we’ll override the method on_epoch_end

First, let’s create a CNN model that classifies the fashion_mnist data

Next, we can create our custom callback that inherits from the class keras.callbacks

Now we can pass the callbacks object into the model fit method as a list

keras custom callback


Without creating a custom class we can also create a simple custom callback on-the-fly using the LambdaCallback.

The signature of the lambda callback is as follows.

Now let’s create a custom lambda callback which stops the training of the model once the validation accuracy hits 90%

Below is the complete code

lambda callback


Love What you Read. Subscribe to our Newsletter.

Stay up to date! We’ll send the content straight to your inbox, once a week. We promise not to spam you.

Subscribe Now! We'll keep you updated.