Algorithmadvanced
Fully connected CRF inference
Also called dense CRF, Krahenbuhl-Koltun CRF.
Mean field inference in a CRF with Gaussian pairwise terms between all pixel pairs, made linear time by high-dimensional filtering of messages.
- Solves
- Semantic segmentation
- Time
- O(N L W H) worst · average · best
- Space
- O(L W H) extra
- Where
- H = the image height in pixels; L = the number of labels; N = the number of mean field iterations; W = the image width in pixels
- Model
- Real RAM
- Properties
- approximate inferencenot convergence guaranteeddeterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Philipp Krähenbühl, Vladlen Koltun, 2011
A fully connected CRF (dense CRF) labels each pixel of an image, for example with an object class, using a conditional random field in which every pair of pixels has a pairwise term, not only neighbors. The pairwise term is a Potts penalty times a sum of Gaussian kernels in position and color, so similar pixels that are close prefer the same label. Exact inference is out of reach, so Krähenbühl and Koltun (2011) use the mean field approximation. This page is about that inference: the update, why it is correct, where it can fail, and how the messages, a sum over all pixel pairs, become a Gaussian filter. The general CRF and the general mean field method are on their own pages. In practice a dense CRF refines the per-pixel scores of a classifier, often a convolutional network; the network is outside this page.
In plain words
A classifier looks at each pixel and gives a score for each label, for example "70 percent road, 30 percent car". These scores are noisy, and they often blur at object edges. A dense CRF lets pixels vote. Each pixel asks every other pixel what it believes, and gives more weight to pixels that are close and have a similar color. Then it updates its own belief with the votes and its own score. After a few rounds of this, a region with one color tends to agree on one label, and the label changes where the color changes.
Asking every other pixel is too slow when done one pair at a time. The trick is that the weighted vote is a blur of the belief images with a Gaussian that also looks at color. A fast filter computes such a blur for all pixels at once.
The problem
The input is an image of pixels, a label set of size , and a unary energy for each pixel and label , usually for the class probabilities of a classifier. Pixel has the position and the color . The energy of a labeling is (Krähenbühl and Koltun 2011, equations 1 to 3)
with the Potts compatibility and weights . The first kernel is the appearance kernel, the second the smoothness kernel. The model is , a Markov random field on the complete graph, with the Potts model as its pair term.
The output is a product distribution that approximates , and the labeling . Mean field picks to make small. Finding the exact minimum energy labeling is NP-hard for the multi-label Potts energy, and this method does not try.
The algorithm
The algorithm is Algorithm 1 of Krähenbühl and Koltun (2011), written for the Potts model with the two kernels merged into .
DENSE-CRF(U, k, N) ▷ U_i(l): unary energies; k(i, j): kernel sum, i ≠ j- 1
for each pixel i and label l do Q_i(l) ← exp(-U_i(l)) / Σ_l' exp(-U_i(l')) - 2
repeat N times - 3
for each pixel i and label l do M_i(l) ← Σ_{j ≠ i} k(i, j) Q_j(l) ▷ message passing - 4
for each pixel i and label l do B_i(l) ← Σ_l' M_i(l') - M_i(l) ▷ Potts compatibility - 5
for each pixel i and label l do Q_i(l) ← exp(-U_i(l) - B_i(l)) ▷ local update - 6
for each pixel i do divide each Q_i(l) by Σ_l' Q_i(l') ▷ normalize - 7
return Q and the labels x_i = argmax_l Q_i(l)
Line L4 is the compatibility transform: for the Potts model, the penalty for label is the total message for all other labels. All pixels update at the same time, from the old .
Messages as filtering. Line L3 is a sum over all pairs, . For each label, is the value at pixel of a Gaussian filter applied to the image , minus the value at itself (equation 5 of the paper). The smoothness kernel is a Gaussian filter in . The appearance kernel is a Gaussian in the 5D space of position and color, the kernel of the bilateral filter. Krähenbühl and Koltun compute both with the permutohedral lattice of Adams, Baek and Davis (2010), which splats the values onto a lattice, blurs on it, and slices back (Algorithm 2 of the paper). Its cost is linear in , and it approximates the sum.
Example
Take one row of 4 pixels with gray values and two labels. A classifier gives the probabilities for label 1, so . Pixel 1 has the color of pixel 0 but leans to label 1. The parameters are , , , , . The kernel values from pixel 1 are
The color difference of 10 almost removes the appearance term between pixels 1 and 2.
In the first iteration, with , and :
- and .
- The Potts penalties are and .
- The new energies are for label 0 and for label 1, so .
Pixel 1 now prefers label 0, like its neighbor with the same color.
| iteration | labels | |||||
|---|---|---|---|---|---|---|
| 0 | 0.2000 | 0.6000 | 0.7000 | 0.9000 | 0 1 1 1 | 2.0853 |
| 1 | 0.2815 | 0.3422 | 0.9256 | 0.9541 | 0 0 1 1 | 1.7535 |
| 2 | 0.1224 | 0.4579 | 0.9306 | 0.9808 | 0 0 1 1 | 1.6964 |
| 5 | 0.1324 | 0.2934 | 0.9369 | 0.9815 | 0 0 1 1 | 1.6484 |
is the mean field free energy of the correctness section. It stays above , computed by brute force over the 16 labelings. The values of go up and down, a small sign of the parallel update. The test file checks these numbers.
Correctness
The full proof is in proofs/correctness.md. The facts that are proved:
- Lines L3 to L6 compute the mean field equation (equation 4 of the paper) for the Potts model.
- For every product distribution , the free energy equals , so .
- With all other pixels fixed, the update of one pixel is the unique minimizer of over that pixel. So sequential updates, one pixel at a time, never increase , and the values of converge. This is the classical mean field result (Wainwright and Jordan 2008, Section 5). It gives a local result, not the global minimum.
- The parallel update of lines L3 to L6 has no such guarantee, as Krähenbühl and Koltun (2013) point out. A two-pixel example with a strong link and opposite unaries makes it swap the beliefs of the two pixels at every step (see the proof). The test file checks it.
- Krähenbühl and Koltun (2013, Section 3) give sufficient conditions under which a parallel scheme converges: positive definite kernels, which the Gaussian kernels are, and a negative semidefinite compatibility, which the Potts model is after a shift by a constant. Their variant of Section 3.2 adds the self term to each message, and then each parallel update is a step of the concave-convex procedure and does not increase an approximate objective. The proof file proves this.
- The separable blur of the smoothness kernel, minus the self term, gives the exact messages of line L3 for that kernel.
What is not proved: the error of the permutohedral lattice, which is an approximation, and the quality of the labels, which is measured on benchmarks.
Proof: Correctness of mean field inference in the fully connected CRFfull
This proof covers lines L1 to L7 of the main page, with exact messages. The model has pixels and labels. The energy of a labeling is
with weights and Gaussian kernels , so . The distribution is . A mean field distribution is , and its free energy is
The pair term is the probability under that , times . Nothing here says that the model labels images well. That is a benchmark question.
Lemma 1 (the lines compute the mean field equation). Given , lines L3 to L6 compute, for each pixel ,
which is equation (4) of Krähenbühl and Koltun (2011) for the Potts compatibility .
Proof. Line L3 sets . Line L4 sets . Lines L5 and L6 exponentiate and divide by the sum over .
Lemma 2 (free energy and the partition function). For every product distribution ,
with equality if and only if .
Proof. . The expectation of under is . For the labels are independent under , so . The entropy of a product is the sum of the entropies. This gives the formula for . The KL divergence is nonnegative, and zero only for (Gibbs inequality).
Lemma 3 (one pixel update is an exact minimization). Fix for all . Over all distributions on the labels, has the unique minimizer of Lemma 1.
Proof. Collect the terms of that contain :
Since , the term equals . So the part of that depends on is , with as in Lemma 1. With this is , which is smallest, and only then, at .
Theorem 1 (sequential updates). If the pixels are updated one at a time with the rule of Lemma 1, each with the current values of the others, then never increases. is bounded below by , so the sequence of values of converges.
Proof. Each step replaces by the minimizer of over with the rest fixed (Lemma 3), so does not increase. A non-increasing sequence that is bounded below (Lemma 2) converges.
This is the classical result for mean field (Wainwright and Jordan 2008, Section 5). It is a statement about the values of , at a local minimum or a saddle in general, not about the global minimum of over all product distributions.
Parallel updates. Lines L3 to L6 update all pixels at once, from the old . Lemma 3 does not apply, because each pixel uses old values of its neighbors. Krähenbühl and Koltun (2013) point out that the parallel update loses the guarantee. A two-pixel example shows that it can fail to converge: , , and . At the start . In each parallel step each pixel adopts the label that the other pixel had, because the Potts penalty outweighs the unary difference 1. The beliefs swap at each step: The sequential rule from the same start converges, with both pixels on label 1. The test file checks this example.
Theorem 2 (a convergent parallel variant). Krähenbühl and Koltun (2013, Section 3.2). Add the self term to the message: with , the value of the kernels at zero distance. Then each parallel update does not increase
where the double sum includes .
Proof. Write with , which is convex, and , where and is the matrix of with the diagonal included. Each Gaussian kernel is positive definite (its Fourier transform is positive, by Bochner's theorem), and the appearance kernel is a Gaussian in the joint feature of position and color. So , a sum of Gram matrices with weights , is positive semidefinite, and is concave.
The concave-convex procedure takes over products of distributions. The objective splits over the pixels, and at pixel and label is . By the argument of Lemma 3, the minimizer is . The line L4 penalty is , which differs from by a constant in , so lines L5 and L6 give the same . Then
The first inequality is concavity of , and the second is the choice of .
differs from only by the self terms and a constant. Krähenbühl and Koltun argue that for wide kernels this part is small. That is an approximation, not a bound proved here. On the two-pixel example the variant converges, but to a state where each pixel keeps its own label, which shows that the self term changes the fixed points.
Lemma 4 (separable filtering of the spatial kernel). For the spatial kernel on the grid, a blur of each label plane along the rows with the 1D Gaussian , then along the columns, gives over all , including . Subtracting gives the message of line L3.
Proof. . The row blur gives , and the column blur gives . The self term has .
The appearance kernel does not split in this way, because it depends on the colors. Krähenbühl and Koltun filter it with the permutohedral lattice of Adams, Baek and Davis (2010), which downsamples, blurs and upsamples. That step is an approximation of the sum, and the proofs above do not cover its error.
Cost. With exact messages, line L3 costs , line L4 costs for the Potts model ( for a general compatibility matrix), and lines L5 and L6 cost . So iterations cost time in the real-RAM model, with , plus for the kernel matrix if it is stored. With a filter whose cost is linear in , an iteration costs times the cost per sample of the filter.
Complexity
The front matter gives the cost with a linear-time filter for the messages, as in the paper, for a fixed feature dimension. The filter is an approximation. With exact messages an iteration costs time for line L3 and for lines L4 to L6, with . That is for iterations, in the real-RAM model. With a filter that is linear in , an iteration costs times the cost per sample of the filter, so for fixed feature dimension. Adams, Baek and Davis state that their filter is linear in the input size and polynomial in the dimension of the feature space. Krähenbühl and Koltun also downsample the images before filtering, by a factor tied to the kernel width (Section 5 of their paper). A general compatibility matrix instead of Potts adds per iteration for line L4. The extra space is for and the messages, plus the lattice. The number of iterations is a choice; it is not given by a bound.
Properties
- Approximate inference. Mean field gives a product distribution and a labeling, not the minimum energy labeling.
- Parallel and simple. Each step is a few filters and per-pixel arithmetic, which suits GPUs.
- No convergence guarantee for the plain parallel update. In practice a few iterations are run. That is a heuristic choice, not a result.
- Edge-preserving. The appearance kernel lets labels follow color edges, like a bilateral filter of the beliefs.
- Differentiable. Each step is smooth in and in the kernel weights. This is what lets later work train the CRF together with a network.
Variants and improvements
- Sequential or damped updates. Updating a subset of pixels at a time, or mixing the new with the old one, avoids oscillation. A sequential schedule has the guarantee of the correctness section, but it is slow with filtering, which works on all pixels at once.
- Convergent parallel mean field (Krähenbühl and Koltun 2013). A CCCP form (Section 3.1) and the cheaper concave approximation (Section 3.2) both converge under the conditions above. The same paper learns the kernel parameters by gradient descent through the inference.
- General compatibilities. A learned matrix lets, for example, "person" and "bicycle" be next to each other at a lower cost than "person" and "sky".
- CRF as a network layer. Later work wrote the mean field iterations as layers of a recurrent network and trained them with a convolutional network end to end (CRF-as-RNN), and the DeepLab models used a dense CRF to sharpen network outputs. These are applications of the same update.
- Other inference. For a CRF with only neighbor terms, graph cuts find the exact minimum of a binary submodular energy, and alpha-expansion is within a factor 2 of the optimum for Potts. These methods do not scale to all pixel pairs.
When to use it
Use a dense CRF to sharpen the output of a per-pixel classifier near object boundaries, when the image colors carry the boundary. It adds long-range consistency at a low cost. Do not use it when the classifier is already sharp at boundaries, as many recent networks are; the gain then is small or negative. Do not use it when you need the exact minimum energy labeling or a certificate, and do not use it when the colors of two classes are the same, because the appearance kernel then pulls their labels together.
Pitfalls
- Self term. The message of line L3 excludes . A filter that sums over all pixels includes it, with weight . Forgetting to subtract it gives the variant of the 2013 paper, which has different fixed points: in the two-pixel example of the proof, each pixel then keeps its own label.
- Oscillation. Strong kernel weights can make the parallel update oscillate. Watch the labels, or use damping.
- Units of the kernels. and are in pixels and in color units. A change of image size or color range changes the model unless the parameters change with it. Krähenbühl and Koltun report that worked well on their data; this is a tuned value, not a result.
- Unary scale. If comes from a network with overconfident probabilities, the pairwise terms have little effect. The balance between and needs tuning.
- Free energy is not accuracy. A lower means a better fit to the model, not more correct labels.
- Filter error. The permutohedral lattice and the downsampling are approximations. Results can differ between implementations, and the messages are not exactly symmetric.
Implementations
The Python code in impl/python/dense_crf.py implements lines L1 to L7 with exact messages over all pixel pairs, for tiny images. It also has the separable Gaussian filter for the smoothness kernel, the sequential update, the variant with the self term, the free energy, and by brute force. It does not implement the permutohedral lattice. The tests check that the marginals are distributions, that zero weights give the unary softmax, that the filter equals the exact sum, that sequential updates never raise , that , the oscillation example, the monotone objective of the variant, and a small denoising example.
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/dense-crf/. The authors are listed in prov/9CMFRH.jsonl.
"""Mean field inference in a fully connected CRF with Gaussian edge potentials.
Pixel i = v * w + u is (u, v) with the gray value img[v][u]. The energy of a
labeling x is
E(x) = sum_i U[i][x_i] + sum_{i < j} [x_i != x_j] k(i, j),
k(i, j) = w1 exp(-|p_i - p_j|^2 / (2 ta^2) - |I_i - I_j|^2 / (2 tb^2))
+ w2 exp(-|p_i - p_j|^2 / (2 tg^2)),
the Potts model with the two kernels of Kraehenbuehl and Koltun (2011). The
messages here are exact sums over all pixel pairs, O(n^2 L) per iteration,
for tiny images. gaussian_messages shows the filtering idea for the spatial
kernel: a separable Gaussian blur minus the self term.
"""
import itertools
import math
def kernel_matrix(img, w1, ta, tb, w2, tg):
"""Return the n x n matrix of k(i, j), with zero diagonal."""
h, w = len(img), len(img[0])
pix = [(u, v, img[v][u]) for v in range(h) for u in range(w)]
n = len(pix)
k = [[0.0] * n for _ in range(n)]
for i in range(n):
ui, vi, ci = pix[i]
for j in range(i + 1, n):
uj, vj, cj = pix[j]
dp = (ui - uj) ** 2 + (vi - vj) ** 2
dc = (ci - cj) ** 2
val = w1 * math.exp(-dp / (2 * ta * ta) - dc / (2 * tb * tb)) + w2 * math.exp(-dp / (2 * tg * tg))
k[i][j] = k[j][i] = val
return k
def softmax_neg(e):
"""Return the distribution proportional to exp(-e)."""
m = min(e)
q = [math.exp(m - x) for x in e]
s = sum(q)
return [x / s for x in q]
def dense_crf(unary, kmat, iters, include_self=0.0):
"""Run iters parallel mean field updates and return Q (n lists of L probabilities).
unary[i][l] is the unary energy and kmat the kernel matrix with zero diagonal.
include_self adds include_self * Q_i(l) to the message of pixel i, which
gives the convergent variant of Kraehenbuehl and Koltun (2013, Section 3.2)
when include_self = k(i, i) = w1 + w2.
"""
n, nl = len(unary), len(unary[0])
q = [softmax_neg(unary[i]) for i in range(n)] # @line L1
for _ in range(iters): # @line L2
msg = [[include_self * q[i][l] for l in range(nl)] for i in range(n)]
for i in range(n): # @line L3
row, mi = kmat[i], msg[i]
for j in range(n):
kij = row[j]
if kij:
qj = q[j]
for l in range(nl):
mi[l] += kij * qj[l]
new = []
for i in range(n):
total = sum(msg[i])
pen = [total - msg[i][l] for l in range(nl)] # @line L4
e = [unary[i][l] + pen[l] for l in range(nl)] # @line L5
new.append(softmax_neg(e)) # @line L6
q = new
return q # @line L7
def labels_of(q):
"""Return the label with the largest marginal for each pixel."""
return [max(range(len(qi)), key=lambda l: qi[l]) for qi in q]
def mean_field_sequential(unary, kmat, sweeps, trace=None):
"""Update one pixel at a time, in index order. If trace is a list, append the free energy after each update."""
n, nl = len(unary), len(unary[0])
q = [softmax_neg(unary[i]) for i in range(n)]
for _ in range(sweeps):
for i in range(n):
m = [0.0] * nl
for j in range(n):
if kmat[i][j]:
for l in range(nl):
m[l] += kmat[i][j] * q[j][l]
total = sum(m)
q[i] = softmax_neg([unary[i][l] + total - m[l] for l in range(nl)])
if trace is not None:
trace.append(free_energy(q, unary, kmat))
return q
def free_energy(q, unary, kmat):
"""Return F(Q) = E_Q[E] - H(Q). F(Q) >= -log Z, with equality only for the true distribution."""
n, nl = len(unary), len(unary[0])
f = 0.0
for i in range(n):
for l in range(nl):
if q[i][l] > 0:
f += q[i][l] * (unary[i][l] + math.log(q[i][l]))
for j in range(i + 1, n):
if kmat[i][j]:
f += kmat[i][j] * (1.0 - sum(q[i][l] * q[j][l] for l in range(nl)))
return f
def concave_objective(q, unary, kmat, self_weight):
"""The approximate KL divergence (up to log Z) of Kraehenbuehl and Koltun (2013, eq. 9) for the Potts model.
The Potts compatibility is written as -[l = l'], which differs from
[l != l'] by a constant, and the kernel matrix gets the diagonal self_weight.
"""
n, nl = len(unary), len(unary[0])
f = 0.0
for i in range(n):
for l in range(nl):
if q[i][l] > 0:
f += q[i][l] * (unary[i][l] + math.log(q[i][l]))
for j in range(n):
kij = self_weight if i == j else kmat[i][j]
if kij:
f -= 0.5 * kij * sum(q[i][l] * q[j][l] for l in range(nl))
return f
def energy(x, unary, kmat):
n = len(x)
e = sum(unary[i][x[i]] for i in range(n))
for i in range(n):
for j in range(i + 1, n):
if x[i] != x[j]:
e += kmat[i][j]
return e
def log_partition(unary, kmat):
"""Return log Z by summing over all labelings. Only for tiny problems."""
n, nl = len(unary), len(unary[0])
es = [-energy(x, unary, kmat) for x in itertools.product(range(nl), repeat=n)]
m = max(es)
return m + math.log(sum(math.exp(e - m) for e in es))
def gaussian_messages(q, w, h, theta):
"""Return sum_{j != i} exp(-|p_i - p_j|^2 / (2 theta^2)) Q_j(l) by a separable blur minus the self term.
The spatial Gaussian factors into a Gaussian in u times a Gaussian in v, so
a blur along the rows and then along the columns gives the full sum over j.
The blur is exact here: it uses all pixels, with no truncation.
"""
nl = len(q[0])
g = [math.exp(-d * d / (2 * theta * theta)) for d in range(max(w, h))]
rows = [[[0.0] * nl for _ in range(w)] for _ in range(h)]
for v in range(h):
for u in range(w):
acc = rows[v][u]
for x in range(w):
c = g[abs(u - x)]
qx = q[v * w + x]
for l in range(nl):
acc[l] += c * qx[l]
out = []
for v in range(h):
for u in range(w):
acc = [0.0] * nl
for y in range(h):
c = g[abs(v - y)]
ry = rows[y][u]
for l in range(nl):
acc[l] += c * ry[l]
qi = q[v * w + u]
out.append([acc[l] - qi[l] for l in range(nl)])
return out
test_dense_crf.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dense-crf/. The authors are listed in prov/9CMFRH.jsonl.
import math
import random
from dense_crf import (
concave_objective,
dense_crf,
free_energy,
gaussian_messages,
kernel_matrix,
labels_of,
log_partition,
mean_field_sequential,
softmax_neg,
)
def random_problem(rng, w, h, nl, levels=3):
img = [[rng.randrange(levels) * 4 for _ in range(w)] for _ in range(h)]
unary = [[rng.uniform(0.0, 2.0) for _ in range(nl)] for _ in range(w * h)]
return img, unary
def test_row_example():
img = [[0, 0, 10, 10]]
unary = [[-math.log(1 - p), -math.log(p)] for p in (0.2, 0.6, 0.7, 0.9)]
k = kernel_matrix(img, 2.0, 2.0, 3.0, 0.5, 1.0)
assert abs(k[0][1] - 2.0683) < 1e-4 and abs(k[1][2] - 0.3101) < 1e-4
q = dense_crf(unary, k, 1)
assert abs(q[1][1] - 0.3422) < 1e-4
assert labels_of(q) == [0, 0, 1, 1]
q5 = dense_crf(unary, k, 5)
assert labels_of(q5) == [0, 0, 1, 1]
assert abs(free_energy(q5, unary, k) - 1.6484) < 1e-4
assert free_energy(q5, unary, k) >= -log_partition(unary, k)
def test_marginals_are_distributions():
rng = random.Random(11)
img, unary = random_problem(rng, 4, 3, 3)
q = dense_crf(unary, kernel_matrix(img, 1.5, 2.0, 3.0, 1.0, 1.0), 4)
for qi in q:
assert all(x > 0 for x in qi) and abs(sum(qi) - 1.0) < 1e-12
def test_zero_weights_give_the_unary_softmax():
rng = random.Random(12)
img, unary = random_problem(rng, 3, 3, 4)
q = dense_crf(unary, kernel_matrix(img, 0.0, 2.0, 3.0, 0.0, 1.0), 5)
for qi, ui in zip(q, unary):
z = sum(math.exp(-x) for x in ui)
assert all(abs(a - math.exp(-x) / z) < 1e-12 for a, x in zip(qi, ui))
def test_separable_filter_equals_the_naive_sum():
rng = random.Random(13)
w, h, nl, theta = 5, 4, 3, 1.3
q = [softmax_neg([rng.uniform(0, 3) for _ in range(nl)]) for _ in range(w * h)]
k = kernel_matrix([[0] * w for _ in range(h)], 0.0, 1.0, 1.0, 1.0, theta)
fast = gaussian_messages(q, w, h, theta)
for i in range(w * h):
for l in range(nl):
naive = sum(k[i][j] * q[j][l] for j in range(w * h))
assert abs(fast[i][l] - naive) < 1e-12
def test_sequential_updates_never_raise_the_free_energy():
rng = random.Random(14)
for _ in range(5):
img, unary = random_problem(rng, 3, 2, 3)
k = kernel_matrix(img, 3.0, 2.0, 2.0, 2.0, 1.0)
trace = []
q = mean_field_sequential(unary, k, 4, trace)
start = free_energy([softmax_neg(u) for u in unary], unary, k)
values = [start] + trace
assert all(b <= a + 1e-12 for a, b in zip(values, values[1:]))
assert values[-1] >= -log_partition(unary, k) - 1e-12
def test_free_energy_bounds_log_z_and_is_tight_without_coupling():
rng = random.Random(15)
img, unary = random_problem(rng, 4, 2, 2)
k = kernel_matrix(img, 1.0, 2.0, 3.0, 1.0, 1.0)
q = dense_crf(unary, k, 6)
assert free_energy(q, unary, k) >= -log_partition(unary, k)
zero = kernel_matrix(img, 0.0, 2.0, 3.0, 0.0, 1.0)
q0 = dense_crf(unary, zero, 1)
assert abs(free_energy(q0, unary, zero) + log_partition(unary, zero)) < 1e-10
def test_parallel_update_can_oscillate():
# Two pixels with a strong Potts link and opposite unaries swap their beliefs each step.
unary = [[0.0, 1.0], [1.0, 0.0]]
k = kernel_matrix([[0, 0]], 0.0, 1.0, 1.0, 5.0, 3.0)
q = [dense_crf(unary, k, t) for t in range(6)]
assert labels_of(q[1]) == [1, 0] and labels_of(q[2]) == [0, 1]
assert labels_of(q[3]) == [1, 0] and labels_of(q[4]) == [0, 1]
seq = mean_field_sequential(unary, k, 3)
assert labels_of(seq) == [1, 1]
def test_self_term_variant_decreases_its_objective():
rng = random.Random(16)
cases = [([[0, 0]], [[0.0, 1.0], [1.0, 0.0]], (0.0, 1.0, 1.0, 5.0, 3.0))]
for _ in range(4):
img, unary = random_problem(rng, 3, 3, 3)
cases.append((img, unary, (2.0, 1.5, 3.0, 1.0, 1.0)))
for img, unary, (w1, ta, tb, w2, tg) in cases:
k = kernel_matrix(img, w1, ta, tb, w2, tg)
values = [concave_objective(dense_crf(unary, k, t, include_self=w1 + w2), unary, k, w1 + w2) for t in range(8)]
assert all(b <= a + 1e-12 for a, b in zip(values, values[1:]))
def test_denoising_two_regions():
rng = random.Random(17)
w = h = 10
truth = [1 if u >= 5 else 0 for v in range(h) for u in range(w)]
img = [[100 * (1 if u >= 5 else 0) + rng.randint(-10, 10) for u in range(w)] for v in range(h)]
unary = []
for t in truth:
# The probability of the true label: right with chance 0.75, wrong otherwise.
p = rng.uniform(0.55, 0.9) if rng.random() < 0.75 else rng.uniform(0.1, 0.45)
probs = [1 - p, p] if t == 1 else [p, 1 - p]
unary.append([-math.log(x) for x in probs])
k = kernel_matrix(img, 3.0, 3.0, 20.0, 1.0, 1.0)
before = sum(a == b for a, b in zip(labels_of(dense_crf(unary, k, 0)), truth))
after = sum(a == b for a, b in zip(labels_of(dense_crf(unary, k, 5)), truth))
assert before < 90 and after == 100
History
Earlier CRFs for segmentation used pairwise terms between neighbor pixels, or terms over regions, because inference over all pairs of pixels was too slow. Krähenbühl and Koltun (2011) noticed that the mean field messages with Gaussian kernels are a high-dimensional Gaussian filter, and used the permutohedral lattice of Adams, Baek and Davis (2010) to compute them in time linear in the number of pixels. They evaluated the method on the MSRC-21 and PASCAL VOC 2010 data sets. In 2013 they studied the convergence of the parallel update and learned the parameters. The method then became a common post-processing step for semantic segmentation with networks.
References
- Philipp Krähenbühl and Vladlen Koltun, Efficient inference in fully connected CRFs with Gaussian edge potentials, NIPS 24, 109-117, 2011, Section 2 (model, equations 1 to 3), Section 3 (mean field, equations 4 and 5, Algorithms 1 and 2), Section 4 (parameters)
- Philipp Krähenbühl and Vladlen Koltun, Parameter learning and convergent inference for dense random fields, ICML 2013, PMLR 28(3), 513-521, Section 3 (convergence conditions, Sections 3.1 and 3.2)
- Andrew Adams, Jongmin Baek and Abe Davis, Fast high-dimensional filtering using the permutohedral lattice, Computer Graphics Forum 29(2), 753-762, 2010, The permutohedral lattice (splat, blur and slice)
- Martin J. Wainwright and Michael I. Jordan, Graphical models, exponential families, and variational inference, Foundations and Trends in Machine Learning 1(1-2), 2008, Section 5, Mean field methods
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 9CMFRH Edit this page History Report an error Markdown