Unable to save unet_learner

Greetings, I’m trying to save the model from an example in Chapter 1 and getting an error. I was able to save a learner model using this method from another example.

from fastai.vision.all import *

path = untar_data(URLs.CAMVID_TINY)
dls = SegmentationDataLoaders.from_label_func(
path, bs=8, fnames = get_image_files(path/“images”),
label_func = lambda o: path/‘labels’/f’{o.stem}_P{o.suffix}',
codes = np.loadtxt(path/‘codes.txt’, dtype=str)
)
learn = unet_learner(dls, resnet34)
learn.fine_tune(8)
learn.path = Path(os.getcwd())
learn.export(‘segment.pkl’)

File “/home/tromanow/.local/lib/python3.11/site-packages/torch/serialization.py”, line 653, in _save
pickler.dump(obj)
_pickle.PicklingError: Can’t pickle <function at 0x7ff796f60f40>: attribute lookup on main failed

The lambda function causes this error but I don’t remember why. Try using normal function that’s not defined through lambda, that would resolve the error.

def f(o): return path/"labels"/f"{o.stem}_P{o.suffix}"

Hope this helps :slight_smile:

Indeed, lambda functions can’t be pickled only named functions can

1 Like