Gibbs and Slice Sampling: Two Cures for Random-Walk MCMC

Gibbs sampling exploits conditionals; slice sampling adapts step size. Both cure random-walk Metropolis on correlated targets, with Python and animations.

Cover Image for Gibbs and Slice Sampling: Two Cures for Random-Walk MCMC

Your sampler keeps accepting proposals, but successive draws look so similar that the chain provides little new information. This can happen when plausible parameter combinations lie in a long, narrow region. Small random steps move safely across its width but explore its length slowly. Gibbs still needs cycles proportional to the squared length-scale ratio, with no step-size setting to tune away that slowdown.

Changing how proposals are chosen does not remove that geometric obstacle. At correlation 0.99, Gibbs needs roughly 100 cycles per independent sample. We build it alongside slice sampling and Metropolis on the same Gaussian, then compare how conditional draws and density-selected regions affect the chains.

Quick Win: Gibbs in Thirty Lines

Open In Colab

For a bivariate Gaussian N(0,Σ)\mathcal{N}(\mathbf{0}, \boldsymbol{\Sigma}) with Σ=(1ρρ1)\boldsymbol{\Sigma} = \begin{pmatrix} 1 & \rho \\ \rho & 1 \end{pmatrix}, the conditionals are themselves Gaussian:

p(z1∣z2)=N ⁣(ρz2, 1−ρ2),p(z2∣z1)=N ⁣(ρz1, 1−ρ2)p(z_1 \mid z_2) = \mathcal{N}\!\left(\rho z_2,\, 1 - \rho^2\right), \qquad p(z_2 \mid z_1) = \mathcal{N}\!\left(\rho z_1,\, 1 - \rho^2\right)

Gibbs sampling cycles between drawing from these two conditionals. The whole sampler fits in a few lines:

import numpy as np

def gibbs_bivariate_normal(n_cycles, rho, x0=None, rng=None):
    rng = rng or np.random.default_rng(42)
    sigma = np.sqrt(1 - rho**2)
    x = np.array([3.5, -3.5]) if x0 is None else np.asarray(x0, dtype=float).copy()
    trace = [x.copy()]
    for _ in range(n_cycles):
        x[0] = rho * x[1] + sigma * rng.standard_normal()  # z1 | z2
        trace.append(x.copy())
        x[1] = rho * x[0] + sigma * rng.standard_normal()  # z2 | z1
        trace.append(x.copy())
    return np.array(trace)

trace = gibbs_bivariate_normal(40, rho=0.95)

Run it on ρ=0.95\rho = 0.95 and the trajectory walks the long axis of the target one axis-aligned step at a time:

Animation of Gibbs sampling on a tilted bivariate Gaussian with rho=0.95. The chain starts at (3.5, -3.5) outside the contours and rapidly walks up the long axis of the ellipse via alternating horizontal and vertical right-angle steps. A counter shows which coordinate was just updated.

Compared to a step-size-tuned random-walk Metropolis sampler on the same target, the difference is visible at 200 steps. Gibbs has settled on the long axis; Metropolis is still making its way out of the corner:

Two-panel comparison of trajectory through the rho=0.95 bivariate Gaussian. Left panel: random-walk MH with 49 percent acceptance, jagged diagonal moves. Right panel: Gibbs sampling, characteristic right-angle staircase through the ellipse.

What Just Happened: Gibbs as Metropolis-Hastings With Always-Accept

Gibbs sampling is not a different algorithm. It is Metropolis-Hastings with a specific proposal that makes the acceptance probability identically one.

The construction

Pick one coordinate zkz_k. Hold the rest, z∖k\mathbf{z}_{\setminus k}, fixed. Propose a new value for zkz_k from the full conditional p(zk∣z∖k)p(z_k \mid \mathbf{z}_{\setminus k}). This is a valid Metropolis-Hastings proposal:

q(z∗∣z)=p(zk∗∣z∖k)q(\mathbf{z}^* \mid \mathbf{z}) = p(z_k^* \mid \mathbf{z}_{\setminus k})

Plug this into the Metropolis-Hastings acceptance ratio. Using the factorisation p(z)=p(zk∣z∖k) p(z∖k)p(\mathbf{z}) = p(z_k \mid \mathbf{z}_{\setminus k})\, p(\mathbf{z}_{\setminus k}) and noting that z∖k∗=z∖k\mathbf{z}^*_{\setminus k} = \mathbf{z}_{\setminus k}, the ratio is:

A(z∗,z)=p(z∗) q(z∣z∗)p(z) q(z∗∣z)=p(zk∗∣z∖k) p(z∖k) p(zk∣z∖k)p(zk∣z∖k) p(z∖k) p(zk∗∣z∖k)=1A(\mathbf{z}^*, \mathbf{z}) = \frac{p(\mathbf{z}^*)\, q(\mathbf{z} \mid \mathbf{z}^*)}{p(\mathbf{z})\, q(\mathbf{z}^* \mid \mathbf{z})} = \frac{p(z_k^* \mid \mathbf{z}_{\setminus k})\, p(\mathbf{z}_{\setminus k})\, p(z_k \mid \mathbf{z}_{\setminus k})}{p(z_k \mid \mathbf{z}_{\setminus k})\, p(\mathbf{z}_{\setminus k})\, p(z_k^* \mid \mathbf{z}_{\setminus k})} = 1

Every Gibbs proposal is accepted. The work shifts from acceptance bookkeeping to deriving the conditionals and sampling from them.

Why the conditionals are easy in graphical models

The full conditional p(zi∣z∖i)p(z_i \mid \mathbf{z}_{\setminus i}) looks intimidating in general, but for distributions with conditional-independence structure it simplifies dramatically. For a directed graphical model, p(zi∣z∖i)p(z_i \mid \mathbf{z}_{\setminus i}) depends only on ziz_i's Markov blanket: its parents, its children, and the co-parents of its children.

Diagram of a directed graphical model around a target node z_i. Two parent nodes feed into z_i, z_i feeds into two child nodes, and each child node also has another parent (a co-parent of z_i). All five neighbour nodes are coloured teal as the Markov blanket; z_i is amber.

For a Bayesian network on hundreds of nodes, the conditional reduces to a small product of factors over the local neighbourhood. This is why Gibbs sampling underpins JAGS, BUGS, and the Bayesian-network pipeline in the clinical decision support post.

The ergodicity caveat

Gibbs is exact only if the chain is ergodic, which requires that none of the conditionals are anywhere zero. A target with isolated regions of zero density (say, two posterior modes separated by a likelihood ridge of exact zero) cannot be visited end-to-end by a Gibbs sampler that makes one-coordinate moves. The chain gets stuck in the basin it starts in. In practice this means: check your conditionals are everywhere positive, or be prepared to switch to a sampler that moves in larger blocks.

Going Deeper: Why Correlation Hurts Gibbs

Gibbs is exact at every step. It is not always efficient. A bivariate-Gaussian analysis is the cleanest illustration. The conditional standard deviation ℓ=1−ρ2\ell = \sqrt{1 - \rho^2} controls the typical step size. The marginal length scale along the long axis is L=1+ρL = \sqrt{1 + \rho}. The number of cycles to obtain an independent sample scales as (L/ℓ)2∝1/(1−ρ)(L / \ell)^2 \propto 1 / (1 - \rho).

We can verify this numerically. As ρ\rho increases, the autocorrelation of z1z_1 over Gibbs cycles decays more slowly, and the empirical effective sample size collapses linearly with 1−ρ1 - \rho:

Two-panel figure. Left: autocorrelation of z_1 over Gibbs cycles for rho in {0, 0.5, 0.9, 0.95, 0.99}. The rho=0 curve drops to zero in one lag; rho=0.99 stays above 0.3 even at lag 60. Right: empirical ESS divided by number of cycles plotted against rho, with a dashed line showing the theoretical 1-rho curve. The empirical line tracks the theory closely down to ESS/n approaching zero at rho=0.99.

Two takeaways. First, the (L/ℓ)2(L/\ell)^2 scaling is real. At ρ=0.99\rho = 0.99 the sampler needs roughly 100 cycles per independent sample. Second, the scaling is independent of how cleverly you tune anything: there is no step size to choose.

Two patches: over-relaxation and blocking

There are two practical fixes. Over-relaxation (Adler 1981) replaces the Gibbs draw with a deterministic reflection biased toward the opposite side of the conditional mean:

zi′=μi+α(zi−μi)+σi1−α2 ν,α∈(−1,1), ν∼N(0,1)z_i' = \mu_i + \alpha (z_i - \mu_i) + \sigma_i \sqrt{1 - \alpha^2}\, \nu, \qquad \alpha \in (-1, 1),\, \nu \sim \mathcal{N}(0, 1)

For α<0\alpha < 0, the new value is on the opposite side of μi\mu_i from the old one, so the chain is encouraged to traverse the distribution rather than diffuse around the mean. The marginals are unchanged.

Blocking Gibbs (Jensen et al. 1995) updates groups of variables jointly, sampling from p(zB∣z∖B)p(\mathbf{z}_B \mid \mathbf{z}_{\setminus B}) rather than one coordinate at a time. When the variables in block BB are strongly correlated with each other but only weakly with the rest, blocking removes the worst within-block correlations. The cost is that you need a tractable joint conditional for the block, which often means the block has to have conjugate structure.

When Gibbs cannot help: HMC's domain

Both fixes leave the basic geometry intact. For a multivariate Gaussian with a correlation length LL orders of magnitude larger than ℓ\ell, even blocked Gibbs walks the long axis. The way out is to abandon coordinate updates entirely. Hamiltonian Monte Carlo (Neal 2011) introduces auxiliary momentum variables and uses gradient information to take long, almost-independent steps. HMC is what underpins NUTS in PyMC, Stan, and the approximate inference comparison post. It deserves its own post; the decision in this post is between MH, Gibbs, and slice.

Slice Sampling: Adaptive Step Size by Construction

Slice sampling (Neal 2003) takes a different approach to fixing random walk. Instead of choosing a step size, it lets the target's local shape choose for you.

The auxiliary-variable trick

Augment zz with a uniform variable uu:

p^(z,u)={1/Zpif 0≤u≤p~(z)0otherwise\widehat{p}(z, u) = \begin{cases} 1 / Z_p & \text{if } 0 \leq u \leq \widetilde{p}(z) \\ 0 & \text{otherwise} \end{cases}

The marginal over zz is p(z)=p~(z)/Zpp(z) = \widetilde{p}(z) / Z_p, the original target. So sampling uniformly from the area under the unnormalised density p~\widetilde{p} and discarding uu gives a draw from pp. Slice sampling alternates between two updates:

  1. Given current z(τ)z^{(\tau)}, draw u∼Uniform(0,p~(z(τ)))u \sim \mathrm{Uniform}(0, \widetilde{p}(z^{(\tau)})). This sets a horizontal "slice" through the density.
  2. Given uu, draw a new z(τ+1)z^{(\tau+1)} uniformly from the slice {z:p~(z)>u}\{z : \widetilde{p}(z) > u\}.

The first step is trivial: p~(z(τ))\widetilde{p}(z^{(\tau)}) is a number, draw uniform below it. The second is the algorithm's hard part. The slice is generally a union of intervals (for multimodal targets, the slice may include disconnected segments) and there is no closed-form way to sample from it.

Stepping out and shrinking

Neal (2003) gives a rejection-style procedure. Place an interval of width ww around z(τ)z^{(\tau)}, step out by extending each end by ww until the endpoints are outside the slice, then shrink by drawing candidates uniformly inside the bracket and contracting the bracket toward z(τ)z^{(\tau)} whenever a candidate lands outside the slice. The first candidate inside the slice is the new sample.

def slice_sampler_1d(p_unnorm, x0, n_steps, w=2.0, rng=None):
    rng = rng or np.random.default_rng(42)
    x = float(x0)
    trace = [x]
    for _ in range(n_steps):
        u = rng.uniform(0, p_unnorm(x))                  # draw the slice level
        L = x - w * rng.uniform()                        # initial bracket
        R = L + w
        while p_unnorm(L) > u: L -= w                    # step-out left
        while p_unnorm(R) > u: R += w                    # step-out right
        while True:                                      # shrink + accept
            z_new = rng.uniform(L, R)
            if p_unnorm(z_new) > u:
                x = z_new
                break
            (L, R) = (z_new, R) if z_new < x else (L, z_new)
        trace.append(x)
    return np.array(trace)

The whole loop is six lines of essentials. Watch one step on a bimodal target. The slice level uu (teal dashed) carves a horizontal line; the bracket steps out (purple), candidates (red ×) get rejected and the bracket shrinks; the accepted point (green) lands in the slice:

Animation of one slice sampler step on a bimodal target. The teal horizontal dashed line is the slice level u drawn at sub-step 1. Purple vertical lines mark the stepping-out bracket at sub-step 2. Rejected candidates accumulate as red x marks at sub-step 3, and the green circle is the accepted z. At sub-step 4, the chain commits the new state at the baseline.

Run for 4,000 steps and the histogram recovers both modes cleanly:

Histogram of 3,800 slice samples from a bimodal target with modes at z=-2 and z=2, both with width 0.7. The teal histogram closely matches the amber target density curve.

The crucial property is that the slice width adapts. When the chain is in a region where p~\widetilde{p} is broad and flat, the slice is wide and the bracket steps out a long way: large moves at low cost. When p~\widetilde{p} is sharply peaked, the slice is narrow and the bracket stays small. There is no step-size hyperparameter to tune. The width ww controls only the initial bracket and amortises across step-out iterations; setting it to roughly the target's typical scale is enough.

Multivariate slice sampling

Slice sampling extends to multivariate targets componentwise: update one coordinate at a time using the univariate slice sampler on the conditional p(zi∣z∖i)p(z_i \mid \mathbf{z}_{\setminus i}). This is the slice analogue of Gibbs and inherits Gibbs's correlation problem. Genuinely multivariate slice samplers exist (elliptical slice sampling for Gaussian priors, Murray et al. 2010).

Three Methods on a Shared Problem

Pick the bivariate Gaussian with ρ∈{0,0.5,0.9,0.99}\rho \in \{0, 0.5, 0.9, 0.99\} and run all three samplers for matched effort. The story holds:

Two-panel comparison. Left: ESS per sampler step at four correlation levels. Gibbs and Slice both retain near-perfect ESS at rho=0 (around 0.95-0.98) but collapse to near zero at rho=0.99. MH is consistently worse but degrades more gradually. Right: ESS per wall-clock second on a log scale. Gibbs is roughly 30 times faster than slice across all correlations because each conditional draw is a single Gaussian. MH is in between.

Two practical lessons emerge:

  1. Per-step quality: Gibbs and slice both produce roughly i.i.d. samples at low correlation; MH produces correlated samples even with optimal step-size tuning. At high correlation (ρ=0.99\rho = 0.99) all three componentwise samplers collapse, which is the regime where HMC matters.
  2. Wall-clock: Gibbs wins by an order of magnitude when the conditionals are tractable, because each draw is a single Gaussian sample. Slice pays for stepping-out and shrinking even when ww is well-chosen. MH is fast per step but produces fewer effective samples per step.

The decision rule is short:

UseWhen
Random-walk MHConditionals not tractable, target unimodal, dimension small. Always tune step size to roughly the proposal-acceptance sweet spot (~25% in high D, ~50% in 1D)
Gibbs samplingConditionals are tractable (typically: graphical models, conjugate hierarchical models, Bayesian networks). Default first choice
Slice samplingConditionals are evaluable but not tractable; you don't want to tune a step size; targets may be multimodal in low D
Blocking GibbsConditionals tractable, but variables form correlated groups
HMC / NUTSContinuous, differentiable target with strong correlations; problem is otherwise intractable to coordinate samplers

Foundations

Gibbs sampling traces to Geman and Geman (1984), an image-restoration paper that gave the algorithm its name (after Josiah Willard Gibbs's work in statistical physics, since the joint distribution being sampled is analogous to a Gibbs distribution). As shown above, it is a special case of Metropolis-Hastings in which every proposal is accepted.

The bivariate-Gaussian mixing analysis is one of the few cases in MCMC where you can write the mixing time in closed form: the number of steps needed to obtain an independent sample is of order (L/ℓ)2(L/\ell)^2. This is the result we verified empirically above. The over-relaxation and blocking-Gibbs extensions are due to Adler (1981) and Jensen, Kong & Kjærulff (1995) respectively.

Slice sampling is Radford Neal's contribution: Slice Sampling (Annals of Statistics, 2003). It provides an adaptive step size that is automatically adjusted to match the characteristics of the distribution. The auxiliary-variable construction, the stepping-out scheme, and the shrinking-region rejection all appear in Neal's paper with full derivations and convergence proofs.

For practical implementations, the PyMC documentation on slice sampling is a useful reference, and the wider Markov-chain Monte Carlo literature is covered comprehensively in Brooks, Gelman, Jones, and Meng's Handbook of Markov Chain Monte Carlo (2011), which is the modern successor to Gilks et al. (1996).

Limitations and Pitfalls

The trade-offs to keep in mind when choosing between these samplers:

  • Gibbs assumes tractable conditionals. If p(zi∣z∖i)p(z_i \mid \mathbf{z}_{\setminus i}) is not in a sampleable family, Gibbs degenerates to plain Metropolis-Hastings inside each conditional update (Metropolis-within-Gibbs), which loses the always-accept property and reintroduces step-size tuning.
  • Both Gibbs and componentwise slice are random-walk in disguise. They escape the random-walk problem of MH by replacing it with a different problem (correlation-driven slow mixing). For correlated targets the only fundamental escape is HMC or another method that uses gradient information.
  • Slice's ww parameter still matters in practice. The theory says any w>0w > 0 produces a valid sampler, but a ww that is much smaller than the target's scale leads to many step-out iterations per sample. A ww much larger than the target's scale leads to many shrink iterations. A factor-of-two error in ww is fine; orders of magnitude slows the sampler considerably.
  • Ergodicity requires positive conditionals. Both Gibbs and slice can fail on targets with isolated zero-density regions. Most real Bayesian posteriors satisfy ergodicity; carefully constructed adversarial examples (mixtures with vanishing component overlap) do not.
  • None of these solve the multimodal problem in high dimensions. Slice handles 1D bimodal targets cleanly because the slice can include disconnected intervals. In D>1D > 1 the chain still has to walk between modes via low-density regions. Tempering and parallel chain methods are the standard cures.

The natural sequels here are HMC for the correlation/gradient escape, and reversible-jump or replica-exchange MCMC for transdimensional and multimodal targets. The sampling-methods post covers what to do when MCMC is overkill for the problem.

Interactive Tools

  • Markov Chain Simulator: visualise the kind of Markov chain that underpins MCMC samplers, with stationary distributions and mixing times.
  • Distribution Explorer: sample from the conditional distributions Gibbs uses, and visualise the slice levels through any 1D density.
  • Bayes' Theorem Calculator: the prior-likelihood-posterior arithmetic that Gibbs and slice are sampling from.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions