Chapter 6
Posterior Approximation with the Gibbs Sampler
The moment we relax the artificial prior coupling from Chapter 5 and specify independent priors , the joint posterior loses its closed form. Yet its conditional distributions— and —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 with semiconjugate (conditionally conjugate) independent priors:
(6.1)Here is fixed directly by domain knowledge (for the midge wing lengths, and so that , placing 97.5% prior mass on positive lengths) rather than tied to . Why not approximate the resulting 2-D posterior on a discrete grid of points? In two dimensions ( grid points), a grid works—but in a -parameter model, a grid requires evaluations (for and , that is 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:
Mean given variance: holding fixed, Proposition 5.1 applies verbatim, giving
(6.2)Precision given mean: holding fixed, the likelihood is proportional to , so multiplying by the prior gives
(6.3)where
can be evaluated in time at every iteration without re-scanning the dataset!
6.2The Gibbs Sampler Algorithm#
Suppose our target joint posterior is and we can sample from every full conditional . 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 in the support of the posterior. For :
- Sample .
- Sample .
- Sample .
Return the Markov chain (typically discarding an initial warm-up/burn-in prefix).
For the two-block semiconjugate normal model (), 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).
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 , then a single conditional update replacing block by preserves the joint distribution: . Consequently, the full systematic scan in Algorithm 6.1 leaves invariant.
Proof. By definition of conditional probability, the joint density of the new state when the previous state was drawn from is
Since every single-block kernel preserves , their composition (the full systematic scan) also preserves . □
Remark 6.3 (Subtle caveats every practitioner should know).
- Invariance is not reversibility: Although each single-coordinate Gibbs step is reversible with respect to , a systematic scan of blocks is generally not reversible as a joint chain (though for , 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 .
- Positivity (irreducibility) is required: If the support of consists of disconnected islands (for instance, uniform on ), 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 from arbitrary starting points.
- 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, and on are both proper exponential densities, yet the only compatible joint density 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 , as :
- the marginal distribution of converges in total variation to , and
- ergodic averages converge almost surely: .
6.3.1Estimation vs. Approximation#
Hoff highlights a conceptual point that prevents endless confusion: increasing the number of MCMC draws improves numerical approximation, never statistical information. With midges, running Gibbs draws pins down the exact posterior mean to five decimals, but the posterior width still reflects only 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 and are positively correlated. Consider the cleanest analytical benchmark: a bivariate normal target with correlation . Alternating draws from and produces a Markov chain whose exact lag- autocorrelation is
(6.4)When , : 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 with and mixture weights —the joint Gibbs sampler alternating and becomes sticky: once is near , stays at component with probability , 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 and lag- autocorrelations , the asymptotic variance of the ergodic average 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
(6.5)The quantity is the **effective sample size (ESS)**: the number of independent posterior draws that would yield the same Monte Carlo standard error as our correlated MCMC draws. For the bivariate normal benchmark (6.4), summing the geometric series gives —so at , Gibbs draws are worth only about 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 for Assessing Convergence of MCMC. Bayesian Analysis, 16(2):667–718, 2021Vehtari et al. (2021) is beyond Hoff (2009): rank-normalized split-, its threshold, and separate bulk and tail effective sample sizes are not in Hoff’s book.
- Traceplots: inspect versus for drift (non-stationarity) or sticky plateaus.
- Multiple overdispersed chains & : launch chains from widely separated starting points; if they fail to overlap (as in a multimodal trap), the split- statistic stays above .
- Autocorrelation function (ACF) and : verify that lag- autocorrelations decay quickly to zero and that is large enough (typically ) for every target quantity and tail quantile of interest.
- 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 and be two copies of the chain in Algorithm 6.1 with the same initial law, lagging by one step, moved by a joint kernel under which each is marginally the Gibbs chain. Let be the meeting time, after which the chains stay equal. Then
(6.6)Why? Telescoping writes ; since has the law of , it may replace , and all terms with are zero. If the chain converges with uniformly bounded moments of of order slightly above two and has geometric tails, the interchange of sum and expectation is justified, and 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 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 by the closest factorized density in .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 gives the CAVI update
(6.7)because, as a function of , the objective is the KL divergence from to this density plus a constant. It is Gibbs with averaging in place of sampling: under (6.1), is normal and is gamma, as in (6.2) and (6.3) with replaced by and by .
For the bivariate normal benchmark behind (6.4), averaging over gives
(6.8)The means converge to the exact value , contracting by per sweep—precisely Gibbs’ lag-1 autocorrelation. But the variance is , the conditional variance, instead of the marginal value : at the reported standard deviation is , 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 that is easy to sample (here, a wide normal), set on , run one chain per , 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 and is rejected with probability , 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 shrinks to ,
(6.9)Why? A state keeps moving in one direction until a rejection reverses it. Crossing two barriers with success probabilities , with all back-and-forth reflections counted, succeeds with probability ; hence 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 . The global communication barrier depends on and , not on the schedule.
When to use it. Plain Gibbs suffices for unimodal posteriors. When exposes separated modes—or the -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})")// 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}]]`const qVar = await show`Simplify[-1/D[${eLog}, {x, 2}]]`const qMean = await show`x /. First[Solve[D[${eLog}, x] == 0, x]]`const sweep = await show`${qMean} /. mY -> rho*mX`await show`Simplify[D[${sweep}, mX] - Integrate[x*(rho^2*x)*Exp[-x^2/2]/Sqrt[2*Pi], {x, -Infinity, Infinity}]]`await show`N[{Sqrt[${qVar}], D[${sweep}, mX], 1/Sqrt[${qVar}]} /. rho -> 99/100]`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 , sums the integrated autocorrelation time to derive , verifies the sum-of-squares decomposition symbolically, and instantiates at .
// 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}`const alpha = await show`D[${transMean}, x]` // AR(1) lag-1 contraction coefficient = rho^2
await show`Simplify[(v + Integrate[(rho*Sqrt[v]*z)^2*Exp[-z^2/2]/Sqrt[2*Pi], {z, -Infinity, Infinity}]) /. v -> 1 - rho^2]`const tauInt = await show`Assuming[-1 < rho < 1, Together[Sum[2*(${alpha})^k, {k, 1, Infinity}] + 1]]`const essRatio = await show`Together[1 / ${tauInt}]`// 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)]`// Instantiate exact S_eff at rho = 99/100, S = 10,000
await show`N[10000 * (${essRatio} /. rho -> 99/100)]`6.7Exercises#
Exercise 6.4. Verify (6.4) by showing that for the bivariate normal target , the Gibbs update satisfies where is independent of . Deduce and .
Symbolic Solution & Instantiation
Simplify the lag- autocorrelation of the bivariate-normal Gibbs chain to .// Ex 6.1: Bivariate-normal Gibbs AR(1) recursion, lag-k ACF, and ESS
await show`Assuming[-1 < rho < 1, FullSimplify[(rho^2)^k]]`const essRatio = await show`Assuming[-1 < rho < 1, Together[1 / (1 + 2*Sum[rho^(2*k), {k, 1, Infinity}])]]`await show`{${essRatio}, N[${essRatio}]} /. rho -> 9/10`Exercise 6.5. Suppose you place the improper prior (flat on , not ) with normal observations. Write down the formal full conditionals and . Verify that both are proper distributions (), yet after integrating out the marginal density of has a tail and is not integrable as !
Symbolic Solution & Instantiation
Record the full-conditional exponent of under the flat prior .// 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]]`const margExp = await show`Assuming[n > 0, FullSimplify[-(n - 1)/2]]`await show`{${condExp}, ${margExp}} /. n -> 3`Exercise 6.6. Implement the trimodal mixture Gibbs sampler from Figure 6.1 in Python and run 4 chains from for iterations. Compute the empirical component frequencies and for . Why does direct ancestral sampling (, then ) have ?
Symbolic Solution & Instantiation
Express the mean residence time in mode as the reciprocal of the one-step escape probability .// 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`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}]`await show`N[{${esc}, ${meanRes} /. pEsc -> ${esc}}]`