Bayesian Statistics
Bayesian analysis treats unknown quantities as distributions rather than fixed points. You start with a prior belief about a parameter, observe data, and obtain a posterior that blends the two in proportion to how plausible each explanation of the data happens to be. The result answers questions people actually ask, such as the probability that a treatment is better rather than a binary verdict about whether a p-value fell below a threshold. This lesson builds that workflow with PyMC, from a first regression through hierarchical models and experimentation.
The update, explained without mysticism
Bayes' rule says the posterior is proportional to the likelihood times the prior. The likelihood asks how well a candidate parameter explains the observations you collected. The prior encodes what you believed beforehand, whether from domain knowledge, an earlier study, or deliberate scepticism. The normalising constant is the evidence, which is often intractable and almost always unnecessary for parameter inference because it does not depend on the parameter.
The practical consequence is that priors matter most when data are scarce and matter least when data are abundant. With fifty observations a weakly informative prior barely dents the posterior; with five observations it dominates, which is exactly what you want, because five points genuinely cannot overturn strong prior knowledge on their own. Where Bayesian and frequentist answers diverge, they usually diverge because of small samples, informative priors, or hierarchical structure rather than because one camp is cheating.
Choosing priors without starting an argument
A prior is a modelling decision that should be documented and stress-tested, not a default you inherit from a library. Three habits cover almost every case. First, keep parameters on sensible scales: a probability lives on the unit interval, a standard deviation is positive, and a regression slope for standardised inputs usually sits within a couple of units of zero. Second, prefer weakly informative priors that prevent absurd values rather than flat priors that assign mass to impossible ones. Third, run a sensitivity check by refitting with a tighter and a looser prior and comparing posteriors.
| Situation | Prior choice | Reasoning |
|---|---|---|
| Unknown probability | Beta with alpha and beta near 1 | Flexible, stays on the unit interval |
| Regression slope, standardised data | Normal centred at 0 with sigma of 2 to 5 | Shrinks implausible magnitudes without much bias |
| Positive scale parameter | HalfNormal or HalfCauchy | Enforces positivity and tolerates outliers |
| Group-level effect | Normal centred at 0 with estimated sigma | Lets the data decide how much groups differ |
Fitting a regression with PyMC
Once the model is written declaratively, PyMC samples it with a gradient-based Markov chain Monte Carlo method and hands back an InferenceData object that ArviZ can summarise, plot, and compare.
import pymc as pm
import numpy as np
import arviz as az
rng = np.random.default_rng(42)
n = 150
x = rng.uniform(0, 10, n)
y = 2.5 * x + 1.0 + rng.normal(0, 1.5, n)
with pm.Model() as regression:
slope = pm.Normal("slope", mu=0, sigma=10)
intercept = pm.Normal("intercept", mu=0, sigma=10)
sigma = pm.HalfNormal("sigma", sigma=5)
mu = slope * x + intercept
y_obs = pm.Normal("y_obs", mu=mu, sigma=sigma, observed=y)
trace = pm.sample(2000, tune=1000, cores=4, return_inferencedata=True)
print(az.summary(trace, var_names=["slope", "intercept", "sigma"]))
Two details matter more than they look. The observed argument is what separates parameters from data, and the number of tuning draws discarded before sampling determines how well the sampler adapts to the posterior geometry.
Reading an MCMC diagnostic before trusting it
A posterior sample is only as good as the sampler that produced it, so diagnostics come before interpretation. Rank plots and trace plots should look like a fuzzy caterpillar with no drift; a trend means the chain has not mixed. The R-hat statistic compares within-chain and between-chain variance and should sit close to 1.0, with anything above 1.01 treated as a failure rather than a rounding error. Effective sample size tells you how many independent draws your correlated chain is really worth.
import arviz as az
def diagnose(trace, var_names=None):
"""Run the standard convergence checks and summarise them."""
rhat = az.rhat(trace, var_names=var_names)
ess = az.ess(trace, var_names=var_names)
divergences = 0
if hasattr(trace, "sample_stats") and trace.sample_stats is not None:
divergences = int(trace.sample_stats.diverging.sum())
return {
"max_rhat": float(rhat.max()),
"min_ess": float(ess.min()),
"divergences": divergences,
"converged": bool(rhat.max() < 1.01 and divergences == 0),
}
print(diagnose(trace, var_names=["slope", "intercept", "sigma"]))
Divergences deserve special attention. They mean the sampler could not faithfully explore a region of the posterior, often because a prior is too tight or a parameterisation creates a funnel. Reparameterising with a non-centred construction usually fixes it; simply raising the target acceptance probability only hides it.
Hierarchical models and partial pooling
Grouped data rarely behave as if every group were independent, nor as if every group were identical. Hierarchical models split the difference through partial pooling: each group gets its own estimate, but those estimates are drawn from a shared distribution whose spread is itself learned. Small groups shrink toward the global mean, large groups stand mostly on their own, and the amount of shrinkage is inferred rather than argued about.
import pymc as pm
import numpy as np
n_groups, n_per_group = 12, 25
rng = np.random.default_rng(7)
group_effect = rng.normal(0, 1.5, n_groups)
group_ids = np.repeat(np.arange(n_groups), n_per_group)
x = rng.normal(0, 1, n_groups * n_per_group)
y = 3 * x + group_effect[group_ids] + rng.normal(0, 1, x.size)
with pm.Model() as hierarchical:
mu_global = pm.Normal("mu_global", mu=0, sigma=5)
sigma_global = pm.HalfNormal("sigma_global", sigma=5)
offset = pm.Normal("offset", mu=0, sigma=1, shape=n_groups)
group_intercept = pm.Deterministic(
"group_intercept", mu_global + sigma_global * offset
)
slope = pm.Normal("slope", mu=0, sigma=10)
sigma = pm.HalfNormal("sigma", sigma=5)
y_obs = pm.Normal(
"y_obs", mu=slope * x + group_intercept[group_ids],
sigma=sigma, observed=y
)
trace_h = pm.sample(2000, tune=1000, cores=4)
The non-centred parameterisation above, where the group effect is built from a standard normal offset scaled by sigma_global, is the standard fix for the funnel geometry that otherwise causes divergences.
Bayesian A/B testing you can defend
Experimentation is where Bayesian reporting shines, because the natural output is the probability that one variant beats another. Fit a Beta-Binomial model for conversion rates, then derive lift and the probability of superiority directly from the posterior draws.
import pymc as pm
import arviz as az
def bayesian_ab_test(conv_a, n_a, conv_b, n_b, draws=4000):
with pm.Model() as ab:
p_a = pm.Beta("p_a", alpha=1, beta=1)
p_b = pm.Beta("p_b", alpha=1, beta=1)
pm.Binomial("obs_a", n=n_a, p=p_a, observed=conv_a)
pm.Binomial("obs_b", n=n_b, p=p_b, observed=conv_b)
lift = pm.Deterministic("lift", (p_b - p_a) / p_a)
better = pm.Deterministic("better", pm.math.gt(p_b, p_a))
trace = pm.sample(draws, tune=2000, cores=4, return_inferencedata=True)
return {
"rate_a": conv_a / n_a,
"rate_b": conv_b / n_b,
"lift_mean": float(trace.posterior["lift"].mean()),
"lift_hdi": az.hdi(trace, var_names=["lift"])["lift"].values.tolist(),
"prob_b_better": float(trace.posterior["better"].mean()),
}
print(bayesian_ab_test(120, 1000, 150, 1000))
Report the probability of superiority and the credible interval on lift, and stakeholders stop asking what a p-value means.
Checking the model against the data it claims to explain
Sampling a posterior successfully does not mean the model is any good. A posterior predictive check pushes the fitted model forward: you draw replicated datasets from the posterior and compare them with the observations you actually collected. If the replicated data systematically miss the spread, the tails, or the grouping structure, the model is wrong in a way its parameter estimates will never reveal.
The checks you run depend on what could plausibly go wrong. Compare histograms of the observed and replicated values for shape, then compare summary statistics such as the maximum, the standard deviation, and the count of extreme values. For grouped data, plot group means side by side. For time series, look at the distribution of run lengths and autocorrelation. A model that reproduces the mean but not the variance is a common failure, and it silently inflates your certainty.
Treat a failed check as a modelling task rather than a nuisance: add the missing structure, refit, and check again.
import pymc as pm
import arviz as az
import numpy as np
with regression:
ppc = pm.sample_posterior_predictive(trace, var_names=["y_obs"])
observed = trace.observed_data["y_obs"]
replicated = ppc.posterior_predictive["y_obs"]
print("observed mean/std:", float(observed.mean()), float(observed.std()))
print("replicated mean/std:", float(replicated.mean()), float(replicated.std()))
tails = np.abs(observed - observed.mean()) > 3 * observed.std()
rep_tails = (np.abs(replicated - replicated.mean()) > 3 * replicated.std()).mean()
print(f"observed extremes: {int(tails.sum())}, replicated rate: {float(rep_tails):.4f}")
Comparing models the honest way
Fitting several models and eyeballing their posteriors invites overfitting by committee. Information criteria give a principled comparison instead. WAIC and leave-one-out cross-validation both estimate out-of-sample predictive accuracy while penalising effective complexity, and they are computed from the posterior draws you already have. The comparison table ranks models by expected accuracy and reports the standard error of each difference, which matters because a gap smaller than its own error bar is not a ranking at all.
When two models are statistically indistinguishable, prefer the simpler one: it will extrapolate better, explain easier, and remain stable under small data shifts. Save the complex model for cases where it wins by a margin that survives the error bar.
Common Mistakes
Reporting a posterior mean without ever looking at R-hat, effective sample size, or divergences
Fix: Treat diagnostics as a gate: if R-hat exceeds 1.01 or divergences are non-zero, fix the model before interpreting any number.
Setting an extremely vague prior because it feels objective
Fix: Use a weakly informative prior on a sensible scale and run a sensitivity check with a tighter alternative.
Fitting separate models per group and comparing them informally
Fix: Use a hierarchical model so small groups shrink toward the shared mean and the pooling amount is estimated.
Best Practices
- Standardise predictors so priors can be written on a common scale
- Reparameterise non-centred when a hierarchical model produces funnels or divergences
- Report credible intervals and probabilities of superiority, not just point estimates
- Compare competing models with WAIC or LOO rather than in-sample fit
- Document the prior and the sensitivity check alongside the results
Key Takeaways
- The posterior combines prior and likelihood, so priors dominate only when data are thin
- Diagnostics precede interpretation: R-hat near 1.0, healthy effective sample size, zero divergences
- Hierarchical models deliver partial pooling, the correct default for grouped data
- Bayesian experiments report the probability a variant is better, which stakeholders understand
- Model comparison should use out-of-sample criteria such as WAIC or LOO