Alternative Frontends for PyMC

Rob Zinkov
2023-11-19

When people are starting to learn pymc they often assume the syntax and workflow for the library is something that’s unchangeable. But thanks to the modular way the library is implemented, I’m going to show that it’s fairly easy to use it in a totally different way!

Sample as a method on the model

Some people see sampling as more a method on the model than a function. We can always extend pm.Model for those that find that more intuitive

Here is a simple example of it in action

Models as parameterised functions

The idea here is to create models by just using a decorator.

With this change our previous model becomes:

In practice, this removes all need to think about context managers

But the real composition happens with how readily helper methods can be used

And since the model returned is an ordinary pymc model object, it can be readily used for things like posterior predictive checks

Finally, one underappreciated aspect of this functional approach to defining model is it avoids the need for pm.MutableData in simpler models. Porting an example from the documentation

We call the logistic_model function with different arguments changing to use x_grid instead of x

This even works really well for coords. It only requires we change model a little bit

Now let’s generate some data and fit a linear model

We can then update the coords seamlessly

While I personally think these changes simplify the models and speed-up the interactive workflow, that’s not the main reason I share them. I share them because more of us should be doing little experiments like these. There are certainly more low-hanging fruits to be had for people who are willing to join in!