Loading models in standalone .py files


#1

Hi Guys

Simple question - I know we can save and load traces, but is it possible to load a model saved in a model.py file, in the same directory as the pymc3 notebook.

So something like

model = pm.Model(filename=‘model.py’)

and the model definition sits within model.py?

Is there a simple way to do this, or not?

thanks!


#2

You can pickle.dump (save a model instance) and then pickle.load (load the instance from a file) to save model instances somewhere and then load them from somewhere else.

The normal pickle extension is .pkl. in your question you are saying you want the model to be stored in a model.py file, but that extension is for python scripts, modules or packages. I may be confusing your intension, but are you trying to do a partial import from a script file that has a model’s definition, or do you just want to simply save and reload instances of models that were created somewhere else?


#3

@lucianopaz - I was thinking of loading and saving a models definition before instantiating the model, rather than instantiating the model and then saving the instance and reloading it later…


#4

You can do it in many ways. You could use __import__ to import from model.py (this could fail if model.py is changed in the middle of the execution because it would have to be reloaded). You could store the model initialization in a string and then eval it. Or you could write down a factory function that would create your model instances, then __import__ that from your file and then call it. I imagine there are many more ways to do this because what you want is a general python issue and is not restricted to pymc3.


#5

If you finally choose to use __import__like alternatives, be aware of how to reload things.


#6

Alternatively I think you can inherited the model class and define your model - there are some examples in the docstring of pm.Model