Tag Archives: History callback Keras

Keras Callbacks – History

In neural networks, the best idea for debugging is to see the relationship between the cost and the number of iterations. This not only ensures that the optimizer is working properly but can also be very useful in the indication of overfitting. Moreover, we can also debug the learning rate based on this relationship. Thus, one should always keep a track on the loss and the accuracy metrics while training a neural network.

Fortunately, in Keras, we don’t need to write a single extra line of code to store all these values. Keras automatically keeps the record of all the events for each epoch. This includes loss and accuracy metrics for both training and validation sets (if used). This is done using the History callback which is automatically applied to every Keras model. This callback records all the events into a History object that gets returned by the fit() method.

How does this work?

First, at the onset of training, this creates an empty dictionary to store all the events. Then at every epoch end, all the events are appended into the dictionary. Below is the code for this taken from the Keras GitHub.

How to use this?

Since all the saved records are returned by the fit() method, we can simply store all the events in any variable. Here, I’ve used “record” as the variable name.

Now, using this record object, we can retrieve any information about the training process. For instance, “record.epoch” returns the list of epochs.

record.history” returns the dictionary containing the event names as the dictionary keys and their values at each epoch in a list.

You can retrieve all the event names using the following command.

You can also get the information about the parameters used while fitting the model. This can be done using the following command.

Not only this, but one can also check which data is used as the validation data using the following command.

These are just a few of functionalities available under the History callback. You can check more of these at Keras GitHub.

Plot the training history

Since all the events are stored in a dictionary, one can easily plot these using any plotting library. Here, I’m using Matplotlib. Below is the code for plotting the loss curves for both training and validation sets.

Similarly, one can plot the accuracy plots. That’s all for History callback. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.