Bayesian inference and MCMC

Bayesian inference and MCMC

How Bayes' theorem updates prior beliefs with data into a posterior distribution, and how Markov chain Monte Carlo sampling makes this possible for models too complex to solve exactly.

What it is

Bayesian inference is a way of learning from data in which uncertainty about unknown quantities, such as a rate constant, a treatment effect or a population mean, is expressed as a probability distribution. A prior distribution encodes what is known before the experiment, the data update it through the likelihood, and the result is a posterior distribution that states what is believed afterward. For all but the simplest models the posterior cannot be written in closed form, and Markov chain Monte Carlo (MCMC) methods draw random samples from it, which makes modern Bayesian analysis practical. It is used in physics, ecology, medicine, machine learning, astronomy and engineering.

It answers questions such as: What is the probability that the effect exceeds zero, given these data? What range of values is the parameter likely to lie in? How should prior knowledge, such as earlier studies, be combined with new measurements? Which of two models is better supported? Unlike a p-value, the posterior gives direct probability statements about parameters.

Fundamentals

Bayes’ theorem

For parameters θ and data D:

p(θ | D) = p(D | θ) p(θ) / p(D)

Here p(θ) is the prior, p(D | θ) is the likelihood (probability of the data for each θ), p(θ | D) is the posterior and p(D) = ∫ p(D | θ) p(θ) dθ is the marginal likelihood (evidence), a normalizing constant. Since p(D) does not depend on θ, the posterior is proportional to likelihood × prior. A classic example is the beta–binomial model: with a Beta(a, b) prior on a success probability and k successes in n trials, the posterior is exactly Beta(a + k, b + n − k), a conjugate update. Choosing priors can be informative (from earlier studies or physical limits), weakly informative (rule out absurd values, such as Normal(0, 10) for a standardized coefficient) or non-informative (flat or Jeffreys priors, although “flat” is not truly neutral under reparameterization). Sensitivity of results to the prior should be checked.

Summarizing the posterior

Posterior summaries include the mean, median or mode (MAP estimate), and credible intervals: a 95% credible interval contains the parameter with 95% posterior probability, a direct statement unlike the frequentist confidence interval, whose meaning relates to repeated sampling. Equal-tailed intervals use the 2.5th and 97.5th percentiles, and highest posterior density (HPD) intervals are the shortest regions containing 95%. Hypotheses are assessed by posterior probabilities such as P(θ > 0 | D), regions of practical equivalence (ROPE), or Bayes factors, BF10 = p(D | M1)/p(D | M0) (values above 10 are often called strong evidence, though they are sensitive to priors).

Why MCMC: sampling the posterior

Integrals over many parameters are intractable analytically, and grid approximations fail in high dimensions. MCMC builds a Markov chain whose long-run distribution is the posterior, so the chain’s samples can approximate any posterior quantity: the mean is estimated by the sample average, a probability by a sample fraction. The key algorithms are:

  • Metropolis–Hastings: from the current θ, propose θ′ from a proposal distribution q(θ′ | θ) and accept with probability min[1, p(θ′ | D) q(θ | θ′) / (p(θ | D) q(θ′ | θ))]. Only the unnormalized posterior is needed, since p(D) cancels.
  • Gibbs sampling: update each parameter in turn by sampling from its full conditional distribution (always accepted), efficient for conjugate hierarchical models (BUGS, JAGS).
  • Hamiltonian Monte Carlo (HMC) and the No-U-Turn Sampler (NUTS): use gradients of the log posterior to simulate physical motion over the posterior surface, making distant yet informed proposals; they explore high-dimensional posteriors much more efficiently and are the default in Stan, PyMC and NumPyro.

Diagnosing the chains

MCMC samples are autocorrelated, and chains begin away from the high-probability region, so convergence must be checked rather than assumed. Run several chains from dispersed starting points, discard a warm-up (burn-in) period, and examine: trace plots (chains should overlap and look like noise, “hairy caterpillars”); the R̂ (Gelman–Rubin) statistic, comparing between-chain and within-chain variance (should be below 1.01 for each parameter); the effective sample size (ESS), the number of independent draws equivalent to the correlated chain, ESS = N / (1 + 2 Σ ρt) (hundreds are usually needed for means and more for tail intervals); and divergent transitions in HMC, which signal problematic posterior geometry (often cured by reparameterization, such as non-centered forms for hierarchical models). Posterior predictive checks, which simulate data from the fitted model and compare with observed data, assess model adequacy, and leave-one-out cross-validation (LOO-CV) or WAIC compares predictive performance of models.

Hierarchical models and workflow

Bayesian methods handle hierarchical models naturally, with group parameters drawn from a population distribution, giving partial pooling (see mixed-effects models). The workflow is iterative: check priors with prior predictive simulations, fit, diagnose, check against data, revise and compare models. Software includes Stan (via rstan, brms), PyMC, NumPyro, JAGS and emcee. Costs are computing time, modeling expertise and the need to state priors openly.

Typical applications and limits

Applications include adaptive clinical trials, cosmological parameter estimation, inverse problems and calibration of simulation models, species abundance models and A/B testing. Limits include prior dependence with sparse data, long run times for large models, hard-to-diagnose convergence in multimodal posteriors, and the risk that a well-sampled posterior still comes from a misspecified model.

Basic operation

  1. Define the model. Write the likelihood for the data and the parameters of interest.
  2. Choose priors. Use weakly informative or evidence-based priors and test them with prior predictive simulation.
  3. Fit with MCMC. Run 4 chains with HMC/NUTS or another sampler and a warm-up phase.
  4. Diagnose convergence. Check R̂, ESS, trace plots and divergences.
  5. Check the model. Compare posterior predictive simulations with the data.
  6. Summarize the posterior. Report means or medians, credible intervals and relevant probabilities.
  7. Test sensitivity and compare models. Vary priors and use LOO-CV or Bayes factors.
  8. Collect the output. You obtain posterior samples and summaries; prior choice and hierarchical models are covered in the video.

Good practice

  • State priors openly. Justify them and test sensitivity.
  • Run several chains. Do not trust a single run.
  • Check diagnostics before interpreting. Poor R̂ or ESS invalidates results.
  • Use posterior predictive checks. A converged chain does not mean a good model.
  • Report intervals, not just point estimates. Uncertainty is the main output.
  • Be transparent and reproducible. Share code, seeds and software versions, and avoid choosing priors after seeing results to obtain a desired conclusion.

Key terms

  • Prior / posterior — beliefs about a parameter before and after seeing the data.
  • Likelihood — the probability of the observed data for a given parameter value.
  • Credible interval — an interval containing the parameter with stated posterior probability.
  • MCMC — Markov chain Monte Carlo, sampling from a distribution with a random walk.
  • R̂ (R-hat) — a diagnostic comparing variation between and within chains.
  • Effective sample size — the number of independent samples equivalent to a correlated chain.
  • Bayes factor — the ratio of marginal likelihoods of two models.

Video coming soon

About five minutes on Bayesian inference and MCMC: how it works in detail, how the data is acquired, and how it is analyzed.

Shopping cart

0
image/svg+xml

No products in the cart.

Continue Shopping