Advanced Bayesian Regression
Bayesian Regression, Model Design, and Efficient Computation
Introducing Bayesian Statistics Through a Concrete Problem
A practical teaching exercise can introduce Bayesian reasoning through a familiar object, such as colored candies. Students investigate whether a machine producing a particular color is malfunctioning.
From observations to a statistical model
Students work in groups to count the candies of each color in a bag. They then identify the quantity that would help answer the factory owner’s question: the proportion of candies that have the color of interest.
The reasoning proceeds step by step:
Define the unknown quantity. Let p represent the proportion of candies that are the color of interest.
Describe plausible values. Since p is a proportion, it must lie between 0 and 1.
Represent prior knowledge. Students consider whether every possible value of p is equally plausible. Knowledge about the product or its manufacturing process may make some values more plausible than others.
Model the data. If each candy is treated as an independent trial with the same probability p of having the target color, the number of target-color candies in a bag of fixed size can be modeled with a binomial distribution.
Combine prior knowledge and evidence. The prior distribution represents what was plausible about p before counting the candies; the observed count updates that distribution to produce a posterior distribution.
If Y is the number of candies of the target color among n candies, the likelihood is:
The Bayesian update can be written as:
This exercise makes the components of Bayesian inference tangible: an unknown quantity, a prior distribution, a model for the observations, and an updated posterior distribution. It also prompts discussion of the binomial model’s assumptions, especially independence and a constant probability of the target color across trials.
The activity is effective because it begins with a concrete question rather than a list of abstract terms. Students can connect their knowledge of the situation to a prior distribution, carry out simple probability calculations, and see how data change what is believed about an unknown quantity.
Bayesian Reasoning and Monte Carlo Computation
Parameters as uncertain quantities
In Bayesian statistics, unknown parameters are represented with probability distributions. The posterior distribution expresses uncertainty about parameter values after accounting for both prior information and observed data.
This differs from the common frequentist framing in which a parameter is treated as fixed, while an interval estimate is interpreted in relation to repeated sampling. Students familiar with frequentist estimation, confidence intervals, and p-values may initially find the Bayesian treatment of parameters as uncertain quantities unfamiliar. Making that shift requires learning to reason about distributions over parameters rather than only point estimates or fixed-parameter intervals.
Why Monte Carlo methods are useful
Monte Carlo computation uses draws from a probability distribution to approximate quantities of interest. Once posterior draws are available, they can be used to estimate many kinds of summaries, including probabilities involving one or more unknown quantities.
This flexibility is especially valuable when the desired summary is not a simple parameter estimate. Rather than relying on a single predefined statistic, analysts can compute posterior quantities that match their substantive question. The central idea is to use the posterior draws to answer questions about the model and its predictions.
Bayesian Model Building with Bambi
Formula-based model specification
Bambi—short for Bayesian Model Building Interface—provides a high-level interface for specifying and fitting Bayesian regression models in Python. Its formula syntax is inspired by the approach commonly used in R. A model can be described in terms of an outcome and its predictors, for example, y∼x1+x2.
A formula-based interface connects the names of variables in a data frame to the corresponding parts of a statistical model. The user describes the model at a relatively high level rather than writing every computational detail directly.
In Python, formula-based modeling has been supported by libraries such as Patsy, which other statistical tools can build on. Bambi applies this style of model specification in a Bayesian setting and is built on PyMC.
What Bambi provides
Bambi supports more than model fitting. It also provides tools and workflows for tasks such as:
Obtaining predictions from fitted models.
Calculating summaries relevant to a particular analysis.
Choosing sensible initial priors for a modeling problem.
Specifying regression structures, including hierarchical or mixed-effects structures.
The terminology for hierarchical models varies across statistical traditions and software. Structures often called random effects, mixed-effects models, or hierarchical models describe related kinds of models.
Why use a high-level interface?
Bambi makes Bayesian modeling more accessible to people who understand their statistical problem but may not be experienced with probabilistic programming. It can lower the programming barrier for analysts who want to fit a known type of model without manually handling all of the model’s indexing and computational structure.
The interface is also useful for rapid model development. A model can be specified and revised quickly, which helps analysts explore a modeling idea before investing in a more detailed implementation.
There is an important trade-off:
Bambi: Offers concise, high-level model specification and convenient modeling tools, but does not expose every possible modeling choice.
PyMC: Offers greater flexibility for specifying complex or unusual models, but requires more direct work with the probabilistic program.
Thus, a practical workflow can begin with Bambi for quick exploration and move to PyMC when a model requires finer control.
The role of default priors
Default priors can help a user quickly build and iterate on a model. They are a convenience, not a substitute for thinking about the problem. A sensible workflow may use defaults during initial exploration, then revisit and refine the priors as the model and the substantive question become clearer.
Regression Models and Their Range
Regression is broader than the simple linear regression often introduced in an introductory statistics course. It is a family of modeling approaches for relating an outcome to predictors, with different forms used for different outcome types and data structures.
Examples include:
Simple linear regression: Relates an outcome to one predictor.
Multiple linear regression: Relates an outcome to several predictors.
Logistic regression: Models outcomes such as binary categories.
Poisson regression: Models count outcomes.
Categorical regression: Handles outcomes with categories.
Multinomial regression: Models outcomes with multiple possible categories.
Zero-inflated regression: Accommodates settings where a model must account for an unusual abundance of zero observations.
Overdispersed regression: Addresses data that vary more than the initial model allows.
Hierarchical regression: Represents grouped or nested structure through group-level parameters.
Many of these models can be understood as extensions of general regression ideas rather than as unrelated techniques. The choice of model depends in part on the kind of outcome being modeled and the structure of the data.
A regression analysis also involves more than fitting a model and reporting a few numbers. Predictions, visualizations, diagnostics, and interpretation are important parts of understanding whether the model is useful and what it implies.
Identifiability and Overparameterization
What the problems mean
A model is identifiable when the available information and the model structure allow its parameters to be distinguished. If different parameter settings produce the same observable behavior, the data cannot determine which setting is responsible.
Overparameterization occurs when a model includes more distinct parameter freedom than its structure can support. It can create redundancy: one parameter may be determined by, or indistinguishable from, other parameters.
These problems are not unique to Bayesian models. They can arise in statistical models more generally, and they can affect estimation, interpretation, and computation. Recognizing them requires examining what the parameters mean and how the model combines them.
Example: category parameters in a multinomial model
For an outcome with K categories, the category probabilities must sum to one:
This means that only K−1 probabilities can vary freely. Once those K−1 probabilities are known, the remaining probability is determined:
Treating all K probabilities as independent free quantities would introduce a redundant parameterization. Regression models for categorical outcomes can present related identification issues in their category-specific parameters.
Reference encoding
One common solution is reference encoding:
Select one category as the reference.
Fix that category’s parameter to a chosen value, commonly zero.
Interpret the other category parameters relative to the reference.
This removes the redundant freedom, but it also gives the parameters a particular interpretation: they describe differences from the chosen reference category. Reference encoding is especially natural when there is a meaningful baseline, such as a control or placebo category.
Zero-sum parameterization
Another approach is to constrain the category parameters to sum to zero. A zero-sum normal distribution provides a convenient way to express normally distributed parameters under that constraint.
Under this approach, no single category must serve as the reference. Instead, category-specific parameters are interpreted as deviations around an overall average. This can be useful when there is no natural baseline category or when a symmetric treatment of the categories is desirable.
The two approaches solve a related redundancy problem but express the parameters differently:
Reference encoding: Parameters are contrasts against one selected category.
Zero-sum encoding: Parameters are deviations from the average across categories.
The appropriate choice depends on the model and the scientific question. A parameter constraint changes the interpretation of the parameters, so it should be chosen deliberately rather than treated as a purely computational setting.
Overdispersion and Model Checking
Overdispersion occurs when observed data vary more than the fitted model adequately represents. A model that fails to capture this variation may give predictions that are too concentrated or otherwise misrepresent uncertainty. A related diagnostic possibility is underdispersion, in which the model’s predictions are less variable than the observed data.
Assessing dispersion involves comparing the behavior of model predictions with the data. Useful practices include:
Creating plots that reveal mismatches in variability.
Comparing model-generated data with observed data.
Defining a statistic that summarizes the aspect of dispersion being investigated.
Evaluating that statistic using posterior samples.
A diagnostic statistic need not be chosen from a fixed, universal list. Posterior samples allow analysts to define a custom test statistic that directly addresses the model feature of concern. The statistic can then be compared between observed data and data generated under the model.
This approach illustrates a broader benefit of Bayesian modeling: posterior draws can support diagnostics tailored to the substantive problem, rather than limiting analysis to a small set of prepackaged summaries.
Sparse Matrices and Faster Computation
What makes a matrix sparse?
A sparse matrix contains mostly zero entries. A dense representation stores every entry, including the many zeros. A sparse representation stores information in a way that takes advantage of the matrix’s pattern of nonzero values.
When a sparse matrix is multiplied by a dense vector, many terms in the calculation contribute nothing because they are multiplied by zero. A computation that ignores those zero entries can therefore use less memory and perform fewer operations.
For a matrix A and vector x, the product is:
If most entries of A are zero, a sparse implementation can avoid repeatedly processing those entries. This can make matrix-vector multiplication more efficient.
Why this matters for Bayesian computation
Linear models often involve matrix-vector products. During Markov chain Monte Carlo, including methods that repeatedly evaluate a model’s log probability and its derivatives, these operations may be performed many times. Improving the efficiency of repeated matrix operations can therefore reduce computation time.
Sparse-matrix support is not only a storage issue. The software must also perform the relevant operations efficiently. Support can differ across computational backends, such as C, Numba, and JAX, so an implementation that works in one setting may not be available or equivalent in another.
Matrix structure can offer further opportunities for optimization. Beyond sparsity, particular structures may allow operations such as products, inverses, transposes, or determinants to be computed more efficiently. Making such techniques broadly usable requires implementation, testing, and support across relevant computational environments.
Hierarchical Models and Connections Between Models
Hierarchical models are a rich area of study because their assumptions affect both interpretation and computation. Building understanding through computational exercises can help develop intuition; studying the mathematical properties adds insight into the assumptions a model makes and the consequences of those assumptions.
Models that initially appear different can sometimes be connected through their priors and structure. For example, a model using splines may be related to a hierarchical model under particular prior choices. Recognizing these connections helps explain how modeling approaches fit into a larger framework and when one formulation can be understood through another.
Learning these relationships also supports better computational decisions. Understanding a model’s structure can help determine whether a general-purpose sampler is appropriate or whether some feature of the model can be exploited to make computation more efficient.
MCMC, Sampling, and Computational Goals
Markov chain Monte Carlo methods generate draws used to approximate posterior distributions. Working with these methods involves more than obtaining samples: analysts may need to consider compilation time, sampling time, convergence, and diagnostic warnings such as divergences.
A general-purpose sampler can be highly effective, but it does not eliminate the need to understand the model. Some models may benefit from methods tailored to their structure, and knowledge of the model’s mathematical properties may reveal opportunities to avoid unnecessary computation or use a specialized sampling strategy.
An ideal future system would automatically recognize relevant model structure and choose an effective way to produce posterior draws, allowing analysts to focus more on interpreting results and less on sampler-specific difficulties. In practice, however, reliable sampling still requires attention to both the statistical model and the computational method used to fit it.

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