Gibbs sampling

Also known as: Gibbs sampler

On this page 7

Gibbs sampling is a Markov chain Monte Carlo (MCMC) algorithm that approximates a multivariate probability distribution by repeatedly drawing each variable from its full conditional distribution given the current values of all other variables. Among probabilistic models, it is one of the classic tools for Bayesian inference, used when the joint posterior is too complex to sample directly but every one-dimensional conditional is easy to sample.

The method is also called the Gibbs sampler. It became widely known in statistics around 1990 and remains central to topic models, hierarchical Bayesian models and image restoration. Its appeal is simplicity: there is no proposal distribution to tune and no rejection step, because every draw is accepted.

How the Gibbs sampler updates variables

The Gibbs sampler builds a Markov chain whose stationary distribution is the target joint distribution. Starting from an initial state, it cycles through the variables and replaces each one with a sample from its conditional distribution, holding every other variable fixed at its latest value.

  1. Choose initial values for all variables, for example from the prior or at random.
  2. For variable 1, sample a new value from p(x1 | x2, …, xn).
  3. For variable 2, sample from p(x2 | x1, x3, …, xn) using the updated x1.
  4. Continue through all variables; one full pass is a sweep.
  5. Repeat for thousands of sweeps, discard the early burn-in draws and keep the rest as approximate samples.

Each conditional update is a special case of the Metropolis-Hastings algorithm with an acceptance probability of exactly one. This is why the sampler never rejects a proposal. In graphical models the conditional of a variable depends only on its Markov blanket, so each update usually touches a small part of the model.

The table below lists the main components of a Gibbs sampling run and what each controls.

ComponentRoleTypical setting
Full conditionalsDistributions sampled at each stepDerived analytically from the model
Burn-inDraws discarded before convergenceHundreds to thousands of sweeps
Scan orderSequence of variable updatesSystematic or random
ThinningKeeping every k-th drawOften unnecessary; saves storage
Number of chainsIndependent runs for diagnosticsTypically 4 or more
Components of a Gibbs sampling run

Variants of Gibbs sampling

Several variants of Gibbs sampling address its weaknesses or adapt it to specific model structures. They differ in which variables are updated together and how the conditionals are obtained.

VariantIdeaWhen it helps
Systematic-scan GibbsUpdate variables in a fixed orderDefault choice for simple models
Random-scan GibbsPick a random variable each stepEasier convergence proofs
Blocked GibbsSample correlated variables jointlyStrong posterior correlations
Collapsed GibbsIntegrate out some parameters firstConjugate models such as LDA
Metropolis-within-GibbsUse a Metropolis step for hard conditionalsNon-conjugate conditionals
Slice-within-GibbsUse slice sampling per variableUnivariate densities known up to a constant
Common Gibbs sampling variants

Collapsed Gibbs sampling is especially important in practice. In latent Dirichlet allocation, integrating out the topic and word proportions leaves only the topic assignments to sample, which reduces variance and speeds mixing compared with sampling every parameter.

Gibbs sampling compared with other inference methods

Gibbs sampling is one of several approaches to approximate Bayesian inference, and the best choice depends on model structure. It excels when conjugate priors make conditionals available in closed form, while gradient-based samplers perform better on continuous, highly correlated posteriors.

MethodRequirementStrengthWeakness
Gibbs samplingSamplable full conditionalsNo tuning, handles discrete variablesSlow with strong correlations
Metropolis-HastingsUnnormalized densityVery generalNeeds a well-tuned proposal
Hamiltonian Monte CarloGradients of the log densityEfficient in high dimensionsCannot handle discrete variables directly
Variational inferenceTractable variational familyFast and scalableBiased, underestimates variance
Gibbs sampling and related inference methods

A common pattern in modern probabilistic programming is to combine methods: continuous parameters are updated with the No-U-Turn Sampler, while discrete latent variables are updated with Gibbs steps.

Convergence, mixing and diagnostics

Gibbs sampling converges to the target distribution under mild conditions, mainly that the chain is irreducible and aperiodic. Convergence in theory, however, says nothing about speed. Mixing describes how quickly the chain explores the distribution, and poor mixing is the main practical problem.

Mixing degrades when variables are strongly correlated in the posterior. Updating one coordinate at a time then produces tiny zigzag steps along a narrow ridge, and successive draws become highly autocorrelated. Practitioners judge the run with several diagnostics.

DiagnosticWhat it measuresWarning sign
Trace plotSampled values over iterationsTrends or long flat stretches
R-hat statisticAgreement between chainsValues above about 1.01
Effective sample sizeIndependent-equivalent drawsFar below the number of draws
AutocorrelationDependence between successive drawsSlow decay over many lags
Diagnostics for Gibbs sampling output

Remedies include blocking correlated variables, reparameterizing the model, collapsing parameters analytically and running longer chains. Thinning alone does not fix poor mixing; it only discards information.

Limitations and common mistakes

The sampler is easy to implement, which makes subtle errors easy to overlook. The following issues appear most often in practice.

  • Multimodal posteriors can trap the chain in one mode for the whole run, giving confident but wrong answers.
  • Label switching in mixture models makes per-component summaries meaningless unless it is handled explicitly.
  • An error in a derived conditional produces a chain that converges to the wrong distribution without any obvious warning.
  • Too short a burn-in biases estimates toward the initial values.
  • Running a single chain hides convergence problems that multiple chains would reveal.

In everyday language

Gibbs sampling is a way to explore a complicated puzzle one piece at a time. Imagine many dials that all affect each other. You cannot set them all at once. So you adjust one dial while holding the others still, then move to the next dial.

You repeat this many times. At first the settings are poor guesses. After enough rounds, the settings you record reflect how likely each combination really is. The key idea is simple: hard joint problems become many easy single steps.

Seen in the real world

A research team at a public library archive wants to find themes in 50,000 digitized newspaper articles without reading them all. The team fits a latent Dirichlet allocation model with 40 topics and uses collapsed Gibbs sampling to infer which topic generated each word.

Each sweep reassigns every word token to a topic based on the current topic counts in its article and across the collection. The team runs four chains of 2,000 sweeps, discards the first 500 as burn-in and checks that the log likelihood traces level off and agree across chains.

The output is a set of coherent topics such as agriculture prices, rail transport and local elections, together with topic proportions for every article. Archivists use these proportions to build a browsing index, and the whole inference finishes overnight on a single workstation.