Unable to load saved model

I’m trying to load a saved model using learner_load() but get errors about missing dls.
It works just fine if I do learn.load(filepath) but I need to load the model from only the filepath.

This is the full code to reproduce the error.

how do I load the model correctly?

from fastai.vision.all import *

path = untar_data(URLs.PETS)
files = get_image_files(path/“images”)

def label_func(f): return f[0].isupper()
dls = ImageDataLoaders.from_name_func(path, files, label_func, item_tfms=Resize(224))

learn = vision_learner(dls, resnet34, metrics=error_rate)
learn.fine_tune(1)
p = learn.save(‘pets’)

learn_inf = load_learner(p)

But this throws the error:


AttributeError Traceback (most recent call last)
Cell In[9], line 1
->—> 1 learn_inf = load_learner(p)

File ~/anaconda3/envs/modelling2/lib/python3.10/site-packages/fastai/learner.py:451, in l>oad_learner(fname, cpu, pickle_module)
449 raise
450 if cpu:
→ 451 res.dls.cpu()
452 if hasattr(res, ‘channels_last’): res = res.to_contiguous(to_fp32=True)
453 elif hasattr(res, ‘mixed_precision’): res = res.to_fp32()

AttributeError: ‘dict’ object has no attribute ‘dls’

fastai.version == ‘2.7.11’

learn.save is paired with learn.load and saves the model, and potentially optimizer. learn.export is paired with load_learner for deployment

3 Likes

Thanks, it works now. But I have a bonus question:
learn.export works just fine if I’m using the code from the tutorial. But if I change the loss function to labelsmoothning:

learn = vision_learner(dls, resnet34, metrics=error_rate, loss_func=LabelSmoothingCrossEntropyFlat())

I get the error "

TypeError: cannot pickle ‘code’ object"

should I just set the loss_func to None before saving? Or shoud the LabelSmoothing function be re-written somehow? It might be good to know if I write more custom codes to my models.

Best regards/

Thanks for your explanation. But in this case, i think the docu and naming of the functions is very missleading… Also, why would it be possible to give an error when somebody is using it wrong?

Did you found your error? When does the error happen, during export or loading?

The docu says:

load_learner requires all your custom code be in the exact same place as when exporting your Learner (the main script, or the module you imported it from).

Hello. This was a long time ago, but I think the error happened during saving. I have not tried recently.