Core ML1984intermediate11 min read

Stochastic Relaxation, Gibbs Distributions, and the Bayesian Restoration of Images

الاسترخاء العشوائي وتوزيعات غيبس والاستعادة البايزية للصور

Geman, S. · Geman, D. — IEEE Transactions on Pattern Analysis and Machine Intelligence

The problem

Real images are corrupted by , blur, and distortion. Restoring them is an ill-posed inverse problem: many possible clean images could have produced the same noisy observation. Traditional methods either used hand-crafted filters with no principled way to incorporate knowledge about natural images, or formulated problems that got stuck in poor local optima because the solution space is astronomically large.

The contribution

A three-part framework that unified statistical physics with Bayesian image analysis. First, the paper showed that Markov random fields — models where each pixel depends only on its neighbors — are mathematically equivalent to Gibbs distributions from statistical mechanics. Second, it introduced the Gibbs sampler: update one variable at a time by from its conditional given all neighbors, generating a that converges to the desired distribution. Third, it combined Gibbs sampling with simulated annealing — gradually lowering a temperature parameter — to find the maximum a posteriori (MAP) estimate, escaping local optima that trap deterministic methods.

The impact

This paper founded the modern MCMC revolution. The Gibbs sampler became the workhorse of Bayesian computation across statistics, physics, genetics, NLP, and machine learning. It enabled Bayesian methods in problems with thousands or millions of variables — from topic models (LDA) to protein structure prediction. The MRF-Gibbs equivalence became a cornerstone of probabilistic graphical models.

Imagine a jigsaw puzzle where half the pieces are missing. You can't solve it in one shot, but you can make progress one piece at a time: pick an empty slot, look at the surrounding pieces, and try a random piece that fits the local pattern. If it clashes, swap it. Keep cycling through every slot, and the picture emerges.

Early on you're adventurous — you try wild colors just to explore. As confidence builds, you become pickier, only accepting pieces that match almost perfectly. That gradual shift from to precision is simulated annealing, and the one-slot-at-a-time strategy is the Gibbs sampler.

The problem: restoring images from noisy observations

A camera captures a scene, but noise corrupts every pixel. The observed image yy is a degraded version of the true image xx: perhaps y=x+noisey = x + \text{noise}, or something more complex involving blur and nonlinear distortion. The restoration problem asks: given yy, what was xx?

This is an inverse problem, and it is ill-posed — many plausible xx's could produce the same yy. To pick the best one, we need two ingredients from :

  • A prior P(x)P(x) — what do clean images generally look like? (Neighboring pixels tend to be similar; edges are sparse.)

  • A P(y∣x)P(y|x) — given a clean image xx, how probable is the observed noisy image yy?

Bayes' theorem combines them into the posterior P(x∣y)∝P(y∣x) P(x)P(x|y) \propto P(y|x) \, P(x). The best restoration is the xx that maximizes this posterior — the MAP estimate.

P(x∣y)∝P(y∣x) P(x)P(x|y) \propto P(y|x) \, P(x)
Bayes' theorem for image restoration — posterior ∝ likelihood × prior — the restored image balances fidelity to observations (likelihood) with prior knowledge about natural images (prior)

The challenge: with a 256×256 image and 256 gray levels, the space of possible images has 25665536256^{65536} states. No can examine them all. We need a way to explore this space efficiently, guided by the posterior. That's where Gibbs distributions and the Gibbs sampler enter.

Open in Lab
Add noise to a clean image, then watch Gibbs sampling gradually restore it.
The demo wakes as you arrive…

The bridge: Markov random fields equal Gibbs distributions

The paper's first key insight is a deep connection between two seemingly different worlds.

On one side: Markov random fields (MRFs) — a way to images where each pixel's value depends only on its immediate neighbors, not on distant pixels. This is a natural model for images: whether a pixel is bright or dark depends mostly on the pixels right around it.

On the other side: Gibbs distributions from statistical physics — distributions over configurations of a system, defined through an . In physics, atoms in a crystal arrange themselves to minimize energy. Low-energy configurations (orderly crystal lattices) are exponentially more probable than high-energy ones (disordered states).

The Hammersley-Clifford theorem establishes that these are the same thing: every MRF is a , and vice versa. This means we can design image models by writing down an energy function — a much more intuitive task than specifying conditional probabilities for every pixel.

P(x)=1Zexp⁡ ⁣(−U(x)T)P(x) = \frac{1}{Z} \exp\!\Bigl(-\frac{U(x)}{T}\Bigr)
Gibbs distribution — U(x) = total energy of configuration x · T = temperature · Z = normalizing constant (partition function). Low energy → high probability. As T→0, all probability concentrates on the lowest-energy (most probable) state.

Think of it as a landscape: the energy function defines hills and valleys over the space of all possible images. Each valley is a plausible image. The Gibbs distribution tells you how probable each point in this landscape is — the deeper the valley, the more probable the configuration. Temperature controls how sharply probability concentrates in the valleys: at high temperature the system explores everywhere; at low temperature it settles into the deepest valleys.

Open in Lab
Toggle the temperature and watch probability concentrate in low-energy states.
The demo wakes as you arrive…

Building the energy function: cliques and neighborhoods

The energy U(x)U(x) is built by summing small, local contributions called clique potentials. A clique is a group of pixels that are all neighbors of each other — in the simplest case, a pair of adjacent pixels.

For image restoration, the energy has two parts:

  • Prior energy — penalizes configurations that don't look like natural images. A simple choice: ∑neighbors i,j(xi−xj)2\sum_{\text{neighbors } i,j} (x_i - x_j)^2. This penalizes large differences between neighbors, encouraging smooth regions. More sophisticated priors add edge-preserving terms that allow sharp boundaries.

  • Data energy — penalizes configurations that disagree with the observed noisy image. Typically: ∑i(yi−xi)2\sum_i (y_i - x_i)^2 for additive Gaussian noise.

The total energy U(x)=Prior energy+λ⋅Data energyU(x) = \text{Prior energy} + \lambda \cdot \text{Data energy} balances smoothness against fidelity. The parameter λ\lambda controls the tradeoff: large λ\lambda trusts the data more; small λ\lambda trusts the prior more.

U(x)=∑⟨i,j⟩Vc(xi,xj)⏟prior+λ∑i(yi−xi)2⏟dataU(x) = \underbrace{\sum_{\langle i,j \rangle} V_c(x_i, x_j)}_{\text{prior}} + \lambda \underbrace{\sum_i (y_i - x_i)^2}_{\text{data}}
Total energy for image restoration — V_c = clique potential penalizing neighbor differences · (yᵢ − xᵢ)² = pixel-wise data fit · λ = balance parameter. Minimizing U(x) finds the MAP estimate.
Open in Lab
Click on a pixel to see how its energy is computed from its neighbors and the noisy observation.
The demo wakes as you arrive…

The Gibbs sampler: updating one variable at a time

The Gibbs sampler is elegantly simple. To sample from a complicated joint distribution P(x1,x2,…,xn)P(x_1, x_2, \ldots, x_n), you don't need to know the whole distribution at once. You just need to know how to sample each variable conditioned on all the others.

The algorithm cycles through all pixels. For each pixel xix_i:

  • Fix every other pixel at its current value.

  • Compute the conditional distribution P(xi∣xneighbors)P(x_i \mid x_{\text{neighbors}}) — this depends only on the neighbors because of the Markov property.

  • Draw a new value for xix_i from this conditional distribution.

After visiting every pixel once (a sweep), you've completed one iteration. The key theorem: as the number of sweeps grows, the distribution of the entire configuration converges to the target joint distribution P(x)P(x). Each sweep brings the image closer to a sample from the posterior.

Open in Lab
Step through the Gibbs sampler on a small grid. Watch each pixel update based on its neighbors.
The demo wakes as you arrive…

Simulated annealing: from sampling to optimization

Gibbs sampling at a fixed temperature generates samples from the posterior — useful for computing averages and uncertainties. But for image restoration, Geman & Geman wanted the single best image: the MAP estimate. This is an optimization problem.

Here's the trick from physics: simulated annealing. At high temperature, the Gibbs distribution is nearly uniform — the sampler explores freely. As temperature decreases, probability concentrates on lower-energy states. At T→0T \to 0, all probability sits on the .

The annealing schedule must cool slowly enough. Geman & Geman proved that if the temperature decreases as T(t)=c/log⁡(1+t)T(t) = c / \log(1 + t) where cc is large enough, the algorithm converges to the global optimum with probability 1. This was the first rigorous guarantee for simulated annealing on a general problem.

T(t)=clog⁡(1+t)T(t) = \frac{c}{\log(1 + t)}
Logarithmic annealing schedule — t = iteration number · c = constant related to the energy landscape depth · cooling must be this slow (logarithmic) to guarantee finding the global optimum

In practice, the logarithmic schedule is too slow. Practitioners use faster cooling (exponential or linear) and accept approximate solutions — which are usually excellent. The theoretical guarantee matters because it showed that stochastic methods can solve global optimization in combinatorial spaces, a result that influenced optimization across all of computer science.

Open in Lab
Watch temperature decrease and the sampler gradually lock onto low-energy configurations.
The demo wakes as you arrive…

Gibbs sampling vs Metropolis-Hastings

The Gibbs sampler is a special case of the Metropolis-Hastings algorithm. Both are MCMC methods that build a Markov chain whose stationary distribution is the target. The difference lies in how they propose updates:

  • Metropolis-Hastings proposes a random change and accepts or rejects it based on an acceptance ratio. Rejections waste computation — the chain stays put.

  • Gibbs sampling proposes from the exact conditional distribution, so every proposal is accepted. No wasted steps, no tuning of proposal distributions.

The tradeoff: Gibbs sampling requires being able to compute and sample from each conditional P(xi∣x−i)P(x_i \mid x_{-i}) — easy for MRFs (thanks to the Markov property) but hard for models without conditional conjugacy. Metropolis-Hastings works for any model as long as you can evaluate the density ratio.

Open in Lab
Compare Gibbs and Metropolis-Hastings sampling side by side on the same 2D distribution.
The demo wakes as you arrive…

The Gibbs sampler in code

Gibbs sampler for binary image denoisingpython

Simplified to show the idea — not the real implementation.

import numpy as np

def gibbs_denoise(noisy, beta=1.5, lam=1.0, T_init=2.0, n_sweeps=50):
    """Denoise a binary image (+1/-1) using Gibbs sampling + annealing."""
    H, W = noisy.shape
    x = noisy.copy()                 # initialize with noisy image

    for sweep in range(n_sweeps):
        T = T_init / np.log(2 + sweep)     # logarithmic cooling

        for i in range(H):
            for j in range(W):
                # Sum of neighbor values (4-connected)
                neighbors = 0
                if i > 0:     neighbors += x[i-1, j]
                if i < H-1:   neighbors += x[i+1, j]
                if j > 0:     neighbors += x[i, j-1]
                if j < W-1:   neighbors += x[i, j+1]

                # Energy difference between x_ij = +1 and x_ij = -1
                # Prior: -beta * x_i * sum(neighbors)
                # Data:  -lambda * x_i * y_i
                delta_E = 2 * (beta * neighbors + lam * noisy[i, j])

                # Conditional probability of x_ij = +1
                p_plus = 1 / (1 + np.exp(-delta_E / T))
                x[i, j] = +1 if np.random.rand() < p_plus else -1

    return x
# Each pixel is updated by looking ONLY at its neighbors + noisy observation.
# Temperature starts high (explores) and drops (sharpens). That's all of it.

Convergence: why does it work?

Two convergence results underpin the paper:

Ergodicity of the Gibbs sampler. At any fixed temperature T>0T > 0, the Markov chain generated by Gibbs sampling is ergodic — it can reach any configuration from any other. This means it has a unique stationary distribution, and that distribution is exactly the Gibbs distribution. After enough sweeps, the samples are faithful representatives of the posterior.

Annealing convergence. If the temperature decreases slowly enough — specifically, T(t)≥c/log⁡(1+t)T(t) \geq c / \log(1+t) for a constant cc related to the energy barrier height — then the probability of being in a global minimum converges to 1. The sampler doesn't just explore: with annealing, it optimizes.

Together, these results mean: Gibbs sampling gives you correct samples (for Bayesian inference), and Gibbs sampling with annealing gives you the global optimum (for MAP estimation).

Impact: the MCMC revolution

  1. 1953

    Metropolis algorithm

    Metropolis et al. introduce the first MCMC algorithm for simulating physical systems. General-purpose but requiring a proposal distribution and accept/reject steps.

  2. 1970

    Hastings generalization

    Hastings extends the Metropolis algorithm to asymmetric proposals, creating the Metropolis-Hastings framework used across statistics.

  3. 1984

    Geman & Geman — this paper

    Introduce the Gibbs sampler, prove MRF-Gibbs equivalence, combine with simulated annealing for MAP estimation. Launch MCMC into mainstream applied statistics and machine learning.

  4. 1990

    Gelfand & Smith

    Demonstrate that Gibbs sampling applies far beyond images — to hierarchical Bayesian models across statistics. Ignite the MCMC revolution in mainstream statistics.

  5. 1993

    BUGS software

    BUGS (Bayesian inference Using Gibbs Sampling) makes MCMC accessible to non-specialists — social scientists, epidemiologists, ecologists all adopt Bayesian methods.

  6. 2003

    Latent Dirichlet Allocation (LDA)

    Blei, Ng, and Jordan use Gibbs sampling for topic modeling in text — every document is a mixture of topics, each topic a distribution over words. Gibbs sampling makes inference tractable.

  7. 2011

    Stan & probabilistic programming

    Stan and other probabilistic programming languages build on MCMC foundations, making Bayesian inference available as a general-purpose tool for any model.

The paper's legacy extends far beyond image restoration. The Gibbs sampler became the computational engine behind Bayesian inference in thousands of applications. Every time a researcher fits a hierarchical model, runs a topic model, or does Bayesian structure learning, they are building on the foundations that Geman & Geman laid in 1984.

CitationGeman, S., Geman, D.. Stochastic Relaxation, Gibbs Distributions, and the Bayesian Restoration of Images. IEEE Transactions on Pattern Analysis and Machine Intelligence, 1984.

Terms in this paper