Bayesian Inference: From Bayes' Theorem to MCMC
A mathematical deep dive into Bayesian inference — from its foundational theorem through conjugate priors and on to Markov Chain Monte Carlo methods for intractable posteriors.
Bayesian inference is a framework for updating beliefs about the world as new evidence arrives. At its core is one equation — Bayes' theorem — but the implications span everything from A/B testing to large-scale neural network training.
This post walks through the theory step by step: from the theorem itself, through conjugate priors (where the math is clean), and into MCMC (where math meets computation).
1. The Theorem
Bayes' theorem follows directly from the definition of conditional probability:
| Symbol | Name | Example |
|---|---|---|
| Posterior | Probability of disease given a positive test | |
| Likelihood | Probability of positive test given disease | |
| Prior | Base rate of disease in the population | |
| Evidence | Overall probability of a positive test |
In parameter estimation, we rewrite it with (the parameters) and (the data):
The denominator expands via the law of total probability:
This integral is the normalising constant — and it's often the hardest part.
Key insight: The posterior is proportional to likelihood × prior. The denominator is just a scale factor:
Deeper: This proportionality is why MCMC methods work — we can sample from the posterior without ever computing , as long as we can evaluate the numerator up to a constant.
2. Conjugate Priors
A prior is conjugate to a likelihood when the posterior has the same functional form as the prior.
Beta-Binomial
The classic example: binomial likelihood + beta prior = beta posterior.
The beta distribution's PDF:
where is the beta function:
Common conjugate pairs
| Likelihood | Prior | Posterior |
|---|---|---|
| (known ) | ||
The Gaussian-normal conjugate posterior demonstrates precision-weighted averaging. The posterior mean:
This is a precision-weighted combination of the prior mean and the data mean . As , the data dominates and .
3. When Conjugacy Breaks
For most real-world models, no conjugate prior exists and the evidence integral becomes intractable:
This is where we turn to Markov Chain Monte Carlo.
4. Markov Chain Monte Carlo
MCMC constructs a Markov chain whose stationary distribution is the posterior . After enough steps, samples from the chain approximate samples from the posterior.
Metropolis-Hastings
The algorithm:
- Start at initial
- For to :
- Propose
- Compute the acceptance ratio:
- Accept with probability
Intuition: Always move to a more probable state; sometimes move to a less probable state (proportional to the ratio). This prevents the chain from getting stuck in local modes.
A minimal Python implementation:
import numpy as np
def metropolis_hastings(
log_posterior, # function: log P(theta | D)
proposal_sampler, # function: draw theta* ~ q(· | theta)
proposal_log_prob, # function: log q(theta* | theta)
theta_0, # initial position
n_steps: int = 10_000,
):
samples = [theta_0]
current = theta_0
for _ in range(n_steps):
proposed = proposal_sampler(current)
# log acceptance ratio
log_alpha = (
log_posterior(proposed)
+ proposal_log_prob(current, proposed)
- log_posterior(current)
- proposal_log_prob(proposed, current)
)
if np.log(np.random.uniform()) < log_alpha:
current = proposed # accept
samples.append(current)
return np.array(samples)For a symmetric proposal (e.g. random-walk: ), the ratio simplifies because the proposal terms cancel:
Burn-in and thinning
Two practical concerns when sampling:
- Burn-in — discard the first samples while the chain converges
- Thinning — keep every -th sample to reduce autocorrelation
The number of effective samples is:
where is the autocorrelation at lag .
A healthy chain:
| Metric | Healthy | Unhealthy |
|---|---|---|
| Acceptance rate | 25–50% | < 1% or > 80% |
| Trace plot | Hairy caterpillar | Stays in place or zigzags |
| (Gelman-Rubin) | < 1.01 | > 1.1 |
| Effective sample size | > 1 000 per chain | < 100 |
Hamiltonian Monte Carlo
For high-dimensional posteriors, Metropolis-Hastings explores too slowly. HMC augments the parameter space with momentum variables and simulates Hamiltonian dynamics to propose distant states with high acceptance.
The Hamiltonian:
where is the momentum and is the mass matrix. The leapfrog integrator discretises the dynamics:
def leapfrog(theta, r, grad_log_p, step_size, n_steps):
"""Simulate Hamiltonian dynamics."""
r += 0.5 * step_size * grad_log_p(theta)
for _ in range(n_steps - 1):
theta += step_size * r
r += step_size * grad_log_p(theta)
theta += step_size * r
r += 0.5 * step_size * grad_log_p(theta)
return theta, rHMC is the backbone of modern probabilistic programming languages like Stan and PyMC.
5. Bayesian vs Frequentist
| Aspect | Bayesian | Frequentist |
|---|---|---|
| Parameters are… | Random variables | Fixed unknowns |
| Probability of… | under repeated sampling | |
| Interval | 95% credible interval | 95% confidence interval |
| Prior | Required | Not used |
| Best for | Complex models, small data, sequential learning | Well-understood sampling distributions |
A concrete example
A coin flipped 10 times lands heads 8 times. Estimate (probability of heads).
Bayesian with a (uniform) prior:
Posterior mean:
95% credible interval:
Frequentist maximum likelihood estimate:
95% Wald confidence interval:
Both give similar numeric answers, but the interpretation is radically different — the Bayesian can directly state "there's a 95% probability lies in ", while the frequentist must say "95% of such intervals would contain the true ".
Wrapping Up
Bayesian inference is beautiful theory — but it's also practical. With MCMC, you can fit models that would be impossible with closed-form statistics.
What to explore next
- Derive Bayes' theorem from the product rule of probability
- Compute a Beta-Binomial posterior by hand
- Implement Metropolis-Hastings for a simple problem
- Read Statistical Rethinking by Richard McElreath
- Explore Hamiltonian Monte Carlo for higher dimensions
- Compare credible vs confidence intervals on real data
Further reading
| Resource | Author | Why |
|---|---|---|
| Statistical Rethinking | McElreath | Best conceptual intro, with R + Stan code |
| Bayesian Data Analysis | Gelman et al. | The canonical graduate text |
| Pattern Recognition and Machine Learning | Bishop | Chapter 2 covers conjugate priors |
| Bayesian Methods for Hackers | Davidson-Pilon | Free, Python-based, intuitive |
"All models are wrong, but some are useful." — George Box (1976)