Let's take a look at the code for
callbacks, and see how it works.
You can see the code here.
Here's the notebook with the code already written,
and here's the class that we
defined to handle the callback,
and here is where we instantiate
the callback class itself.
Finally, here's where we set up
the callback to be called as part of the training loop.
As we begin training,
note that we asked it to train for five epochs.
Now, keep an eye on the losses that trains.
We want to break when it goes below 0.4,
and by the end of the first epoch
we're actually getting close already.
As the second epoch begins,
it has already dropped below 0.4,
but the callback hasn't been hit yet.
That's because we set it up for on epoch end.
It's good practice to do this,
because with some data and some algorithms,
the loss may vary up and down during the epoch,
because all of the data hasn't yet been processed.
So, I like to wait for the end to be sure.
Now the epoch has ended,
we can see that the training ends,
even though we've only done two epochs.
Note that we're sure we asked for
five epochs and that we ended after two,
because the loss is below 0.4,
which we checked for in
the callback. It's pretty cool right?