Chapter 4
Monte Carlo Approximation
Closed-form formulas only carry us so far. Even with conjugate posteriors, computing , finding the posterior distribution of a nonlinear transformation such as the log-odds or ratio , or evaluating a goodness-of-fit test statistic quickly leads to awkward multidimensional integrals or doubly infinite sums. Monte Carlo approximation replaces analytical integration with a single universal recipe: draw random samples from the posterior and compute empirical averages.Peter D. Hoff. A First Course in Bayesian Statistical Methods. Springer Texts in Statistics. Springer, New York, 2009. ISBN 978-0-387-92299-7. doi: 10.1007/978-0-387-92407-6; and Christian P. Robert and George Casella. Monte Carlo Statistical Methods. Springer, New York, second edition, 2004
4.1The Monte Carlo Method and Standard Error#
Suppose we can draw independent samples directly from the posterior distribution:
(4.1)By the Strong Law of Large Numbers, for any function with ,
(4.2)Setting , , or taking empirical quantiles of immediately approximates posterior means, variances, tail probabilities, medians, and credible intervals to arbitrary precision.
How large must be? Whenever ,Always check that the target moment is finite! For example, if , then requires and requires . When variance is infinite, sample averages still converge by the LLN (if ), but the classical CLT standard error fails. the Central Limit Theorem implies that is approximately normal around with standard error . Replacing the unknown variance by the sample variance yields the **Monte Carlo standard error (MCSE)**:
(4.3)To guarantee that lies within tolerance of with roughly 95% probability, we require , i.e., . Notice both the scaling—cutting simulation error in half requires four times as many draws—and the factor for quantiles: extreme tail quantiles (where density is tiny) require many more draws than the mean or median!
4.2Push-Forward Sampling and Multidimensional Comparisons#
One of the greatest strengths of sampling-based inference is effortless push-forward sampling: to obtain exact i.i.d. draws from the posterior of any derived quantity —without ever computing a Jacobian!—simply apply to each draw:
- Draw for .
- Compute .
Then is an exact i.i.d. sample from the push-forward posterior . Note why this matters: by Jensen’s inequality, for nonlinear —plugging the posterior mean into introduces bias, whereas averaging estimates consistently. Two textbook examples illustrate the payoff:
Log-odds: Given agreements out of non-Protestant GSS respondents under a prior, . Transforming draws via directly yields the posterior density and credible intervals of the log-odds.
Two-group comparisons: For independent posteriors and , drawing pairs lets us approximate
(exact value , verified below) and plot the entire posterior of the ratio in three lines of code.
4.3Ancestral Sampling from Predictive Distributions#
A predictive distribution conditions on everything known and integrates out everything unknown:
- Prior predictive: (useful for checking whether a chosen prior implies sensible observables before seeing data).
- Posterior predictive: .
Even when this integral has no closed form, ancestral (two-stage) sampling draws exact samples from :
(4.4)Each pair is a draw from the joint posterior , so discarding leaves marginal draws . For the GSS birth-rate groups, comparing paired draws and replaces a doubly infinite negative-binomial sum with a single vectorized comparison, giving .
Remark 4.1 (Rao–Blackwellization: integrating analytically when you can). Whenever the conditional expectation is known in closed form, averaging across draws achieves strictly smaller Monte Carlo variance than averaging simulated , because
This variance-reduction principle—Rao–Blackwellization—carries directly into the Gibbs samplers of Part II.
4.4Posterior Predictive Model Checking#
Because Bayesian inference always conditions on a chosen sampling model , we must ask: does the fitted model actually generate datasets that resemble the one we observed? This is posterior predictive model checking.Donald B. Rubin. Bayesianly Justifiable and Relevant Frequency Calculations for the Applied Statistician. The Annals of Statistics, 12(4):1151–1172, 1984; and Andrew Gelman, Xiao-Li Meng, and Hal Stern. Posterior Predictive Assessment of Model Fitness via Realized Discrepancies. Statistica Sinica, 6(4):733–807, 1996
Algorithm 4.2 (Posterior Predictive Check (PPC)). Choose a diagnostic test statistic capturing a structural feature of interest (skewness, overdispersion, zero inflation, or a specific count ratio). Generate replicated datasets of the same size as :
- Sample .
- Sample a replicated dataset .
- Compute .
Compare the observed value against the empirical distribution of via the posterior predictive tail probability
If lies far in the tail, the model fails to reproduce that feature of the population.
In the GSS fertility data for women without a bachelor’s degree (), 38 women had 2 children while only 19 had 1 child, so . As Figure 4.1 (right panel) shows, only of Poisson posterior predictive replicates in our -draw simulation reach (exact value ): no Poisson distribution with mean near —where the theoretical ratio is —can exhibit such a sharp cultural spike at two children!
Remark 4.3 (Interpreting PPC p-values and misspecified models). Two subtleties govern posterior predictive checks:
- Conservatism under the null: Because is used twice—both to fit and to evaluate —posterior predictive -values are not uniformly distributed on even when the model is exact; they tend to concentrate near , making very small values (like ) genuinely strong evidence of misfitM. J. Bayarri and James O. Berger. Values for Composite Null Models. Journal of the American Statistical Association, 95(452):1127–1142, 2000.
- Misspecified models can still be useful: A failing PPC does not invalidate every inferenceHalbert White. Maximum Likelihood Estimation of Misspecified Models. Econometrica, 50(1):1–25, 1982. In the GSS data, the sample mean () and sample variance () are nearly equal, so the Poisson model still provides a consistent estimate and accurate credible interval for the population mean—even though it is unsuitable for estimating individual cell probabilities (for which a multinomial model would be needed). Always check the features relevant to your inferential question.
import numpy as np
rng = np.random.default_rng(42)
S = 50_000
a, b = 2, 1
n1, sy1 = 111, 217
n2, sy2 = 44, 66
# 1. Group comparison & ratio of means with MCSE
th1 = rng.gamma(a + sy1, 1.0 / (b + n1), size=S)
th2 = rng.gamma(a + sy2, 1.0 / (b + n2), size=S)
p_gt = np.mean(th1 > th2)
mcse_p = np.sqrt(p_gt * (1 - p_gt) / S)
print(f"Pr(theta1 > theta2 | y) = {p_gt:.4f} +/- {2*mcse_p:.4f} (2 MCSE)")
# 2. Posterior predictive individual comparison
y1_tilde = rng.poisson(th1)
y2_tilde = rng.poisson(th2)
print(f"Pr(Y1_tilde > Y2_tilde | y) = {np.mean(y1_tilde > y2_tilde):.4f}")
# 3. Posterior predictive check: t(Y) = #(Y==2) / #(Y==1)
Y_rep = rng.poisson(th1[:, None], size=(S, n1))
t_rep = np.sum(Y_rep == 2, axis=1) / np.maximum(np.sum(Y_rep == 1, axis=1), 1)
p_ppc = np.mean(t_rep >= 2.0)
print(f"PPC tail prob Pr(t(Y_rep) >= 2.0) = {p_ppc:.4f} +/- {2*np.sqrt(p_ppc*(1-p_ppc)/S):.4f}")4.5Modern Developments: Predictive Evaluation and Validated Computation#
4.5.1PSIS-LOO and LOO-PIT#
Pareto-smoothed importance sampling leave-one-out cross-validation (PSIS-LOO) estimates how well a model predicts each observation from all the others, using the single set of draws in (4.1).Beyond Hoff (2009). This material is not in Hoff’s book; it follows Vehtari, Gelman, and Gabry and Vehtari et al., with the sample-size theory of Chatterjee and Diaconis. It modernizes the posterior predictive check of Algorithm 4.2.Aki Vehtari, Andrew Gelman, and Jonah Gabry. Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27(5):1413–1432, 2017. doi: 10.1007/s11222-016-9696-4; Aki Vehtari, Daniel Simpson, Andrew Gelman, Yuling Yao, and Jonah Gabry. Pareto Smoothed Importance Sampling. Journal of Machine Learning Research, 25(72):1–58, 2024; and Sourav Chatterjee and Persi Diaconis. The sample size required in importance sampling. The Annals of Applied Probability, 28(2):1099–1135, 2018. doi: 10.1214/17-AAP1326 For conditionally independent data,
(4.5)where is with its largest values smoothed by a fitted generalized Pareto tail.
Why it holds: ; integrate both sides. The Pareto shape estimate is the diagnostic: Vehtari et al. flag the result when . A heavy tail means the two posteriors differ, and importance sampling needs on the order of draws. The Poisson–gamma model offers an exact check: , so is a probability, and the raw ratios have tail shape , below exactly when that gamma is proper.
The LOO-PIT values (randomized over ties for counts) should look approximately uniform when the model is adequate. Since does not inform its own prediction, they address the double use of data in Remark 4.3.
When to use it. Use PSIS-LOO to compare predictive models and LOO-PIT to check marginal calibration, refitting without wherever is large. Hoff’s check remains the tool for a specific feature, such as the spike at two children.
4.5.2Simulation-Based Calibration#
Simulation-based calibration (SBC) tests whether the code that claims to draw from a posterior really does.Beyond Hoff (2009). This material is not in Hoff’s book; it follows Talts et al., Modrák et al., and Säilynoja, Bürkner, and Vehtari. Where Algorithm 4.2 checks the model, SBC checks the computation.Sean Talts, Michael Betancourt, Daniel Simpson, Aki Vehtari, and Andrew Gelman. Validating Bayesian Inference Algorithms with Simulation-Based Calibration, 2018. URL https://arxiv.org/abs/1804.06788. arXiv:1804.06788; Martin Modrák, Angie H. Moon, Shinyoung Kim, Paul Bürkner, Niko Huurre, Kateřina Faltejsková, Andrew Gelman, and Aki Vehtari. Simulation-Based Calibration Checking for Bayesian Computation: The Choice of Test Quantities Shapes Sensitivity. Bayesian Analysis, 20(2):461–488, 2025. doi: 10.1214/23-BA1404; and Teemu Säilynoja, Paul-Christian Bürkner, and Aki Vehtari. Graphical test for discrete uniformity and its applications in goodness-of-fit evaluation and multiple sample comparison. Statistics and Computing, 32(2):32, 2022. doi: 10.1007/s11222-022-10090-6 Run the ancestral scheme (4.4) from the prior, then fit the simulated data and rank the true value, by a test quantity , among posterior draws:
(4.6)If the sampler is exact and ties have probability zero (otherwise break them at random), is uniform on .
Why it holds: the joint density factors as , so given the value is itself a posterior draw, i.i.d. with the , and every rank is equally likely. Repeat over many simulated datasets and compare the ranks with uniformity through the empirical distribution function and its simultaneous confidence bands, which avoid the arbitrary bins of a histogram.
The converse fails. A broken sampler that ignores and returns prior draws gives uniform ranks for every , because and the are then i.i.d. from the prior. Data-dependent quantities such as the log-likelihood can expose it: was generated from , which therefore tends to rank high.
When to use it. Run SBC before trusting a new sampler, thinning autocorrelated draws such as those of Chapter 6. It complements Hoff’s MCSE (4.3), which measures noise but not bias, and his predictive checks: passing SBC says nothing about whether the model fits the observed data.
4.5.3Computational & Symbolic Check#
For the GSS posterior the importance ratios in (4.5) have tail shape below for these , so even the raw harmonic-mean estimate is stable; the Python block compares it with the exact negative-binomial value, and the Wolfram sequence proves the identity.Beyond Hoff (2009). This computational check and its Wolfram symbolic counterpart below verify the modern methods in this section and are not in Hoff’s book.
import numpy as np
from scipy import stats
rng = np.random.default_rng(42)
an, bn, S = 219, 112, 200_000
theta = rng.gamma(an, 1.0 / bn, size=S) # full-data posterior draws
for yi in range(4):
exact = stats.nbinom.pmf(yi, an - yi, (bn - 1) / bn) # NB(an - yi, bn - 1)
r = 1.0 / stats.poisson.pmf(yi, theta) # raw importance ratios
loo = 1.0 / r.mean() # harmonic-mean identity
mcse = loo**2 * r.std() / np.sqrt(S) # delta method
print(f"y_i={yi}: exact={exact:.6f}, MC LOO={loo:.6f} +/- {2*mcse:.6f}, "
f"tail shape={max(1/bn, yi/an):.4f}")// Chapter 4 (modern): exact Poisson-gamma LOO vs. the harmonic-mean identity
const looNB = await show`Gamma[an]/(Gamma[an - yi]*yi!)*((bn - 1)/bn)^(an - yi)*(1/bn)^yi`await show`Assuming[bn > 1 && yi >= 0 && an > yi && Element[yi, Integers], FullSimplify[
Integrate[th^yi*Exp[-th]/yi! * (bn - 1)^(an - yi)/Gamma[an - yi]*th^(an - yi - 1)*Exp[-(bn - 1)*th],
{th, 0, Infinity}] / (${looNB})]]`const invP = await show`Assuming[bn > 1 && yi >= 0 && an > yi && Element[yi, Integers], FullSimplify[
Integrate[yi!*Exp[th]*th^(-yi) * bn^an/Gamma[an]*th^(an - 1)*Exp[-bn*th], {th, 0, Infinity}]]]`await show`Assuming[bn > 1 && yi >= 0 && an > yi && Element[yi, Integers], FullSimplify[(1/(${invP})) / (${looNB})]]`await show`N[Table[(${looNB}) /. {an -> 219, bn -> 112}, {yi, 0, 3}]]`4.6Symbolic Check in Wolfram Language#
Derives the exact push-forward log-odds density via change-of-variables Jacobian, the closed-form Gamma-ratio mean and variance (exposing the poles at ), the symbolic Gamma CDF , and the general Beta representation of , then instantiates all symbolic expressions on the GSS fertility posteriors to benchmark the Monte Carlo estimates.
Invert : the inverse is the logistic function.// Chapter 4: Symbolic log-odds density, Gamma-ratio moments & symbolic Gamma tail probabilities
const thOfG = await show`th /. First[Solve[Log[th / (1 - th)] == g, th, Reals]]`const jac = await show`FullSimplify[D[${thOfG}, g], Element[g, Reals]]`await show`FullSimplify[(${thOfG}^(a - 1)*(1 - ${thOfG})^(b - 1)/Beta[a, b]) * ${jac}, Element[g, Reals]]`// Exact symbolic moments of ratio R = th1 / th2 for independent Gamma(a1,b1), Gamma(a2,b2)
const eR = await show`Assuming[a1 > 0 && b1 > 0 && a2 > 1 && b2 > 0,
FullSimplify[(a1/b1)*Integrate[(b2^a2/Gamma[a2])*t^(a2 - 2)*Exp[-b2*t], {t, 0, Infinity}]]]`await show`Assuming[a1 > 0 && b1 > 0 && a2 > 2 && b2 > 0,
FullSimplify[(a1*(a1 + 1)/b1^2)*Integrate[(b2^a2/Gamma[a2])*t^(a2 - 3)*Exp[-b2*t], {t, 0, Infinity}] - (${eR})^2]]`// Symbolic Gamma CDF Pr(th < c) and general Beta-representation of Pr(th1 > th2)
const gamCdf = await show`Assuming[a2 > 0 && b2 > 0 && c > 0,
FullSimplify[Integrate[(b2^a2/Gamma[a2])*t^(a2 - 1)*Exp[-b2*t], {t, 0, c}]]]`const pGtSym = await show`1 - Beta[b1 / (b1 + b2), a1, a2] / Beta[a1, a2]`// Instantiate at GSS fertility posteriors Gamma(219,112) vs Gamma(68,45) and c = 7/4
await show`N[{${pGtSym} /. {a1 -> 219, b1 -> 112, a2 -> 68, b2 -> 45}, ${gamCdf} /. {a2 -> 68, b2 -> 45, c -> 7/4}}]`4.7Exercises#
Exercise 4.4. For , use Monte Carlo draws to compare against , and compare against . Explain the sign of each discrepancy via Jensen’s inequality.
Symbolic Solution & Instantiation
Express for in terms of the digamma function .// Ex 4.1: Exact Jensen discrepancies for Beta(a, b): E[logit(theta)] and E[1/theta]
const eLogit = await show`Assuming[a > 0 && b > 0, FullSimplify[PolyGamma[0, a] - PolyGamma[0, b]]]`const eInv = await show`Assuming[a > 1 && b > 0, FullSimplify[Integrate[(1/th)*th^(a - 1)*(1 - th)^(b - 1)/Beta[a, b], {th, 0, 1}]]]`await show`Factor[${eInv} - (a + b)/a]`await show`N[{${eLogit}, Log[a/b], ${eInv}, (a + b)/a} /. {a -> 2, b -> 40}]`Exercise 4.5. For and , compare the empirical variance across 500 repeated runs ( draws each) of (a) the naive predictive mean versus (b) the Rao–Blackwellized estimator . How closely does the variance ratio match ?
Symbolic Solution & Instantiation
Take the ratio of predictive variance to posterior variance to derive the exact Rao–Blackwell efficiency gain.// Ex 4.2: Exact Rao-Blackwell variance reduction ratio Var(Ytilde | y) / Var(theta | y)
const rbRatio = await show`FullSimplify[((an*(bn + 1))/bn^2) / (an/bn^2)]`await show`${rbRatio} /. {an -> 68, bn -> 45}`Exercise 4.6. Design a posterior predictive check for overdispersion using the dispersion index . Simulate a negative-binomial dataset with mean and variance (), fit a conjugate Poisson–Gamma model, and verify that Algorithm 4.2 flags the overdispersion clearly.
Symbolic Solution & Instantiation
Compute the Negative Binomial dispersion index symbolically.// Ex 4.3: Symbolic Negative Binomial dispersion index Var(Y) / E[Y] = 1 + 1/b
const dispIdx = await show`FullSimplify[((a*(b + 1))/b^2) / (a/b)]`const sol = await show`First[Solve[{a/b == 2, (a*(b + 1))/b^2 == 6}, {a, b}]]`await show`${dispIdx} /. ${sol}`