#!/usr/bin/env python # coding: utf-8 # # Tracking Callbacks # In[1]: from fastai.gen_doc.nbdoc import * from fastai.callbacks.general_sched import * from fastai import * from fastai.vision import * # This module regroups the callbacks that track one of the metrics computed at the end of each epoch to take some decision about training. To show examples of use, we'll use our sample of MNIST and a simple cnn model. # In[5]: path = untar_data(URLs.MNIST_SAMPLE) data = ImageDataBunch.from_folder(path) # In[2]: show_doc(TerminateOnNaNCallback) # Sometimes, training diverges and the loss goes to nan. In that case, there's no point continuing, so this callback stops the training. # In[7]: model = simple_cnn((3,16,16,2)) learn = Learner(data, model, metrics=[accuracy]) learn.fit(2,1e4) # Using it prevents that situation to happen. # In[8]: model = simple_cnn((3,16,16,2)) learn = Learner(data, model, metrics=[accuracy], callbacks=[TerminateOnNaNCallback()]) learn.fit(2,1e4) # In[3]: show_doc(EarlyStoppingCallback) # This callback tracks the quantity in `monitor` during the training of `learn`. `mode` can be forced to 'min' or 'max' but will automatically try to determine if the quantity should be the lowest possible (validation loss) or the highest possible (accuracy). Will stop training after `patience` epochs if the quantity hasn't improved by `min_delta`. # In[10]: model = simple_cnn((3,16,16,2)) learn = Learner(data, model, metrics=[accuracy], callback_fns=[partial(EarlyStoppingCallback, monitor='accuracy', min_delta=0.01, patience=3)]) learn.fit(50,1e-42) # In[4]: show_doc(SaveModelCallback) # This callback tracks the quantity in `monitor` during the training of `learn`. `mode` can be forced to 'min' or 'max' but will automatically try to determine if the quantity should be the lowest possible (validation loss) or the highest possible (accuracy). Will save the model in `name` whenever determined by `every` ('improvement' or 'epoch'). Loads the best model at the end of training is `every='improvement'`. # In[5]: show_doc(ReduceLROnPlateauCallback) # This callback tracks the quantity in `monitor` during the training of `learn`. `mode` can be forced to 'min' or 'max' but will automatically try to determine if the quantity should be the lowest possible (validation loss) or the highest possible (accuracy). Will reduce the learning rate by `factor` after `patience` epochs if the quantity hasn't improved by `min_delta`. # In[6]: show_doc(TrackerCallback)