Overview

5 Monte Carlo methods: Inference by sampling: Being a tour guide for unknown Bayesian posteriors

This chapter introduces Monte Carlo sampling as the practical answer to Bayesian posteriors that cannot be worked out in closed form. Earlier examples were easy because conjugate priors made the posterior analytically tractable, but realistic models often require priors that better reflect domain knowledge, even when that breaks conjugacy. In those cases, the posterior is still defined by Bayes’ theorem, but only up to a constant that is hard to compute. Instead of solving the posterior exactly, we generate samples from it and use those samples as a stand-in for the full distribution.

The chapter then explains why sampling works and why Markov chain Monte Carlo is so useful. Good samples should ideally be independent and identically distributed, but that is difficult to obtain directly from complex posteriors, especially in high-dimensional spaces where grid-based methods become infeasible. MCMC avoids this curse of dimensionality by constructing a chain that moves through the parameter space, spending more time in regions of higher posterior density. The Metropolis–Hastings algorithm is presented as a concrete example: propose a move from the current state, compare posterior densities through an accept/reject rule, and either move or stay put. This produces dependent samples, but if designed well, the chain still approximates the target posterior effectively.

The final part focuses on how to use MCMC responsibly in practice. It recommends discarding early samples during burn-in, running multiple chains from different starting points, checking convergence with statistics such as R-hat, and evaluating effective sample size to judge how informative the draws are. It also emphasizes inspecting trace plots for good mixing, where chains should move around the target distribution smoothly rather than get stuck, and performing posterior predictive checks to verify that the model reproduces observed data well. Using PyMC and ArviZ, the chapter shows how these ideas are implemented in software, making sampling-based Bayesian inference both practical and diagnostically sound.

Comparison between a posterior distribution available in closed form and Monte Carlo samples. The samples’ histogram matches the true PDF, and the various statistics from the samples give reasonable approximations to the corresponding true quantities.
Comparison between a posterior distribution available in closed form and Monte Carlo samples. The samples’ histogram matches the true PDF, and the various statistics from the samples give reasonable approximations to the corresponding true quantities.
We need exponentially more samples for a grid approximation as the dimensionality grows.
We need exponentially more samples for a grid approximation as the dimensionality grows.
Differences between i.i.d. sampling (left) and MCMC (right). MCMC generates a chain of dependent samples (order indicated by arrows) that approximates the distribution.
Differences between i.i.d. sampling (left) and MCMC (right). MCMC generates a chain of dependent samples (order indicated by arrows) that approximates the distribution.
Comparison between samples during and after the burn-in period. Burn-in samples might not represent the target distribution well, so we should remove these initial samples prior to any subsequent analysis.
Comparison between samples during and after the burn-in period. Burn-in samples might not represent the target distribution well, so we should remove these initial samples prior to any subsequent analysis.
Various statistics describing the posterior samples generated by PyMC. The R̂ statistic at the end indicates that our MCMC chains have converged, while ESS statistics tell us about the effective sample size.
Various statistics describing the posterior samples generated by PyMC. The R̂ statistic at the end indicates that our MCMC chains have converged, while ESS statistics tell us about the effective sample size.
Left: the distribution of the posterior samples of 𝑝 from the four chains. Right: The trace plot of these chains, which shows hairy caterpillar patterns indicating good mixing.
Left: the distribution of the posterior samples of 𝑝 from the four chains. Right: The trace plot of these chains, which shows hairy caterpillar patterns indicating good mixing.
Posterior predictive check plot generated by ArviZ. The observed data lies inside the range simulated by the posterior predictive samples, indicating that our model passes the posterior predictive check.
Posterior predictive check plot generated by ArviZ. The observed data lies inside the range simulated by the posterior predictive samples, indicating that our model passes the posterior predictive check.

Summary

  • Monte Carlo (MC) methods approximate posteriors by generating samples instead of deriving them analytically.
  • Conjugate priors allow exact posteriors, but many real-world problems require non-conjugate priors that make closed-form solutions impossible.
  • MC sampling works even when we know only the unnormalized posterior, allowing us to compute statistics like means, credible intervals, and tail probabilities.
  • Independent and identically distributed (i.i.d.) samples are the gold standard, but are unavailable when the posterior is not analytically tractable; Markov chain Monte Carlo (MCMC) generates dependent samples that still approximate the target.
  • Grid approximation works only in low dimensions and wastes computation on low-density regions.
  • MCMC uses a chain of dependent samples to efficiently explore the posterior’s high-density regions.
  • Metropolis–Hastings builds this chain by proposing moves from a proposal distribution and accepting/rejecting based on posterior density ratios.
  • Discarding burn-in MCMC samples removes bias from poor starting points.
  • Running multiple MCMC chains avoids dependence on any single initialization.
  • We can assess MCMC convergence using R̂ (close to 1) and sampling efficiency using ESS (at least 400 for bulk and tail).
  • When checking mixing via trace plots, look for “hairy caterpillars,” not flat lines or jumps.
  • Perform posterior predictive checks to ensure simulated data matches observed data.
  • PyMC provides simple, readable syntax and integrates tightly with ArviZ for diagnostics and visualization.

FAQ

1. Why do Bayesian models sometimes need sampling methods instead of closed-form posteriors?When the prior is not conjugate to the likelihood, the posterior may still be defined mathematically but become too difficult to derive or normalize in closed form. Sampling methods like Monte Carlo let us approximate that posterior without solving the integral exactly.
2. What is Monte Carlo sampling in Bayesian inference?Monte Carlo methods use randomly generated samples to approximate a distribution that is hard to compute directly. In Bayesian inference, those samples act as a surrogate for the posterior, letting us estimate means, credible intervals, predictive quantities, and more.
3. Why is the denominator of Bayes’ theorem a problem when working with non-conjugate priors?The denominator is the evidence term, p(D), which is an integral over all possible parameter values. For many non-conjugate models, this integral is complicated and cannot be computed easily, even though the posterior is still proportional to the prior times the likelihood.
4. What does it mean that the posterior is known only up to a constant?It means we can compute the unnormalized posterior as p(D | θ)p(θ), but not the normalizing constant p(D). That is enough for many sampling algorithms, because they only need relative densities, not the exact normalized posterior.
5. What kind of quantities can be estimated from posterior samples?Posterior samples can be used to estimate the mean, credible intervals, cumulative probabilities, posterior predictive checks, and even future observations. In practice, they let us approximate many posterior summaries without knowing the full posterior analytically.
6. What are i.i.d. samples, and why are they ideal?i.i.d. means independent and identically distributed. These samples are ideal because standard statistical approximations, such as sample means and credible intervals, become reliable as the number of samples increases.
7. Why are grid approximations not a good solution in high dimensions?Grid methods require evaluating many points across the hypothesis space, and the number of grid points grows exponentially with dimension. This makes them computationally expensive and inefficient in higher-dimensional models.
8. What is Markov chain Monte Carlo (MCMC)?MCMC is a family of algorithms that generates a sequence of dependent samples designed to approximate a target distribution. The key idea is that the chain spends time in regions proportional to the posterior density, allowing us to learn about the posterior through the samples.
9. How does the Metropolis–Hastings algorithm work at a high level?It starts at an initial point, proposes a new point from a proposal distribution, and then accepts or rejects the proposal based on an accept/reject rule. Repeating this process produces a chain of samples that explores the posterior distribution.
10. What are the main MCMC best practices discussed in the chapter?The chapter recommends discarding burn-in samples, running multiple chains, checking convergence with R-hat, checking effective sample size, inspecting mixing with trace plots, and performing posterior predictive checks to ensure the model fits the observed data well.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Grokking Bayes Grokking Bayes ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Grokking Bayes Grokking Bayes ebook for free