Skip to content

Probabilistic inference, Monte Carlo, and posterior computation · Probabilistic computation and inference foundations · INF010 · Algorithm

Gibbs sampling

Samples a joint distribution by repeatedly sampling blocks from their full conditional distributions. It is central to conjugate latent-variable models, graphical models, and Bayesian mixtures;

Runs as a notebook Complete calculation CodeSplash's run and the reference's record

In CodeSplash

No method yet, but the reference's example runs here as a notebook.

Do it in CodeSplash Open the reference's example as a Python or R notebook.

Availability
Runs as a notebook
Code example
Complete calculation
Who ran it
CodeSplash's run and the reference's record
CodeSplash's run
The reference's example ran here in one language.
The reference's record
Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

Samples a joint distribution by repeatedly sampling blocks from their full conditional distributions. It is central to conjugate latent-variable models, graphical models, and Bayesian mixtures; blocked and collapsed forms improve the transition structure without defining new predictive architectures.

Question / hypotheses

Can tractable conditional distributions be composed into a chain exploring the desired joint posterior?

Architecture / computational structure

A systematic sweep uses newly updated coordinates immediately; random-scan Gibbs chooses blocks stochastically. Marginalizing variables before sampling gives a collapsed target, after which omitted quantities need their own conditional reconstruction. The example samples a correlated bivariate Gaussian with exactly known conditionals.

Assumptions

Full conditional distributions must correspond to a compatible joint target, be sampled correctly, and allow the chain to reach the relevant support. Deterministic constraints and highly correlated parameters can prevent or severely slow exploration. An approximate conditional update is not automatically exact Gibbs.

Formula / computational definition

zj(t+1)∼p(zj∣z1(t+1),…,zj−1(t+1),zj+1(t),…,zd(t),x).z_j^{(t+1)}\sim p(z_j\mid z_1^{(t+1)},\ldots,z_{j-1}^{(t+1)},z_{j+1}^{(t)},\ldots,z_d^{(t)},x).

Parameters and notation

Chain states represent posterior quantities; conditional-distribution parameters are recalculated from current values. Hyperparameters include block structure, scan order, collapsed variables, chain lengths, and initialization. Priors and likelihood parameters define the model separately. Block choices should respond to dependence and conditional sampling cost.

Fitting, fine-tuning, and adaptation

Ordinary Gibbs does not fine-tune network weights by gradient descent. Refit by starting chains under the changed posterior, preserving only valid initialization information. If using neural networks to approximate conditional proposals, add an appropriate correction or identify the procedure as approximate; learned proposals are not automatically full conditionals.

How to use and calibrate

Verify every conditional algebraically and compare moments against analytic special cases. Plot paired coordinate traces and joint scatter; monitor multiple-chain diagnostics and Monte Carlo error for functions that matter. Benchmark blocking strategies at matched compute, including factorization or latent-sum costs.

Example application

Sample component assignments and conjugate parameters in a Bayesian mixture, or infer hidden categorical states and transition probabilities where conditional updates are available.

Interpretation / pitfalls

Watch out

Acceptance is effectively one for exact conditionals, yet mixing can be arbitrarily slow. A mixture’s label switching can make parameter means misleading. Sampling all coordinates simultaneously from conditionals evaluated at the old state generally defines a different kernel and need not preserve the target.

Python and R code examples

Scope: Complete short systematic-scan Gibbs chain for a known correlated two-dimensional Gaussian; no model-specific mixture sampler.

Implementation route: NumPy normal draws and R rnorm are native. Real graphical models require derivation and testing of each conditional, or a probabilistic engine that implements those exact conditional updates.

Dependencies and validation: Python — executed successfully on the supplied synthetic inputs; imports identify NumPy/SciPy dependencies. R — base R, reviewed but not executed because Rscript is unavailable. Random-number streams differ between languages; matching seed integers do not imply matching draws.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Complete calculation — Complete short systematic-scan Gibbs chain for a known correlated two-dimensional Gaussian; no model-specific mixture sampler. · needs numpy

import numpy as np
rng=np.random.default_rng(7); rho=.8; sd=np.sqrt(1-rho*rho); z=np.zeros(2); out=[]
for _ in range(6000):
    z[0]=rng.normal(rho*z[1],sd)
    z[1]=rng.normal(rho*z[0],sd)
    out.append(z.copy())
d=np.array(out[1000:]); print('mean',d.mean(0)); print('covariance',np.cov(d,rowvar=False))
R

Complete calculation — Complete short systematic-scan Gibbs chain for a known correlated two-dimensional Gaussian; no model-specific mixture sampler.

set.seed(7); rho <- .8; sd.cond <- sqrt(1-rho*rho); z <- c(0,0); out <- matrix(0,6000,2)
for(i in 1:6000) {
  z[1] <- rnorm(1,rho*z[2],sd.cond)
  z[2] <- rnorm(1,rho*z[1],sd.cond)
  out[i,] <- z
}
d <- out[1001:6000,,drop=FALSE]; print(colMeans(d)); print(cov(d))

Sources

From the CodeSplash reference, entry INF010.