Algorithm Search⌘K

Algorithmintro

Iterated conditional modes

Also called ICM.

Minimize an MRF energy by setting each variable in turn to its best label given its neighbors, until nothing changes. Fast, but it stops at a local minimum that depends on the order.

Time
O(k L (n + m)) worst · averageO(L (n + m)) best
Space
O(n + m) extra
Where
L = the number of labels; k = the number of sweeps; m = the number of neighbor pairs; n = the number of sites
Properties
deterministicnot exactofflineiterative
Origin
Julian Besag, 1986

Iterated conditional modes (ICM) is the simplest method to minimize the energy of a Markov random field, that is, to find an approximate MAP labeling. It visits the sites one at a time and gives each site the label of least cost given the current labels of its neighbors, which is the mode of the conditional distribution of that site. It repeats such sweeps until no site changes. Each change lowers the energy, so the method stops, at a labeling that no change of one site can improve. It is coordinate descent on a discrete problem and the zero temperature limit of Gibbs sampling. ICM is fast and needs no condition on the pairwise term, but the local minimum it finds depends on the start and the visiting order, and on vision energies it is usually far worse than alpha-expansion or loopy belief propagation.

In plain words

Each pixel has a label, and it pays for a label that does not fit its data and for every neighbor that has a different label. Go over the pixels one by one. For each pixel, look at its neighbors as they are now, and give it the label that costs least. If no label is cheaper than the one it has, leave it. Go over the image again and again until a full pass changes nothing. The total cost goes down at every change, so the process always ends. But it can get stuck: sometimes two pixels would both have to change at once to make things better, and a pass that changes one pixel at a time never sees that.

The problem

Input. Sites with neighbor pairs N\mathcal{N} and weights wpqw_{pq}, LL labels, data costs Dp(ℓ)D_p(\ell), a pairwise table VV, a start labeling ff and an order of the sites.

Output. A labeling ff that is a local minimum of

E(f)=∑pDp(fp)+∑(p,q)∈Nwpq V(fp,fq)E(f) = \sum_p D_p(f_p) + \sum_{(p,q) \in \mathcal{N}} w_{pq}\, V(f_p, f_q)

for changes of one site: for every site pp and label ℓ\ell, the labeling with fpf_p replaced by ℓ\ell has energy at least E(f)E(f). VV need not be symmetric, a metric or submodular.

The algorithm

  1. ICM(D, V, N, f, order)
  2. 1repeat
  3. 2changed ← false
  4. 3for each site p in the fixed order do
  5. 4for each label ℓ: c(ℓ) ← D_p(ℓ) + Σ over the neighbors q of p of w_pq V(ℓ, f_q)
  6. 5ℓ* ← the least label with the least c(ℓ*)
  7. 6if c(ℓ*) < c(f_p) then f_p ← ℓ*; changed ← true
  8. 7until changed = false
  9. 8return f

Line L4 uses the labels of the neighbors as they are at that moment, so a site already sees the changes made earlier in the same sweep. Line L6 changes a site only on a strict improvement, which keeps the energy falling and avoids cycling between labels of equal cost. With an asymmetric VV the code uses V(ℓ,fq)V(\ell, f_q) or V(fq,ℓ)V(f_q, \ell) according to the order of the pair.

Example

Restore a noisy binary row y=(0,1,0,0,1,1,0,1,1,1)y = (0, 1, 0, 0, 1, 1, 0, 1, 1, 1) with Dp(ℓ)=2[ℓ≠yp]D_p(\ell) = 2 [\ell \ne y_p] and the Ising or Potts term V(a,b)=3[a≠b]V(a, b) = 3 [a \ne b] on neighbors. Start from f=yf = y, with E=5⋅3=15E = 5 \cdot 3 = 15 for the five changes along the row.

site neighbors c(0)c(0) c(1)c(1) action
0 f1=1f_1 = 1 3 2 change to 1
1 f0=1f_0 = 1, f2=0f_2 = 0 5 3 keep 1
2 to 5 keep
6 f5=1f_5 = 1, f7=1f_7 = 1 6 2 change to 1
7 to 9 keep

After the first sweep f=(1,1,0,0,1,1,1,1,1,1)f = (1, 1, 0, 0, 1, 1, 1, 1, 1, 1) with E=2+2+2⋅3=10E = 2 + 2 + 2 \cdot 3 = 10, and the second sweep changes nothing. The optimum is (0,0,0,0,1,1,1,1,1,1)(0, 0, 0, 0, 1, 1, 1, 1, 1, 1) with E=7E = 7. To reach it from the result, sites 0 and 1 must both change to 0. Changing site 0 alone costs c(0)−c(1)=1c(0) - c(1) = 1, and changing site 1 alone costs 2, so ICM is stuck. Visiting the sites in the reverse order, site 1 is visited while site 0 is still 0, it changes to 0, and ICM reaches the optimum E=7E = 7.

Correctness

The full proof is in proofs/correctness.md. The key fact is that c(ℓ)−c(fp)c(\ell) - c(f_p) equals the change of the total energy when site pp alone takes label ℓ\ell, because all terms that do not touch pp cancel. So each change of line L6 lowers EE strictly. A labeling cannot repeat, there are finitely many labelings, and so the loop stops. In the last sweep nothing changed, so every site was checked against the final labeling and no single change lowers EE.

Proof: Correctness of iterated conditional modesfull

The energy is E(f)=∑pDp(fp)+∑(p,q)∈NwpqV(fp,fq)E(f) = \sum_p D_p(f_p) + \sum_{(p,q) \in \mathcal{N}} w_{pq} V(f_p, f_q) with real costs; VV is any table. We prove that ICM never raises the energy, that it stops after finitely many sweeps, and that the output is a local minimum for changes of one site: no labeling that differs from it at one site has smaller energy.

Lemma (local costs)

Fix ff and a site pp. For a label ℓ\ell let fp→ℓf^{p \to \ell} be ff with fpf_p replaced by ℓ\ell, and let

c(ℓ)=Dp(ℓ)+∑(p,q)∈NwpqV(ℓ,fq)+∑(q,p)∈NwqpV(fq,ℓ),c(\ell) = D_p(\ell) + \sum_{(p,q) \in \mathcal{N}} w_{pq} V(\ell, f_q) + \sum_{(q,p) \in \mathcal{N}} w_{qp} V(f_q, \ell),

the cost of line L4. Then E(fp→ℓ)−E(f)=c(ℓ)−c(fp)E(f^{p \to \ell}) - E(f) = c(\ell) - c(f_p).

Proof. fp→ℓf^{p \to \ell} and ff differ only at pp. The terms of EE that do not contain pp are equal in both and cancel. The terms that contain pp are the data term of pp and the pair terms of pp, and their sum is c(ℓ)c(\ell) for fp→ℓf^{p \to \ell} and c(fp)c(f_p) for ff. □\square

The energy does not rise

Line L6 changes fpf_p only if c(ℓ)<c(fp)c(\ell) < c(f_p). By the lemma, the energy then drops by c(fp)−c(ℓ)>0c(f_p) - c(\ell) > 0. All other steps leave ff unchanged. So the energy after each step is at most the energy before it, and it drops strictly at each change.

Termination

There are LnL^n labelings. The energy drops strictly at each change, so no labeling occurs twice, and there are at most Ln−1L^n - 1 changes. Each sweep that does not stop at line L7 makes at least one change, so there are at most LnL^n sweeps. With integer costs each change lowers the energy by at least 1, so the number of changes is also at most E(f0)−min⁡EE(f_0) - \min E.

Local minimality

The loop stops after a sweep with no change. During that sweep ff stayed the same, so for every site pp line L6 found c(ℓ)≥c(fp)c(\ell) \ge c(f_p) for the least c(ℓ)c(\ell), and therefore for every label ℓ\ell. By the lemma, E(fp→ℓ)≥E(f)E(f^{p \to \ell}) \ge E(f) for every site pp and label ℓ\ell. □\square

What is not claimed

The output need not be a global minimum, and it depends on the start and on the order of the sites; the worked example on the page has two orders with energies 10 and 7. The proof uses that sites are updated one at a time. If all sites are updated at once from the old labeling, the lemma no longer applies to the joint change, and the energy can rise or cycle.

Complexity

The model is the real RAM.

  • One sweep. Line L4 costs O(L(1+deg⁡p))O(L(1 + \deg p)) for site pp, so a sweep costs O(L(n+m))O(L(n + m)).
  • Number of sweeps. With integer costs, each sweep except the last lowers the energy by at least 1, so k≤E(f0)−min⁡E+1k \le E(f_0) - \min E + 1. In general only k≤Lnk \le L^n is known. On image energies a few sweeps usually suffice; this is an observation, not a bound.
  • Space. O(n+m)O(n + m) for the labeling and the neighbor lists.

Properties

  • Monotone. The energy never rises.
  • Local. The output is a local minimum for changes of one site, the weakest of the usual notions. Local minima of swap and expansion are also ICM local minima, but not the other way.
  • Order and start dependent. Different orders or starts give different results, as in the example.
  • No condition on VV. Any table works, which makes ICM a fallback for energies that no cut can handle.
  • Exact without pair terms. If V=0V = 0, one sweep gives the label of least data cost at each site, the global minimum.
  • No quality bound. Its energy can be far above the optimum. In the benchmark of Szeliski et al. (2008) it was the weakest method on most energies.

Variants and improvements

  • Better starts. Start from the best data label, or from the output of a faster or coarser method.
  • Coding and checkerboard order. Sites that are not neighbors can be updated in parallel. On a 4-connected grid, update all black squares, then all white squares; each half-sweep is still a valid ICM step.
  • Stochastic versions. Gibbs sampling draws the label from the conditional distribution instead of taking its mode, and simulated annealing lowers a temperature so that the method ends as ICM.
  • Block ICM. Optimize a whole row or a small block at a time, exactly by dynamic programming on a chain. This escapes some of the traps of single sites.
  • Large moves. Alpha-expansion and alpha-beta swap change many sites at once by a minimum cut, and are the usual replacement.

When to use it

Use ICM as a baseline, to polish the output of another method, or when the energy has a pairwise term that no other method accepts and speed matters more than quality. For Potts or truncated linear terms, use alpha-expansion; for general terms, loopy belief propagation or TRW-S.

Pitfalls

  • Synchronous updates. Updating all sites at once from the old labeling is not ICM and can oscillate. Two neighbors with labels 0 and 1 and a strong Potts term swap their labels at each step forever. Update in place.
  • Ties. Change a site only on a strict improvement, or the method can cycle between labels of equal energy.
  • Blaming the model. When ICM gives a poor result, the cause can be the optimizer and not the energy. A small group of noisy sites can hold each other in place, as sites 0 and 1 do in the example. Compare with a method with large moves before you conclude that the model is bad.
  • Reading the result as MAP. The result is a local minimum. Do not report it as the MAP estimate.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

iterated_conditional_modes.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iterated-conditional-modes/. The authors are listed in prov/ZDD3HA.jsonl.
"""Iterated conditional modes (ICM) for a pairwise MRF energy.

The energy of a labeling f (one label in 0 .. L - 1 per site) is

    E(f) = sum_p D[p][f[p]] + sum_{(p, q, w) in pairs} w * V[f[p]][f[q]].

V may be any L x L matrix; it need not be symmetric or a metric. ICM visits
the sites in a fixed order and gives each site the label of least local
cost, given the current labels of its neighbors. A site changes only when
the new label is strictly better, so the energy never rises.
"""

from __future__ import annotations

from typing import List, Optional, Sequence, Tuple

Pairs = Sequence[Tuple[int, int, float]]


def energy(D, pairs: Pairs, V, f: Sequence[int]) -> float:
    return (sum(D[p][f[p]] for p in range(len(D)))
            + sum(w * V[f[p]][f[q]] for (p, q, w) in pairs))


def neighbor_lists(n: int, pairs: Pairs):
    """For each site, the pairs it is in: (other site, weight, is_first)."""
    nbrs: List[List[Tuple[int, float, bool]]] = [[] for _ in range(n)]
    for (p, q, w) in pairs:
        nbrs[p].append((q, w, True))
        nbrs[q].append((p, w, False))
    return nbrs


def local_costs(D, V, nbrs, f: Sequence[int], p: int) -> List[float]:
    """c(l) = D_p(l) + the pair terms of p with the neighbors fixed."""
    L = len(V)
    c = list(D[p])
    for (q, w, first) in nbrs[p]:
        for l in range(L):
            c[l] += w * (V[l][f[q]] if first else V[f[q]][l])
    return c


def icm(D, pairs: Pairs, V, f: Optional[Sequence[int]] = None,
        order: Optional[Sequence[int]] = None,
        max_sweeps: int = 10 ** 6) -> Tuple[List[int], int]:
    """Return (labeling, number of sweeps). The start is f, or the label of
    least data cost at each site; the default order is 0, 1, ..., n - 1."""
    n, L = len(D), len(V)
    if f is None:
        f = [min(range(L), key=lambda l: D[p][l]) for p in range(n)]
    f = list(f)
    order = list(range(n)) if order is None else list(order)
    nbrs = neighbor_lists(n, pairs)
    sweeps = 0
    while sweeps < max_sweeps:  # @line L1
        sweeps += 1
        changed = False  # @line L2
        for p in order:  # @line L3
            c = local_costs(D, V, nbrs, f, p)  # @line L4
            best = min(range(L), key=lambda l: c[l])  # @line L5
            if c[best] < c[f[p]]:  # @line L6
                f[p] = best  # @line L6
                changed = True  # @line L6
        if not changed:  # @line L7
            break
    return f, sweeps  # @line L8


def is_icm_local_minimum(D, pairs: Pairs, V, f: Sequence[int]) -> bool:
    """True if no change of a single site lowers the energy."""
    e = energy(D, pairs, V, f)
    g = list(f)
    for p in range(len(D)):
        for l in range(len(V)):
            g[p] = l
            if energy(D, pairs, V, g) < e:
                return False
        g[p] = f[p]
    return True
test_iterated_conditional_modes.py 95 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iterated-conditional-modes/. The authors are listed in prov/ZDD3HA.jsonl.

import itertools
import random

from iterated_conditional_modes import (
    energy,
    icm,
    is_icm_local_minimum,
    local_costs,
    neighbor_lists,
)


def grid_pairs(w, h, rng):
    out = []
    for v in range(h):
        for u in range(w):
            if u + 1 < w:
                out.append((v * w + u, v * w + u + 1, rng.randint(1, 3)))
            if v + 1 < h:
                out.append((v * w + u, (v + 1) * w + u, rng.randint(1, 3)))
    return out


def random_instance(rng):
    w, h, L = rng.randint(1, 4), rng.randint(1, 3), rng.randint(2, 4)
    while L ** (w * h) > 4096:
        h -= 1
    n = w * h
    D = [[rng.randint(-5, 9) for _ in range(L)] for _ in range(n)]
    V = [[rng.randint(0, 6) for _ in range(L)] for _ in range(L)]  # any matrix
    return D, grid_pairs(w, h, rng), V


def test_local_costs_match_energy_differences():
    rng = random.Random(1)
    for _ in range(100):
        D, pairs, V = random_instance(rng)
        n, L = len(D), len(V)
        f = [rng.randrange(L) for _ in range(n)]
        nbrs = neighbor_lists(n, pairs)
        p = rng.randrange(n)
        c = local_costs(D, V, nbrs, f, p)
        for l in range(L):
            g = list(f)
            g[p] = l
            assert energy(D, pairs, V, g) - energy(D, pairs, V, f) == c[l] - c[f[p]]


def test_result_is_a_local_minimum_and_energy_does_not_rise():
    rng = random.Random(2)
    for _ in range(120):
        D, pairs, V = random_instance(rng)
        n, L = len(D), len(V)
        f0 = [rng.randrange(L) for _ in range(n)]
        e0 = energy(D, pairs, V, f0)
        prev = e0
        for sweeps in range(1, 8):
            g, _ = icm(D, pairs, V, f0, max_sweeps=sweeps)
            e = energy(D, pairs, V, g)
            assert e <= prev
            prev = e
        f, _ = icm(D, pairs, V, f0)
        assert is_icm_local_minimum(D, pairs, V, f)
        opt = min(energy(D, pairs, V, g) for g in itertools.product(range(L), repeat=n))
        assert opt <= energy(D, pairs, V, f) <= e0


def test_no_pair_terms_gives_the_exact_minimum():
    rng = random.Random(3)
    for _ in range(50):
        n, L = rng.randint(1, 8), rng.randint(2, 5)
        D = [[rng.randint(0, 9) for _ in range(L)] for _ in range(n)]
        V = [[0] * L for _ in range(L)]
        f, sweeps = icm(D, [], V, [0] * n)
        assert energy(D, [], V, f) == sum(min(row) for row in D)
        assert sweeps <= 2


def test_worked_example_and_order_dependence():
    y = [0, 1, 0, 0, 1, 1, 0, 1, 1, 1]
    D = [[0 if l == v else 2 for l in (0, 1)] for v in y]
    pairs = [(i, i + 1, 1) for i in range(len(y) - 1)]
    V = [[0, 3], [3, 0]]
    assert energy(D, pairs, V, y) == 15
    f, sweeps = icm(D, pairs, V)
    assert f == [1, 1, 0, 0, 1, 1, 1, 1, 1, 1] and sweeps == 2
    assert energy(D, pairs, V, f) == 10
    g, _ = icm(D, pairs, V, order=list(range(9, -1, -1)))
    assert g == [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
    assert energy(D, pairs, V, g) == 7
    best = min(energy(D, pairs, V, h) for h in itertools.product((0, 1), repeat=10))
    assert best == 7

History

Besag (1986) proposed ICM in his paper on the statistical analysis of "dirty pictures", as a fast deterministic alternative to the stochastic relaxation of Geman and Geman (1984), and used it to restore images under Markov random field priors. Its strict local moves were the motivation for the large moves of Boykov, Veksler and Zabih (2001). In the benchmark of Szeliski et al. (2008), ICM served as the baseline against which graph cuts, belief propagation and TRW-S were measured.

References

  1. Julian Besag, On the statistical analysis of dirty pictures, Journal of the Royal Statistical Society Series B 48(3), 1986, 259-279 (the paper; the discussion follows), the definition of iterated conditional modes as an approximation to the maximum a posteriori estimate, and its use for the restoration of images
  2. Richard Szeliski, Ramin Zabih, Daniel Scharstein, Olga Veksler, Vladimir Kolmogorov, Aseem Agarwala, Marshall Tappen and Carsten Rother, A comparative study of energy minimization methods for Markov random fields with smoothness-based priors, IEEE Transactions on Pattern Analysis and Machine Intelligence 30(6), 2008, 1068-1080, ICM as the baseline of the comparison, and its energies against those of graph cuts, loopy belief propagation and TRW-S
  3. Yuri Boykov, Olga Veksler and Ramin Zabih, Fast approximate energy minimization via graph cuts, IEEE Transactions on Pattern Analysis and Machine Intelligence 23(11), 2001, 1222-1239, Section 3 (standard moves, which change one site at a time, against the large moves of swap and expansion)
  4. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 4, Model fitting and optimization (Markov random fields and their inference)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example