Advanced Bayesian Regression


Advanced Bayesian Regression

Anna
Today we’re exploring how Bayesian statistics can be taught in an approachable way, how the Python library Bambi helps people build Bayesian models, and what gets tricky in advanced regression. Our guide is Tommy Capretto, a data scientist at PMC Labs, a statistics educator at Universidad Nacional de Rosario in Argentina, and an open-source contributor, especially to Bambi, PyMC, and ArviZ.

Michael
That combination of industry work, teaching, and software development gives him an interesting perspective. At PMC Labs, he works on Bayesian statistics projects with a team that also builds tools he uses. And at the university where he studied, he teaches a Bayesian statistics course to students who have already taken many statistics courses, but mostly from a frequentist perspective.

Anna
One of his favorite ways to begin that course is with a concrete mystery involving colorful candy. The students work in groups, open a bag of M&M’s—or a local equivalent—and count how many pieces are each color. The imagined factory owner suspects that the machine producing one particular color may be malfunctioning, and the students have to figure out what the observed colors can tell them.

Michael
I like that because the statistical question emerges from the activity. Students first decide what quantity matters: the proportion of candies that are the color under investigation. They recognize that it must lie between zero and one. To do the calculation by hand, they discretize it into eleven possible values from zero to one, then ask whether those values should all be considered equally plausible.

Anna
And that question introduces the prior without beginning with a definition on a slide. The students bring their knowledge of the situation to the problem: with five colors, for instance, they may not think it equally likely that one color makes up 20 percent of the candies as that it makes up 80 percent. They turn that judgment into a probability distribution over the unknown proportion.

Michael
Then they connect the observed counts to a binomial model. They discuss the assumptions involved, including independence and a constant probability, and combine the prior with the data using Bayes’ theorem. The arithmetic is deliberately simple, but it lets students see each step of Bayesian reasoning and how their prior information and observations work together.

Anna
The course’s message is essentially: what we just did by hand is the approach we’ll develop throughout the term. It’s also memorable because the students know the candy, they can inspect the evidence themselves, and—at the end—they can eat the data. The instructors have used different treats in different course editions, but kept the underlying teaching idea.

Michael
That concrete beginning matters because the students are not new to statistics. They’ve spent years learning frequentist methods, including maximum likelihood, confidence intervals, and p-values. So one major shift is learning to represent unknown parameters with probability distributions, rather than treating parameters as fixed quantities and uncertainty as being about an interval that either contains the parameter or does not.

Anna
Tommy says that transition takes time, but students often become excited when they encounter Monte Carlo methods. They can use samples from a probability distribution to estimate quantities they care about, including probabilities involving several random variables. Once students see how many questions they can ask with that approach, Bayesian modeling can feel powerful rather than merely unfamiliar.

Michael
Some of those students go on to contribute to the field themselves. Tommy mentioned a student working on a Google Summer of Code project involving Bambi, and the possibility of another student working on a hierarchical-model project. That’s a nice example of teaching, open-source software, and research feeding into one another.

Anna
Let’s explain Bambi. A useful shorthand is that it’s like brms for Python. In R, model formulas provide a compact way to say what the outcome is and which predictors explain it. A formula and a data frame can be passed to a function, which maps the variable names into a statistical model.

Michael
That formula approach is deeply established in R and has been extended by many packages. For example, mixed-effects or hierarchical models can express group-level structure through an extension of the formula syntax. Python is a general-purpose language rather than one with model formulas built in, but libraries such as Patsy brought formula-style model specification into Python, and other packages built on that foundation.

Anna
Bambi uses a similar formula interface to build Bayesian models in Python. Its name stands for Bayesian Model Building Interface, and it’s built on top of PyMC. Beyond specifying and fitting a model, Bambi offers tools for working with it, such as making predictions and calculating quantities of interest. It also provides default priors that can help someone start iterating quickly.

Michael
But defaults are a starting point, not a substitute for thinking carefully about the problem. Tommy’s point is that a quick first model can help you explore an idea; once the model is more refined, you should consider the priors deliberately. And there’s a trade-off in the interface: Bambi can express many models in just a few lines, while PyMC gives you greater flexibility when you need to write a more complex model directly.

Anna
Tommy’s first major contribution to Bambi was adding support for a formula syntax for random effects, which Python’s formula tools didn’t then provide. He wrote a parser for model formulas, and the project went on to expand its supported likelihoods and improve its default-prior capabilities. His work illustrates how a familiar, high-level interface can make Bayesian modeling easier to approach.

Michael
That accessibility is important for two groups. It helps beginners and students learn the structure of a model without immediately wrestling with every programming detail. And it helps people who are not statisticians but need to analyze data: they may know which model they want, yet find writing a full probabilistic program in PyMC—or coding everything in Stan—too demanding for the task.

Anna
Bambi can also support a faster modeling workflow. You can sketch and test an idea with the formula interface, then move to PyMC when you need more control. That doesn’t mean every project should stay with default settings or that Bambi can express every possible model. It means the interface can lower the initial barrier while preserving a path to more flexible modeling.

Michael
That’s the motivation behind the course Tommy helped create, Advanced Regression with Bambi and PyMC. It took about two years to develop and is designed as a next step for someone who has taken an introductory course and wants to learn more. ‘Advanced’ doesn’t mean beginning with the most intimidating mathematics; it means going beyond the brief treatment regression often gets in introductory statistics.

Anna
The course starts with simple and multiple linear regression, then expands to logistic and Poisson regression, categorical and multinomial regression, zero-inflated models, overdispersion, and hierarchical regression. It shows how to work with models using Bambi and PyMC, and uses visualizations to explore posterior distributions and predictions. The goal is not only to fit a model, but to understand what it says and how to assess it.

Michael
That broad view challenges the idea that regression is just a simple line relating one predictor to an outcome. Many models used in practice can be understood as linear models in a broader sense, including models for different types of outcomes and more elaborate structures. Getting comfortable with regression therefore builds tools that are useful well beyond an introductory linear-regression example.

Anna
A central theme of the course is parameter identifiability and overparameterization. In plain language, parameters are not identifiable when the information in the model cannot distinguish between some of their values. Overparameterization can arise when the model includes redundant parameters—so multiple ways of setting them describe the same thing.

Michael
For example, suppose a categorical outcome has N possible categories, each with a probability. Because those probabilities sum to one, once you know N minus one of them, the last is determined. Treating all N probabilities as independent quantities introduces redundancy. That’s not a problem unique to Bayesian statistics; it can occur in statistical models more generally.

Anna
The course returns to identifiability and redundancy across several lessons because they are easy to miss if they’re presented only once. Students examine different situations in which they occur and different ways to handle them. Repeatedly seeing the issue helps build intuition for recognizing it in models, rather than just memorizing a rule.

Michael
One common solution for categorical effects is reference encoding. You choose one category as a reference and fix its parameter—often to zero—then interpret the other category parameters relative to it. That’s useful when there’s a meaningful reference category, such as a control or placebo group.

Anna
Another option is a zero-sum parameterization. Instead of privileging one category as the reference, you constrain the category parameters to sum to zero. Then each parameter can be interpreted as an offset from the average across categories. That can be attractive when there isn’t an obvious category to use as the reference.

Michael
In PyMC, a ZeroSumNormal distribution makes that constraint relatively convenient to express. Rather than manually constructing a vector, appending a fixed zero, and managing the resulting parameterization, a user can use the distribution designed for the zero-sum structure. That’s also helpful for the software experience, though you still need to understand what the constraint does and how it changes the meaning of the parameters.

Anna
Exactly. There isn’t one parameterization that’s always right. The choice depends on the model and the interpretation you want. A reference category gives comparisons to that particular category; a zero-sum constraint gives comparisons around an overall average. The important habit is to think about the restriction you’re adding and what it means for the quantities you report.

Michael
Another substantial course topic is overdispersion: when the variability in the observed data is greater than the model’s assumed distribution accounts for. Tommy described spending more time than expected finding useful references and worked examples for this topic, including reading older research papers. That extra work shaped a lesson that doesn’t stop at fitting a model.

Anna
The lesson also explores how to diagnose whether a model is over- or under-dispersed relative to the data. It uses visual checks and a custom test statistic to examine the discrepancy. In Bayesian analysis, you have posterior samples to work with, so you can construct a statistic that addresses your particular question rather than relying only on a prepackaged test.

Michael
That’s a useful response to a common beginner’s question: ‘Can I calculate a test statistic in Bayesian statistics?’ Yes. You can define a statistic based on the problem you’re investigating and evaluate it using posterior draws. The key is to be clear about what the statistic measures and how it helps assess the model.

Anna
The hosts also emphasize visualization as a teaching and modeling tool. For each model, the course uses plots to inspect posterior distributions, explore predictions, and communicate findings. The aim is to go beyond showing a couple of numbers and make it easier to see what a model implies.

Michael
A related computational topic Tommy is exploring is sparse matrices. Many models involve multiplying a matrix by a vector. In a sparse matrix, most entries are zero, so multiplying every entry as if it were meaningful wastes both storage and computation. If the computer is told the matrix is sparse, it can store the nonzero entries more efficiently and avoid calculations that contribute nothing.

Anna
That can matter especially in Bayesian computation, where a model’s log probability and its derivatives may be evaluated many times during sampling. If those calculations repeatedly involve a large sparse matrix, making matrix-vector multiplication more efficient could reduce computation time. The mathematical operation is familiar; the challenge is representing and using the structure effectively in software.

Michael
PyTensor has some sparse-matrix support, but Tommy described it as having limitations, including differences across its C, Numba, and JAX backends. For particular projects, he has written custom operations for multiplying a sparse matrix by a dense vector and tested them with different backends. The longer-term goal would be broadly usable support, rather than a solution that works for only one specific model or backend.

Anna
So this is an open-source opportunity as much as a technical problem. Existing methods and ideas are available, but making them robust, tested, and accessible to the wider community takes design and programming work. Tommy said he’d welcome collaborators who are interested in contributing, even if they’re still learning the topic.

Michael
When he talked about what he wants to learn next, he mentioned hierarchical models and the value of understanding them from both computational exercises and more formal mathematical sources. He’s interested in the assumptions behind these models, what follows from those assumptions, and whether some computations can be avoided in particular cases.

Anna
He’s also thinking about situations where a general-purpose sampler may be inefficient. Hamiltonian Monte Carlo is powerful, but a model with a very large number of parameters can still take a long time. If you understand a model well, it may be worth considering whether a more specialized approach could help. That doesn’t diminish the value of general methods; it’s about knowing when the structure of a problem might offer another route.

Michael
Another interest is the connections among richly parameterized models. Models that look different on the surface can sometimes be related through their priors or mathematical structure. For example, a spline model and a hierarchical model can connect under particular choices. Seeing those relationships can deepen your understanding of both modeling approaches.

Anna
And if Tommy could solve one grand problem with unlimited time and resources, he’d love a method that produced reliable posterior samples without making users worry about divergences, convergence, or long sampling times. He enjoys learning how samplers work, but he imagines a tool that could handle those details so analysts could focus more on interpreting results.

Michael
His dinner guest would be Alan Turing. Tommy was fascinated by the story of codebreaking and by the mix of technical, political, and human decisions involved. He’d want to ask how the work was organized, how ideas were developed, and what it was like to decide how to use the information they uncovered.

Anna
We’ve covered a lot: a hands-on way to introduce Bayesian reasoning, the role of Bambi in making Bayesian regression more accessible, and the deeper challenges of regression models—from identifiability and overdispersion to computation with sparse matrices. The thread connecting them is that good statistical work takes both clear ideas and practical tools.

Michael
And the best way to learn those tools is to use them. For the course, that means doing the exercises, looking through the solutions, and asking and answering questions in the community—not only watching the videos. Building a model, checking its predictions, and understanding its assumptions are skills you develop through practice.

Ask anything
We've read this whole study set, so questions about it get the best answers.