Chapter 6

Posterior Approximation with the Gibbs Sampler

The moment we relax the artificial prior coupling Var⁡(θ∣σ2)=σ2/κ0\operatorname{Var}(\theta \mid \sigma^2) = \sigma^2/\kappa_0 from Chapter 5 and specify independent priors p(θ,σ2)=p(θ) p(σ2)p(\theta, \sigma^2) = p(\theta)\,p(\sigma^2), the joint posterior p(θ,σ2∣y)p(\theta, \sigma^2 \mid y) loses its closed form. Yet its conditional distributions—p(θ∣σ2,y)p(\theta \mid \sigma^2, y) and p(σ2∣θ,y)p(\sigma^2 \mid \theta, y)—remain completely standard! Chapter 6 introduces the Gibbs samplerStuart Geman and Donald Geman. Stochastic Relaxation, Gibbs Distributions, and the Bayesian Restoration of Images. IEEE Transactions on Pattern Analysis and Machine Intelligence, 6:721–741, 1984; Alan E. Gelfand and Adrian F. M. Smith. Sampling-Based Approaches to Calculating Marginal Densities. Journal of the American Statistical Association, 85(410):398–409, 1990; and Peter D. Hoff. A First Course in Bayesian Statistical Methods. Springer Texts in Statistics. Springer, New York, 2009. ISBN 978-0-387-92299-7. doi: 10.1007/978-0-387-92407-6, our first **Markov chain Monte Carlo (MCMC)** algorithm, which turns a sequence of tractable full conditional draws into dependent samples from an intractable joint posterior.

6.1Semiconjugate Priors and the Curse of Dimensionality

Consider the normal sampling model Y1,…,Yn∣θ,σ2∼i.i.d.normal⁡(θ,σ2)Y_1, \dots, Y_n \mid \theta, \sigma^2 \stackrel{\text{i.i.d.}}{\sim} \operatorname{normal}(\theta, \sigma^2) with semiconjugate (conditionally conjugate) independent priors:

θ∼normal⁡(μ0,τ02),σ~2=1σ2∼gamma⁡ ⁣(ν02, ν0σ022),p(θ,σ2)=p(θ) p(σ2). \theta \sim \operatorname{normal}(\mu_0, \tau_0^2), \qquad \tilde{\sigma}^2 = \frac{1}{\sigma^2} \sim \operatorname{gamma}\!\left(\frac{\nu_0}{2},\, \frac{\nu_0 \sigma_0^2}{2}\right), \qquad p(\theta, \sigma^2) = p(\theta)\,p(\sigma^2). (6.1)

Here τ02\tau_0^2 is fixed directly by domain knowledge (for the midge wing lengths, μ0=1.9\mu_0 = 1.9 and τ0=0.95\tau_0 = 0.95 so that μ0−2τ0=0\mu_0 - 2\tau_0 = 0, placing 97.5% prior mass on positive lengths) rather than tied to σ2\sigma^2. Why not approximate the resulting 2-D posterior p(θ,σ~2∣y)p(\theta, \tilde{\sigma}^2 \mid y) on a discrete grid of G×GG \times G points? In two dimensions (G=100  ⟹  104G = 100 \implies 10^4 grid points), a grid works—but in a dd-parameter model, a grid requires GdG^d evaluations (for d=20d = 20 and G=100G = 100, that is 104010^{40} points!). This curse of dimensionality forces us to abandon grids in favor of simulation methods that concentrate automatically where posterior mass lives.

6.1.1Full Conditional Distributions

A full conditional distribution is the posterior distribution of one parameter block given the data and all remaining parameters. Under (6.1), both full conditionals are obtained immediately by kernel recognition:

  1. Mean given variance: holding σ2\sigma^2 fixed, Proposition 5.1 applies verbatim, giving

    θ∣σ2,y1:n∼normal⁡(μn,τn2),τn2=(1τ02+nσ2)−1,μn=τn2 ⁣(μ0τ02+ny¯σ2). \theta \mid \sigma^2, y_{1:n} \sim \operatorname{normal}(\mu_n, \tau_n^2), \qquad \tau_n^2 = \left(\frac{1}{\tau_0^2} + \frac{n}{\sigma^2}\right)^{-1}, \qquad \mu_n = \tau_n^2\!\left(\frac{\mu_0}{\tau_0^2} + \frac{n\bar{y}}{\sigma^2}\right). (6.2)
  2. Precision given mean: holding θ\theta fixed, the likelihood is proportional to (σ~2)n/2exp⁡(−12σ~2∑i=1n(yi−θ)2)(\tilde{\sigma}^2)^{n/2}\exp\bigl(-\frac{1}{2}\tilde{\sigma}^2\sum_{i=1}^n (y_i - \theta)^2\bigr), so multiplying by the gamma⁡(ν0/2,ν0σ02/2)\operatorname{gamma}(\nu_0/2, \nu_0\sigma_0^2/2) prior gives

    σ~2∣θ,y1:n∼gamma⁡ ⁣(ν0+n2,  ν0σ02+nsn2(θ)2), \tilde{\sigma}^2 \mid \theta, y_{1:n} \sim \operatorname{gamma}\!\left(\frac{\nu_0 + n}{2},\; \frac{\nu_0 \sigma_0^2 + n s_n^2(\theta)}{2}\right), (6.3)

    where

nsn2(θ)=∑i=1n(yi−θ)2=(n−1)s2+n(y¯−θ)2 n s_n^2(\theta) = \sum_{i=1}^n (y_i - \theta)^2 = (n - 1)s^2 + n(\bar{y} - \theta)^2

can be evaluated in O(1)O(1) time at every iteration without re-scanning the dataset!

6.2The Gibbs Sampler Algorithm

Suppose our target joint posterior is p(ϕ1,…,ϕp∣y)p(\phi_1, \dots, \phi_p \mid y) and we can sample from every full conditional p(ϕj∣ϕ−j,y)p(\phi_j \mid \phi_{-j}, y). The systematic-scan Gibbs sampler cycles through the blocks, always conditioning on the most recently updated values:

Algorithm 6.1 (Systematic-Scan Gibbs Sampler). Initialize ϕ(0)=(ϕ1(0),…,ϕp(0))\phi^{(0)} = (\phi_1^{(0)}, \dots, \phi_p^{(0)}) in the support of the posterior. For s=1,2,…,Ss = 1, 2, \dots, S:

  1. Sample ϕ1(s)∼p(ϕ1∣ϕ2(s−1),ϕ3(s−1),…,ϕp(s−1),y)\phi_1^{(s)} \sim p(\phi_1 \mid \phi_2^{(s-1)}, \phi_3^{(s-1)}, \dots, \phi_p^{(s-1)}, y).
  2. Sample ϕ2(s)∼p(ϕ2∣ϕ1(s),ϕ3(s−1),…,ϕp(s−1),y)\phi_2^{(s)} \sim p(\phi_2 \mid \phi_1^{(s)}, \phi_3^{(s-1)}, \dots, \phi_p^{(s-1)}, y).
  3.   ⋮\;\vdots
  4. Sample ϕp(s)∼p(ϕp∣ϕ1(s),…,ϕp−1(s),y)\phi_p^{(s)} \sim p(\phi_p \mid \phi_1^{(s)}, \dots, \phi_{p-1}^{(s)}, y).

Return the Markov chain ϕ(1),…,ϕ(S)\phi^{(1)}, \dots, \phi^{(S)} (typically discarding an initial warm-up/burn-in prefix).

For the two-block semiconjugate normal model (ϕ=(θ,σ~2)\phi = (\theta, \tilde{\sigma}^2)), each iteration simply alternates one draw from (6.2) and one draw from (6.3). Because each move updates only one coordinate at a time, the trajectory takes axis-aligned horizontal and vertical steps across the posterior contours (Figure 6.1, left panel).

Three panels: semiconjugate Gibbs sampler trajectory stepping across the midge wing-length posterior contours; slow mixing histogram versus true trimodal normal mixture density; and sticky traceplot showing infrequent jumps between modes at -3, 0, and +3
Figure 6.1: Left: semiconjugate Gibbs trajectory on the midge wing-length posterior, rapidly entering the high-density region within a few iterations. Center and right: Hoff’s trimodal mixture diagnostic (0.45 𝒩(−3,13)+0.10 𝒩(0,13)+0.45 𝒩(3,13)0.45\,\mathcal{N}(-3, \tfrac13) + 0.10\,\mathcal{N}(0, \tfrac13) + 0.45\,\mathcal{N}(3, \tfrac13))—the Gibbs sampler gets trapped in individual modes for hundreds of steps, producing severe autocorrelation and a distorted empirical histogram after 1,500 draws.

6.3Why Does Gibbs Sampling Work? Theory and Pitfalls

At first sight it feels almost magical that alternating conditional draws recovers the joint distribution. The mathematical mechanism rests on stationarity and ergodicity:

Proposition 6.2 (Invariance of the Target Posterior under Gibbs Updates). If ϕ(s−1)∼p(ϕ∣y)\phi^{(s-1)} \sim p(\phi \mid y), then a single conditional update replacing block ϕj\phi_j by ϕj′∼p(ϕj∣ϕ−j(s−1),y)\phi_j' \sim p(\phi_j \mid \phi_{-j}^{(s-1)}, y) preserves the joint distribution: (ϕj′,ϕ−j(s−1))∼p(ϕ∣y)(\phi_j', \phi_{-j}^{(s-1)}) \sim p(\phi \mid y). Consequently, the full systematic scan in Algorithm 6.1 leaves p(ϕ∣y)p(\phi \mid y) invariant.

Proof. By definition of conditional probability, the joint density of the new state (ϕj′,ϕ−j)(\phi_j', \phi_{-j}) when the previous state was drawn from p(ϕ∣y)p(\phi \mid y) is

pnew(ϕj′,ϕ−j)=p(ϕ−j∣y) p(ϕj′∣ϕ−j,y)=p(ϕj′,ϕ−j∣y). p_{\text{new}}(\phi_j', \phi_{-j}) = p(\phi_{-j} \mid y)\,p(\phi_j' \mid \phi_{-j}, y) = p(\phi_j', \phi_{-j} \mid y).

Since every single-block kernel preserves p(ϕ∣y)p(\phi \mid y), their composition (the full systematic scan) also preserves p(ϕ∣y)p(\phi \mid y). □

Remark 6.3 (Subtle caveats every practitioner should know).

  1. Invariance is not reversibility: Although each single-coordinate Gibbs step is reversible with respect to p(ϕ∣y)p(\phi \mid y), a systematic scan of p≥2p \ge 2 blocks is generally not reversible as a joint chain (though for p=2p = 2, each marginal coordinate subchain is reversible); it preserves the target by Proposition 6.2 without obeying detailed balance for the whole sweep. In Chapter 10 we show each single-block Gibbs update is a Metropolis–Hastings move with acceptance probability r≡1r \equiv 1.
  2. Positivity (irreducibility) is required: If the support of p(ϕ1,ϕ2∣y)p(\phi_1, \phi_2 \mid y) consists of disconnected islands (for instance, uniform on [0,1]2∪[2,3]2[0, 1]^2 \cup [2, 3]^2), every coordinate-wise Gibbs step is trapped forever in whichever island it starts in! Strict positivity on a product support—or connectivity via coordinate moves—is required for convergence to p(ϕ∣y)p(\phi \mid y) from arbitrary starting points.
  3. Proper conditionals do not guarantee a proper joint: A notorious trap with improper priors is that well-defined full conditionals can correspond to an improper (non-integrable) joint posterior. For example, p(x∣y)=ye−xyp(x \mid y) = y e^{-xy} and p(y∣x)=xe−xyp(y \mid x) = x e^{-xy} on (0,∞)2(0, \infty)^2 are both proper exponential densities, yet the only compatible joint density p(x,y)∝e−xyp(x, y) \propto e^{-xy} has infinite integral! Always check joint propriety when using improper priors.

Under irreducibility and aperiodicity (formalized in Chapter 10), the Ergodic Theorem guarantees that regardless of the starting point ϕ(0)\phi^{(0)}, as S→∞S \to \infty:

  • the marginal distribution of ϕ(s)\phi^{(s)} converges in total variation to p(ϕ∣y)p(\phi \mid y), and
  • ergodic averages converge almost surely: 1S∑s=1Sg(ϕ(s))→E[g(ϕ)∣y]\frac{1}{S}\sum_{s=1}^S g(\phi^{(s)}) \to E[g(\phi) \mid y].

6.3.1Estimation vs. Approximation

Hoff highlights a conceptual point that prevents endless confusion: increasing the number of MCMC draws SS improves numerical approximation, never statistical information. With n=9n = 9 midges, running S=106S = 10^6 Gibbs draws pins down the exact posterior mean E[θ∣y]E[\theta \mid y] to five decimals, but the posterior width still reflects only n=9n = 9 observations. Simulation cannot manufacture data!

6.4Diagnostics: Autocorrelation, Mixing, and Effective Sample Size

Unlike i.i.d. Monte Carlo draws in Chapter 4, consecutive Gibbs draws ϕ(s−1)\phi^{(s-1)} and ϕ(s)\phi^{(s)} are positively correlated. Consider the cleanest analytical benchmark: a bivariate normal target with correlation ρ\rho. Alternating draws from X∣Y∼𝒩(ρY,1−ρ2)X \mid Y \sim \mathcal{N}(\rho Y, 1 - \rho^2) and Y∣X∼𝒩(ρX,1−ρ2)Y \mid X \sim \mathcal{N}(\rho X, 1 - \rho^2) produces a Markov chain whose exact lag-kk autocorrelation is

Corr⁡(X(s),X(s+k))=ρ2k. \operatorname{Corr}\bigl(X^{(s)}, X^{(s+k)}\bigr) = \rho^{2k}. (6.4)

When ρ=0.99\rho = 0.99, ρ2=0.9801\rho^2 = 0.9801: consecutive draws are 98% redundant, and the chain crawls agonizingly along the diagonal ridge! Even worse, in a multimodal target—such as Hoff’s three-component normal mixture θ∣δ∼𝒩(μδ,13)\theta \mid \delta \sim \mathcal{N}(\mu_\delta, \tfrac13) with μ=(−3,0,3)\mu = (-3, 0, 3) and mixture weights (0.45,0.10,0.45)(0.45, 0.10, 0.45)—the joint Gibbs sampler alternating θ∣δ\theta \mid \delta and δ∣θ\delta \mid \theta becomes sticky: once θ\theta is near −3-3, δ\delta stays at component 11 with probability >0.999> 0.999, and the chain barely crosses the low-density valley (Figure 6.1, center and right).

How does autocorrelation inflate our Monte Carlo variance? For a stationary chain with posterior variance σg2=Var⁡[g(ϕ)∣y]\sigma_g^2 = \operatorname{Var}[g(\phi) \mid y] and lag-kk autocorrelations ρk=Corr⁡(g(ϕ(s)),g(ϕ(s+k)))\rho_k = \operatorname{Corr}(g(\phi^{(s)}), g(\phi^{(s+k)})), the asymptotic variance of the ergodic average g¯S=1S∑s=1Sg(ϕ(s))\bar{g}_S = \frac{1}{S}\sum_{s=1}^S g(\phi^{(s)}) isCharles J. Geyer. Practical Markov Chain Monte Carlo. Statistical Science, 7:473–483, 1992; and Christian P. Robert and George Casella. Monte Carlo Statistical Methods. Springer, New York, second edition, 2004

Var⁡(g¯S)≈σg2S(1+2∑k=1∞ρk)=σg2Seff,Seff=S1+2∑k=1∞ρk. \operatorname{Var}(\bar{g}_S) \approx \frac{\sigma_g^2}{S}\left(1 + 2\sum_{k=1}^{\infty} \rho_k\right) = \frac{\sigma_g^2}{S_{\text{eff}}}, \qquad S_{\text{eff}} = \frac{S}{1 + 2\sum_{k=1}^{\infty} \rho_k}. (6.5)

The quantity SeffS_{\text{eff}} is the **effective sample size (ESS)**: the number of independent posterior draws that would yield the same Monte Carlo standard error as our SS correlated MCMC draws. For the bivariate normal benchmark (6.4), summing the geometric series gives Seff=S 1−ρ21+ρ2S_{\text{eff}} = S\,\frac{1 - \rho^2}{1 + \rho^2}—so at ρ=0.99\rho = 0.99, S=10,000S = 10{,}000 Gibbs draws are worth only about 100100 independent draws!

In practice, always combine four diagnostic habits:Andrew Gelman and Donald B. Rubin. Inference from Iterative Simulation Using Multiple Sequences. Statistical Science, 7:457–472, 1992; and Aki Vehtari, Andrew Gelman, Daniel Simpson, Bob Carpenter, and Paul-Christian Bürkner. Rank-Normalization, Folding, and Localization: An Improved R̂\widehat{R} for Assessing Convergence of MCMC. Bayesian Analysis, 16(2):667–718, 2021Vehtari et al. (2021) is beyond Hoff (2009): rank-normalized split-R̂\widehat{R}, its 1.011.01 threshold, and separate bulk and tail effective sample sizes are not in Hoff’s book.

  1. Traceplots: inspect ϕ(s)\phi^{(s)} versus ss for drift (non-stationarity) or sticky plateaus.
  2. Multiple overdispersed chains & R̂\widehat{R}: launch chains from widely separated starting points; if they fail to overlap (as in a multimodal trap), the split-R̂\widehat{R} statistic stays above 1.011.01.
  3. Autocorrelation function (ACF) and SeffS_{\text{eff}}: verify that lag-kk autocorrelations decay quickly to zero and that SeffS_{\text{eff}} is large enough (typically Seff≥1,000S_{\text{eff}} \ge 1{,}000) for every target quantity and tail quantile of interest.
  4. Reparameterization or blocking: when high correlation slows Gibbs mixing, sample strongly correlated parameters jointly in one block or reparameterize to decouple them (a theme we revisit in Chapter 8 and Chapter 12).
import numpy as np

# Semiconjugate Gibbs sampler for Hoff's midge wing length data
y = np.array([1.64, 1.70, 1.72, 1.74, 1.82, 1.82, 1.82, 1.90, 2.08])
n, ybar, s2 = len(y), np.mean(y), np.var(y, ddof=1)
mu0, t20, s20, nu0 = 1.9, 0.95**2, 0.01, 1.0

rng = np.random.default_rng(42)
S = 5_000
theta = np.empty(S)
sigma2 = np.empty(S)
s2_cur = s2  # initialize variance at sample variance

for s in range(S):
    # 1. Full conditional for theta | sigma^2, y
    t2n = 1.0 / (1.0 / t20 + n / s2_cur)
    mun = t2n * (mu0 / t20 + n * ybar / s2_cur)
    th_cur = rng.normal(mun, np.sqrt(t2n))
    # 2. Full conditional for 1/sigma^2 | theta, y (O(1) sum-of-squares identity)
    ss = nu0 * s20 + (n - 1) * s2 + n * (ybar - th_cur)**2
    prec_cur = rng.gamma(shape=(nu0 + n) / 2.0, scale=2.0 / ss)
    s2_cur = 1.0 / prec_cur
    theta[s], sigma2[s] = th_cur, s2_cur

def ess_fft(x):
    """Estimate ESS via initial positive sequence of FFT autocorrelations."""
    x = x - np.mean(x)
    n_x = len(x)
    f = np.fft.rfft(x, n=2 * n_x)
    acf = np.fft.irfft(f * np.conjugate(f))[:n_x]
    acf /= acf[0]
    # Sum paired autocorrelations (Geyer's initial positive sequence: (rho_0+rho_1), (rho_2+rho_3), ...)
    tau = -1.0
    for k in range(0, n_x // 2, 2):
        pair = acf[k] + acf[k + 1]
        if pair <= 0:
            break
        tau += 2.0 * pair
    return n_x / max(tau, 1.0)

print(f"Posterior theta: mean={theta.mean():.4f}, 95% CI={np.round(np.quantile(theta, [0.025, 0.975]), 4)}")
print(f"ESS(theta) = {ess_fft(theta):.0f} / {S}, ESS(sigma^2) = {ess_fft(sigma2):.0f} / {S}")

6.5Modern Developments: Couplings, Variational Inference, and Tempering

6.5.1Unbiased MCMC via Couplings

Running two Gibbs chains that eventually meet removes burn-in bias exactly, rather than waiting for it to become negligible.Beyond Hoff (2009). This material is not in Hoff’s book; Jacob, O’Leary and Atchadé (2020) turn coupling, an older proof technique, into a practical estimator.Pierre E. Jacob, John O’Leary, and Yves F. Atchadé. Unbiased Markov Chain Monte Carlo Methods with Couplings. Journal of the Royal Statistical Society Series B: Statistical Methodology, 82(3):543–600, 2020. doi: 10.1111/rssb.12336 Let (Xt)(X_t) and (Yt)(Y_t) be two copies of the chain in Algorithm 6.1 with the same initial law, YY lagging by one step, moved by a joint kernel under which each is marginally the Gibbs chain. Let τ=inf⁡{t≥1:Xt=Yt−1}\tau = \inf\{t \ge 1 : X_t = Y_{t-1}\} be the meeting time, after which the chains stay equal. Then

Hk=h(Xk)+∑t=k+1τ−1[h(Xt)−h(Yt−1)],E[Hk]=E[h(ϕ)∣y]. H_k = h(X_k) + \sum_{t=k+1}^{\tau - 1}\bigl[h(X_t) - h(Y_{t-1})\bigr], \qquad E[H_k] = E[h(\phi) \mid y]. (6.6)

Why? Telescoping writes E[h(ϕ)∣y]=E[h(Xk)]+∑t>k(E[h(Xt)]−E[h(Xt−1)])E[h(\phi) \mid y] = E[h(X_k)] + \sum_{t > k}\bigl(E[h(X_t)] - E[h(X_{t-1})]\bigr); since Yt−1Y_{t-1} has the law of Xt−1X_{t-1}, it may replace Xt−1X_{t-1}, and all terms with t≥τt \ge \tau are zero. If the chain converges with uniformly bounded moments of hh of order slightly above two and τ\tau has geometric tails, the interchange of sum and expectation is justified, and HkH_k has finite variance and finite expected cost. For Gibbs, draw each full conditional (6.2)–(6.3) from a maximal coupling of the two chains’ versions, which makes the two draws equal with the largest possible probability.

When to use it. Independent replicates of HkH_k can be averaged across processors, with ordinary i.i.d. standard errors in place of (6.5). For one long, fast-mixing chain, Hoff’s recipe is cheaper. In a sticky multimodal target unbiasedness still holds in expectation, but rare enormous corrections make the variance misleading.

6.5.2Coordinate Ascent Variational Inference

Variational inference replaces simulation by optimization, approximating p(ϕ∣y)p(\phi \mid y) by the closest factorized density q(ϕ)=∏jqj(ϕj)q(\phi) = \prod_j q_j(\phi_j) in KL⁡(q ∥ p)\operatorname{KL}(q \,\|\, p).Beyond Hoff (2009). This material is not in Hoff’s book; mean-field methods came from machine learning before 2009, and Blei, Kucukelbir and McAuliffe (2017) give the standard statistical account.David M. Blei, Alp Kucukelbir, and Jon D. McAuliffe. Variational Inference: A Review for Statisticians. Journal of the American Statistical Association, 112(518):859–877, 2017. doi: 10.1080/01621459.2017.1285773 Holding the other factors fixed, minimizing over qjq_j gives the CAVI update

qj(ϕj)  ∝  exp⁡{Eq−j[log⁡p(ϕj∣ϕ−j,y)]}, q_j(\phi_j) \;\propto\; \exp\bigl\{E_{q_{-j}}\bigl[\log p(\phi_j \mid \phi_{-j}, y)\bigr]\bigr\}, (6.7)

because, as a function of qjq_j, the objective is the KL divergence from qjq_j to this density plus a constant. It is Gibbs with averaging in place of sampling: under (6.1), q(θ)q(\theta) is normal and q(σ~2)q(\tilde{\sigma}^2) is gamma, as in (6.2) and (6.3) with σ~2\tilde{\sigma}^2 replaced by Eq[σ~2]E_q[\tilde{\sigma}^2] and (y¯−θ)2(\bar{y} - \theta)^2 by Eq[(y¯−θ)2]E_q[(\bar{y} - \theta)^2].

For the bivariate normal benchmark behind (6.4), averaging −(x−ρY)22(1−ρ2)-\frac{(x - \rho Y)^2}{2(1 - \rho^2)} over qYq_Y gives

qX=𝒩(ρ mY,  1−ρ2),mX(s+1)=ρ mY(s),mY(s)=ρ mX(s)  ⟹  mX(s+1)=ρ2 mX(s). q_X = \mathcal{N}\bigl(\rho\,m_Y,\; 1 - \rho^2\bigr), \qquad m_X^{(s+1)} = \rho\,m_Y^{(s)}, \quad m_Y^{(s)} = \rho\,m_X^{(s)} \;\Longrightarrow\; m_X^{(s+1)} = \rho^2\,m_X^{(s)}. (6.8)

The means converge to the exact value 00, contracting by ρ2\rho^2 per sweep—precisely Gibbs’ lag-1 autocorrelation. But the variance is 1−ρ21 - \rho^2, the conditional variance, instead of the marginal value 11: at ρ=0.99\rho = 0.99 the reported standard deviation is 0.1410.141, about seven times too small, and no amount of iteration repairs it.

When to use it. Use CAVI for fast point estimates or initialization on large problems; keep Gibbs whenever interval widths matter.

6.5.3Non-Reversible Parallel Tempering

Parallel tempering can cure the sticky trimodal example of Figure 6.1 by linking it to an easy distribution through a ladder of intermediate ones.Beyond Hoff (2009). This material is not in Hoff’s book; parallel tempering itself predates 2009, but the round-trip and communication-barrier analysis of non-reversible swap schedules is due to Syed et al. (2022).Saifuddin Syed, Alexandre Bouchard-Côté, George Deligiannidis, and Arnaud Doucet. Non-Reversible Parallel Tempering: A Scalable Highly Parallel MCMC Scheme. Journal of the Royal Statistical Society Series B: Statistical Methodology, 84(2):321–350, 2022. doi: 10.1111/rssb.12464 Choose a reference π0\pi_0 that is easy to sample (here, a wide normal), set πβ∝π01−β πβ\pi_\beta \propto \pi_0^{1-\beta}\,\pi^{\beta} on 0=β0<⋯<βN=10 = \beta_0 < \dots < \beta_N = 1, run one chain per βi\beta_i, and propose to swap the states of neighbours. The non-reversible scheme alternates deterministically between swapping the even pairs and the odd pairs, instead of choosing between them at random. If the swap between levels i−1i-1 and ii is rejected with probability rir_i, and swaps behave independently across iterations (efficient local exploration), the total rate of reference-to-target round trips is, with the limit taken as the largest gap βi−βi−1\beta_i - \beta_{i-1} shrinks to 00,

𝒯=12+2∑i=1Nri1−ri  ⟶  12+2Λ(N→∞),Λ=lim⁡N→∞∑i=1Nri. \mathcal{T} = \frac{1}{2 + 2\sum_{i=1}^N \frac{r_i}{1 - r_i}} \;\longrightarrow\; \frac{1}{2 + 2\Lambda} \quad (N \to \infty), \qquad \Lambda = \lim_{N \to \infty}\sum_{i=1}^N r_i. (6.9)

Why? A state keeps moving in one direction until a rejection reverses it. Crossing two barriers with success probabilities p1,p2p_1, p_2, with all back-and-forth reflections counted, succeeds with probability p1p2/[1−(1−p1)(1−p2)]p_1p_2/[1 - (1 - p_1)(1 - p_2)]; hence 1/p−1=r/(1−r)1/p - 1 = r/(1-r) adds along the ladder. Refining the ladder therefore does no harm, whereas random alternation makes each state a diffusive random walk whose round-trip rate tends to 00. The global communication barrier Λ\Lambda depends on π0\pi_0 and π\pi, not on the schedule.

When to use it. Plain Gibbs suffices for unimodal posteriors. When R̂\widehat{R} exposes separated modes—or the ≈306\approx 306-step residence time in Exercise 6.6—temper, with a reference wide enough to cover every mode.

6.5.4Computational & Symbolic Check

The script iterates the CAVI update (6.8) from the target’s precision matrix, and runs the Gibbs sampler on the same target to compare its lag-1 autocorrelation and standard deviation.Beyond Hoff (2009). This computational check and its Wolfram symbolic counterpart below verify the modern methods in this section and are not in Hoff’s book.

import numpy as np

# CAVI on the standardized bivariate normal, written in terms of its precision matrix
rho = 0.99
Om = np.linalg.inv(np.array([[1.0, rho], [rho, 1.0]]))
m_x, means = 3.0, [3.0]
for _ in range(400):
    m_y = -Om[1, 0] * m_x / Om[1, 1]
    m_x = -Om[0, 1] * m_y / Om[0, 0]
    means.append(m_x)
print(f"CAVI: mean {m_x:.5f}, SD {np.sqrt(1 / Om[0, 0]):.4f} (exact 1), rate {means[1] / means[0]:.4f}")

# Gibbs on the same target: same rate, as lag-1 autocorrelation, but the correct marginal SD
rng, S, sd = np.random.default_rng(6), 200_000, np.sqrt(1 - rho**2)
Z, x, cur = rng.normal(size=(S, 2)), np.empty(S), 0.0
for s in range(S):
    cur = rho * (rho * cur + sd * Z[s, 0]) + sd * Z[s, 1]
    x[s] = cur
print(f"Gibbs: SD {x.std():.3f}, lag-1 ACF {np.corrcoef(x[:-1], x[1:])[0, 1]:.4f} (exact {rho**2:.4f})")
Average the log kernel of p(x∣Y)p(x \mid Y) over qYq_Y with mean mYm_Y and variance vYv_Y, writing Y=mY+vY ZY = m_Y + \sqrt{v_Y}\,Z with Z∼𝒩(0,1)Z \sim \mathcal{N}(0, 1).
// Chapter 6 (modern): CAVI fixed-point update on the standardized bivariate normal
const eLog = await show`Assuming[vY > 0 && Element[{mY, x, rho}, Reals],
  Integrate[-(x - rho*(mY + Sqrt[vY]*z))^2/(2*(1 - rho^2))*Exp[-z^2/2]/Sqrt[2*Pi], {z, -Infinity, Infinity}]]`
EqY ⁣[−(x−ρY)22(1−ρ2)]=−(x−ρmY)2+ρ2vY2(1−ρ2) E_{q_Y}\!\left[-\frac{(x - \rho Y)^2}{2(1-\rho^2)}\right] = -\frac{(x-\rho m_Y)^2+\rho^2 v_Y}{2 \left(1-\rho^2\right)} The curvature in xx gives the CAVI variance, whatever vYv_Y is.
const qVar = await show`Simplify[-1/D[${eLog}, {x, 2}]]`
Var⁡q(X)=1−ρ2 \operatorname{Var}_{q}(X) = 1-\rho^2 Solve for the stationary point in xx to obtain the mean update.
const qMean = await show`x /. First[Solve[D[${eLog}, x] == 0, x]]`
Eq[X]=mYρ E_{q}[X] = m_Y \rho Compose the YY and XX updates into one full sweep, mX↦ρ2mXm_X \mapsto \rho^2 m_X.
const sweep = await show`${qMean} /. mY -> rho*mX`
mX(s+1)=mXρ2 m_X^{(s+1)} = m_X \rho^2 Subtract Gibbs’ lag-1 autocorrelation E[X⋅E[X(s+1)∣X]]=E[X⋅ρ2X]E\bigl[X \cdot E[X^{(s+1)} \mid X]\bigr] = E[X \cdot \rho^2 X] from the CAVI contraction rate.
await show`Simplify[D[${sweep}, mX] - Integrate[x*(rho^2*x)*Exp[-x^2/2]/Sqrt[2*Pi], {x, -Infinity, Infinity}]]`
∂mX(s+1)∂mX(s)−Corr⁡ ⁣(X(s),X(s+1))Gibbs=0 \frac{\partial m_X^{(s+1)}}{\partial m_X^{(s)}} - \operatorname{Corr}\!\left(X^{(s)}, X^{(s+1)}\right)_{\text{Gibbs}} = 0 Instantiate the CAVI standard deviation, the contraction rate, and the factor by which the true SD is understated, at ρ=0.99\rho = 0.99.
await show`N[{Sqrt[${qVar}], D[${sweep}, mX], 1/Sqrt[${qVar}]} /. rho -> 99/100]`
(SD⁡q(X),  rate,  SD⁡p(X)/SD⁡q(X))ρ=0.99={0.141067,0.9801,7.08881} \begin{aligned} &\bigl(\operatorname{SD}_q(X),\; \text{rate},\; \operatorname{SD}_p(X)/\operatorname{SD}_q(X)\bigr)_{\rho=0.99} \\ &= \{0.141067,0.9801,7.08881\} \end{aligned}

6.6Symbolic Check in Wolfram Language

Computes the bivariate-normal Gibbs transition mean and variance symbolically in wolfram-ws-bridge JavaScript mode, extracts the AR(1) contraction factor α=ρ2\alpha = \rho^2, sums the integrated autocorrelation time to derive Seff/S=(1−ρ2)/(1+ρ2)S_{\text{eff}}/S = (1 - \rho^2)/(1 + \rho^2), verifies the O(1)O(1) sum-of-squares decomposition symbolically, and instantiates SeffS_{\text{eff}} at ρ=0.99\rho = 0.99.

Integrate one full two-step Gibbs sweep of a bivariate normal to derive the conditional mean E[X(s+1)∣X(s)=x]=ρ2xE[X^{(s+1)} \mid X^{(s)} = x] = \rho^2 x.
// Chapter 6: Symbolic bivariate-normal Gibbs transition, ACF, ESS & O(1) sum-of-squares identity
const transMean = await show`Assuming[v > 0 && Element[m, Reals],
  Simplify[Integrate[rho*(m + Sqrt[v]*z)*Exp[-z^2/2]/Sqrt[2*Pi], {z, -Infinity, Infinity}]]] /. {m -> rho*x, v -> 1 - rho^2}`
𝔼 ⁣[X(s+1)∣X(s)=x]=ρ2x \mathbb{E}\!\left[X^{(s+1)} \mid X^{(s)} = x\right] = \rho^2 x Differentiate the transition mean in xx to read off the AR(1) contraction coefficient α\alpha.
const alpha = await show`D[${transMean}, x]`   // AR(1) lag-1 contraction coefficient = rho^2
α=∂∂x 𝔼 ⁣[X(s+1)∣X(s)=x]=ρ2 \alpha = \frac{\partial}{\partial x}\,\mathbb{E}\!\left[X^{(s+1)} \mid X^{(s)} = x\right] = \rho^2 Compute the one-step conditional variance 1−ρ41 - \rho^4, confirming an exact AR(1) transition.
await show`Simplify[(v + Integrate[(rho*Sqrt[v]*z)^2*Exp[-z^2/2]/Sqrt[2*Pi], {z, -Infinity, Infinity}]) /. v -> 1 - rho^2]`
Var⁡ ⁣(X(s+1)∣X(s)=x)=1−ρ4 \operatorname{Var}\!\left(X^{(s+1)} \mid X^{(s)} = x\right) = 1-\rho^4 Sum 1+2∑k=1∞ρ2k1 + 2\sum_{k=1}^\infty \rho^{2k} to obtain the integrated autocorrelation time τint\tau_{\text{int}}.
const tauInt = await show`Assuming[-1 < rho < 1, Together[Sum[2*(${alpha})^k, {k, 1, Infinity}] + 1]]`
τint=1+2∑k=1∞ρ2k=−1−ρ2−1+ρ2 \tau_{\text{int}} = 1 + 2\sum_{k=1}^\infty \rho^{2k} = \frac{-1-\rho^2}{-1+\rho^2} Invert τint\tau_{\text{int}} to express the effective sample size ratio Seff/S=(1−ρ2)/(1+ρ2)S_{\text{eff}}/S = (1 - \rho^2)/(1 + \rho^2).
const essRatio = await show`Together[1 / ${tauInt}]`
SeffS=1τint=1−ρ21+ρ2 \frac{S_{\text{eff}}}{S} = \frac{1}{\tau_{\text{int}}} = \frac{1-\rho^2}{1+\rho^2} Verify the O(1)O(1) sum-of-squares decomposition symbolically for n=3n = 3 observations.
// Symbolic verification of the O(1) Gibbs sum-of-squares decomposition (n = 3)
await show`Expand[Sum[(y[i] - th)^2, {i, 3}]
  - (Sum[(y[i] - (y[1] + y[2] + y[3])/3)^2, {i, 3}] + 3*((y[1] + y[2] + y[3])/3 - th)^2)]`
∑i=13(yi−θ)2−[∑i=13(yi−y¯)2+3(y¯−θ)2]=0 \begin{aligned} &\sum_{i=1}^3 (y_i - \theta)^2 - \left[\sum_{i=1}^3 (y_i - \bar{y})^2 + 3(\bar{y} - \theta)^2\right] \\ &= 0 \end{aligned} Instantiate SeffS_{\text{eff}} at ρ=0.99\rho = 0.99 and S=10,000S = 10{,}000, illustrating severe correlation loss.
// Instantiate exact S_eff at rho = 99/100, S = 10,000
await show`N[10000 * (${essRatio} /. rho -> 99/100)]`
Seff∣ρ=0.99,  S=10,000=100.5 S_{\text{eff}}\big|_{\rho=0.99,\; S=10{,}000} = 100.5

6.7Exercises

Exercise 6.4. Verify (6.4) by showing that for the bivariate normal target (X,Y)∼𝒩2(0,(1ρρ1))(X, Y) \sim \mathcal{N}_2\bigl(0, \bigl(\begin{smallmatrix} 1 & \rho \\ \rho & 1 \end{smallmatrix}\bigr)\bigr), the Gibbs update satisfies X(s)=ρ2X(s−1)+η(s)X^{(s)} = \rho^2 X^{(s-1)} + \eta^{(s)} where η(s)∼𝒩(0,1−ρ4)\eta^{(s)} \sim \mathcal{N}(0, 1 - \rho^4) is independent of X(s−1)X^{(s-1)}. Deduce Corr⁡(X(s),X(s+k))=ρ2k\operatorname{Corr}(X^{(s)}, X^{(s+k)}) = \rho^{2k} and Seff=S 1−ρ21+ρ2S_{\text{eff}} = S\,\frac{1-\rho^2}{1+\rho^2}.

Symbolic Solution & InstantiationSimplify the lag-kk autocorrelation of the bivariate-normal Gibbs chain to (ρ2)k(\rho^2)^k.
// Ex 6.1: Bivariate-normal Gibbs AR(1) recursion, lag-k ACF, and ESS
await show`Assuming[-1 < rho < 1, FullSimplify[(rho^2)^k]]`
Corr⁡ ⁣(X(s),X(s+k))=(ρ2)k \operatorname{Corr}\!\left(X^{(s)}, X^{(s+k)}\right) = \left(\rho^2\right)^k Sum the geometric series to obtain the exact ESS ratio (1−ρ2)/(1+ρ2)(1 - \rho^2)/(1 + \rho^2).
const essRatio = await show`Assuming[-1 < rho < 1, Together[1 / (1 + 2*Sum[rho^(2*k), {k, 1, Infinity}])]]`
ESS⁡S=11+2∑k=1∞ρ2k=1−ρ21+ρ2 \begin{aligned} &\frac{\operatorname{ESS}}{S} = \frac{1}{1 + 2\sum_{k=1}^\infty \rho^{2k}} \\ &= \frac{1-\rho^2}{1+\rho^2} \end{aligned} Instantiate the exact fraction and decimal ESS ratio at ρ=0.90\rho = 0.90.
await show`{${essRatio}, N[${essRatio}]} /. rho -> 9/10`
(ESS⁡Sexact,  ESS⁡Sdecimal)ρ=0.9={19181,0.104972} \begin{aligned} &\left(\frac{\operatorname{ESS}}{S}_{\text{exact}},\; \frac{\operatorname{ESS}}{S}_{\text{decimal}}\right)_{\rho=0.9} \\ &= \left\{\frac{19}{181},0.104972\right\} \end{aligned}

Exercise 6.5. Suppose you place the improper prior p(θ,σ2)∝1p(\theta, \sigma^2) \propto 1 (flat on σ2\sigma^2, not 1/σ21/\sigma^2) with n=3n = 3 normal observations. Write down the formal full conditionals p(θ∣σ2,y)p(\theta \mid \sigma^2, y) and p(σ2∣θ,y)p(\sigma^2 \mid \theta, y). Verify that both are proper distributions (σ2∣θ,y∼inverse-gamma⁡(1/2,SS/2)\sigma^2 \mid \theta, y \sim \operatorname{inverse-gamma}(1/2, \text{SS}/2)), yet after integrating out θ\theta the marginal density of σ2\sigma^2 has a (σ2)−1(\sigma^2)^{-1} tail and is not integrable as σ2→∞\sigma^2 \to \infty!

Symbolic Solution & InstantiationRecord the full-conditional exponent −n/2-n/2 of σ2\sigma^2 under the flat prior p(θ,σ2)∝1p(\theta, \sigma^2) \propto 1.
// Ex 6.2: Flat prior p(theta, sigma^2) ~ 1 at n = 3 -> proper conditionals, improper marginal!
const condExp = await show`Assuming[n > 0, FullSimplify[-n/2]]`
Full-conditional exponent of σ2 in p(σ2∣θ,y)=−n2 \begin{aligned} &\text{Full-conditional exponent of } \sigma^2 \text{ in } p(\sigma^2 \mid \theta, y) \\ &= -\frac{n}{2} \end{aligned} Record the marginal exponent (1−n)/2(1 - n)/2 of σ2\sigma^2 after integrating out θ\theta.
const margExp = await show`Assuming[n > 0, FullSimplify[-(n - 1)/2]]`
Marginal exponent of σ2 in p(σ2∣y)=1−n2 \text{Marginal exponent of } \sigma^2 \text{ in } p(\sigma^2 \mid y) = \frac{1-n}{2} Evaluate both exponents at n=3n = 3, exposing a proper conditional (−3/2-3/2) alongside a divergent marginal (−1-1).
await show`{${condExp}, ${margExp}} /. n -> 3`
(cond. exponent,  marginal exponent)n=3={−32,−1} \begin{aligned} &\bigl(\text{cond. exponent},\; \text{marginal exponent}\bigr)_{n=3} \\ &= \left\{-\frac{3}{2},-1\right\} \end{aligned}

Exercise 6.6. Implement the trimodal mixture Gibbs sampler from Figure 6.1 in Python and run 4 chains from δ(0)∈{1,2,3}\delta^{(0)} \in \{1, 2, 3\} for S=2,000S = 2{,}000 iterations. Compute the empirical component frequencies and SeffS_{\text{eff}} for θ\theta. Why does direct ancestral sampling (δ∼Categorical(0.45,0.10,0.45)\delta \sim \text{Categorical}(0.45, 0.10, 0.45), then θ∣δ\theta \mid \delta) have Seff=SS_{\text{eff}} = S?

Symbolic Solution & InstantiationExpress the mean residence time in mode −3-3 as the reciprocal of the one-step escape probability pescp_{\text{esc}}.
// Ex 6.3: One-step escape probability & mean residence time from mode -3 in Hoff's trimodal Gibbs sampler
const meanRes = await show`1 / pEsc`
𝔼[steps before escaping mode −3]=1pesc \mathbb{E}[\text{steps before escaping mode } -3] = \frac{1}{p_{\text{esc}}} Integrate numerically the probability that, from θ∼𝒩(−3,13)\theta \sim \mathcal{N}(-3, \tfrac13), the next δ\delta-update leaves mode −3-3.
const esc = await show`NIntegrate[(Exp[-(th + 3)^2/(2/3)]/Sqrt[2*Pi/3]) * (1 - (45/100*Exp[-(th + 3)^2/(2/3)]) / (45/100*Exp[-(th + 3)^2/(2/3)] + 10/100*Exp[-th^2/(2/3)] + 45/100*Exp[-(th - 3)^2/(2/3)])), {th, -7, 7}]`
pesc=∫−7732π e−32(θ+3)2(1−0.45 e−32(θ+3)20.45 e−32(θ+3)2+0.10 e−32θ2+0.45 e−32(θ−3)2)dθ=0.00327041 \begin{aligned} &p_{\text{esc}} = \int_{-7}^{7} \sqrt{\tfrac{3}{2\pi}}\, e^{-\frac{3}{2}(\theta+3)^2} \left(1-\frac{0.45\, e^{-\frac{3}{2}(\theta+3)^2}}{0.45\, e^{-\frac{3}{2}(\theta+3)^2}+0.10\, e^{-\frac{3}{2}\theta^2}+0.45\, e^{-\frac{3}{2}(\theta-3)^2}}\right) d\theta \\ &= 0.00327041 \end{aligned} Plug pescp_{\text{esc}} into 1/pesc1/p_{\text{esc}} to get the expected number of trapped iterations.
await show`N[{${esc}, ${meanRes} /. pEsc -> ${esc}}]`
(pesc,  𝔼[steps trapped])mode −3={0.00327041,305.772} \begin{aligned} &\bigl(p_{\text{esc}},\; \mathbb{E}[\text{steps trapped}]\bigr)_{\text{mode }-3} \\ &= \{0.00327041,305.772\} \end{aligned}