12  Markov Chain Monte Carlo

Author

Longhai Li

Published

November 27, 2026

Code
library(truncnorm)
library(rstan)
rstan_options(auto_write = TRUE)

The last two chapters drew from a fixed proposal \(g\): an envelope for rejection sampling, an importance distribution for reweighting. Both work well when \(g\) can be made to resemble the target \(f\) over its whole support, but in more than a handful of dimensions no fixed \(g\) does — the target occupies an ever-thinner sliver of the space \(g\) covers, exactly the curse of dimensionality met already for quadrature grids. Markov chain Monte Carlo (MCMC) answers this differently: instead of one global proposal, build a random process \(\theta^{(0)}, \theta^{(1)}, \theta^{(2)}, \ldots\) that moves locally — each step depends only on where the chain currently is — and is engineered so that, after enough steps, \(\theta^{(t)}\) is (approximately) distributed as the target \(f\). The price is that consecutive draws are dependent and the guarantee is only asymptotic; the payoff is that the same local-move idea scales to any dimension.

This chapter develops the Markov chain theory that makes this work, then builds three increasingly automatic ways to construct such a chain — Gibbs sampling, Metropolis–Hastings, and Hamiltonian Monte Carlo — and ends with Stan, which automates the last of these for essentially arbitrary models. Each method is presented first as theory, followed by one or more examples, each named after the problem it solves. A final section applies Stan to a practical problem, a sparse logistic regression with as many predictors as cases, and compares it with glm and the LASSO.

12.1 Markov Chains

12.1.1 Definition and the convergence question

A sequence \(\theta^{(0)}, \theta^{(1)}, \theta^{(2)}, \ldots\) is a Markov chain if the future depends on the past only through the present, \[ P\big(\theta^{(i)} \mid \theta^{(0)}, \ldots, \theta^{(i-1)}\big) = T\big(\theta^{(i)} \mid \theta^{(i-1)}\big), \] where \(T\), the transition distribution, does not depend on \(i\). A chain is completely specified by a starting value (or distribution) and \(T\); simulating it just means repeatedly drawing \(\theta^{(i)} \sim T(\cdot \mid \theta^{(i-1)})\).

A distribution \(\pi\) is the equilibrium (or limiting) distribution of the chain if, for every starting value \(\theta^{(0)}\), \[ \lim_{n\to\infty} P\big(\theta^{(n)} = \theta \mid \theta^{(0)}\big) = \pi(\theta): \] after many steps the chain forgets where it started. The usual Markov-chain question is given \(T\), find \(\pi\). MCMC reverses it: given a target \(\pi\) known only up to a constant, can we design a \(T\) such that, no matter where the chain starts, \(\theta^{(i)}\) converges in distribution to \(\pi\) as \(i \to \infty\)? If so, running the chain for a long time and averaging \(a(\theta^{(i)})\) over the later iterations estimates \(E_\pi[a(\theta)]\) — this is what “MCMC” means in practice.

12.1.2 Invariance, detailed balance, and convergence

\(\pi\) is an invariant (or stationary) distribution of transition \(T\) if \[ \int \pi(\theta)\, T(\theta \to \theta') \, d\theta = \pi(\theta') \qquad \text{for all } \theta'. \] In words: if \(\theta \sim \pi\) and one step of the chain is applied, the result is again distributed as \(\pi\) — \(\pi\) is a fixed point of \(T\). Invariance alone does not guarantee the chain converges to \(\pi\) from an arbitrary start (a chain that never moves leaves every distribution invariant), so two more conditions are needed: aperiodicity (the chain does not cycle deterministically through a fixed sequence of states) and irreducibility (every state can eventually be reached from every other). Under all three, \(\theta^{(i)} \to \pi\) in distribution from any starting point, and ergodic averages converge, \(\frac1n\sum_i a(\theta^{(i)}) \to E_\pi[a(\theta)]\).

Invariance is a global condition (it involves integrating over all \(\theta\)) and is awkward to check directly for a proposed \(T\). The standard shortcut is a local, pairwise condition. \(T\) satisfies detailed balance with respect to \(\pi\) if \[ \pi(\theta)\, T(\theta \to \theta') = \pi(\theta')\, T(\theta' \to \theta) \qquad \text{for all } \theta, \theta', \] i.e. the flow of probability from \(\theta\) to \(\theta'\) under \(\pi\) exactly balances the reverse flow (the transition \(T\) itself need not be symmetric — only the \(\pi\)-weighted flow is). Detailed balance implies invariance: integrating both sides over \(\theta\), \[ \begin{aligned} \int \pi(\theta)\, T(\theta \to \theta') \, d\theta &= \int \pi(\theta')\, T(\theta' \to \theta) \, d\theta \\ &= \pi(\theta') \underbrace{\int T(\theta' \to \theta)\, d\theta}_{=\,1} = \pi(\theta'). \end{aligned} \] Every construction in this chapter — Gibbs, Metropolis–Hastings, Hamiltonian Monte Carlo — is a recipe for building a \(T\) that satisfies detailed balance (or, for Gibbs, invariance directly) with respect to a given target \(\pi\), so that simulating the chain long enough and discarding an initial burn-in period produces (dependent) draws from \(\pi\).

12.1.3 Example 1: Two Random Walks on a Cycle

The machinery above can be run in the direction opposite to MCMC: take a transition \(T\) and find its equilibrium by solving the detailed-balance equations. Consider two chains on the eleven states \(\{0, 1, \ldots, 10\}\) arranged on a circle, with indices taken mod 11, so that \(10\) and \(0\) are neighbours and \(5\) sits in the middle. At each step a chain moves to one of its two neighbours or stays put, and the two chains differ only in the probabilities:

  • the cyclic walk moves forward (clockwise) with probability \(0.45\), backward with probability \(0.45\), and stays with probability \(0.1\);
  • the walk toward 5 moves to the neighbour closer to 5 with probability \(0.4\), to any other neighbour with probability \(0.2\), and stays with the remaining probability.

Writing \(d(i) = |i - 5|\) for the distance from \(i\) to \(5\) (which is also the distance around the circle), the second chain has, for a neighbour \(j = i \pm 1\), \[ T_5(i \to j) = \begin{cases} 0.4, & d(j) < d(i) \quad (\text{toward } 5), \\ 0.2, & \text{otherwise}, \end{cases} \qquad T_5(i \to i) = 1 - T_5(i \to i+1) - T_5(i \to i-1), \] so the probability of staying is \(0.4\) at every state except \(5\), where both moves lead away from \(5\) and it is \(0.6\). The neighbours \(10\) and \(0\) are both at distance \(5\), so a move between them is “other” in both directions and has probability \(0.2\).

Code
par(mfrow = c(1, 2), mar = c(0.5, 0.5, 2, 0.5), cex = 1.1)
ang <- -pi / 2 - 2 * pi * ((0:10) - 5) / 11; rr <- 0.13; dl <- 0.11   # clockwise, 5 at the bottom
draw_cycle <- function(main, col_fwd, col_bwd, lwd_fwd, lwd_bwd, node_bg = rep("white", 11)) {
    plot(NA, xlim = c(-1.45, 1.45), ylim = c(-1.35, 1.35), asp = 1, axes = FALSE, xlab = "", ylab = "", main = main)
    for (i in 0:10) {
        a1 <- ang[i + 1]; a2 <- ang[(i + 1) %% 11 + 1]
        arrows(1.07 * cos(a1 - dl), 1.07 * sin(a1 - dl), 1.07 * cos(a2 + dl), 1.07 * sin(a2 + dl),
               length = 0.07, col = col_fwd[i + 1], lwd = lwd_fwd[i + 1])        # i -> i + 1 (clockwise)
        arrows(0.93 * cos(a2 + dl), 0.93 * sin(a2 + dl), 0.93 * cos(a1 - dl), 0.93 * sin(a1 - dl),
               length = 0.07, col = col_bwd[i + 1], lwd = lwd_bwd[i + 1])        # i + 1 -> i
    }
    symbols(cos(ang), sin(ang), circles = rep(rr, 11), inches = FALSE, add = TRUE, bg = node_bg, lwd = 2)
    text(cos(ang), sin(ang), 0:10)
}
draw_cycle("cyclic walk", rep("gray40", 11), rep("gray40", 11), rep(1.8, 11), rep(1.8, 11))
text(0, 0.1, "each move 0.45", col = "gray30"); text(0, -0.1, "stay 0.1", col = "gray30")
## clockwise i -> i + 1 is toward 5 for i = 0, ..., 4; i + 1 -> i is toward 5 for i = 5, ..., 9;
## the pair (10, 0) is at equal distance from 5, so 0.2 both ways
toward_fwd <- (0:10) <= 4; toward_bwd <- (0:10) >= 5 & (0:10) <= 9
draw_cycle("walk toward 5",
           ifelse(toward_fwd, "steelblue", "firebrick"), ifelse(toward_bwd, "steelblue", "firebrick"),
           ifelse(toward_fwd, 3, 1.5), ifelse(toward_bwd, 3, 1.5), node_bg = ifelse(0:10 == 5, "gold", "white"))
text(0, 0.2, "toward 5: 0.4", col = "steelblue"); text(0, 0, "other: 0.2", col = "firebrick")
text(0, -0.2, "stay: the rest", col = "gray30")
Figure 12.1: Shows the transition structure of two random walks on eleven states arranged on a circle. Left: the cyclic walk, which moves to either neighbour with probability 0.45. Right: the walk toward 5, which moves toward state 5 (thick blue arrows) with probability 0.4 and in any other direction (thin red arrows) with probability 0.2.

Detailed balance only involves neighbours. In both chains \(T(i \to j) = 0\) unless \(j\) is a neighbour of \(i\), so for non-neighbours both sides of the detailed-balance equation are \(0\), and for \(i = j\) the equation is trivial. Only the eleven neighbouring pairs \((i, i+1)\) need to be checked, and the stay probabilities never enter.

The cyclic walk. For every pair, \[ \pi(i)\, T(i \to i+1) = \pi(i+1)\, T(i+1 \to i) \quad\Longleftrightarrow\quad 0.45\, \pi(i) = 0.45\, \pi(i+1) \quad\Longleftrightarrow\quad \pi(i+1) = \pi(i), \] so going around the circle \(\pi(0) = \pi(1) = \cdots = \pi(10)\) and, normalizing, \(\pi_{\text{cyc}}(i) = 1/11\). By the theorem above this \(\pi\) is invariant; the chain is irreducible (every state is reached by moving around the circle) and aperiodic (it can stay put), so the uniform distribution is its equilibrium. Every state has the same local picture, so the equilibrium treats them all alike.

The walk toward 5. In every neighbouring pair except \(\{10, 0\}\), one state \(j\) is one step closer to \(5\) than the other state \(i\), and detailed balance reads \[ \pi(i)\, \underbrace{T(i \to j)}_{0.4\ (\text{toward})} = \pi(j)\, \underbrace{T(j \to i)}_{0.2\ (\text{away})} \quad\Longleftrightarrow\quad \pi(j) = 2\, \pi(i), \] while the pair \(\{10, 0\}\), both at distance \(5\), gives \(0.2\,\pi(10) = 0.2\,\pi(0)\). Each step closer to \(5\) doubles \(\pi\), so \(\pi(i) \propto 2^{-|i-5|}\), and normalizing with \(\sum_i 2^{5 - |i-5|} = 32 + 2(16 + 8 + 4 + 2 + 1) = 94\), \[ \pi_5(i) = \frac{2^{\,5 - |i-5|}}{94}, \qquad i = 0, 1, \ldots, 10. \] The equations are consistent around the circle (\(\pi\) doubles five times from \(0\) up to \(5\), halves five times down to \(10\), and \(\pi(10) = \pi(0)\)), and the chain is irreducible and aperiodic, so this is its equilibrium: symmetric, with a peak of \(32/94 \approx 0.34\) at \(5\), falling by half for each step away.

Empirical check. Each chain is simulated by a one-line step function that, given the current state and a uniform draw \(u\), returns the next state:

Code
cyc_step <- function(s, u)
    ifelse(u < 0.45, (s + 1) %% 11, ifelse(u < 0.9, (s - 1) %% 11, s))
toward5_step <- function(s, u) {
    fwd <- (s + 1) %% 11; bwd <- (s - 1) %% 11
    p_fwd <- ifelse(abs(fwd - 5) < abs(s - 5), 0.4, 0.2)     # toward 5: 0.4, other: 0.2
    p_bwd <- ifelse(abs(bwd - 5) < abs(s - 5), 0.4, 0.2)
    ifelse(u < p_fwd, fwd, ifelse(u < p_fwd + p_bwd, bwd, s))
}
sim_chain <- function(step, ini, iters) {
    mc <- integer(iters + 1); mc[1] <- ini
    for (i in 2:(iters + 1)) mc[i] <- step(mc[i - 1], runif(1))
    mc
}
set.seed(1)
cyc <- sim_chain(cyc_step, 2, 20000)
tw5 <- sim_chain(toward5_step, 2, 20000)
pi_cyc <- rep(1 / 11, 11); pi_5 <- 2^(5 - abs(0:10 - 5)) / 94       # from detailed balance
freq <- function(mc) as.vector(table(factor(mc[-(1:200)], levels = 0:10))) / length(mc[-(1:200)])
Code
par(mfrow = c(2, 2), mar = c(4, 4, 2, 1))
plot(cyc[1:300], type = "s", col = "steelblue", xlab = "step", ylab = "state", ylim = c(0, 10),
     main = "cyclic walk: first 300 steps", yaxt = "n"); axis(2, at = 0:10, las = 1)
plot(tw5[1:300], type = "s", col = "firebrick", xlab = "step", ylab = "state", ylim = c(0, 10),
     main = "walk toward 5: first 300 steps", yaxt = "n"); axis(2, at = 0:10, las = 1)
bp <- barplot(freq(cyc), names.arg = 0:10, col = "lightsteelblue", ylim = c(0, 0.4),
              xlab = "state", ylab = "frequency", main = "cyclic walk: uniform, 1/11")
points(bp, pi_cyc, pch = 19, col = "steelblue4", cex = 1.3)
bp <- barplot(freq(tw5), names.arg = 0:10, col = "mistyrose", ylim = c(0, 0.5),
              xlab = "state", ylab = "frequency", main = "walk toward 5")
points(bp, pi_5, pch = 19, col = "firebrick4", cex = 1.3)
legend("topleft", bty = "n", pch = c(15, 19), col = c("mistyrose", "firebrick4"), pt.cex = c(2, 1.3),
       legend = c("observed frequency", "equilibrium from detailed balance"))
Figure 12.2: Confirms the equilibrium distributions found from detailed balance by simulating the two random walks. One chain of each kind, started at state 2 and run for 20,000 steps. Top: the first 300 steps. Bottom: long-run frequencies of the states after discarding 200 steps (bars), against the equilibrium from detailed balance (points): uniform for the cyclic walk, and 2^(5 - |i - 5|)/94 for the walk toward 5.
Code
tab <- rbind("cyclic walk, frequency" = freq(cyc), "cyclic walk, equilibrium" = pi_cyc,
             "walk toward 5, frequency" = freq(tw5), "walk toward 5, equilibrium" = pi_5)
colnames(tab) <- 0:10
knitr::kable(tab, digits = 3)
Table 12.1: Compares the long-run state frequencies of the two simulated random walks with their equilibrium distributions from detailed balance. Frequencies over 20,000 steps after discarding the first 200.
0 1 2 3 4 5 6 7 8 9 10
cyclic walk, frequency 0.097 0.092 0.086 0.086 0.084 0.086 0.088 0.091 0.092 0.098 0.101
cyclic walk, equilibrium 0.091 0.091 0.091 0.091 0.091 0.091 0.091 0.091 0.091 0.091 0.091
walk toward 5, frequency 0.007 0.015 0.038 0.078 0.167 0.358 0.176 0.088 0.044 0.019 0.009
walk toward 5, equilibrium 0.011 0.021 0.043 0.085 0.170 0.340 0.170 0.085 0.043 0.021 0.011

The observed frequencies agree with the equilibria found from detailed balance up to Monte Carlo error. The two chains differ only in their transition probabilities, yet one spreads its time evenly over the circle and the other concentrates around state \(5\): the equilibrium is determined entirely by \(T\), and the pairwise detailed-balance equations are the easiest way to read it off. MCMC turns this around: it starts from the target \(\pi\) and chooses a \(T\) whose detailed-balance equations \(\pi\) satisfies.

12.2 Gibbs Sampling

12.2.1 The idea and why it works

Suppose \(\theta = (\theta_1, \theta_2)\) and both full conditionals \(\pi(\theta_1 \mid \theta_2)\) and \(\pi(\theta_2 \mid \theta_1)\) can be sampled directly, even though the joint \(\pi(\theta_1, \theta_2)\) has no closed form or cannot be sampled directly. The Gibbs sampler alternates \[ \theta_1^{(t)} \sim \pi\big(\theta_1 \mid \theta_2^{(t-1)}\big), \qquad \theta_2^{(t)} \sim \pi\big(\theta_2 \mid \theta_1^{(t)}\big). \] Each half-step leaves \(\pi\) invariant: if \((\theta_1, \theta_2) \sim \pi\), then \(\theta_2 \sim \pi(\theta_2)\) (its marginal), and replacing \(\theta_1\) by a fresh draw from \(\pi(\theta_1 \mid \theta_2)\) produces a pair with joint density \(\pi(\theta_2)\,\pi(\theta_1 \mid \theta_2) = \pi(\theta_1, \theta_2)\) — exactly \(\pi\) again. Cycling through both coordinates therefore also leaves \(\pi\) invariant, and as long as the full conditionals are everywhere positive the chain is irreducible and aperiodic. No proposal, no acceptance step, no tuning: Gibbs sampling only needs full conditionals that can be sampled.

12.2.2 Data augmentation

Gibbs sampling extends immediately to models with latent variables. If the target \(\pi(\theta)\) is awkward but can be written as the marginal of a joint density \(\pi(\theta, z)\) over \(\theta\) and some extra unknowns \(z\), \[ \pi(\theta) = \int \pi(\theta, z)\, dz, \] then a Gibbs sampler on \((\theta, z)\) that alternates \(z \sim \pi(z \mid \theta)\) and \(\theta \sim \pi(\theta \mid z)\) has \(\pi(\theta, z)\) as its invariant distribution, so its \(\theta\)-coordinates are draws from \(\pi(\theta)\): the \(z\)’s are simply discarded. This data augmentation pays off when the conditionals given \(z\) are standard even though \(\pi(\theta)\) itself is not. The \(z\) may be real missing data (Example 3, where exact values are hidden by censoring) or a purely mathematical device (Example 4, where a latent variance per observation turns a Cauchy likelihood into a normal one).

12.2.3 Example 2: Normal Data with Unknown Mean and Variance

12.2.3.1 The full conditionals

The running example for this half of the book is \(x_1, \ldots, x_n \mid \mu, \sigma^2 \overset{iid}{\sim} N(\mu, \sigma^2)\), with independent priors \(\mu \sim N(\mu_0, \sigma_0^2)\) and \(\sigma^2 \sim \mathrm{IG}(a_0, \lambda_0)\) (inverse-gamma: \(1/\sigma^2 \sim \mathrm{Gamma}(a_0, \lambda_0)\), so \(a_0\) is a shape and \(\lambda_0\) a rate/scale). The joint posterior is \[ \begin{aligned} P(\mu, \sigma^2 \mid x) \ \propto\ {} & e^{-(\mu-\mu_0)^2 / (2\sigma_0^2)} \cdot (\sigma^2)^{-(a_0+1)} e^{-\lambda_0/\sigma^2} \\ & \times (\sigma^2)^{-n/2} \exp\Big\{-\sum_{i=1}^n \tfrac{(x_i-\mu)^2}{2\sigma^2}\Big\}, \end{aligned} \] two-dimensional with no closed-form normalizing constant, but each conditional is standard.

The model is easiest to read as a graph (Figure 12.3). Squares are fixed hyperparameters, open circles are unknown random quantities, shaded circles are observed data, and each arrow points from a quantity to one whose distribution depends on it. The box (a plate) stands for \(n\) copies of what it contains, one for each observation. The full conditional of a node depends only on its parents, its children and its children’s other parents, which is why the conditional of \(\mu\) needs only its prior constants, the data, and \(\sigma^2\) (the other parent of the data), and likewise for \(\sigma^2\).

Code
### draw a directed acyclic graph of a Bayesian model:
### squares = fixed hyperparameters, open circles = unknown random quantities,
### shaded circles = observed data (type "observed_square" draws observed data as a
### shaded square; type "dots" is a bare label, e.g. for an omitted stretch of a chain); arrows point from parent to child, and a
### rounded box (plate) holds the quantities repeated over i = 1, ..., n
draw_dag <- function(nodes, edges, plates = list(), main = "", r = 0.33,
                     xlim = range(nodes$x) + c(-0.8, 0.8), ylim = range(nodes$y) + c(-0.8, 0.8)) {
    plot.new(); plot.window(xlim = xlim, ylim = ylim, asp = 1)
    title(main, cex.main = 1)
    for (p in plates) {
        rect(p$x[1], p$y[1], p$x[2], p$y[2], border = "gray45", lwd = 1.5)
        text(p$x[2] - 0.08, p$y[1] + 0.08, p$label, adj = c(1, 0), cex = 0.85, col = "gray30")
    }
    for (k in seq_len(nrow(edges))) {
        a <- nodes[nodes$id == edges$from[k], ]; b <- nodes[nodes$id == edges$to[k], ]
        d <- c(b$x - a$x, b$y - a$y); u <- d / sqrt(sum(d^2))
        arrows(a$x + r * u[1], a$y + r * u[2], b$x - (r + 0.03) * u[1], b$y - (r + 0.03) * u[2],
               length = 0.08, lwd = 1.4, col = if (is.null(edges$col)) "gray20" else edges$col[k])
    }
    th <- seq(0, 2 * pi, length.out = 100)
    for (k in seq_len(nrow(nodes))) {
        nd <- nodes[k, ]
        if (nd$type == "dots") {
            # placeholder for the omitted middle of a chain: label only
        } else if (nd$type %in% c("fixed", "observed_square")) {
            rect(nd$x - r * 0.85, nd$y - r * 0.85, nd$x + r * 0.85, nd$y + r * 0.85,
                 col = if (nd$type == "observed_square") "gray80" else "white",
                 border = "gray20", lwd = 1.5)
        } else {
            polygon(nd$x + r * cos(th), nd$y + r * sin(th), border = "gray20", lwd = 1.5,
                    col = if (nd$type == "observed") "gray80" else "white")
        }
        text(nd$x, nd$y, parse(text = nd$label), cex = 1.05)
    }
}
Code
par(mar = c(0.5, 0.5, 0.5, 0.5))
nodes_norm <- data.frame(
    id    = c("m0", "s0", "a0", "l0", "mu", "s2", "x"),
    label = c("mu[0]", "sigma[0]^2", "a[0]", "lambda[0]", "mu", "sigma^2", "x[i]"),
    x = c(-1.6, -0.6, 0.6, 1.6, -1.1, 1.1, 0), y = c(2, 2, 2, 2, 1, 1, -0.2),
    type = c(rep("fixed", 4), "latent", "latent", "observed"))
edges_norm <- data.frame(from = c("m0", "s0", "a0", "l0", "mu", "s2"),
                         to   = c("mu", "mu", "s2", "s2", "x", "x"))
draw_dag(nodes_norm, edges_norm,
         plates = list(list(x = c(-0.8, 0.8), y = c(-0.9, 0.5), label = "i = 1, ..., n")))
Figure 12.3: Shows the structure of the normal model with unknown mean and variance as a directed graph. Squares: fixed hyperparameters; open circles: unknown parameters; shaded circle: observed data. The plate repeats x_i for i = 1, …, n.

Conditional of \(\mu\). Collect the factors that involve \(\mu\) and expand \(\sum_i(x_i-\mu)^2 = n\mu^2 - 2n\mu\bar x + \sum_i x_i^2\): \[ \begin{aligned} P(\mu \mid \sigma^2, x) \ \propto\ \exp\Big\{-\tfrac12\Big[ & \big(\tfrac{1}{\sigma_0^2} + \tfrac{n}{\sigma^2}\big)\mu^2 \\ & - 2\big(\tfrac{\mu_0}{\sigma_0^2} + \tfrac{n\bar x}{\sigma^2}\big)\mu\Big]\Big\}, \end{aligned} \] which is the kernel of \(N(m, v)\) with \(1/v = 1/\sigma_0^2 + n/\sigma^2\) and \(m/v = \mu_0/\sigma_0^2 + n\bar x/\sigma^2\) — a precision-weighted average of the prior mean and the sample mean, with \(n/\sigma^2\) the weight the data contribute. As \(n \to \infty\), \(m \to \bar x\) and \(v \approx \sigma^2/n\): the prior is overwhelmed.

Conditional of \(\sigma^2\). Collect the factors involving \(\sigma^2\): \[ \begin{aligned} P(\sigma^2 \mid \mu, x) & \ \propto\ (\sigma^2)^{-(a_0+1)} e^{-\lambda_0/\sigma^2} \cdot (\sigma^2)^{-n/2} e^{-\sum_i(x_i-\mu)^2/(2\sigma^2)} \\ & \ =\ (\sigma^2)^{-\left(\frac n2 + a_0 + 1\right)} \exp\Big\{-\tfrac{\lambda_0 + \frac12\sum_i(x_i-\mu)^2}{\sigma^2}\Big\}, \end{aligned} \] again an inverse-gamma kernel, \(\sigma^2 \mid \mu, x \sim \mathrm{IG}\big(\tfrac n2 + a_0,\ \tfrac12\sum_i(x_i-\mu)^2 + \lambda_0\big)\): the prior contributes \(a_0\) “pseudo-observations” worth of shape and \(\lambda_0\) worth of sum-of-squares, and the data add \(n\) and \(\sum_i(x_i-\mu)^2\) to each.

12.2.3.2 Implementation

We use the weak prior \(\mu_0 = 0\), \(\sigma_0^2 = 100\), \(a_0 = \lambda_0 = 1\), stored once as mu0, s02, a0 and lam0 and reused by every sampler of this model in the chapter. Each line of the loop is one of the two full conditionals above; an inverse-gamma draw is the reciprocal of a gamma draw with the same shape and rate.

Code
mu0 <- 0; s02 <- 100; a0 <- 1; lam0 <- 1                       # prior
gibbs_norm <- function(iters, x, mu_init = 0, s2_init = 1) {
    n <- length(x)
    out <- matrix(NA_real_, iters, 2, dimnames = list(NULL, c("mu", "s2")))
    mu <- mu_init; s2 <- s2_init
    for (t in seq_len(iters)) {
        v  <- 1 / (1 / s02 + n / s2)                            # mu | sigma^2, x ~ N(m, v)
        mu <- rnorm(1, v * (mu0 / s02 + sum(x) / s2), sqrt(v))
        s2 <- 1 / rgamma(1, shape = n / 2 + a0, rate = sum((x - mu)^2) / 2 + lam0)   # IG
        out[t, ] <- c(mu, s2)
    }
    out
}

A preallocated matrix filled by a plain for loop replaces the original replicate()-with-<<- pattern: it does the same work with one direct assignment per iteration instead of a closure mutating variables in its enclosing scope, and it makes the recurrence — each row built from the previous one — visually explicit.

Code
set.seed(2)
x <- rnorm(50, 10, 2)
draws_gibbs <- gibbs_norm(10000, x)
burn <- 1:200
mu_g  <- draws_gibbs[-burn, "mu"]
sd_g  <- sqrt(draws_gibbs[-burn, "s2"])

par(mfrow = c(2, 2), mar = c(4, 4, 2, 1))
plot(mu_g, type = "l", col = "steelblue", xlab = "iteration", ylab = expression(mu), main = "trace of mu")
plot(density(mu_g), col = "steelblue", lwd = 2, main = "posterior density of mu", xlab = expression(mu))
plot(sd_g, type = "l", col = "firebrick", xlab = "iteration", ylab = expression(sigma), main = "trace of sigma")
plot(density(sd_g), col = "firebrick", lwd = 2, main = "posterior density of sigma", xlab = expression(sigma))
Figure 12.4: Demonstrates the Gibbs sampler on a normal model with unknown mean and standard deviation, using trace plots to check convergence and densities to summarize the posterior. Gibbs sampler on 50 simulated N(10, 2^2) observations: trace plots and posterior densities for mu and sigma, with the weak prior.
Code
gibbs_summary <- data.frame(
    parameter = c("mu", "sigma"),
    mean = c(mean(mu_g), mean(sd_g)),
    sd   = c(sd(mu_g), sd(sd_g)),
    q025 = c(quantile(mu_g, 0.025), quantile(sd_g, 0.025)),
    q975 = c(quantile(mu_g, 0.975), quantile(sd_g, 0.975))
)
knitr::kable(gibbs_summary, digits = 3,
             col.names = c("parameter", "mean", "sd", "2.5%", "97.5%"),
             align = c("l", "r", "r", "r", "r"))
Table 12.2: Summarizes the posterior distribution obtained from the Gibbs sampler. Posterior summaries from the Gibbs sampler (after discarding a 200-iteration burn-in).
parameter mean sd 2.5% 97.5%
mu 10.141 0.330 9.489 10.791
sigma 2.293 0.239 1.885 2.809

Because each update changes one coordinate while holding the other fixed, the path of a Gibbs sampler on the joint posterior is a staircase of horizontal and vertical moves (Figure 12.5). From a poor start the chain reaches the bulk of the posterior within a few iterations.

Code
set.seed(21)
d2 <- gibbs_norm(30, x, mu_init = 8, s2_init = 8)
lpost <- function(mu, s2) sum(dnorm(x, mu, sqrt(s2), log = TRUE)) + dnorm(mu, mu0, sqrt(s02), log = TRUE) -
    (a0 + 1) * log(s2) - lam0 / s2
mg <- seq(7.5, 11.5, length.out = 100); sg <- seq(1.5, 9, length.out = 100)
Z <- outer(mg, sg, Vectorize(lpost)); Z <- exp(Z - max(Z))
layout(matrix(c(1, 1, 2, 3), 2)); par(mar = c(4, 4, 2, 1))
contour(mg, sg, Z, nlevels = 8, drawlabels = FALSE, xlab = expression(mu), ylab = expression(sigma^2),
        main = "Gibbs path: first 30 moves from (8, 8)")
pp <- rbind(c(8, 8)); for (t in 1:30) pp <- rbind(pp, c(d2[t, 1], pp[nrow(pp), 2]), d2[t, ])   # horizontal then vertical
lines(pp, col = "firebrick", lwd = 1.5); points(d2, pch = 19, col = "firebrick", cex = 0.7)
points(8, 8, pch = 17, cex = 1.5)
plot(draws_gibbs[1:100, "mu"], type = "l", xlab = "t", ylab = expression(mu), main = "trace of mu")
plot(draws_gibbs[1:100, "s2"], type = "l", xlab = "t", ylab = expression(sigma^2), main = "trace of sigma^2")
Figure 12.5: Shows how the Gibbs sampler moves on the joint posterior of the normal model, one coordinate at a time. Left: the first 30 moves from the poor start (8, 8) (triangle) over the contours of the exact posterior; each move is horizontal (a mu update) or vertical (a sigma^2 update). Right: trace plots of the first 100 iterations of the main run.

12.2.4 Example 3: Interval-Censored Normal Data

The problem. The quantities of interest are \(x_1, \ldots, x_n \mid \mu, \sigma^2 \overset{iid}{\sim} N(\mu, \sigma^2)\), with the priors of Example 2, but not every \(x_i\) is seen exactly. For each unit we observe a pair \((I_i, \delta_i)\):

  • \(\delta_i = 1\) means \(x_i\) is not censored: it is observed exactly, and \(I_i = \{x_i\}\).
  • \(\delta_i = 0\) means \(x_i\) is censored: we only learn an interval \(I_i = [a_i, b_i)\) that contains it. The interval may be bounded (a value recorded only to the nearest decade, or between two inspection times) or open-ended, \(b_i = \infty\) (a value known only to exceed a detection or follow-up limit, which is right censoring).

The observed data are the \((I_i, \delta_i)\), and the censored \(x_i\) are unknown. The indicators \(\delta_i\) are independent of the \(x_i\) and of \((\mu, \sigma^2)\), so they carry no information about the parameters, and the likelihood is \[ \begin{aligned} L(\mu, \sigma^2) = {} & \prod_{i:\,\delta_i = 1} \frac{1}{\sigma}\,\varphi\Big(\frac{x_i - \mu}{\sigma}\Big) \\ & \times \prod_{i:\,\delta_i = 0} \Big[\Phi\Big(\frac{b_i - \mu}{\sigma}\Big) - \Phi\Big(\frac{a_i - \mu}{\sigma}\Big)\Big], \end{aligned} \] where \(\varphi\) and \(\Phi\) are the standard normal density and CDF. The products of \(\Phi\) differences make the posterior non-standard: neither conditional of \(\mu\) or \(\sigma^2\) is a normal or inverse-gamma distribution.

Data augmentation. Treat the unobserved \(x_i\) as extra unknowns. Given all \(x_i\), the data are complete and the conditionals of \(\mu\) and \(\sigma^2\) are exactly those of Example 2. Given \((\mu, \sigma^2)\) and the observed \((I_i, \delta_i)\), a censored \(x_i\) has density proportional to the \(N(\mu, \sigma^2)\) density times the indicator that \(x_i \in I_i\): \[ x_i \mid \mu, \sigma^2, I_i, \delta_i = 0 \ \sim\ N(\mu, \sigma^2) \text{ truncated to } [a_i, b_i), \] while an uncensored \(x_i\) is fixed at its observed value. One Gibbs iteration is \[ \begin{aligned} x_i^{(t)} & \sim P\big(x_i \mid \mu^{(t-1)}, \sigma^{2(t-1)}, I_i, \delta_i\big) \quad (\text{censored } i), \\ \mu^{(t)} & \sim P\big(\mu \mid x^{(t)}, \sigma^{2(t-1)}\big), \qquad \sigma^{2(t)} \sim P\big(\sigma^2 \mid x^{(t)}, \mu^{(t)}\big). \end{aligned} \] Integrating the latent \(x_i\) out of the augmented model gives back exactly the likelihood above, since \(\int_{a_i}^{b_i} \sigma^{-1}\varphi((x - \mu)/\sigma)\,dx\) is the bracketed \(\Phi\) difference.

In the graph of the model (Figure 12.6), \(x_i\) is an unknown circle below the parameters, and the observed interval \(I_i\) and indicator \(\delta_i\) are shaded squares. \(I_i\) contains \(x_i\) (and equals it when \(\delta_i = 1\)), so \(x_i\) is its parent. The indicator \(\delta_i\) is independent of \(x_i\) and of the parameters (whether a unit is observed exactly does not depend on its value), so it has no arrows: it carries no information about \((\mu, \sigma^2)\).

Code
par(mar = c(0.5, 0.5, 0.5, 0.5))
nodes_cens <- rbind(nodes_norm[1:6, ], data.frame(
    id = c("x", "d", "I"), label = c("x[i]", "delta[i]", "I[i]"),
    x = c(0, 1.3, 0), y = c(-0.2, -1.4, -1.4),
    type = c("latent", "observed_square", "observed_square")))
edges_cens <- rbind(edges_norm, data.frame(from = "x", to = "I"))
draw_dag(nodes_cens, edges_cens,
         plates = list(list(x = c(-0.8, 2.0), y = c(-2.1, 0.5), label = "i = 1, ..., n")))
Figure 12.6: Shows the structure of the interval-censored normal model as a directed graph, with the exact values as latent variables. The exact value x_i (open circle) is unknown. The observed data (shaded squares) are the interval I_i that contains x_i and the indicator delta_i, which is 1 when x_i is observed exactly (I_i is the single point x_i) and 0 when it is censored. delta_i is independent of x_i and the parameters, so it has no arrows.

The sampler below stores each interval as its endpoints a, b, with a = b = x for an uncensored unit. The censored \(x_i\) are drawn from their truncated normals with truncnorm::rtruncnorm, which also handles \(b_i = \infty\):

Code
gibbs_norm_censored <- function(iters, a, b, delta) {      # prior constants mu0, s02, a0, lam0 of Example 2
    n <- length(a); cens <- delta == 0
    x <- ifelse(cens, pmin(a + 1, b), a)     # start: exact values, or a point in the interval
    mu <- mean(x); s2 <- var(x)
    out <- matrix(NA_real_, iters, 2)
    for (t in seq_len(iters)) {
        ### censored units: x_i | mu, sigma^2 ~ N(mu, sigma^2) truncated to [a_i, b_i)
        x[cens] <- rtruncnorm(sum(cens), a = a[cens], b = b[cens], mean = mu, sd = sqrt(s2))
        ### complete-data conditionals of Example 2
        v  <- 1 / (1 / s02 + n / s2)
        mu <- rnorm(1, v * (mu0 / s02 + sum(x) / s2), sqrt(v))
        s2 <- 1 / rgamma(1, shape = n / 2 + a0, rate = sum((x - mu)^2) / 2 + lam0)
        out[t, ] <- c(mu, s2)
    }
    list(mu = out[, 1], sd = sqrt(out[, 2]))
}

To test it, simulate \(n = 200\) values from \(N(100, 40^2)\). Each is observed exactly with probability \(0.3\). Otherwise it is censored: values above \(150\) are only known to be at least \(150\) (right censoring, \(I_i = [150, \infty)\)), and the rest are only known to the decade, \(I_i = [10k, 10k + 10)\).

Code
set.seed(3)
n_c <- 200
x_true <- rnorm(n_c, 100, 40)
delta  <- rbinom(n_c, 1, 0.3)
a_obs  <- ifelse(delta == 1, x_true, ifelse(x_true >= 150, 150, floor(x_true / 10) * 10))
b_obs  <- ifelse(delta == 1, x_true, ifelse(x_true >= 150, Inf, a_obs + 10))
fit_cens <- gibbs_norm_censored(5000, a_obs, b_obs, delta)
burn2 <- 1:200
knitr::kable(data.frame(
    quantity = c("exact / interval / right-censored", "mu", "sigma"),
    truth = c(sprintf("%d / %d / %d", sum(delta == 1), sum(delta == 0 & is.finite(b_obs)),
                      sum(is.infinite(b_obs))), "100", "40"),
    naive = c("", sprintf("%.2f", mean(a_obs)), sprintf("%.2f", sd(a_obs))),
    posterior = c("", sprintf("%.2f (%.2f, %.2f)", mean(fit_cens$mu[-burn2]),
                              quantile(fit_cens$mu[-burn2], 0.025), quantile(fit_cens$mu[-burn2], 0.975)),
                  sprintf("%.2f (%.2f, %.2f)", mean(fit_cens$sd[-burn2]),
                          quantile(fit_cens$sd[-burn2], 0.025), quantile(fit_cens$sd[-burn2], 0.975)))
), col.names = c("", "truth", "naive", "posterior mean (95% interval)"), align = c("l", "r", "r", "r"))
Table 12.3: Shows that Gibbs sampling extends to interval-censored data by treating the exact values as latent variables, and that the parameters are still recovered. n = 200 values from N(100, 40^2): 30% observed exactly, the rest censored to a decade or, above 150, right-censored at 150. The naive estimates treat each censored value as its interval’s lower end.
truth naive posterior mean (95% interval)
exact / interval / right-censored 70 / 121 / 9
mu 100 96.88 93.38 (87.89, 98.69)
sigma 40 38.00 39.65 (35.75, 43.93)

Censoring removes a great deal of information: most units only say which decade \(x_i\) fell in, and the largest values are only known to exceed \(150\). Treating each censored value as the lower end of its interval biases both estimates downward, and the naive estimates come with no honest measure of their uncertainty. The augmented Gibbs sampler still recovers \(\mu\) and \(\sigma\), because it imputes each censored \(x_i\) from its conditional distribution given the current parameters and so propagates the uncertainty about where in \(I_i\) it lies.

12.2.5 Example 4: Cauchy Data with Unknown Location and Scale

The problem. Observations \(y_1, \ldots, y_n\) are modelled as \(\text{Cauchy}(\mu, \sigma)\), a heavy-tailed model that is robust to outliers: \[ p(y_i \mid \mu, \sigma) = \frac{1}{\pi\sigma\,\big(1 + r_i^2\big)}, \qquad r_i = \frac{y_i - \mu}{\sigma}. \] The priors are \(\mu \sim N(\mu_0, \tau^2)\) and \(\sigma^2 \sim \mathrm{IG}(a_0, b_0)\), with density \(p(\sigma^2) \propto (\sigma^2)^{-(a_0+1)}e^{-b_0/\sigma^2}\). The posterior of \((\mu, \sigma^2)\) is proportional to \(e^{-(\mu-\mu_0)^2/(2\tau^2)}\,(\sigma^2)^{-(a_0+1)}e^{-b_0/\sigma^2}\prod_i \sigma^{-1}(1 + r_i^2)^{-1}\). Neither conditional is a standard distribution, because of the factors \((1 + r_i^2)^{-1}\). Data augmentation fixes this.

12.2.5.1 Step 1: the Cauchy as a scale mixture of normals

Introduce a latent variance \(v_i\) for each observation, with \[ \begin{aligned} & y_i \mid \mu, \sigma^2, v_i \sim N(\mu, \sigma^2 v_i), \qquad v_i \sim \mathrm{IG}\big(\tfrac12, \tfrac12\big), \\ & p(v_i) = \frac{(1/2)^{1/2}}{\Gamma(1/2)}\, v_i^{-3/2} e^{-1/(2v_i)} = \frac{1}{\sqrt{2\pi}}\, v_i^{-3/2} e^{-1/(2v_i)}. \end{aligned} \] Integrating out \(v_i\) gives back the Cauchy density: \[ \begin{aligned} & \int_0^\infty p(y_i \mid \mu, \sigma^2, v_i)\, p(v_i)\, dv_i \\ &\quad = \int_0^\infty \frac{1}{\sqrt{2\pi\sigma^2 v_i}}\, e^{-r_i^2/(2v_i)} \cdot \frac{1}{\sqrt{2\pi}}\, v_i^{-3/2} e^{-1/(2v_i)}\, dv_i \\ &\quad = \frac{1}{2\pi\sigma} \int_0^\infty v_i^{-2} \exp\Big\{-\frac{1 + r_i^2}{2v_i}\Big\}\, dv_i \\ &\quad = \frac{1}{2\pi\sigma}\cdot\frac{2}{1 + r_i^2} = \frac{1}{\pi\sigma(1 + r_i^2)}, \end{aligned} \] using \(\int_0^\infty v^{-2}e^{-c/v}\,dv = 1/c\) (substitute \(u = 1/v\)). So the augmented model has exactly the original posterior as its \((\mu, \sigma^2)\) marginal, and a Gibbs sampler on \((v, \mu, \sigma^2)\) samples the Cauchy posterior once the \(v_i\) are ignored.

Figure 12.7 shows this augmented model. Compared with Figure 12.3, each observation has its own latent variance \(v_i\), a child of the fixed constants \(\tfrac12, \tfrac12\) of its \(\mathrm{IG}\) prior and a parent of \(y_i\). Since \(v_i\) has only one child, its full conditional involves only \(y_i\), \(\mu\) and \(\sigma^2\), as Step 3 below confirms.

Code
par(mar = c(0.5, 0.5, 0.5, 0.5))
nodes_cauchy <- data.frame(
    id    = c("m0", "t2", "a0", "b0", "mu", "s2", "half", "v", "y"),
    label = c("mu[0]", "tau^2", "a[0]", "b[0]", "mu", "sigma^2", "frac(1, 2)", "v[i]", "y[i]"),
    x = c(-1.6, -0.6, 0.6, 1.6, -1.1, 1.1, -2.4, -1.3, 0),
    y = c(2, 2, 2, 2, 1, 1, -0.2, -0.2, -1.2),
    type = c(rep("fixed", 4), "latent", "latent", "fixed", "latent", "observed"))
edges_cauchy <- data.frame(from = c("m0", "t2", "a0", "b0", "half", "mu", "s2", "v"),
                           to   = c("mu", "mu", "s2", "s2", "v", "y", "y", "y"))
draw_dag(nodes_cauchy, edges_cauchy,
         plates = list(list(x = c(-1.9, 0.6), y = c(-1.9, 0.4), label = "i = 1, ..., n")))
Figure 12.7: Shows the structure of the augmented Cauchy model as a directed graph. Each observation y_i has its own latent variance v_i with a fixed IG(1/2, 1/2) prior; integrating v_i out gives the Cauchy model for y_i.

12.2.5.2 Step 2: the augmented joint posterior

Multiplying priors, the latent-variable densities and the normal likelihood, \[ \begin{aligned} p(\mu, \sigma^2, v \mid y) \propto {} & e^{-\frac{(\mu-\mu_0)^2}{2\tau^2}} \,(\sigma^2)^{-(a_0+1)} e^{-b_0/\sigma^2} \\ & \times \prod_{i=1}^n \Big[ (\sigma^2 v_i)^{-1/2} \exp\Big\{-\frac{(y_i-\mu)^2}{2\sigma^2 v_i}\Big\} \cdot v_i^{-3/2} e^{-1/(2v_i)} \Big]. \end{aligned} \] Each full conditional is read off by keeping only the factors that contain the parameter being updated and recognizing the kernel.

12.2.5.3 Step 3: the full conditional of each \(v_i\)

The factors containing \(v_i\) are those in the \(i\)-th term of the product: \[ \begin{aligned} p(v_i \mid \mu, \sigma^2, y) & \propto v_i^{-1/2}\, v_i^{-3/2} \exp\Big\{-\frac{1}{v_i}\Big(\frac{(y_i-\mu)^2}{2\sigma^2} + \frac12\Big)\Big\} \\ & = v_i^{-(1+1)} \exp\Big\{-\frac{(1 + r_i^2)/2}{v_i}\Big\}. \end{aligned} \] This is the \(\mathrm{IG}(a, b)\) kernel \(v^{-(a+1)}e^{-b/v}\) with \(a = 1\) and \(b = (1 + r_i^2)/2\): \[ v_i \mid \mu, \sigma^2, y \sim \mathrm{IG}\Big(1,\ \frac{1 + r_i^2}{2}\Big), \qquad i = 1, \ldots, n, \] independently across \(i\), since \(v_i\) appears in no other factor. The scale \((1 + r_i^2)/2\) grows with the standardized residual \(r_i\), so an outlier gets a large latent variance.

12.2.5.4 Step 4: the full conditional of \(\mu\)

The factors containing \(\mu\) are the prior and the exponentials of the likelihood. Writing \(w_i = 1/(\sigma^2 v_i)\) for the precision of observation \(i\), \[ \begin{aligned} p(\mu \mid \sigma^2, v, y) & \propto \exp\Big\{-\frac{(\mu-\mu_0)^2}{2\tau^2} - \sum_i \frac{w_i (y_i-\mu)^2}{2}\Big\} \\ & \propto \exp\Big\{-\frac12\Big[\Big(\frac{1}{\tau^2} + \sum_i w_i\Big)\mu^2 - 2\Big(\frac{\mu_0}{\tau^2} + \sum_i w_i y_i\Big)\mu\Big]\Big\}, \end{aligned} \] after expanding the squares and dropping terms free of \(\mu\). Completing the square gives a normal distribution: \[ \begin{aligned} & \mu \mid \sigma^2, v, y \sim N\big(m, s^2\big), \\ & \frac{1}{s^2} = \frac{1}{\tau^2} + \sum_{i=1}^n w_i, \qquad m = s^2\Big(\frac{\mu_0}{\tau^2} + \sum_{i=1}^n w_i y_i\Big). \end{aligned} \] This is a precision-weighted mean of the prior mean and the observations, as in Example 2, except that each observation now has its own weight \(w_i\). An outlier, with a large \(v_i\), has a small weight and barely moves \(\mu\); this is where the robustness of the Cauchy model comes from.

12.2.5.5 Step 5: the full conditional of \(\sigma^2\)

The factors containing \(\sigma^2\) are its prior and the likelihood terms \((\sigma^2)^{-1/2}\) and \(\exp\{-(y_i-\mu)^2/(2\sigma^2 v_i)\}\): \[ \begin{aligned} p(\sigma^2 \mid \mu, v, y) & \propto (\sigma^2)^{-(a_0+1)} e^{-b_0/\sigma^2} \cdot (\sigma^2)^{-n/2} \exp\Big\{-\frac{1}{\sigma^2}\sum_i \frac{(y_i-\mu)^2}{2v_i}\Big\} \\ & = (\sigma^2)^{-(a_0 + \frac n2 + 1)} \exp\Big\{-\frac{b_0 + \sum_i (y_i-\mu)^2/(2v_i)}{\sigma^2}\Big\}, \end{aligned} \] again an inverse-gamma kernel: \[ \sigma^2 \mid \mu, v, y \sim \mathrm{IG}\Big(a_0 + \frac n2,\ b_0 + \sum_{i=1}^n \frac{(y_i-\mu)^2}{2v_i}\Big). \]

12.2.5.6 The sampler and a check against the exact posterior

One Gibbs iteration draws all \(v_i\) (Step 3), then \(\mu\) (Step 4), then \(\sigma^2\) (Step 5), each from its full conditional at the current values of the others. We use \(\mu_0 = 0\), \(\tau = 10\) and \(a_0 = b_0 = 1\), and 30 observations from \(\text{Cauchy}(2, 1)\), which include several outliers (the largest is above 35). Because the posterior of \((\mu, \sigma)\) is only two-dimensional, it can also be computed exactly on a grid, which gives an independent check of the sampler. On the \(\sigma\) scale the prior density is \(p(\sigma^2)\cdot 2\sigma\), by the change of variable \(\sigma^2 \to \sigma\).

Code
gibbs_cauchy <- function(iters, y, mu0 = 0, tau = 10, a0 = 1, b0 = 1, mu = 0, s2 = 1) {
    n <- length(y)
    out <- matrix(NA_real_, iters, 2, dimnames = list(NULL, c("mu", "sigma")))
    for (t in seq_len(iters)) {
        ### Step 3: v_i | mu, sigma^2 ~ IG(1, (1 + r_i^2) / 2), drawn as 1 / Gamma
        v <- 1 / rgamma(n, shape = 1, rate = (1 + (y - mu)^2 / s2) / 2)
        ### Step 4: mu | sigma^2, v ~ N(m, s^2), with observation weights w_i = 1 / (sigma^2 v_i)
        w <- 1 / (s2 * v)
        prec <- 1 / tau^2 + sum(w)
        mu <- rnorm(1, (mu0 / tau^2 + sum(w * y)) / prec, sqrt(1 / prec))
        ### Step 5: sigma^2 | mu, v ~ IG(a0 + n / 2, b0 + sum (y_i - mu)^2 / (2 v_i))
        s2 <- 1 / rgamma(1, shape = a0 + n / 2, rate = b0 + sum((y - mu)^2 / (2 * v)))
        out[t, ] <- c(mu, sqrt(s2))
    }
    out
}

### exact log posterior of (mu, sigma), up to a constant, for the grid check
log_post_cauchy <- function(mu, sigma, y, mu0 = 0, tau = 10, a0 = 1, b0 = 1) {
    sum(dcauchy(y, mu, sigma, log = TRUE)) + dnorm(mu, mu0, tau, log = TRUE) -
        (a0 + 1) * log(sigma^2) - b0 / sigma^2 + log(2 * sigma)
}

set.seed(7)
y_cauchy <- rcauchy(30, location = 2, scale = 1)
draws_cauchy <- gibbs_cauchy(20000, y_cauchy, mu = -5, s2 = 25)   # deliberately poor start
keep_c <- -(1:1000)

mu_grid <- seq(0, 4, length.out = 300); sg_grid <- seq(0.2, 3.5, length.out = 300)
lp <- outer(mu_grid, sg_grid, Vectorize(function(m, s) log_post_cauchy(m, s, y_cauchy)))
post <- exp(lp - max(lp)); post <- post / sum(post)
Code
par(mfrow = c(1, 3), mar = c(4, 4, 2, 1))
contour(mu_grid, sg_grid, post, nlevels = 8, drawlabels = FALSE, col = "gray55",
        xlim = c(-5.5, 4), ylim = c(0, 5.5), xlab = expression(mu), ylab = expression(sigma),
        main = "first 15 iterations")
path <- rbind(c(-5, 5), draws_cauchy[1:15, ])
for (t in 1:15) {   # mu moves first (horizontal leg), then sigma (vertical leg)
    segments(path[t, 1], path[t, 2], path[t + 1, 1], path[t, 2], col = "darkorange", lwd = 1.5)
    segments(path[t + 1, 1], path[t, 2], path[t + 1, 1], path[t + 1, 2], col = "steelblue", lwd = 1.5)
}
points(-5, 5, pch = 17, cex = 1.4)
plot(draws_cauchy[1:500, "mu"], type = "l", col = "darkorange", xlab = "iteration",
     ylab = expression(mu), main = "trace of mu")
plot(draws_cauchy[1:500, "sigma"], type = "l", col = "steelblue", xlab = "iteration",
     ylab = expression(sigma), main = "trace of sigma")
Figure 12.8: Demonstrates the data-augmentation Gibbs sampler for Cauchy data with unknown location and scale, checked against the exact posterior. Left: the first 15 iterations from a poor start (triangle), drawn as the staircase of mu- and sigma-updates, over the contours of the exact posterior computed on a grid. Middle and right: trace plots of mu and sigma for the first 500 iterations; the chain reaches the posterior within a few iterations.
Code
grid_mean <- function(g, margin) sum(apply(post, margin, sum) * g)
grid_sd   <- function(g, margin) sqrt(sum(apply(post, margin, sum) * g^2) - grid_mean(g, margin)^2)
knitr::kable(data.frame(
    quantity = c("posterior mean of mu", "posterior sd of mu",
                 "posterior mean of sigma", "posterior sd of sigma"),
    gibbs = c(mean(draws_cauchy[keep_c, "mu"]), sd(draws_cauchy[keep_c, "mu"]),
              mean(draws_cauchy[keep_c, "sigma"]), sd(draws_cauchy[keep_c, "sigma"])),
    exact = c(grid_mean(mu_grid, 1), grid_sd(mu_grid, 1),
              grid_mean(sg_grid, 2), grid_sd(sg_grid, 2))
), digits = 3, col.names = c("quantity", "Gibbs", "exact (grid)"), align = c("l", "r", "r"))
Table 12.4: Checks the data-augmentation Gibbs sampler for the Cauchy model against the exact posterior computed on a grid. Posterior means and standard deviations of mu and sigma from 19,000 Gibbs draws (after a 1,000-iteration burn-in) and from the exact grid posterior. The sample median and the sample standard deviation are shown for contrast: the outliers inflate the standard deviation, while the Cauchy posterior is not affected by them.
quantity Gibbs exact (grid)
posterior mean of mu 2.228 2.228
posterior sd of mu 0.179 0.179
posterior mean of sigma 0.768 0.765
posterior sd of sigma 0.181 0.178

The Gibbs estimates agree with the exact posterior to Monte Carlo error. For comparison, the sample mean of these data is 3.68 and the sample standard deviation is 6.43, both dragged far off by the outliers, while the posterior mean of \(\mu\) stays near the centre of the bulk of the data. A shinylive app runs this sampler one conditional update at a time: it shows the \(v\), \(\mu\) and \(\sigma\) updates as separate steps on the exact posterior, and the latent variances \(v_i\) of the outliers.

12.3 Metropolis–Hastings

12.3.1 The algorithm

Gibbs sampling needs full conditionals that are both known and directly sample-able — a strong requirement outside conjugate models. Metropolis–Hastings (MH) needs only a target \(\pi(\theta)\) computable up to a constant and any proposal distribution \(\tilde T(\theta^* \mid \theta)\) we can sample from. Starting from \(\theta^{(0)}\), repeat:

  1. Draw a proposal \(\theta^* \sim \tilde T(\cdot \mid \theta^{(t-1)})\).
  2. Compute the acceptance ratio \(r = \min\Big\{\dfrac{\pi(\theta^*)\,\tilde T(\theta^{(t-1)} \mid \theta^*)}{\pi(\theta^{(t-1)})\,\tilde T(\theta^* \mid \theta^{(t-1)})},\ 1\Big\}\).
  3. With probability \(r\) set \(\theta^{(t)} = \theta^*\) (accept); otherwise set \(\theta^{(t)} = \theta^{(t-1)}\) (reject and repeat the current value).

Only the ratio \(\pi(\theta^*)/\pi(\theta^{(t-1)})\) is needed, so any normalizing constant of \(\pi\) cancels — exactly as in rejection sampling, but here a rejected proposal still contributes a draw (the repeated current value) rather than being discarded, which is what lets MH work even when \(\pi\) has no available envelope. One can show (by checking detailed balance directly, splitting into the “propose and accept” and “reject and stay” cases and using the \(\min\{\cdot,\cdot\}\) identity \(\min\{a,b\} = \min\{b,a\}\)) that this \(T\) leaves \(\pi\) invariant regardless of what \(\tilde T\) is, as long as its support is compatible with \(\pi\)’s.

12.3.2 Random-walk Metropolis

If \(\tilde T\) is symmetric, \(\tilde T(\theta^* \mid \theta) = \tilde T(\theta \mid \theta^*)\) — e.g. \(\theta^* \sim N(\theta^{(t-1)}, \varsigma^2)\) — the proposal terms cancel and \(r = \min\{\pi(\theta^*)/\pi(\theta^{(t-1)}), 1\}\): uphill proposals are always accepted, downhill ones accepted in proportion to how much worse they are. \(\varsigma\), the step size, is the only tuning parameter.

Code
met_gauss <- function(iters, log_f, stepsizes, ini_value, ...) {
    state <- ini_value; no_var <- length(state)
    logf <- log_f(ini_value, ...)
    if (!is.finite(logf)) stop("Initial value has zero probability")
    out <- matrix(NA_real_, iters, no_var); n_acc <- 0
    for (t in seq_len(iters)) {
        proposal <- rnorm(no_var, state, stepsizes)
        new_logf <- log_f(proposal, ...)
        if (log(runif(1)) < new_logf - logf) {
            state <- proposal; logf <- new_logf; n_acc <- n_acc + 1
        }
        out[t, ] <- state
    }
    attr(out, "accept_rate") <- n_acc / iters
    out
}

12.3.3 Choosing the step size

The chain’s draws are dependent, and what determines the precision of an ergodic average is not the acceptance rate itself but the resulting autocorrelation: for a stationary chain with lag-\(k\) autocorrelation \(\rho_k\), \[ \begin{aligned} \mathrm{Var}\Big(\tfrac1T\sum_{t=1}^T \theta^{(t)}\Big) & \approx \frac{\sigma^2}{T}\Big(1 + 2\sum_{k \ge 1} \rho_k\Big) \\ & = \frac{\sigma^2}{T_\text{eff}}, \end{aligned} \] so the tuning goal is small autocorrelation, not a high acceptance rate as such. A step too small is accepted almost every time but crawls (highly autocorrelated); a step too large is almost always rejected, so the chain barely moves either. Both extremes waste the same \(T\) iterations on far fewer effective ones — the figure below (three step sizes on a \(N(0,1)\) target) makes this visible directly in the trace and the ACF.

Code
mh_std_normal <- function(sig, n = 2000) {
    th <- numeric(n); th[1] <- 0; acc <- 0
    for (t in 2:n) {
        p <- th[t - 1] + rnorm(1, 0, sig)
        if (runif(1) < dnorm(p) / dnorm(th[t - 1])) { th[t] <- p; acc <- acc + 1 } else th[t] <- th[t - 1]
    }
    list(th = th, acc = acc / (n - 1))
}
res <- lapply(c(0.1, 2.4, 40), mh_std_normal)
labs <- c("too small", "about right", "too large")
par(mfrow = c(2, 3), mar = c(4, 4, 2, 1))
for (k in 1:3) plot(res[[k]]$th[1:500], type = "l", col = "steelblue", xlab = "t", ylab = expression(theta^(t)),
                     ylim = c(-3.5, 3.5), main = sprintf("%s: accept %.2f", labs[k], res[[k]]$acc))
for (k in 1:3) acf(res[[k]]$th, lag.max = 50, main = "ACF")
Figure 12.9: Illustrates the trade-off in choosing the step size of a random-walk Metropolis-Hastings sampler, using trace plots and autocorrelation. Step size too small, about right, and too large: trace (top) and autocorrelation (bottom) for a random walk targeting N(0, 1).

For random-walk Metropolis on a smooth target, theory recommends an acceptance rate near \(0.234\) in high dimension (up to about \(0.44\) in one dimension) as the rate that minimizes autocorrelation for a given computational budget — a useful rule of thumb, not a target to hit exactly.

12.3.4 Metropolis-within-Gibbs

The two ideas combine directly. If \(\theta = (\theta_1, \theta_2)\) and \(\pi(\theta_1 \mid \theta_2)\) has no convenient sampler while \(\pi(\theta_2 \mid \theta_1)\) does, replace only the first Gibbs step by a Metropolis–Hastings update that targets \(\pi(\theta_1 \mid \theta_2)\) (evaluated at the current \(\theta_2\)) and leave the second step as an exact conditional draw. Each block transition leaves \(\pi\) invariant on its own — the Gibbs argument applies verbatim to any \(\pi(\theta_j \mid \theta_{-j})\)-invariant transition, not only an exact conditional draw — so the composite sweep leaves the full joint \(\pi\) invariant. This “Gibbs where conjugate, Metropolis elsewhere” pattern, iterated one parameter or block at a time, is how most general-purpose Bayesian software before Hamiltonian methods actually worked.

12.3.5 Example 5: A Normal Truncated to Its Tail

The problem. Draw from \(N(0, 2^2)\) truncated to \([4, 5]\), a sliver of the far right tail, \[ \pi(\theta) \propto \varphi\Big(\frac{\theta}{2}\Big)\, I(4 \le \theta \le 5). \] Sampling from \(N(0, 2^2)\) and keeping the draws that land in \([4, 5]\) is exact but wasteful: only a fraction \(\Phi(2.5) - \Phi(2) \approx 0.017\) of the draws is kept, about one in 60, and a target further in the tail would be worse still.

Random-walk Metropolis. The indicator needs no special handling: a proposal landing outside \([4, 5]\) has \(\pi(\theta^*) = 0\), hence \(r = 0\), and is automatically rejected, while inside the interval the acceptance probability is the ratio of normal densities. Starting inside the interval, the chain never leaves it, and every iteration produces a draw. Figure 12.10 runs met_gauss with three step sizes and reports the acceptance rate and the effective sample size \(T_\text{eff}\) of each chain.

Code
log_tnorm <- function(x, mu, sigma, lb, ub) {
    if (x > lb && x < ub) dnorm(x, mu, sigma, log = TRUE) else -Inf
}
set.seed(6); steps <- c(0.1, 1, 2)
mcs <- lapply(steps, function(st) met_gauss(5000, log_tnorm, stepsizes = st, ini_value = 4.5,
                                            mu = 0, sigma = 2, lb = 4, ub = 5))
ess_fn <- function(th) {                 # effective sample size T / (1 + 2 sum rho_k), summed to the first rho_k < 0
    rho <- acf(th, lag.max = 200, plot = FALSE)$acf[-1]
    k <- which(rho < 0)[1]; if (is.na(k)) k <- length(rho) + 1
    length(th) / (1 + 2 * sum(rho[seq_len(k - 1)]))
}
ess <- sapply(mcs, ess_fn)
par(mfrow = c(1, 3), mar = c(4, 4, 2, 1))
for (k in 1:3) plot(mcs[[k]], type = "l", col = "steelblue", xlab = "iteration", ylab = expression(theta),
    main = sprintf("step = %.1f, accept = %.2f, ESS = %.0f", steps[k], attr(mcs[[k]], "accept_rate"), ess[k]))
Figure 12.10: Demonstrates random-walk Metropolis-Hastings on a normal distribution truncated to its tail, where sampling the untruncated normal and keeping the draws in range is wasteful. Random-walk MH targeting N(0, 2^2) truncated to [4, 5], for three step sizes, with the acceptance rate and effective sample size (ESS) of each chain of 5,000 iterations.

The three chains differ in how efficiently they explore \([4, 5]\), as measured by the effective sample size; as in Figure 12.9, the smallest step is accepted most often but moves least. The chain with the largest ESS, step \(1\), reproduces the exact truncated density (Figure 12.11), including its decline across the interval: \(\varphi\) is decreasing there, so states near \(4\) are visited about \(3.1\) times as often as states near \(5\).

Code
best <- which.max(ess); th_best <- mcs[[best]][, 1]
par(mar = c(4, 4, 2, 1))
hist(th_best, breaks = 40, freq = FALSE, col = "gray85", border = "white", xlim = c(3.9, 5.1),
     xlab = expression(theta), ylab = "density",
     main = sprintf("step = %.1f (accept %.2f)", steps[best], attr(mcs[[best]], "accept_rate")))
curve(dnorm(x, 0, 2) / (pnorm(5, 0, 2) - pnorm(4, 0, 2)), 4, 5, add = TRUE, col = "firebrick", lwd = 2, lty = 2)
legend("topright", bty = "n", lwd = c(NA, 2), lty = c(NA, 2), pch = c(15, NA), pt.cex = 2,
       col = c("gray85", "firebrick"), legend = c("histogram of the draws", "exact truncated normal density"))
Figure 12.11: Checks the random-walk Metropolis-Hastings sampler for the truncated normal against the exact density. Histogram of the 5,000 states of the chain with the largest effective sample size, with the exact N(0, 2^2) density truncated to [4, 5] (dashed).

12.3.6 Example 6: Normal Data with Unknown Mean and Variance, Revisited

This is the model, prior and data of Example 2, \[ x_1, \ldots, x_n \mid \mu, \sigma^2 \overset{iid}{\sim} N(\mu, \sigma^2), \qquad \mu \sim N(\mu_0, \sigma_0^2), \qquad \sigma^2 \sim \mathrm{IG}(a_0, \lambda_0), \] now sampled by random-walk Metropolis–Hastings.

The model on the log scale. \(\sigma^2 > 0\) makes a symmetric normal random walk directly on \(\sigma^2\) wasteful (many proposals land below zero and are rejected), so reparametrize \[ w = \log \sigma^2 \in \mathbb R, \qquad \sigma^2 = e^w. \] By the change-of-variables formula, if \(X \sim f_X\) and \(Y = t(X)\), then \(f_Y(y) = f_X\big(t^{-1}(y)\big)\,\big|\tfrac{d t^{-1}(y)}{dy}\big|\). Here \(t^{-1}(w) = e^w\), so the Jacobian is \(e^w\), and \[ P(\mu, w \mid x) \ \propto\ \underbrace{e^{-\frac{(\mu-\mu_0)^2}{2\sigma_0^2}}}_{p(\mu)} \cdot \underbrace{(e^w)^{-(a_0+1)} e^{-\lambda_0 e^{-w}}}_{p_{\sigma^2}(e^w)} \cdot \underbrace{(e^w)^{-n/2} e^{-\sum_i (x_i-\mu)^2 e^{-w}/2}}_{\text{likelihood}} \cdot \underbrace{e^w}_{\text{Jacobian}}. \] Collecting the powers of \(e^w\), \(-(a_0+1) - \tfrac n2 + 1 = -(a_0 + \tfrac n2)\), so \[ \log P(\mu, w \mid x) = -\frac{(\mu-\mu_0)^2}{2\sigma_0^2} - \Big(a_0 + \frac n2\Big) w - \Big(\lambda_0 + \frac12 \sum_{i=1}^n (x_i - \mu)^2\Big) e^{-w} + \text{const}. \] Omitting the Jacobian \(e^w\) would target the wrong distribution.

The sampler. A random-walk proposal on \((\mu, w)\) jointly, with met_gauss from above; the log posterior in the code is the formula above, term by term:

Code
log_post_mu_w <- function(mu, w)                    # prior constants mu0, s02, a0, lam0 from Example 2
    -(mu - mu0)^2 / (2 * s02) - (a0 + length(x) / 2) * w - (lam0 + sum((x - mu)^2) / 2) * exp(-w)
mh_norm <- function(iters, stepsizes) {
    mc <- met_gauss(iters, function(th) log_post_mu_w(th[1], th[2]), stepsizes, ini_value = c(0, 0))
    list(mu = mc[, 1], sd = exp(mc[, 2] / 2), accept_rate = attr(mc, "accept_rate"))   # sigma = e^{w/2}
}
Code
set.seed(5)
scales <- c(20, 10, 4, 2)
fits <- lapply(scales, function(s) mh_norm(10000, c(s, s) / sqrt(length(x))))
par(mfcol = c(2, 4), mar = c(4, 4, 2, 1))
for (k in seq_along(fits)) {
    plot(fits[[k]]$mu[1:1000], type = "l", col = "steelblue", xlab = "t", ylab = expression(mu),
         main = sprintf("scale %g, accept %.2f", scales[k], fits[[k]]$accept_rate))
    acf(fits[[k]]$mu[-(1:500)], main = "ACF")
}

Scale \(4\) gives the least autocorrelated trace among the four, consistent with an acceptance rate closer to the \(0.2\)–\(0.4\) range than the very low or very high rates at the extremes. The posterior densities estimated from that chain already match those of the Gibbs sampler (Figure 12.13).

Code
best5 <- fits[[3]]; keep5 <- -(1:500)
par(mfrow = c(1, 2), mar = c(4, 4, 2, 1))
plot(density(best5$mu[keep5]), col = "steelblue", lwd = 2, xlab = expression(mu), main = "posterior density of mu")
lines(density(mu_g), col = "gray30", lwd = 2, lty = 2)
legend("topright", bty = "n", lwd = 2, lty = c(1, 2), col = c("steelblue", "gray30"), legend = c("MH, scale 4", "Gibbs"))
plot(density(best5$sd[keep5]), col = "firebrick", lwd = 2, xlab = expression(sigma), main = "posterior density of sigma")
lines(density(sd_g), col = "gray30", lwd = 2, lty = 2)
legend("topright", bty = "n", lwd = 2, lty = c(1, 2), col = c("firebrick", "gray30"), legend = c("MH, scale 4", "Gibbs"))
Figure 12.13: Compares the posterior densities from the best-tuned Metropolis-Hastings chain with those from the Gibbs sampler. Kernel densities of mu and sigma from the scale-4 chain of the preliminary runs (10,000 iterations, first 500 discarded; solid) and from the Gibbs sampler of Example 2 (dashed).

Running a long chain at that scale and comparing to the Gibbs sampler on the same data:

Code
mh_long <- mh_norm(50000, c(4, 4) / sqrt(length(x)))
keep_mh <- -(1:1000)
coherence <- data.frame(
    method = c("Metropolis-Hastings", "Gibbs"),
    mean_mu = c(mean(mh_long$mu[keep_mh]), mean(mu_g)),
    sd_mu   = c(sd(mh_long$mu[keep_mh]), sd(mu_g)),
    mean_sigma = c(mean(mh_long$sd[keep_mh]), mean(sd_g)),
    sd_sigma   = c(sd(mh_long$sd[keep_mh]), sd(sd_g))
)
knitr::kable(coherence, digits = 3, align = c("l", "r", "r", "r", "r"))
Table 12.5: Checks the Metropolis-Hastings sampler against Gibbs sampling on the same problem. Posterior mean and sd from Metropolis-Hastings versus Gibbs sampling, same data and priors: the two exact samplers of the same posterior agree up to Monte Carlo error.
method mean_mu sd_mu mean_sigma sd_sigma
Metropolis-Hastings 10.128 0.320 2.257 0.225
Gibbs 10.130 0.324 2.255 0.230

12.4 Hamiltonian Monte Carlo and Stan

12.4.1 Why random walks struggle

A random-walk proposal has no sense of direction: reaching a point one posterior standard deviation away takes \(O(d)\) steps in \(d\) dimensions, and far more along a narrow, correlated ridge, since most proposed directions immediately step off the ridge and get rejected. Gibbs suffers the same way when parameters are strongly correlated, since each step moves along only one coordinate axis. Hamiltonian Monte Carlo (HMC) uses the gradient \(\nabla \log \pi(\theta)\) to propose points far away with high probability of acceptance.

Introduce an auxiliary momentum variable \(p \in \mathbb R^d\) and the joint density \(\pi(\theta, p) \propto \exp\{-H(\theta,p)\}\) with \[ H(\theta, p) = \underbrace{-\log \pi(\theta)}_{\text{potential } U(\theta)} + \underbrace{\tfrac12 p^\top M^{-1} p}_{\text{kinetic } K(p)}, \] so that the \(\theta\)-marginal is exactly the target and \(p \sim N_d(0, M)\) independently. Physically: a particle at position \(\theta\) with momentum \(p\) rolling frictionlessly on the potential surface \(U(\theta)\). Hamilton’s equations move \((\theta,p)\) so as to conserve \(H\) exactly and are volume-preserving and reversible; discretizing them with the leapfrog integrator (step size \(\epsilon\), \(L\) steps), \[ \begin{aligned} p & \leftarrow p + \tfrac\epsilon2 \nabla\log\pi(\theta), \qquad \theta \leftarrow \theta + \epsilon M^{-1}p, \\ p & \leftarrow p + \tfrac\epsilon2\nabla\log\pi(\theta), \end{aligned} \] keeps volume-preservation and reversibility exactly (negating \(p\) and re-running gives back the start) while introducing only an \(O(\epsilon^2)\) error in \(H\), which a Metropolis accept/reject step then corrects exactly.

12.4.2 The algorithm

Starting from \(\theta^{(0)}\), repeat: draw a fresh \(p \sim N_d(0,M)\); run \(L\) leapfrog steps from \((\theta^{(t-1)}, p)\) to reach \((\theta^*, p^*)\); accept \(\theta^{(t)} = \theta^*\) with probability \(\min\{\exp[H(\theta^{(t-1)},p) - H(\theta^*,p^*)], 1\}\), else repeat \(\theta^{(t-1)}\). Drawing \(p\) is a Gibbs step from its own conditional (it doesn’t depend on \(\theta\)), and the leapfrog-plus-accept step is a Metropolis update with a deterministic, reversible proposal — so each half leaves \(\pi(\theta,p)\) invariant, and because \(H\) is nearly conserved, acceptance stays high (typically \(0.65\)–\(0.8\)) even though \(\theta^*\) may be far from \(\theta^{(t-1)}\).

Code
hmc <- function(log_pi, grad_log_pi, theta, eps, L, iters, M = diag(length(theta))) {
    d <- length(theta); Minv <- solve(M); R <- chol(M)
    out <- matrix(NA_real_, iters, d); n_acc <- 0
    for (t in seq_len(iters)) {
        p0 <- as.vector(t(R) %*% rnorm(d))
        th <- theta; p <- p0 + eps / 2 * grad_log_pi(th)
        for (l in seq_len(L)) {
            th <- th + eps * as.vector(Minv %*% p)
            if (l < L) p <- p + eps * grad_log_pi(th)
        }
        p <- p + eps / 2 * grad_log_pi(th)
        H0 <- -log_pi(theta) + 0.5 * sum(p0 * (Minv %*% p0))
        H1 <- -log_pi(th)    + 0.5 * sum(p  * (Minv %*% p))
        if (log(runif(1)) < H0 - H1) { theta <- th; n_acc <- n_acc + 1 }
        out[t, ] <- theta
    }
    attr(out, "accept_rate") <- n_acc / iters
    out
}

12.4.3 Example 7: Bivariate Normal with Correlation 0.98

A strongly correlated bivariate normal is the simplest target on which a random walk struggles. Both samplers below get the same budget of 2,000 iterations and start from the same point.

Code
set.seed(4)
Sigma <- matrix(c(1, 0.98, 0.98, 1), 2); Sinv <- solve(Sigma)
log_pi_corr  <- function(z) -0.5 * sum(z * (Sinv %*% z))
grad_pi_corr <- function(z) -as.vector(Sinv %*% z)

rw <- matrix(NA_real_, 2000, 2); cur <- c(-2, -2); lp <- log_pi_corr(cur); acc <- 0
for (t in 1:2000) {
    pr <- cur + 0.3 * rnorm(2); lpp <- log_pi_corr(pr)
    if (log(runif(1)) < lpp - lp) { cur <- pr; lp <- lpp; acc <- acc + 1 }
    rw[t, ] <- cur
}
draws_hmc <- hmc(log_pi_corr, grad_pi_corr, theta = c(-2, -2), eps = 0.05, L = 30, iters = 2000)

g <- seq(-3.5, 3.5, length.out = 80)
Z <- outer(g, g, Vectorize(function(a, b) exp(-0.5 * c(a, b) %*% Sinv %*% c(a, b))))
par(mfrow = c(1, 3), mar = c(4, 4, 2, 1))
for (nm in c("random walk", "HMC")) {
    d <- if (nm == "random walk") rw else draws_hmc
    ar <- if (nm == "random walk") acc / 2000 else attr(draws_hmc, "accept_rate")
    contour(g, g, Z, nlevels = 6, drawlabels = FALSE, col = "gray60",
            xlab = expression(theta[1]), ylab = expression(theta[2]),
            main = sprintf("%s: accept %.2f", nm, ar))
    lines(d[1:100, ], col = if (nm == "random walk") "firebrick" else "steelblue", lwd = 1.5)
    points(d[1:100, ], pch = 19, cex = 0.5, col = if (nm == "random walk") "firebrick" else "steelblue")
}
a1 <- acf(rw[, 1], lag.max = 60, plot = FALSE)$acf
a2 <- acf(draws_hmc[, 1], lag.max = 60, plot = FALSE)$acf
plot(0:60, a1, type = "h", lwd = 2, col = "firebrick", xlab = "lag", ylab = "ACF", ylim = c(-0.2, 1), main = "autocorrelation")
lines((0:60) + 0.3, a2, type = "h", lwd = 2, col = "steelblue")
legend("topright", bty = "n", lwd = 2, col = c("firebrick", "steelblue"), legend = c("random walk", "HMC"))
Figure 12.14: Compares Hamiltonian Monte Carlo with random-walk Metropolis on a highly correlated target, where the random walk struggles. Target: bivariate normal with correlation 0.98. Left/middle: first 100 draws over the posterior contours for random-walk Metropolis and HMC, same iteration budget. Right: autocorrelation of the first coordinate – HMC crosses the ridge in one trajectory and its draws decorrelate almost immediately.

Chi Feng’s MCMC simulators let you tune the step size and number of leapfrog steps of Hamiltonian Monte Carlo, and compare it with other samplers, to see how they affect its exploration of a correlated target.

12.4.4 Stan: automating HMC

Every sampler above needed something derived by hand: Gibbs needed full conditionals worked out algebraically; Metropolis–Hastings needed only a target density but still needed step sizes tuned by trial and error; HMC needed an analytic gradient and needed \(\epsilon\) and \(L\) tuned by hand. Stan is a probabilistic programming language that automates all of this: given a model written declaratively (data, parameters, and a log-density), it computes gradients by automatic differentiation and runs an adaptive variant of HMC — the No-U-Turn Sampler (NUTS), which picks a good \(L\) on the fly by extending the leapfrog trajectory until it starts to double back — with step size tuned during a warm-up phase. The user never derives a conditional or a gradient.

12.4.5 Where Stan earns its keep

The normal-mean/variance model of Examples 2 and 6 is simple enough that Gibbs sampling is not just possible but easy, so Stan’s advantage is not visible yet. Its real value shows up on models where hand-deriving conditionals or gradients would be a serious undertaking: hierarchical models with many levels of latent structure, time-series models with an unobserved latent state at every time point, or anything with a non-conjugate likelihood/prior combination. Example 9 gives a small taste of this: the Cauchy model needed a scale-mixture trick and three derivations for Gibbs sampling, but only its model statement in Stan.

12.4.6 Example 8: Normal Data with Unknown Mean and Variance, in Stan

To confirm Stan lands on the same posterior as the Gibbs and MH samplers of Examples 2 and 6, fit the identical normal-mean/variance model with the identical priors and data:

Code
stan_normal_code <- "
data {
  int<lower=0> n;
  vector[n] x;
  real mu0;
  real<lower=0> s02;
  real<lower=0> a0;
  real<lower=0> lam0;
}
parameters {
  real mu;
  real<lower=0> sigma2;
}
model {
  mu ~ normal(mu0, sqrt(s02));
  sigma2 ~ inv_gamma(a0, lam0);
  x ~ normal(mu, sqrt(sigma2));
}
"
Code
fit_stan <- stan(
    model_code = stan_normal_code,
    data = list(n = length(x), x = x, mu0 = mu0, s02 = s02, a0 = a0, lam0 = lam0),
    chains = 4, iter = 2000, warmup = 1000, seed = 5, refresh = 0
)
Code
stan_summary <- summary(fit_stan, pars = c("mu", "sigma2"))$summary
stan_sigma_draws <- sqrt(as.matrix(fit_stan, pars = "sigma2")[, 1])
three_way <- data.frame(
    method = c("Gibbs", "Metropolis-Hastings", "Stan (NUTS)"),
    mean_mu = c(mean(mu_g), mean(mh_long$mu[keep_mh]), stan_summary["mu", "mean"]),
    sd_mu   = c(sd(mu_g), sd(mh_long$mu[keep_mh]), stan_summary["mu", "sd"]),
    mean_sigma = c(mean(sd_g), mean(mh_long$sd[keep_mh]), mean(stan_sigma_draws)),
    sd_sigma   = c(sd(sd_g), sd(mh_long$sd[keep_mh]), sd(stan_sigma_draws))
)
knitr::kable(three_way, digits = 3, align = c("l", "r", "r", "r", "r"))
Table 12.6: Validates Stan’s sampler against the samplers written by hand earlier in the chapter. Posterior mean and sd: hand-written Gibbs and Metropolis-Hastings versus Stan’s NUTS sampler, same data, priors, and model. All three samplers target the identical posterior and agree up to Monte Carlo error.
method mean_mu sd_mu mean_sigma sd_sigma
Gibbs 10.141 0.330 2.293 0.239
Metropolis-Hastings 10.141 0.325 2.298 0.236
Stan (NUTS) 10.132 0.326 2.295 0.245

The three completely independent implementations — hand-derived conditionals, a hand-tuned random walk, and Stan’s automatic NUTS — agree to within Monte Carlo noise, which is exactly the coherence check this book has used throughout: independent methods with no shared code path landing on the same answer is evidence that none of them is wrong.

12.4.7 Example 9: Cauchy Data with Unknown Location and Scale, in Stan

Example 4 needed a page of algebra: a scale-mixture representation, an augmented posterior, and three full conditionals. In Stan none of that is needed. The model is written exactly as stated in Example 4, with the Cauchy likelihood used directly and no latent variances, and NUTS samples the two-dimensional posterior of \((\mu, \sigma^2)\) using gradients from automatic differentiation. The data and priors are those of Example 4: \(\mu \sim N(0, 10^2)\), \(\sigma^2 \sim \mathrm{IG}(1, 1)\) and the same 30 observations.

Code
stan_cauchy_code <- "
data {
  int<lower=0> n;
  vector[n] y;
  real mu0;
  real<lower=0> tau;
  real<lower=0> a0;
  real<lower=0> b0;
}
parameters {
  real mu;
  real<lower=0> sigma2;
}
transformed parameters {
  real<lower=0> sigma = sqrt(sigma2);
}
model {
  mu ~ normal(mu0, tau);
  sigma2 ~ inv_gamma(a0, b0);
  y ~ cauchy(mu, sigma);
}
"
Code
fit_cauchy_stan <- stan(
    model_code = stan_cauchy_code,
    data = list(n = length(y_cauchy), y = y_cauchy, mu0 = 0, tau = 10, a0 = 1, b0 = 1),
    chains = 4, iter = 2000, warmup = 1000, seed = 8, refresh = 0
)
Code
st_c <- as.matrix(fit_cauchy_stan, pars = c("mu", "sigma"))
knitr::kable(data.frame(
    quantity = c("posterior mean of mu", "posterior sd of mu",
                 "posterior mean of sigma", "posterior sd of sigma"),
    gibbs = c(mean(draws_cauchy[keep_c, "mu"]), sd(draws_cauchy[keep_c, "mu"]),
              mean(draws_cauchy[keep_c, "sigma"]), sd(draws_cauchy[keep_c, "sigma"])),
    stan = c(mean(st_c[, "mu"]), sd(st_c[, "mu"]), mean(st_c[, "sigma"]), sd(st_c[, "sigma"])),
    exact = c(grid_mean(mu_grid, 1), grid_sd(mu_grid, 1),
              grid_mean(sg_grid, 2), grid_sd(sg_grid, 2))
), digits = 3, col.names = c("quantity", "Gibbs (Example 4)", "Stan (NUTS)", "exact (grid)"),
   align = c("l", "r", "r", "r"))
Table 12.7: Checks Stan’s NUTS sampler for the Cauchy model against the data-augmentation Gibbs sampler of Example 4 and the exact grid posterior. Posterior means and standard deviations of mu and sigma, same data and priors. Stan samples the Cauchy likelihood directly, without latent variables; all three agree up to Monte Carlo error.
quantity Gibbs (Example 4) Stan (NUTS) exact (grid)
posterior mean of mu 2.228 2.234 2.228
posterior sd of mu 0.179 0.177 0.179
posterior mean of sigma 0.768 0.764 0.765
posterior sd of sigma 0.181 0.180 0.178
Code
summary(fit_cauchy_stan, pars = c("mu", "sigma"))$summary[, c("mean", "sd", "n_eff", "Rhat")]
           mean        sd    n_eff      Rhat
mu    2.2343723 0.1774277 2268.452 0.9999983
sigma 0.7638365 0.1799397 2618.336 1.0004121

The three answers agree, and \(\hat R \approx 1\) with effective sample sizes in the thousands shows that the four chains have mixed. The comparison shows the trade-off between the two approaches. The Gibbs sampler of Example 4 needs no tuning and each iteration is cheap, but it needed the scale-mixture trick and three derivations. Stan needed only the model statement, and it would work unchanged with a different prior or a Student-\(t\) likelihood with any degrees of freedom, where the Gibbs derivation would have to be redone.

12.5 A Final Practical Example: Sparse Logistic Regression

The examples so far were chosen to show how each sampler works, on models small enough to check against an exact answer. This section puts the pieces together on a problem where Bayesian computation earns its place in practice: a logistic regression with as many unknowns as there are cases, where maximum likelihood breaks down, the prior decides the quality of the answer, and Stan makes the fit routine. The posterior is compared with two standard non-Bayesian fits, glm and the LASSO, on new test data.

12.5.1 The problem

Binary responses \(y_1, \ldots, y_n\) depend on \(p\) candidate predictors through the logistic regression model \[ y_i \mid \alpha, \beta \sim \text{Bernoulli}\big(\text{logit}^{-1}(\alpha + x_i^\top \beta)\big), \qquad \text{logit}^{-1}(\eta) = \frac{1}{1 + e^{-\eta}}. \] Here there are \(p = 50\) predictors for only \(n = 100\) cases. The predictors are standard normal and only two carry signal: the true values are \(\alpha = 0\), \(\beta_1 = 1\), \(\beta_2 = -1\) and \(\beta_3 = \cdots = \beta_{50} = 0\).

12.5.2 Why maximum likelihood fails

With 51 unknowns and only 100 cases, it is very likely, and true for these data, that some linear combination \(\alpha + x_i^\top\beta\) is positive for every case with \(y_i = 1\) and negative for every case with \(y_i = 0\): the data are perfectly separable. Multiplying such a \(\beta\) by a larger and larger constant pushes every fitted probability towards its observed \(0\) or \(1\), so the likelihood keeps increasing and the MLE does not exist. glm stops after a fixed number of iterations with very large coefficients (here up to about \(60\) in absolute value) and warns that the algorithm did not converge and that fitted probabilities are numerically \(0\) or \(1\).

12.5.3 A sparse prior: the horseshoe

A Bayesian fit always has a proper posterior, but the prior now matters a great deal. A vague prior such as \(\beta_j \sim N(0, 2.5^2)\) lets all 48 null coefficients wander, and their sum swamps the signal. We want a prior that says most coefficients are near 0, but a few may be large. The horseshoe prior does this with two levels of scale: \[ \beta_j = \tau\,\lambda_j\, z_j, \qquad z_j \sim N(0, 1), \qquad \lambda_j \sim \text{Cauchy}^+(0, 1), \qquad \tau \sim \text{Cauchy}^+(0, 0.1), \] where \(\text{Cauchy}^+\) is the Cauchy distribution restricted to positive values. The global scale \(\tau\) is small, so it shrinks every coefficient strongly towards \(0\). The local scale \(\lambda_j\) has a heavy tail, so a coefficient that the data support can take a large \(\lambda_j\) and escape the shrinkage. The intercept gets \(\alpha \sim N(0, 5^2)\). Writing \(\beta_j\) as a product with a standard normal \(z_j\) is the non-centred form used for Stan, and a smaller step size (adapt_delta = 0.995) helps NUTS handle the very different scales of \(\tau\) and the \(\lambda_j\), which otherwise cause many divergent transitions. If a handful remain, Stan reports them as a warning; with only a few out of 8,000 draws, \(\hat R\) near 1 and large effective sample sizes, they would not noticeably affect the summaries.

12.5.4 Fitting in Stan

The horseshoe model in Stan, and the same model with the vague normal prior for comparison:

Code
stan_logit_hs_code <- "
data {
  int<lower=0> n;
  int<lower=1> p;
  matrix[n, p] X;
  array[n] int<lower=0, upper=1> y;
}
parameters {
  real alpha;
  real<lower=0> tau;             // global scale
  vector<lower=0>[p] lambda;     // local scales
  vector[p] z;
}
transformed parameters {
  vector[p] beta = tau * lambda .* z;
}
model {
  alpha ~ normal(0, 5);
  tau ~ cauchy(0, 0.1);
  lambda ~ cauchy(0, 1);
  z ~ std_normal();
  y ~ bernoulli_logit(alpha + X * beta);
}
"
### the same model with a vague normal prior on every coefficient, for comparison
stan_logit_normal_code <- "
data {
  int<lower=0> n;
  int<lower=1> p;
  matrix[n, p] X;
  array[n] int<lower=0, upper=1> y;
}
parameters {
  real alpha;
  vector[p] beta;
}
model {
  alpha ~ normal(0, 5);
  beta ~ normal(0, 2.5);
  y ~ bernoulli_logit(alpha + X * beta);
}
"
Code
set.seed(2024)
n_lr <- 100; p_lr <- 50
X_lr <- matrix(rnorm(n_lr * p_lr), n_lr, p_lr)
beta_true <- c(1, -1, rep(0, p_lr - 2))
y_lr <- rbinom(n_lr, 1, plogis(drop(X_lr %*% beta_true)))
data_lr <- list(n = n_lr, p = p_lr, X = X_lr, y = y_lr)
fit_logit <- stan(model_code = stan_logit_hs_code, data = data_lr,
                  chains = 4, iter = 3000, warmup = 1000, seed = 9, refresh = 0,
                  control = list(adapt_delta = 0.995))
fit_logit_normal <- stan(model_code = stan_logit_normal_code, data = data_lr,
                         chains = 4, iter = 2000, warmup = 1000, seed = 9, refresh = 0)

12.5.5 The horseshoe posterior

Table 12.8 summarizes the horseshoe posterior of the first ten coefficients: the two signals and eight of the 48 nulls.

Code
sm_logit <- summary(fit_logit, pars = sprintf("beta[%d]", 1:10))$summary
knitr::kable(data.frame(
    coefficient = sprintf("beta[%d]", 1:10),
    true = beta_true[1:10],
    mean = sm_logit[, "mean"], sd = sm_logit[, "sd"],
    q025 = sm_logit[, "2.5%"], q975 = sm_logit[, "97.5%"],
    n_eff = round(sm_logit[, "n_eff"]), Rhat = sm_logit[, "Rhat"],
    row.names = NULL),
    digits = c(0, 0, 3, 3, 3, 3, 0, 3),
    col.names = c("coefficient", "true", "mean", "sd", "2.5%", "97.5%", "n_eff", "Rhat"),
    align = c("l", rep("r", 7)))
Table 12.8: Summarizes the posterior distribution of the first ten coefficients of a logistic regression with 50 predictors and 100 cases, under the horseshoe prior. Only the first two coefficients carry signal. Posterior mean, standard deviation and 95% credible interval from 8,000 NUTS draws, next to the true value. Rhat near 1 and large effective sample sizes show that the chains have mixed.
coefficient true mean sd 2.5% 97.5% n_eff Rhat
beta[1] 1 0.977 0.391 0.043 1.727 2713 1.001
beta[2] -1 -1.215 0.372 -1.983 -0.521 5868 1.000
beta[3] 0 -0.035 0.123 -0.404 0.124 6675 1.001
beta[4] 0 -0.036 0.119 -0.386 0.118 7601 1.000
beta[5] 0 0.032 0.115 -0.129 0.363 7517 1.000
beta[6] 0 -0.023 0.101 -0.302 0.129 6936 1.000
beta[7] 0 0.002 0.085 -0.173 0.190 8124 1.001
beta[8] 0 -0.037 0.121 -0.404 0.112 7818 1.000
beta[9] 0 -0.012 0.089 -0.248 0.152 7483 1.000
beta[10] 0 -0.009 0.087 -0.227 0.156 7305 1.000

The null coefficients are shrunk tightly around \(0\), with posterior standard deviations near \(0.1\). The two signals escape the shrinkage: their posterior means are close to the true values \(1\) and \(-1\), and both 95% intervals exclude \(0\). Figure 12.15 shows the posterior draws of the two signals and two of the nulls.

Code
draws_beta <- as.matrix(fit_logit, pars = "beta")
par(mfrow = c(2, 2), mar = c(4, 4, 2.5, 1))
for (j in 1:4) {
    hist(draws_beta[, j], breaks = 60, freq = FALSE, col = "gray80", border = "white",
         xlim = range(c(quantile(draws_beta[, j], c(0.001, 0.999)), 0, beta_true[j])),
         main = bquote(beta[.(j)] ~ "(true value" ~ .(beta_true[j]) * ")"),
         xlab = bquote(beta[.(j)]))
    abline(v = beta_true[j], col = "firebrick", lwd = 2.5)
    abline(v = 0, lty = 2)
}
Figure 12.15: Shows the posterior distributions of two signal and two null coefficients in a logistic regression with 50 predictors and 100 cases, under the horseshoe prior. Histograms of 8,000 NUTS draws of beta_1 and beta_2 (signals, top) and beta_3 and beta_4 (nulls, bottom). The red line marks the true value and the dashed line marks 0. The null posteriors are concentrated at 0; the signal posteriors are centred near the true values, with only a small spike at 0 for beta_1.

12.5.6 Prediction on test data

To see how well each method predicts, simulate a test set of \(m = 1000\) new cases from the same design, independently of the training data. For a test case with predictors \(\tilde x\), the posterior predictive probability averages the success probability over the posterior: \[ \begin{aligned} P(\tilde y = 1 \mid \tilde x, \text{data}) & = \int \text{logit}^{-1}(\alpha + \tilde x^\top \beta)\, p(\alpha, \beta \mid \text{data})\, d(\alpha, \beta) \\ & \approx \frac1S \sum_{s=1}^S \text{logit}^{-1}\big(\alpha^{(s)} + \tilde x^\top \beta^{(s)}\big), \end{aligned} \] an average over the \(S\) posterior draws. No extra package (such as brms) is needed: the Stan draws and one matrix product give all \(m\) probabilities at once. We compare five sets of predicted probabilities \(\hat p_i\):

  • the posterior predictive probabilities under the horseshoe prior;
  • the same under the vague \(N(0, 2.5^2)\) prior;
  • the plug-in probabilities from the LASSO, which maximizes the penalized log-likelihood \(\log L(\alpha, \beta) - \lambda \sum_j |\beta_j|\), with the penalty \(\lambda\) chosen by 10-fold cross-validation (glmnet::cv.glmnet);
  • the plug-in probabilities \(\text{logit}^{-1}(\hat\alpha + \tilde x^\top\hat\beta)\) from glm;
  • the true probabilities \(\text{logit}^{-1}(\tilde x^\top \beta_{\text{true}})\), the best that any method could do.

Each is scored on the test responses in two ways:

  • the test deviance \(-2\sum_{i=1}^m \log \hat P(\tilde y_i)\), where \(\hat P(\tilde y_i) = \hat p_i\) if \(\tilde y_i = 1\) and \(1 - \hat p_i\) if \(\tilde y_i = 0\). It rewards well-calibrated probabilities, and smaller is better. Predicting \(\hat p_i = 0.5\) for every case gives \(2m\log 2 \approx 1386.3\), a useful baseline;
  • the error rate of the classification \(\hat y_i = 1\{\hat p_i > 0.5\}\), summarized together with its confusion matrix of predicted against actual classes.
Code
set.seed(2025)
m_test <- 1000
X_test <- matrix(rnorm(m_test * p_lr), m_test, p_lr)
y_test <- rbinom(m_test, 1, plogis(drop(X_test %*% beta_true)))

### posterior predictive probabilities: average logit^{-1}(alpha + x beta) over the draws
post_pred <- function(fit) {
    a <- as.matrix(fit, pars = "alpha")[, 1]
    b <- as.matrix(fit, pars = "beta")
    colMeans(plogis(sweep(b %*% t(X_test), 1, a, "+")))      # S x m, then average
}
p_hs <- post_pred(fit_logit)
p_normal <- post_pred(fit_logit_normal)

### maximum likelihood with glm: the data are separable, so glm warns and
### returns very large coefficients; its plug-in probabilities
fit_glm <- suppressWarnings(glm(y ~ ., family = binomial, data = data.frame(y = y_lr, X_lr)))
p_glm <- suppressWarnings(predict(fit_glm, newdata = data.frame(X_test), type = "response"))

### the LASSO: lambda by 10-fold cross-validation (minimum CV deviance)
set.seed(10)
fit_lasso <- glmnet::cv.glmnet(X_lr, y_lr, family = "binomial", alpha = 1, nfolds = 10)
p_lasso <- as.vector(predict(fit_lasso, X_test, s = "lambda.min", type = "response"))

### the true probabilities, the best any method could do
p_true <- plogis(drop(X_test %*% beta_true))

### scores: test deviance -2 sum log P(y_i), error rate, confusion matrix
test_deviance <- function(p, y) -2 * sum(dbinom(y, 1, p, log = TRUE))
error_rate    <- function(p, y) mean((p > 0.5) != y)
confusion     <- function(p, y) table(predicted = factor(as.integer(p > 0.5), 0:1), actual = y)
methods <- list("Bayes, horseshoe prior" = p_hs, "Bayes, N(0, 2.5^2) prior" = p_normal,
                "LASSO (CV)" = p_lasso, "glm (MLE)" = p_glm, "true probabilities" = p_true)
Code
conf <- t(sapply(methods, function(p) {
    cm <- confusion(p, y_test)                  # rows: predicted class, columns: actual class
    c(cm["0", "0"], cm["1", "0"], cm["0", "1"], cm["1", "1"])
}))
knitr::kable(data.frame(method = names(methods), conf, row.names = NULL),
             col.names = c("method", "0 as 0", "0 as 1", "1 as 0", "1 as 1"),
             align = c("l", "r", "r", "r", "r"))
Table 12.9: Summarizes the classifications of 1,000 test cases by each method in flattened confusion matrices. One row per method. Column ‘a as b’ counts the test cases of actual class a classified as b (predicted probability above 0.5 for class 1); ‘0 as 0’ and ‘1 as 1’ are correct, the other two are errors.
method 0 as 0 0 as 1 1 as 0 1 as 1
Bayes, horseshoe prior 369 106 180 345
Bayes, N(0, 2.5^2) prior 330 145 222 303
LASSO (CV) 394 81 229 296
glm (MLE) 299 176 225 300
true probabilities 337 138 134 391
Code
knitr::kable(data.frame(
    method = names(methods),
    deviance = sapply(methods, test_deviance, y = y_test),
    error = sapply(methods, error_rate, y = y_test), row.names = NULL),
    digits = c(0, 1, 3), col.names = c("method", "test deviance", "error rate"),
    align = c("l", "r", "r"))
Table 12.10: Compares the test-set predictions of the Bayesian logistic regressions with those of the LASSO and glm, by test deviance and error rate, when there are as many predictors as cases. m = 1,000 test cases. Test deviance is -2 times the sum of the log predicted probabilities of the observed responses (smaller is better); predicting 0.5 for every case gives 1386.3. The last row uses the true probabilities, the best possible score.
method test deviance error rate
Bayes, horseshoe prior 1104.3 0.286
Bayes, N(0, 2.5^2) prior 2643.8 0.367
LASSO (CV) 1170.8 0.310
glm (MLE) 25472.5 0.401
true probabilities 1062.2 0.272

The comparison is very different from what one sees with few predictors. glm predicts badly: its error rate of 0.401 is far above the 0.272 of the true probabilities, and its test deviance of 25472 is about 18 times the \(1386.3\) of always predicting \(0.5\). Its fitted probabilities are almost all \(0\) or \(1\), so every wrong prediction costs a huge \(-2\log \hat P(\tilde y_i)\). A Bayesian fit is not automatically better: with the vague normal prior the test deviance, 2644, is also worse than the baseline. The LASSO, with test deviance 1171 and error rate 0.310, beats the baseline but not the horseshoe; the next two subsections show why. The horseshoe prior, which encodes the belief that only a few predictors matter, reduces the test deviance to 1104 and the error rate to 0.286, against 1062 and 0.272 for the true probabilities. When the number of predictors is a large fraction of the number of cases, the prior is not a detail to be made as vague as possible but the part of the model that makes good prediction possible.

12.5.7 What glm and the LASSO estimate

The test-set scores are explained by the fitted coefficients. Table 12.11 shows the maximum-likelihood fit of the first ten coefficients, with Wald 95% intervals \(\hat\beta_j \pm 1.96\,\widehat{\text{SE}}_j\).

Code
cf <- summary(fit_glm)$coefficients[sprintf("X%d", 1:10), ]
knitr::kable(data.frame(
    coefficient = sprintf("beta[%d]", 1:10), true = beta_true[1:10],
    estimate = sprintf("%.1f", cf[, "Estimate"]), se = sprintf("%.0fk", cf[, "Std. Error"] / 1000),
    ci = sprintf("(%.0fk, %.0fk)", (cf[, "Estimate"] - 1.96 * cf[, "Std. Error"]) / 1000,
                 (cf[, "Estimate"] + 1.96 * cf[, "Std. Error"]) / 1000),
    row.names = NULL),
    col.names = c("coefficient", "true", "estimate", "SE", "95% Wald interval"),
    align = c("l", "r", "r", "r", "r"))
Table 12.11: Shows the maximum-likelihood estimates of the first ten coefficients of the logistic regression with 50 predictors and 100 separable cases. Estimates from glm with standard errors and Wald 95% intervals; k = thousands. The algorithm did not converge, and the intervals carry no information.
coefficient true estimate SE 95% Wald interval
beta[1] 1 38.4 111k (-218k, 218k)
beta[2] -1 -63.8 70k (-138k, 138k)
beta[3] 0 22.3 91k (-179k, 179k)
beta[4] 0 -30.5 89k (-174k, 174k)
beta[5] 0 6.4 154k (-301k, 301k)
beta[6] 0 10.4 93k (-183k, 183k)
beta[7] 0 10.7 79k (-155k, 155k)
beta[8] 0 -13.1 105k (-205k, 205k)
beta[9] 0 18.2 169k (-332k, 332k)
beta[10] 0 -35.0 82k (-161k, 161k)

glm stopped after 25 iterations without converging, because on separable data the likelihood keeps rising as \(\|\beta\| \to \infty\). Its estimates are large and arbitrary (the null coefficient \(\beta_4\) is estimated as -30.5), and the standard errors are of order \(10^5\): the intervals contain every plausible value and say nothing about which predictors matter.

The LASSO penalty \(\lambda \sum_j |\beta_j|\) has a corner at \(0\), so it sets small coefficients exactly to \(0\). Figure 12.16 shows the 10-fold cross-validated deviance as a function of \(\lambda\), and Table 12.12 the resulting estimates next to the horseshoe posterior means.

Code
par(mar = c(4, 4, 3, 1)); plot(fit_lasso)
Figure 12.16: Shows how the LASSO penalty is chosen by cross-validation for the logistic regression with 50 predictors. 10-fold cross-validated binomial deviance (with one-standard-error bars) against -log(lambda); the numbers on top are the numbers of predictors kept. The right dashed line marks the lambda with the smallest cross-validated deviance, which is used here; the left one the largest lambda within one standard error of it.
Code
b_lasso <- as.vector(coef(fit_lasso, s = "lambda.min"))[-1]
knitr::kable(data.frame(
    coefficient = sprintf("beta[%d]", 1:10), true = beta_true[1:10],
    lasso = b_lasso[1:10],
    hs = summary(fit_logit, pars = sprintf("beta[%d]", 1:10))$summary[, "mean"],
    row.names = NULL),
    digits = c(0, 0, 2, 2), col.names = c("coefficient", "true", "LASSO", "horseshoe mean"),
    align = c("l", "r", "r", "r"))
Table 12.12: Compares the LASSO estimates of the first ten coefficients with the horseshoe posterior means. The LASSO penalty is chosen by 10-fold cross-validation; only the first two coefficients carry signal.
coefficient true LASSO horseshoe mean
beta[1] 1 0.47 0.98
beta[2] -1 -0.60 -1.22
beta[3] 0 0.00 -0.04
beta[4] 0 0.00 -0.04
beta[5] 0 0.00 0.03
beta[6] 0 0.00 -0.02
beta[7] 0 0.00 0.00
beta[8] 0 0.00 -0.04
beta[9] 0 0.00 -0.01
beta[10] 0 0.00 -0.01

The LASSO keeps 3 of the 50 predictors, including both signals, and sets the nulls among \(\beta_3, \ldots, \beta_{10}\) to exactly \(0\). But the same penalty that removes the nulls also shrinks the signals toward \(0\) (\(1 \to 0.47\) and \(-1 \to -0.60\)), which is why its predicted probabilities are too cautious and its test deviance trails the horseshoe; it also gives no interval estimates. The horseshoe shrinks the nulls just as hard, but its heavy-tailed local scales \(\lambda_j\) let the signals escape the shrinkage.

12.6 Summary

  • A Markov chain converges to a target \(\pi\) from any starting point if its transition \(T\) leaves \(\pi\) invariant and is aperiodic and irreducible; detailed balance, a pairwise condition, is the standard route to invariance.
  • Gibbs sampling cycles through exact draws from each full conditional; free of tuning, but needs conditionals that are both known and directly sample-able, and data augmentation extends it to models with latent variables.
  • Metropolis–Hastings accepts or rejects a proposal from any distribution with probability depending on the target-density ratio (times a proposal-symmetry correction); random-walk MH needs a tuned step size, aimed at low autocorrelation rather than high acceptance.
  • Hamiltonian Monte Carlo adds momentum and follows gradient-driven trajectories, discretized by the leapfrog integrator and corrected by a Metropolis step, giving distant, nearly independent proposals even on strongly correlated targets — at the cost of needing a gradient and two tuning parameters (\(\epsilon\), \(L\)).
  • Stan automates gradient computation and adaptive HMC (NUTS) for essentially any model expressible in its declarative syntax, turning what would otherwise be a hand-derivation (as the Cauchy model of Examples 4 and 9 shows) into a direct transcription of the model.
  • In the sparse logistic regression with as many predictors as cases, maximum likelihood fails on separable data and the LASSO over-shrinks the signals, while the horseshoe posterior, fitted by Stan, comes closest to the true probabilities: when the data are thin, the prior is part of what makes good prediction possible.

This is the last of the sampling-methods chapters in the book: quadrature (Chapter 8) and Laplace’s method (Chapter 9) work in low dimension by grid or by a local Gaussian approximation; rejection and importance sampling (Chapters 10–11) draw independently from a fixed proposal; Gibbs, Metropolis–Hastings, HMC, and Stan (this chapter) let a Markov chain do the work instead, and are, in practice, how most modern Bayesian computation is actually done.