A question I often get at this point from programmers in
particular when experimenting with
different numbers of epochs is,
How can I stop training when I
reach a point that I want to be at?
What do I always have to hard code it
to go for certain number of epochs?
Well, the good news is that,
the training loop does support callbacks.
So in every epoch,
you can callback to a code function,
having checked the metrics.
If they're what you want to say,
then you can cancel the training at
that point. Let's take a look.
Okay, so here's our code for training
the neural network to recognize the fashion images.
In particular, keep an eye on the
model.fit function that executes the training loop.
You can see that here.
What we'll now do is write
a callback in Python. Here's the code.
It's implemented as a separate class,
but that can be in-line with your other code.
It doesn't need to be in a separate file.
In it, we'll implement the on_epoch_end function,
which gets called by the callback
whenever the epoch ends.
It also sends a logs object which contains
lots of great information
about the current state of training.
For example, the current loss is available in the logs,
so we can query it for certain amount.
For example, here I'm checking if the loss is less than
0.4 and canceling the training itself.
Now that we have our callback,
let's return to the rest of the code,
and there are two modifications that we need to make.
First, we instantiate the class that we just created,
we do that with this code.
Then, in my model.fit,
I used the callbacks parameter
and pass it this instance of the class.
Let's see this in action.