Chapter 4

Monte Carlo Approximation

Closed-form formulas only carry us so far. Even with conjugate posteriors, computing Pr⁡(θ1>θ2∣y)\Pr(\theta_1 > \theta_2 \mid y), finding the posterior distribution of a nonlinear transformation such as the log-odds γ=log⁡θ1−θ\gamma = \log\frac{\theta}{1-\theta} or ratio θ1/θ2\theta_1 / \theta_2, 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 SS independent samples directly from the posterior distribution:

θ(1),θ(2),…,θ(S)∼i.i.d.p(θ∣y1,…,yn). \theta^{(1)}, \theta^{(2)}, \dots, \theta^{(S)} \stackrel{\text{i.i.d.}}{\sim} p(\theta \mid y_1, \dots, y_n). (4.1)

By the Strong Law of Large Numbers, for any function g(θ)g(\theta) with E[∣g(θ)∣∣y]<∞E[\lvert g(\theta) \rvert \mid y] < \infty,

g^S=1S∑s=1Sg(θ(s))  →S→∞  E[g(θ)∣y1,…,yn]=∫Θg(θ) p(θ∣y1,…,yn) dθ. \hat{g}_S = \frac{1}{S}\sum_{s=1}^S g\bigl(\theta^{(s)}\bigr) \;\xrightarrow{S \to \infty}\; E\bigl[g(\theta) \mid y_1, \dots, y_n\bigr] = \int_{\Theta} g(\theta)\,p(\theta \mid y_1, \dots, y_n)\,d\theta. (4.2)

Setting g(θ)=θg(\theta) = \theta, g(θ)=𝟏(θ≤c)g(\theta) = \mathbf{1}(\theta \le c), or taking empirical quantiles of {θ(1),…,θ(S)}\{\theta^{(1)}, \dots, \theta^{(S)}\} immediately approximates posterior means, variances, tail probabilities, medians, and credible intervals to arbitrary precision.

How large must SS be? Whenever Var⁡[g(θ)∣y]<∞\operatorname{Var}[g(\theta) \mid y] < \infty,Always check that the target moment is finite! For example, if θ2∣y2∼gamma⁡(a2,b2)\theta_2 \mid y_2 \sim \operatorname{gamma}(a_2, b_2), then E[θ1/θ2∣y]E[\theta_1/\theta_2 \mid y] requires a2>1a_2 > 1 and Var⁡[θ1/θ2∣y]<∞\operatorname{Var}[\theta_1/\theta_2 \mid y] < \infty requires a2>2a_2 > 2. When variance is infinite, sample averages still converge by the LLN (if a2>1a_2 > 1), but the classical CLT standard error fails. the Central Limit Theorem implies that g^S\hat{g}_S is approximately normal around E[g(θ)∣y]E[g(\theta) \mid y] with standard error Var⁡[g(θ)∣y]/S\sqrt{\operatorname{Var}[g(\theta) \mid y] / S}. Replacing the unknown variance by the sample variance σ^g2=1S−1∑s=1S(g(θ(s))−g^S)2\hat{\sigma}_g^2 = \frac{1}{S-1}\sum_{s=1}^S (g(\theta^{(s)}) - \hat{g}_S)^2 yields the **Monte Carlo standard error (MCSE)**:

Expectation g^S:MCSE⁡(g^S)=σ^gS,Probability p^S=1S∑s=1S𝟏(θ(s)∈A):MCSE⁡(p^S)=p^S(1−p^S)S,q-Quantile θ^q,S:MCSE⁡(θ^q,S)≈q(1−q)S p(θq∣y). \begin{aligned} \text{Expectation } \hat{g}_S: &\quad \operatorname{MCSE}(\hat{g}_S) = \frac{\hat{\sigma}_g}{\sqrt{S}}, \\ \text{Probability } \hat{p}_S = \frac{1}{S}\sum_{s=1}^S \mathbf{1}(\theta^{(s)} \in A): &\quad \operatorname{MCSE}(\hat{p}_S) = \sqrt{\frac{\hat{p}_S(1 - \hat{p}_S)}{S}}, \\ \text{$q$-Quantile } \hat{\theta}_{q,S}: &\quad \operatorname{MCSE}(\hat{\theta}_{q,S}) \approx \frac{\sqrt{q(1 - q)}}{\sqrt{S}\,p(\theta_q \mid y)}. \end{aligned} (4.3)

To guarantee that θ¯S\bar{\theta}_S lies within tolerance ϵ\epsilon of E[θ∣y]E[\theta \mid y] with roughly 95% probability, we require 2σ^/S<ϵ2\hat{\sigma}/\sqrt{S} < \epsilon, i.e., S>4σ^2/ϵ2S > 4\hat{\sigma}^2 / \epsilon^2. Notice both the 1/S1/\sqrt{S} scaling—cutting simulation error in half requires four times as many draws—and the 1/p(θq∣y)1/p(\theta_q \mid y) factor for quantiles: extreme tail quantiles (where density p(θq∣y)p(\theta_q \mid y) is tiny) require many more draws than the mean or median!

Three panels showing cumulative Monte Carlo estimates of the mean and tail probability of Gamma(68, 45) converging within a two-MCSE envelope, and a histogram of the posterior predictive check ratio t(Y_rep) with observed value 2.0 in the upper tail (tail probability 0.0051)
Figure 4.1: Left and center: cumulative Monte Carlo estimates of E[θ∣y]E[\theta \mid y] (with ±2 MCSE\pm 2\,\text{MCSE} envelope) and Pr⁡(θ<1.75∣y)\Pr(\theta < 1.75 \mid y) for gamma⁡(68,45)\operatorname{gamma}(68, 45) converging to the exact analytical values. Right: posterior predictive check of the Poisson model on GSS fertility counts (S=50,000S = 50{,}000 replicates)—only 0.51%0.51\% of simulated datasets reach the observed ratio t(yobs)=#{Y=2}/#{Y=1}=2.0t(y_{\text{obs}}) = \#\{Y=2\}/\#\{Y=1\} = 2.0.

4.2Push-Forward Sampling and Multidimensional Comparisons

One of the greatest strengths of sampling-based inference is effortless push-forward sampling: to obtain SS exact i.i.d. draws from the posterior of any derived quantity γ=g(θ)\gamma = g(\theta)—without ever computing a Jacobian!—simply apply gg to each draw:

  1. Draw θ(s)∼p(θ∣y)\theta^{(s)} \sim p(\theta \mid y) for s=1,…,Ss = 1, \dots, S.
  2. Compute γ(s)=g(θ(s))\gamma^{(s)} = g(\theta^{(s)}).

Then {γ(1),…,γ(S)}\{\gamma^{(1)}, \dots, \gamma^{(S)}\} is an exact i.i.d. sample from the push-forward posterior p(γ∣y)p(\gamma \mid y). Note why this matters: by Jensen’s inequality, E[g(θ)∣y]≠g(E[θ∣y])E[g(\theta) \mid y] \neq g(E[\theta \mid y]) for nonlinear gg—plugging the posterior mean into gg introduces bias, whereas averaging g(θ(s))g(\theta^{(s)}) estimates E[g(θ)∣y]E[g(\theta) \mid y] consistently. Two textbook examples illustrate the payoff:

  • Log-odds: Given y=441y = 441 agreements out of n=860n = 860 non-Protestant GSS respondents under a beta⁡(1,1)\operatorname{beta}(1, 1) prior, θ∣y∼beta⁡(442,420)\theta \mid y \sim \operatorname{beta}(442, 420). Transforming draws via γ(s)=log⁡[θ(s)/(1−θ(s))]\gamma^{(s)} = \log[\theta^{(s)} / (1 - \theta^{(s)})] directly yields the posterior density and credible intervals of the log-odds.

  • Two-group comparisons: For independent posteriors θ1∣y1∼gamma⁡(219,112)\theta_1 \mid y_1 \sim \operatorname{gamma}(219, 112) and θ2∣y2∼gamma⁡(68,45)\theta_2 \mid y_2 \sim \operatorname{gamma}(68, 45), drawing pairs (θ1(s),θ2(s))(\theta_1^{(s)}, \theta_2^{(s)}) lets us approximate

    Pr⁡(θ1>θ2∣y)≈1S∑s=1S𝟏(θ1(s)>θ2(s))≈0.973 \Pr(\theta_1 > \theta_2 \mid y) \approx \frac{1}{S}\sum_{s=1}^S \mathbf{1}(\theta_1^{(s)} > \theta_2^{(s)}) \approx 0.973

    (exact value 0.97260.9726, verified below) and plot the entire posterior of the ratio θ1/θ2\theta_1 / \theta_2 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: p(y~)=∫p(y~∣θ) p(θ) dθp(\tilde{y}) = \int p(\tilde{y} \mid \theta)\,p(\theta)\,d\theta (useful for checking whether a chosen prior implies sensible observables before seeing data).
  • Posterior predictive: p(y~∣y)=∫p(y~∣θ) p(θ∣y) dθp(\tilde{y} \mid y) = \int p(\tilde{y} \mid \theta)\,p(\theta \mid y)\,d\theta.

Even when this integral has no closed form, ancestral (two-stage) sampling draws exact samples from p(y~∣y)p(\tilde{y} \mid y):

For s=1,…,S:θ(s)∼p(θ∣y),y~(s)∼p(y~∣θ(s)). \text{For } s = 1, \dots, S: \quad \theta^{(s)} \sim p(\theta \mid y), \qquad \tilde{y}^{(s)} \sim p(\tilde{y} \mid \theta^{(s)}). (4.4)

Each pair (θ(s),y~(s))(\theta^{(s)}, \tilde{y}^{(s)}) is a draw from the joint posterior p(θ,y~∣y)p(\theta, \tilde{y} \mid y), so discarding θ(s)\theta^{(s)} leaves marginal draws y~(s)∼p(y~∣y)\tilde{y}^{(s)} \sim p(\tilde{y} \mid y). For the GSS birth-rate groups, comparing paired draws y~1(s)∼Poisson⁡(θ1(s))\tilde{y}_1^{(s)} \sim \operatorname{Poisson}(\theta_1^{(s)}) and y~2(s)∼Poisson⁡(θ2(s))\tilde{y}_2^{(s)} \sim \operatorname{Poisson}(\theta_2^{(s)}) replaces a doubly infinite negative-binomial sum with a single vectorized comparison, giving Pr⁡(Y~1>Y~2∣y)≈0.482\Pr(\tilde{Y}_1 > \tilde{Y}_2 \mid y) \approx 0.482.

Remark 4.1 (Rao–Blackwellization: integrating analytically when you can). Whenever the conditional expectation E[Y~∣θ]E[\tilde{Y} \mid \theta] is known in closed form, averaging E[Y~∣θ(s)]E[\tilde{Y} \mid \theta^{(s)}] across draws achieves strictly smaller Monte Carlo variance than averaging simulated y~(s)\tilde{y}^{(s)}, because

Var⁡(E[Y~∣θ])=Var⁡(Y~)−E[Var⁡(Y~∣θ)]≤Var⁡(Y~). \operatorname{Var}(E[\tilde{Y} \mid \theta]) = \operatorname{Var}(\tilde{Y}) - E[\operatorname{Var}(\tilde{Y} \mid \theta)] \le \operatorname{Var}(\tilde{Y}).

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 p(y∣θ)p(y \mid \theta), 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 t(y)t(y) capturing a structural feature of interest (skewness, overdispersion, zero inflation, or a specific count ratio). Generate SS replicated datasets of the same size nn as yobsy_{\text{obs}}:

  1. Sample θ(s)∼p(θ∣yobs)\theta^{(s)} \sim p(\theta \mid y_{\text{obs}}).
  2. Sample a replicated dataset Y~(s)=(y~1(s),…,y~n(s))∼i.i.d.p(y∣θ(s))\tilde{Y}^{(s)} = (\tilde{y}_1^{(s)}, \dots, \tilde{y}_n^{(s)}) \stackrel{\text{i.i.d.}}{\sim} p(y \mid \theta^{(s)}).
  3. Compute t(s)=t(Y~(s))t^{(s)} = t(\tilde{Y}^{(s)}).

Compare the observed value t(yobs)t(y_{\text{obs}}) against the empirical distribution of {t(1),…,t(S)}\{t^{(1)}, \dots, t^{(S)}\} via the posterior predictive tail probability

p^PPC=1S∑s=1S𝟏(t(s)≥t(yobs)). \hat{p}_{\text{PPC}} = \frac{1}{S}\sum_{s=1}^S \mathbf{1}\bigl(t^{(s)} \ge t(y_{\text{obs}})\bigr).

If t(yobs)t(y_{\text{obs}}) 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 (n1=111n_1 = 111), 38 women had 2 children while only 19 had 1 child, so t(yobs)=#{yi=2}/#{yi=1}=2.0t(y_{\text{obs}}) = \#\{y_i = 2\} / \#\{y_i = 1\} = 2.0. As Figure 4.1 (right panel) shows, only 0.51%0.51\% of Poisson posterior predictive replicates in our 50,00050{,}000-draw simulation reach t(Y~)≥2.0t(\tilde{Y}) \ge 2.0 (exact value ≈0.0057±0.0002\approx 0.0057 \pm 0.0002): no Poisson distribution with mean near 1.951.95—where the theoretical ratio is p(2)/p(1)=θ/2≈0.98p(2)/p(1) = \theta/2 \approx 0.98—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:

  1. Conservatism under the null: Because yobsy_{\text{obs}} is used twice—both to fit p(θ∣yobs)p(\theta \mid y_{\text{obs}}) and to evaluate t(yobs)t(y_{\text{obs}})—posterior predictive pp-values are not uniformly distributed on [0,1][0, 1] even when the model is exact; they tend to concentrate near 0.50.5, making very small values (like 0.0050.005) genuinely strong evidence of misfitM. J. Bayarri and James O. Berger. pp Values for Composite Null Models. Journal of the American Statistical Association, 95(452):1127–1142, 2000.
  2. 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 (1.951.95) and sample variance (1.901.90) 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 p(y=2)p(y = 2) (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,

p(yi∣y−i)=1E[ 1/p(yi∣θ) ∣ y ]≈∑swi(s) p(yi∣θ(s))∑swi(s),ri(s)=1p(yi∣θ(s)), p(y_i \mid y_{-i}) = \frac{1}{E\bigl[\,1/p(y_i \mid \theta) \,\big|\, y\,\bigr]} \approx \frac{\sum_{s} w_i^{(s)}\,p(y_i \mid \theta^{(s)})}{\sum_{s} w_i^{(s)}}, \qquad r_i^{(s)} = \frac{1}{p(y_i \mid \theta^{(s)})}, (4.5)

where wi(s)w_i^{(s)} is ri(s)r_i^{(s)} with its largest values smoothed by a fitted generalized Pareto tail.

Why it holds: p(θ∣y−i)∝p(θ∣y)/p(yi∣θ)p(\theta \mid y_{-i}) \propto p(\theta \mid y)/p(y_i \mid \theta); integrate both sides. The Pareto shape estimate k^\hat{k} is the diagnostic: Vehtari et al. flag the result when k^>min⁡(1−1/log⁡10S, 0.7)\hat{k} > \min(1 - 1/\log_{10} S,\, 0.7). A heavy tail means the two posteriors differ, and importance sampling needs on the order of exp⁡{KL⁡(p(θ∣y−i) ∥ p(θ∣y))}\exp\{\operatorname{KL}(p(\theta \mid y_{-i}) \,\Vert\, p(\theta \mid y))\} draws. The Poisson–gamma model offers an exact check: θ∣y−i∼gamma⁡(an−yi, bn−1)\theta \mid y_{-i} \sim \operatorname{gamma}(a_n - y_i,\, b_n - 1), so p(yi∣y−i)p(y_i \mid y_{-i}) is a negative binomial⁡(an−yi, bn−1)\operatorname{negative\ binomial}(a_n - y_i,\, b_n - 1) probability, and the raw ratios ri∝eθθ−yir_i \propto e^{\theta}\theta^{-y_i} have tail shape max⁡(1/bn, yi/an)\max(1/b_n,\, y_i/a_n), below 11 exactly when that gamma is proper.

The LOO-PIT values Pr⁡(Y~i≤yi∣y−i)\Pr(\tilde{Y}_i \le y_i \mid y_{-i}) (randomized over ties for counts) should look approximately uniform when the model is adequate. Since yiy_i 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 yiy_i wherever k^\hat{k} 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 f(θ,y)f(\theta, y), among LL posterior draws:

θ~∼p(θ),y∼p(y∣θ~),θ(1),…,θ(L)∼i.i.d.p(θ∣y),R=∑l=1L𝟏(f(θ(l),y)<f(θ~,y)). \tilde{\theta} \sim p(\theta), \quad y \sim p(y \mid \tilde{\theta}), \quad \theta^{(1)}, \dots, \theta^{(L)} \stackrel{\text{i.i.d.}}{\sim} p(\theta \mid y), \qquad R = \sum_{l=1}^{L} \mathbf{1}\bigl(f(\theta^{(l)}, y) < f(\tilde{\theta}, y)\bigr). (4.6)

If the sampler is exact and ties have probability zero (otherwise break them at random), RR is uniform on {0,1,…,L}\{0, 1, \dots, L\}.

Why it holds: the joint density factors as p(θ~) p(y∣θ~)=p(y) p(θ~∣y)p(\tilde{\theta})\,p(y \mid \tilde{\theta}) = p(y)\,p(\tilde{\theta} \mid y), so given yy the value θ~\tilde{\theta} is itself a posterior draw, i.i.d. with the θ(l)\theta^{(l)}, 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 yy and returns prior draws gives uniform ranks for every f(θ)f(\theta), because θ~\tilde{\theta} and the θ(l)\theta^{(l)} are then i.i.d. from the prior. Data-dependent quantities such as the log-likelihood f(θ,y)=log⁡p(y∣θ)f(\theta, y) = \log p(y \mid \theta) can expose it: yy was generated from θ~\tilde{\theta}, 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 gamma⁡(219,112)\operatorname{gamma}(219, 112) the importance ratios in (4.5) have tail shape below 1/21/2 for these yiy_i, 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}")
Write the exact leave-one-out predictive: a negative binomial with shape an−yia_n - y_i and rate bn−1b_n - 1.
// 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`
p(yi∣y−i)=(1bn)yi(−1+bnbn)an−yiΓ(an)yi!Γ(an−yi) p(y_i \mid y_{-i}) = \frac{\left(\frac{1}{b_n}\right)^{y_i} \left(\frac{-1+b_n}{b_n}\right)^{a_n -y_i} \Gamma (a_n)}{y_i ! \Gamma (a_n -y_i)} Verify it by integrating Poisson⁡(yi∣θ)\operatorname{Poisson}(y_i \mid \theta) over the leave-one-out posterior gamma⁡(an−yi,bn−1)\operatorname{gamma}(a_n - y_i, b_n - 1).
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})]]`
1NB⁡(yi)∫0∞Poisson⁡(yi∣θ) Gamma⁡(θ∣an−yi,bn−1) dθ=1 \frac{1}{\operatorname{NB}(y_i)}\int_0^\infty \operatorname{Poisson}(y_i \mid \theta)\,\operatorname{Gamma}(\theta \mid a_n - y_i, b_n - 1)\,d\theta = 1 Integrate 1/p(yi∣θ)1/p(y_i \mid \theta) over the full posterior gamma⁡(an,bn)\operatorname{gamma}(a_n, b_n): the posterior mean of the inverse likelihood.
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}]]]`
𝔼[p(yi∣θ)−1∣y]=yi!  bnan (bn−1)yi−an Γ(an−yi)Γ(an) \mathbb{E}\bigl[p(y_i \mid \theta)^{-1} \mid y\bigr] = \frac{y_i!\; b_n^{a_n}\,(b_n-1)^{y_i-a_n}\,\Gamma(a_n-y_i)}{\Gamma(a_n)} Invert it and divide by the exact LOO predictive: the harmonic-mean identity returns the same probability.
await show`Assuming[bn > 1 && yi >= 0 && an > yi && Element[yi, Integers], FullSimplify[(1/(${invP})) / (${looNB})]]`
1/𝔼[p(yi∣θ)−1∣y]p(yi∣y−i)=1 \frac{1/\mathbb{E}\bigl[p(y_i \mid \theta)^{-1} \mid y\bigr]}{p(y_i \mid y_{-i})} = 1 Instantiate the exact LOO predictive at the GSS posterior for yi=0,1,2,3y_i = 0, 1, 2, 3 to benchmark the Monte Carlo column.
await show`N[Table[(${looNB}) /. {an -> 219, bn -> 112}, {yi, 0, 3}]]`
(p(yi∣y−i))yi=03∣an=219,  bn=112={0.140277,0.275498,0.269293,0.174677} \bigl(p(y_i \mid y_{-i})\bigr)_{y_i=0}^{3}\big|_{a_n=219,\; b_n=112} = \{0.140277,0.275498,0.269293,0.174677\}

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 a2=1,2a_2 = 1, 2), the symbolic Gamma CDF Pr⁡(θ2<c)\Pr(\theta_2 < c), and the general Beta representation of Pr⁡(θ1>θ2)\Pr(\theta_1 > \theta_2), then instantiates all symbolic expressions on the GSS fertility posteriors to benchmark the Monte Carlo estimates.

Invert γ=logit⁡(θ)\gamma = \operatorname{logit}(\theta): 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]]`
θ(g)=logit⁡−1(g)=eg1+eg \theta(g) = \operatorname{logit}^{-1}(g) = \frac{e^g}{1+e^g} Differentiate the inverse map to get the Jacobian dθ/dg=θ(1−θ)d\theta/dg = \theta(1 - \theta).
const jac = await show`FullSimplify[D[${thOfG}, g], Element[g, Reals]]`
dθdg=eg(1+eg)2 \frac{d\theta}{dg} = \frac{e^g}{\left(1+e^g\right)^2} Multiply the beta density at θ(g)\theta(g) by the Jacobian to derive the exact log-odds density.
await show`FullSimplify[(${thOfG}^(a - 1)*(1 - ${thOfG})^(b - 1)/Beta[a, b]) * ${jac}, Element[g, Reals]]`
pγ(g)=pθ ⁣(eg1+eg)∣dθdg∣=eag(1+eg)−a−bB(a,b) \begin{aligned} &p_\gamma(g) = p_\theta\!\left(\frac{e^g}{1+e^g}\right)\left|\frac{d\theta}{dg}\right| \\ &= \frac{e^{a g} \left(1+e^g\right)^{-a-b}}{B(a,b)} \end{aligned} Integrate 1/θ21/\theta_2 against gamma⁡(a2,b2)\operatorname{gamma}(a_2, b_2) to compute the exact mean of the rate ratio θ1/θ2\theta_1/\theta_2.
// 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}]]]`
𝔼[θ1/θ2]=a1b2(−1+a2)b1 \mathbb{E}[\theta_1 / \theta_2] = \frac{a_1 b_2}{(-1+a_2) b_1} Compute the second moment of θ1/θ2\theta_1/\theta_2 symbolically to obtain Var⁡(θ1/θ2)\operatorname{Var}(\theta_1/\theta_2) for a2>2a_2 > 2.
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]]`
Var⁡(θ1/θ2)=a1(−1+a1+a2)b22(−2+a2)(−1+a2)2b12 \begin{aligned} &\operatorname{Var}(\theta_1 / \theta_2) \\ &= \frac{a_1 (-1+a_1 +a_2) b_2^2}{(-2+a_2) (-1+a_2)^2 b_1^2} \end{aligned} Integrate the gamma⁡(a2,b2)\operatorname{gamma}(a_2, b_2) density up to cc to express its CDF via the incomplete Gamma function.
// 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}]]]`
Pr⁡(θ2<c)=1−Γ(a2,b2c)Γ(a2) \Pr(\theta_2 < c) = 1-\frac{\Gamma (a_2,b_2 c)}{\Gamma (a_2)} Express Pr⁡(θ1>θ2)\Pr(\theta_1 > \theta_2) for independent Gammas via the regularized incomplete Beta function.
const pGtSym = await show`1 - Beta[b1 / (b1 + b2), a1, a2] / Beta[a1, a2]`
Pr⁡(θ1>θ2)=1−Bb1b1+b2(a1,a2)B(a1,a2) \Pr(\theta_1 > \theta_2) = 1-\frac{B_{\frac{b_1}{b_1 +b_2}}(a_1,a_2)}{B(a_1,a_2)} Instantiate both exact GSS fertility tail probabilities to benchmark Monte Carlo estimates.
// 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}}]`
(Pr⁡(θ1>θ2∣y),  Pr⁡(θ2<1.75∣y))GSS={0.97256,0.899829} \begin{aligned} &\bigl(\Pr(\theta_1 > \theta_2 \mid y),\; \Pr(\theta_2 < 1.75 \mid y)\bigr)_{\text{GSS}} \\ &= \{0.97256,0.899829\} \end{aligned}

4.7Exercises

Exercise 4.4. For θ∣y∼beta⁡(2,40)\theta \mid y \sim \operatorname{beta}(2, 40), use S=50,000S = 50{,}000 Monte Carlo draws to compare E[log⁡θ1−θ∣y]E[\log\frac{\theta}{1-\theta} \mid y] against log⁡E[θ∣y]1−E[θ∣y]\log\frac{E[\theta \mid y]}{1 - E[\theta \mid y]}, and compare E[1/θ∣y]E[1/\theta \mid y] against 1/E[θ∣y]1 / E[\theta \mid y]. Explain the sign of each discrepancy via Jensen’s inequality.

Symbolic Solution & InstantiationExpress E[logit⁡(θ)]E[\operatorname{logit}(\theta)] for θ∼beta⁡(a,b)\theta \sim \operatorname{beta}(a, b) in terms of the digamma function ψ(0)\psi^{(0)}.
// 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]]]`
𝔼 ⁣[log⁡θ1−θ]=ψ(0)(a)−ψ(0)(b) \mathbb{E}\!\left[\log\frac{\theta}{1-\theta}\right] = \psi^{(0)}(a)-\psi^{(0)}(b) Integrate 1/θ1/\theta against beta⁡(a,b)\operatorname{beta}(a, b) to obtain E[1/θ]E[1/\theta] for a>1a > 1.
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}]]]`
𝔼 ⁣[1θ]=1+b−1+a \mathbb{E}\!\left[\frac{1}{\theta}\right] = 1+\frac{b}{-1+a} Subtract 1/E[θ]1/E[\theta] to isolate the exact positive Jensen gap b/[a(a−1)]b/[a(a-1)].
await show`Factor[${eInv} - (a + b)/a]`
𝔼 ⁣[1θ]−1𝔼[θ]=b(−1+a)a \mathbb{E}\!\left[\frac{1}{\theta}\right] - \frac{1}{\mathbb{E}[\theta]} = \frac{b}{(-1+a) a} Evaluate E[logit⁡θ]E[\operatorname{logit}\theta], logit⁡E[θ]\operatorname{logit}E[\theta], E[1/θ]E[1/\theta], and 1/E[θ]1/E[\theta] at beta⁡(2,40)\operatorname{beta}(2, 40).
await show`N[{${eLogit}, Log[a/b], ${eInv}, (a + b)/a} /. {a -> 2, b -> 40}]`
(𝔼[logit⁡θ],  logit⁡𝔼[θ],  𝔼[θ−1],  (𝔼[θ])−1)Beta⁡(2,40)={−3.25354,−2.99573,41.,21.} \begin{aligned} &\bigl(\mathbb{E}[\operatorname{logit}\theta],\; \operatorname{logit}\mathbb{E}[\theta],\; \mathbb{E}[\theta^{-1}],\; (\mathbb{E}[\theta])^{-1}\bigr)_{\operatorname{Beta}(2,40)} \\ &= \{-3.25354,-2.99573,41.,21.\} \end{aligned}

Exercise 4.5. For θ∣y∼gamma⁡(68,45)\theta \mid y \sim \operatorname{gamma}(68, 45) and Y~∣θ∼Poisson⁡(θ)\tilde{Y} \mid \theta \sim \operatorname{Poisson}(\theta), compare the empirical variance across 500 repeated runs (S=200S = 200 draws each) of (a) the naive predictive mean 1S∑y~(s)\frac{1}{S}\sum \tilde{y}^{(s)} versus (b) the Rao–Blackwellized estimator 1S∑θ(s)\frac{1}{S}\sum \theta^{(s)}. How closely does the variance ratio match Var⁡(Y~∣y)/Var⁡(θ∣y)=(bn+1)/1=46\operatorname{Var}(\tilde{Y} \mid y) / \operatorname{Var}(\theta \mid y) = (b_n + 1)/1 = 46?

Symbolic Solution & InstantiationTake 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)]`
Var⁡(Y~∣y)Var⁡(θ∣y)=1+bn \frac{\operatorname{Var}(\tilde{Y} \mid y)}{\operatorname{Var}(\theta \mid y)} = 1+b_n Instantiate the variance reduction factor at the GSS degree posterior gamma⁡(68,45)\operatorname{gamma}(68, 45).
await show`${rbRatio} /. {an -> 68, bn -> 45}`
Var⁡(Y~∣y)Var⁡(θ∣y)∣an=68,  bn=45=46 \begin{aligned} &\left.\frac{\operatorname{Var}(\tilde{Y} \mid y)}{\operatorname{Var}(\theta \mid y)}\right|_{a_n=68,\; b_n=45} \\ &= 46 \end{aligned}

Exercise 4.6. Design a posterior predictive check for overdispersion using the dispersion index t(Y)=s2(Y)/Y¯t(Y) = s^2(Y) / \bar{Y}. Simulate a negative-binomial dataset with mean 22 and variance 66 (n=100n = 100), fit a conjugate Poisson–Gamma model, and verify that Algorithm 4.2 flags the overdispersion clearly.

Symbolic Solution & InstantiationCompute the Negative Binomial dispersion index Var⁡(Y)/E[Y]=1+1/b\operatorname{Var}(Y)/E[Y] = 1 + 1/b 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)]`
Var⁡(Y)𝔼[Y]=1+1b \frac{\operatorname{Var}(Y)}{\mathbb{E}[Y]} = 1+\frac{1}{b} Solve for the Gamma hyperparameters (a,b)(a, b) matching E[Y]=2E[Y] = 2 and Var⁡(Y)=6\operatorname{Var}(Y) = 6.
const sol = await show`First[Solve[{a/b == 2, (a*(b + 1))/b^2 == 6}, {a, b}]]`
Solution for (𝔼[Y]=2,  Var⁡(Y)=6)={a→1,b→12} \begin{aligned} &\text{Solution for } (\mathbb{E}[Y]=2,\; \operatorname{Var}(Y)=6) \\ &= \left\{a\to 1,b\to \frac{1}{2}\right\} \end{aligned} Verify that the solved parameters yield a dispersion index of 33 (triple the Poisson baseline).
await show`${dispIdx} /. ${sol}`
Var⁡(Y)𝔼[Y]∣a=1,  b=1/2=3 \left.\frac{\operatorname{Var}(Y)}{\mathbb{E}[Y]}\right|_{a=1,\; b=1/2} = 3