pythondeep-learningcomputer-visionpicklefast-ai

How Do I Load FastAI's exported pkl file?


I have trained my resnet model using the Google Colab's free GPU since my laptop does not have a GPU. You can find that here - https://colab.research.google.com/drive/1FjwI26-fv1h3w5hlg-M5Fl_2nvWBvFzq?usp=sharing

Now, it's time to finally make predictions using the model which I have created. But the main problem which I am facing is the loading of the model. Of course, I will load the pkl or pth file onto my local environment and call the predict() method on it but apparently, in order to load the model, you need the object of the Learner class itself.

In my case, it should be the object of the cnn_learner class. In order to make the object of that class, I will need to define everything - the ImageDataLoaders and load the images too and only then, i'll be able to make the object of cnn_learner class by going model = cnn_learner(dls, resnet18, metrics=error_rate where dls would be the object of ImageDataLoaders

How do I work around this? Because honestly this seems a little bit counter-intuitive to me. Even the fastai documentation suggests that I will need all the code when I was exporting my model in order to load the model. But the main point of exporting the fully trained model is to use it on any environment I wish to just because it is fully trained and I can just call the predict() method on it and get my predictions!

Also, I have saved the model in both the pkl format by using model.export and pth format by using model.save

If someone could help me in this, it would be really appreciated.

Thanks a lot!

Tried everything. Browsed the documentation and also experimented with the documentation code on my own but it was no luck.


Solution

  • You can use export method of learner as follows

    learn.export("/content/model.pkl")
    

    To load the model again, use load_learner

    load_learner('/content/model.pkl')
    

    https://docs.fast.ai/learner.html