Algorithmadvanced
Alpha-expansion
Also called expansion move algorithm, Boykov-Veksler-Zabih expansion.
Minimize a multi-label energy with a metric pairwise term by repeated min cuts, each letting any set of sites switch to one label alpha. Within 2c of the optimum, so 2 for Potts.
- Solves
- MAP inference
- Time
- O(k L (F + n + m)) worst · averageO(L (F + n + m)) best
- Space
- O(n + m) extra
- Where
- F = the time of one max flow on n + 2 nodes and n + m edges; L = the number of labels; k = the number of cycles over the labels; m = the number of neighbor pairs; n = the number of sites
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Yuri Boykov, Olga Veksler, Ramin Zabih, 2001
Alpha-expansion is a method for labeling problems: give each of sites one of labels so that a sum of costs is small. Each site pays a cost for its own label, and each neighbor pair pays a cost that depends on the two labels, for example a fixed penalty when they differ. The method improves a labeling by moves. An -expansion move picks one label and lets any subset of the sites change to at once, while the other sites keep their labels. There are such subsets, but when is a metric the best one is found exactly by one minimum cut, because the energy of the move is a regular binary energy (the Kolmogorov-Zabih theorem). The algorithm cycles over the labels until no move lowers the energy. Finding the best labeling is NP-hard already for the Potts model with three labels, but the result of alpha-expansion is within a factor of the optimum, where is the ratio of the largest to the smallest cost of two different labels, so within 2 for Potts. It is a standard method for MAP inference in Markov random fields on images and meshes: stereo, segmentation, image stitching and mesh segmentation.
In plain words
Each pixel needs a label, such as a depth or a color class. A label that fits the pixel is cheap, and two neighbors with different labels pay a penalty. Start with any labeling. Now pick one label and ask: which pixels should switch to this label, all at once, to lower the total cost the most? Any group of pixels may switch, which is far more than trying one pixel at a time, and a minimum cut in a graph finds the best group exactly. Do this for each label in turn, and repeat the whole round until no label helps. The answer is not always the best one, but it cannot be worse than twice the best for the simple penalty.
The problem
Input. A set of sites, a set of neighbor pairs with weights , a set of labels, data costs , and a metric on the labels: exactly when , , and .
Output. A labeling with small energy
which no -expansion improves, for any label . An -expansion of is any labeling with for all .
Examples of metrics are the Potts model and the truncated linear distance on ordered labels. The truncated quadratic is not a metric; it is only a semimetric, which suits alpha-beta swap.
The algorithm
ALPHA-EXPANSION(D, V, N, f)- 1
repeat - 2
success ← false - 3
for each label α do - 4
build the binary energy B(x) = E(g(x)), where g(x)_p = α if x_p = 1 and f_p if x_p = 0 - 5
x ← a minimizer of B by one minimum cut - 6
f' ← g(x) - 7
if E(f') < E(f) then f ← f'; success ← true - 8
until success = false - 9
return f
For a pair , the move energy has the four values , , and for . It is regular when , which is the triangle inequality. Line L5 builds the graph of the theorem page: an edge of capacity for each pair, and an edge from the source or to the sink for the linear part of each site. Boykov, Veksler and Zabih built a different graph, with an extra node on each pair whose ends have different labels; both give the same minimum. The code checks regularity and stops with an error on a nonregular pair term, which happens when is not a metric.
Example
Take four sites in a row, labels 0, 1, 2, the Potts model with , and the data costs
| site | |||
|---|---|---|---|
| 0 | 0 | 5 | 1 |
| 1 | 2 | 6 | 0 |
| 2 | 6 | 0 | 5 |
| 3 | 0 | 2 | 5 |
Start from the best label of each site, , with .
| cycle | best -expansion | accepted | ||
|---|---|---|---|---|
| 1 | 0 | 8 | yes | |
| 1 | 1 | 8 | no | |
| 1 | 2 | 8 | no | |
| 2 | 0, 1, 2 | no move below 8 | 8 | no |
The algorithm stops after two cycles at with . The optimum is with . From , no single move reaches it, because it uses two new labels. Every 2-expansion that changes a site costs at least 10, for example , and the best 1-expansion only ties at 8. The ratio is well below the bound 2.
Correctness
The full proof is in proofs/correctness.md. It has three parts. First, the binary energy of line L4 equals the energy of the labeling it describes, and its pair terms are regular by the triangle inequality, so the cut of line L5 gives the best expansion. Second, each accepted move lowers the energy strictly and there are finitely many labelings, so the loop stops, and in the last cycle no label gives an improving expansion. Third, the bound of Theorem 6.1 of Boykov, Veksler and Zabih: compare the output with the expansion that copies an optimal labeling on the sites where . Each such comparison bounds the energy of on those sites and their pairs. Summed over , every pair with appears twice and pays at most times its cost in , which gives .
Proof: Correctness of alpha-expansionfull
The energy is with weights . We prove three facts: each move of lines L4 to L6 returns a labeling of least energy among all -expansions of ; the loop stops at a labeling that no expansion move improves; and if is a metric and , then for an optimal , where .
A metric here is a function with if and only if , , and .
1. Each move is optimal in its move space
An -expansion of is a labeling with for every . Write with if and if ; when both values give the same label. Line L4 builds the binary energy
with , , and where and . By construction for every .
Each pairwise term is regular:
by and the triangle inequality. So is in the class and regular, and by the Kolmogorov-Zabih theorem it is represented by the graph that the code builds: for each pair term, the edge of capacity , and for the coefficient of in the remaining linear part, an edge of capacity if or an edge of capacity if . A minimum cut gives a minimizer of with on the source side (the last paragraph of the proof on the theorem page). Line L6 returns , which therefore has the least energy among all -expansions of .
2. Termination and local optimality
Line L7 replaces only by a labeling of strictly smaller energy. There are labelings, so there are finitely many replacements, and some cycle of lines L3 to L7 has no replacement. Then line L8 stops. In that last cycle did not change, so for every label the optimal -expansion of has energy at least . Since is itself an -expansion of (with ), no -expansion has smaller energy than , for any . With integer energies there are at most cycles.
3. The bound
Let be the output and an optimal labeling. For a label let , and let be the -expansion of with for and otherwise. Split the pairs into (both ends in ), (exactly one end in ) and the rest. For a set of sites and a set of pairs write and .
By part 2, . The labelings and agree outside , so the terms of the sites outside and of the pairs with no end in cancel, and
On , , so the first two terms on the right equal and . For a pair of with and , we have , and . If this is 0. Otherwise it is at most . So
Sum over all labels . The sets partition the sites, so the data terms sum to and . A pair with is in exactly one and in no ; a pair with is in exactly two sets and in no . On the left every pair appears at least once and , so the left sum is at least . On the right the pairs of the first kind have , and those of the second kind appear twice with the factor . Hence
where the last step uses and . For the Potts model and the factor is 2.
The bound needs only that is a local minimum for expansion moves, so it holds for any order of the labels and any start. It is Theorem 6.1 of Boykov, Veksler and Zabih (2001).
Complexity
The model is the real RAM; the tests use integer costs, so that the cuts and the comparisons are exact.
- One move. Building the graph takes time, and the cut takes the time of one max-flow computation on nodes and at most edges. The code uses Edmonds-Karp for clarity; programs on images use the Boykov-Kolmogorov algorithm, whose speed on such grids is measured, not bounded.
- One cycle. moves and energy evaluations, .
- Number of cycles. With integer costs each accepted move lowers by at least 1, so . There is no better general bound. On image energies programs usually stop after a few cycles; this is an observation, not a bound.
- Space. for the graph and the labeling.
Properties
- Approximation. for a metric and . For Potts, . For truncated linear on the integer labels with , .
- Strong moves. A local minimum for expansion moves is also a local minimum for single-site changes, the moves of ICM, because changing one site to is an -expansion.
- Hard problem. Minimizing the Potts energy with labels is NP-hard, by a reduction from the multiway cut problem (Section 7 and the Appendix of the paper). So an exact polynomial algorithm is not expected, and a guarantee like is the realistic goal.
- Two labels. For , start from the labeling with all sites at 0. The move space of label 1 then contains every labeling, so one move gives the exact minimum.
- Deterministic. For a fixed order of labels and fixed tie-breaking in the cut, the output is fixed. Different orders can stop at different local minima.
Variants and improvements
- Graph with auxiliary nodes. The original construction puts an extra node on each pair with . It gives the same move.
- Swap moves. Alpha-beta swap needs only a semimetric but has no constant factor bound.
- Fusion moves. Lempitsky, Rother, Roth and Blake (2010) combine the current labeling with any proposal labeling, not only a constant one; the move energy is then often nonregular and is solved by QPBO.
- Primal-dual view. Komodakis and Tziritas (2007) explained expansion as a primal-dual method for the linear programming relaxation, and the FastPD code of Komodakis, Tziritas and Paragios reuses the dual solution between moves.
- Reuse of flows. Consecutive cuts differ a little, so dynamic max-flow codes reuse the residual graph of the last cycle.
- Ordered labels. For a convex on ordered labels, Ishikawa (2003) gives an exact solution by one cut on a graph with nodes.
When to use it
Use alpha-expansion for energies with a metric pairwise term, such as Potts or truncated linear: stereo with a smoothness prior (graph cut stereo), segmentation into several regions, image stitching and the segmentation of 3D meshes. In the comparison of Szeliski et al. (2008), expansion was among the best methods on most of the energies and much better than ICM. Use swap or loopy belief propagation when is not a metric, and TRW-S when a lower bound is needed.
Pitfalls
- Nonmetric terms. With truncated quadratic or another semimetric, some move energies are not regular, and a cut does not give the best move. Truncating the nonregular terms makes the method run but voids the bound.
- Negative data costs. The bound needs . Add a constant to each site to make the costs nonnegative; this changes the bound but not the moves.
- Ties. Accept a move only if it lowers the energy strictly, or the loop can cycle between labelings of equal energy.
- Floating point. Large and small costs together make the cut inexact. Scale costs to integers when possible.
- The bound is loose. In practice the result is usually much closer to the optimum than , but is all that is proved. Do not quote the measured gap as a guarantee.
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/alpha-expansion/. The authors are listed in prov/V82D4Y.jsonl.
"""Alpha-expansion for multi-label energies with a metric pairwise term.
The energy of a labeling f (a list with 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]],
with D[p][l] the data cost, pairs the neighbor pairs with weights w >= 0,
and V an L x L matrix. Each expansion move is solved exactly by one
minimum cut on the graph of the Kolmogorov-Zabih construction.
"""
from __future__ import annotations
from collections import deque
from typing import List, Optional, Sequence, Tuple
Pairs = Sequence[Tuple[int, int, float]]
def energy(D: Sequence[Sequence[float]], pairs: Pairs,
V: Sequence[Sequence[float]], 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 _min_cut_source_side(nn: int, edges, s: int, t: int) -> List[bool]:
"""Edmonds-Karp max flow; return the nodes that s reaches at the end."""
adj: List[List[int]] = [[] for _ in range(nn)]
to: List[int] = []
cap: List[float] = []
for (u, v, c) in edges:
adj[u].append(len(to))
to.append(v)
cap.append(c)
adj[v].append(len(to))
to.append(u)
cap.append(0)
while True:
prev = [-1] * nn
seen = [False] * nn
seen[s] = True
queue = deque([s])
while queue and not seen[t]:
u = queue.popleft()
for e in adj[u]:
if cap[e] > 0 and not seen[to[e]]:
seen[to[e]] = True
prev[to[e]] = e
queue.append(to[e])
if not seen[t]:
return seen
path = []
v = t
while v != s:
path.append(prev[v])
v = to[prev[v] ^ 1]
delta = min(cap[e] for e in path)
for e in path:
cap[e] -= delta
cap[e ^ 1] += delta
def minimize_regular_binary(n: int, unary: Sequence[Tuple[float, float]],
terms: Sequence[Tuple[int, int, float, float, float, float]]
) -> List[int]:
"""Minimize sum_p unary[p][x_p] + sum theta(x_p, x_q) over x in {0,1}^n.
Each term is (p, q, A, B, C, D) with A = theta(0,0), B = theta(0,1),
C = theta(1,0), D = theta(1,1), and must be regular: A + D <= B + C.
x_p = 0 is the source side. Raises ValueError on a nonregular term.
"""
s, t = n, n + 1
lin = [u1 - u0 for (u0, u1) in unary] # coefficient of x_p
edges = []
for (p, q, A, B, C, Dd) in terms:
k = B + C - A - Dd
if k < 0:
raise ValueError("nonregular pairwise term: the move is not a cut")
# theta = A + (C - A) x_p + (Dd - C) x_q + k (1 - x_p) x_q
lin[p] += C - A
lin[q] += Dd - C
if k > 0:
edges.append((p, q, k))
for p in range(n):
if lin[p] > 0:
edges.append((s, p, lin[p])) # paid when x_p = 1
elif lin[p] < 0:
edges.append((p, t, -lin[p])) # paid when x_p = 0
side = _min_cut_source_side(n + 2, edges, s, t)
return [0 if side[p] else 1 for p in range(n)]
def expansion_move(D, pairs: Pairs, V, f: Sequence[int], alpha: int) -> List[int]:
"""The labeling of least energy among those that move any subset of
sites to alpha and keep the others (one minimum cut)."""
n = len(D)
unary = [(D[p][f[p]], D[p][alpha]) for p in range(n)] # @line L4
terms = [(p, q, w * V[f[p]][f[q]], w * V[f[p]][alpha], # @line L4
w * V[alpha][f[q]], w * V[alpha][alpha]) for (p, q, w) in pairs] # @line L4
x = minimize_regular_binary(n, unary, terms) # @line L5
return [alpha if x[p] else f[p] for p in range(n)] # @line L6
def alpha_expansion(D, pairs: Pairs, V, f: Optional[Sequence[int]] = None,
order: Optional[Sequence[int]] = None) -> Tuple[List[int], int]:
"""Run expansion moves over all labels until none lowers the energy.
Returns (labeling, number of cycles). The start is f, or the labeling
that takes the best data cost at each site.
"""
L = len(V)
if f is None:
f = [min(range(L), key=lambda l: D[p][l]) for p in range(len(D))]
f = list(f)
order = list(range(L)) if order is None else list(order)
e = energy(D, pairs, V, f)
cycles = 0
while True: # @line L1
cycles += 1
success = False # @line L2
for alpha in order: # @line L3
g = expansion_move(D, pairs, V, f, alpha) # @line L4
eg = energy(D, pairs, V, g) # @line L7
if eg < e: # @line L7
f, e, success = g, eg, True # @line L7
if not success: # @line L8
return f, cycles # @line L9
def is_metric(V: Sequence[Sequence[float]]) -> bool:
L = len(V)
for a in range(L):
for b in range(L):
if (V[a][b] == 0) != (a == b) or V[a][b] != V[b][a] or V[a][b] < 0:
return False
for c in range(L):
if V[a][b] > V[a][c] + V[c][b]:
return False
return True
def bound_factor(V: Sequence[Sequence[float]]) -> float:
"""c = max V / min V over pairs of distinct labels."""
vals = [V[a][b] for a in range(len(V)) for b in range(len(V)) if a != b]
return max(vals) / min(vals)
def potts(L: int, lam: float = 1) -> List[List[float]]:
return [[0 if a == b else lam for b in range(L)] for a in range(L)]
def truncated_linear(L: int, k: float) -> List[List[float]]:
return [[min(abs(a - b), k) for b in range(L)] for a in range(L)]
def grid_pairs(w: int, h: int, weight: float = 1) -> List[Tuple[int, int, float]]:
"""4-neighbor pairs of a w x h grid, site (u, v) has index v * w + u."""
out = []
for v in range(h):
for u in range(w):
if u + 1 < w:
out.append((v * w + u, v * w + u + 1, weight))
if v + 1 < h:
out.append((v * w + u, (v + 1) * w + u, weight))
return out
test_alpha_expansion.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alpha-expansion/. The authors are listed in prov/V82D4Y.jsonl.
import itertools
import random
import pytest
from alpha_expansion import (
alpha_expansion,
bound_factor,
energy,
expansion_move,
grid_pairs,
is_metric,
minimize_regular_binary,
potts,
truncated_linear,
)
def brute_optimum(D, pairs, V):
n, L = len(D), len(V)
return min(energy(D, pairs, V, f) for f in itertools.product(range(L), repeat=n))
def brute_move(D, pairs, V, f, alpha):
n = len(D)
best = None
for x in itertools.product((0, 1), repeat=n):
g = [alpha if x[p] else f[p] for p in range(n)]
e = energy(D, pairs, V, g)
if best is None or e < best:
best = e
return best
def random_instance(rng, n_max=8):
w = rng.randint(1, 4)
h = rng.randint(1, max(1, n_max // w))
L = rng.randint(2, 4)
while L ** (w * h) > 4096:
h -= 1
n = w * h
D = [[rng.randint(0, 9) for _ in range(L)] for _ in range(n)]
pairs = [(p, q, rng.randint(1, 3)) for (p, q, _) in grid_pairs(w, h)]
V = potts(L, rng.randint(1, 4)) if rng.random() < 0.5 else truncated_linear(L, rng.randint(1, 3))
return D, pairs, V
def test_binary_cut_against_brute_force():
rng = random.Random(1)
for _ in range(200):
n = rng.randint(2, 7)
unary = [(rng.randint(-5, 5), rng.randint(-5, 5)) for _ in range(n)]
terms = []
for _ in range(rng.randint(0, 2 * n)):
p, q = rng.sample(range(n), 2)
A, B, C = rng.randint(-3, 3), rng.randint(-3, 3), rng.randint(-3, 3)
Dd = B + C - A - rng.randint(0, 4)
terms.append((p, q, A, B, C, Dd))
def e(x):
return (sum(unary[p][x[p]] for p in range(n))
+ sum((A, B, C, Dd)[2 * x[p] + x[q]] for (p, q, A, B, C, Dd) in terms))
x = minimize_regular_binary(n, unary, terms)
assert e(x) == min(e(y) for y in itertools.product((0, 1), repeat=n))
def test_nonregular_term_is_rejected():
with pytest.raises(ValueError):
minimize_regular_binary(2, [(0, 0), (0, 0)], [(0, 1, 1, 0, 0, 1)])
def test_move_is_optimal_in_its_space():
rng = random.Random(2)
for _ in range(150):
D, pairs, V = random_instance(rng)
L = len(V)
f = [rng.randrange(L) for _ in D]
alpha = rng.randrange(L)
g = expansion_move(D, pairs, V, f, alpha)
assert all(g[p] in (f[p], alpha) for p in range(len(D)))
assert energy(D, pairs, V, g) == brute_move(D, pairs, V, f, alpha)
def test_bound_and_local_minimum():
rng = random.Random(3)
for _ in range(120):
D, pairs, V = random_instance(rng)
assert is_metric(V)
L = len(V)
f0 = [rng.randrange(L) for _ in D]
f, _ = alpha_expansion(D, pairs, V, f0)
ef = energy(D, pairs, V, f)
assert ef <= energy(D, pairs, V, f0)
opt = brute_optimum(D, pairs, V)
assert opt <= ef <= 2 * bound_factor(V) * opt
for alpha in range(L):
assert brute_move(D, pairs, V, f, alpha) == ef
def test_worked_example():
# Four sites in a row, Potts with lambda = 4, labels 0, 1, 2.
D = [[0, 5, 1], [2, 6, 0], [6, 0, 5], [0, 2, 5]]
pairs = [(0, 1, 1), (1, 2, 1), (2, 3, 1)]
V = potts(3, 4)
f0 = [0, 2, 1, 0]
assert energy(D, pairs, V, f0) == 12
assert expansion_move(D, pairs, V, f0, 0) == [0, 0, 0, 0]
f, cycles = alpha_expansion(D, pairs, V, f0)
assert f == [0, 0, 0, 0] and energy(D, pairs, V, f) == 8 and cycles == 2
assert brute_optimum(D, pairs, V) == 7
assert energy(D, pairs, V, [2, 2, 1, 1]) == 7
def test_truncated_quadratic_is_not_metric():
V = [[min((a - b) ** 2, 4) for b in range(3)] for a in range(3)]
assert not is_metric(V)
D = [[0, 9, 9], [9, 9, 0]]
with pytest.raises(ValueError):
expansion_move(D, [(0, 1, 1)], V, [0, 2], 1)
History
Boykov, Veksler and Zabih introduced expansion and swap moves at ICCV 1999 and in the journal paper of 2001, with a graph for each move and the proof of the factor . They also showed that the Potts energy is NP-hard to minimize. Kolmogorov and Zabih (2004) gave the general rule for which binary energies a cut can minimize, which explains the metric condition. Szeliski et al. (2008) compared the move algorithms with ICM, loopy belief propagation and TRW-S on a common benchmark of vision energies, and expansion became a default method for multi-label problems in vision and graphics.
References
- 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 (the move spaces and the expansion algorithm), Section 5 with Theorem 5.4 and Corollary 5.5 (the graph of an expansion move), Section 6.1 with Theorem 6.1 (the bound 2c), Section 7 and the Appendix (NP-hardness of the Potts energy), Section 8 (experiments)
- Vladimir Kolmogorov and Ramin Zabih, What energy functions can be minimized via graph cuts?, IEEE Transactions on Pattern Analysis and Machine Intelligence 26(2), 2004, 147-159, Theorem 4.1 and Section 4.1 (the graph for a regular binary energy, used here for each move)
- 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, the comparison of expansion, swap, ICM, loopy belief propagation and TRW-S on stereo, segmentation, photomontage and denoising energies
- Andrew Blake, Pushmeet Kohli and Carsten Rother (editors), Markov Random Fields for Vision and Image Processing, MIT Press, 2011, Part I, Algorithms for inference of MAP estimates for MRFs (the chapters on graph cuts and move making algorithms)
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 4, Model fitting and optimization (Markov random fields, graph cuts and alpha-expansion)
Where this leads
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 V82D4Y Edit this page History Report an error Markdown