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.
- Solves
- MAP inference
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 and weights , labels, data costs , a pairwise table , a start labeling and an order of the sites.
Output. A labeling that is a local minimum of
for changes of one site: for every site and label , the labeling with replaced by has energy at least . need not be symmetric, a metric or submodular.
The algorithm
ICM(D, V, N, f, order)- 1
repeat - 2
changed ← false - 3
for each site p in the fixed order do - 4
for each label ℓ: c(ℓ) ← D_p(ℓ) + Σ over the neighbors q of p of w_pq V(ℓ, f_q) - 5
ℓ* ← the least label with the least c(ℓ*) - 6
if c(ℓ*) < c(f_p) then f_p ← ℓ*; changed ← true - 7
until changed = false - 8
return 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 the code uses or according to the order of the pair.
Example
Restore a noisy binary row with and the Ising or Potts term on neighbors. Start from , with for the five changes along the row.
| site | neighbors | action | ||
|---|---|---|---|---|
| 0 | 3 | 2 | change to 1 | |
| 1 | , | 5 | 3 | keep 1 |
| 2 to 5 | keep | |||
| 6 | , | 6 | 2 | change to 1 |
| 7 to 9 | keep |
After the first sweep with , and the second sweep changes nothing. The optimum is with . To reach it from the result, sites 0 and 1 must both change to 0. Changing site 0 alone costs , 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 .
Correctness
The full proof is in proofs/correctness.md. The key fact is that equals the change of the total energy when site alone takes label , because all terms that do not touch cancel. So each change of line L6 lowers 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 .
Proof: Correctness of iterated conditional modesfull
The energy is with real costs; 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 and a site . For a label let be with replaced by , and let
the cost of line L4. Then .
Proof. and differ only at . The terms of that do not contain are equal in both and cancel. The terms that contain are the data term of and the pair terms of , and their sum is for and for .
The energy does not rise
Line L6 changes only if . By the lemma, the energy then drops by . All other steps leave unchanged. So the energy after each step is at most the energy before it, and it drops strictly at each change.
Termination
There are labelings. The energy drops strictly at each change, so no labeling occurs twice, and there are at most changes. Each sweep that does not stop at line L7 makes at least one change, so there are at most sweeps. With integer costs each change lowers the energy by at least 1, so the number of changes is also at most .
Local minimality
The loop stops after a sweep with no change. During that sweep stayed the same, so for every site line L6 found for the least , and therefore for every label . By the lemma, for every site and label .
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 for site , so a sweep costs .
- Number of sweeps. With integer costs, each sweep except the last lowers the energy by at least 1, so . In general only is known. On image energies a few sweeps usually suffice; this is an observation, not a bound.
- Space. 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 . Any table works, which makes ICM a fallback for energies that no cut can handle.
- Exact without pair terms. If , 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.
# 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
- 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
- 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag ZDD3HA Edit this page History Report an error Markdown