NameError: name 'SaveModelCallback' is not defined

Hi, I wish to save my best model. So I wanted to to use the SaveModelCallback callback as mentioned in the documentation. However, using it gives me the following error:

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
in ()
----> 1 learn.fit_one_cycle(5,1e-4, callbacks=SaveModelCallback(learn, every=‘epoch’, monitor=‘accuracy’, name=‘model’))

NameError: name ‘SaveModelCallback’ is not defined

Please let me know where I’m going wrong

2 Likes

Maybe use the following function to add a save callback:

def addSaveCallback(learner):
    learner.callback_fns.append(partial(callbacks.SaveModelCallback, 
                              monitor='error_rate',
                              mode='min',
                              name='tmp')
1 Like

Thanks Patrick! Works fine now.
What went wrong though?

I think you forgot to include the callbacks class, respectively to call callbacks.XXXCallback.

1 Like

For others that may come across this - an alternative solution is to make sure you have the proper imports in your code. If you have the standard from fastai.[APPLICATION] import * such as:

from fastai.vision import *

The callbacks are available via the namespace callbacks so to use SaveModelCallback, you would use:

 learn.fit_one_cycle(5,1e-4, callbacks=callbacks.SaveModelCallback(learn, every=‘epoch’, monitor=‘accuracy’, name=‘model’))

Alternatively, if you don’t want to prepend callbacks. you can add this additional import:

from fastai.callbacks import *

Which allows you to then have the learn.fit_one_cycle() call as the OP - @tanmay97 - listed it.

8 Likes