Algorithmresearch
Variational Bayes blind deconvolution
Also called Fergus blind deblurring.
Estimate a blur kernel by variational Bayes with a sparse gradient prior on the image, averaging over the image instead of taking a joint MAP estimate of image and kernel.
- Solves
- Image deblurring
- Time
- Θ(K (n³ + 2^m m³)) worst · average · best
- Space
- Θ(n²) extra
- Where
- K = the number of passes; m = the number of kernel entries; n = the number of pixels
- Model
- Real RAM
- Properties
- deterministiciterativenot linearmonotone free energyneeds good startnonnegative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- James Miskin, David J. C. MacKay, Rob Fergus, Barun Singh, Aaron Hertzmann, Sam T. Roweis, William T. Freeman, Anat Levin, Yair Weiss, Frédo Durand, 2000
Variational Bayes blind deconvolution estimates an unknown blur kernel from one blurred image by averaging over the unknown sharp image instead of estimating it jointly with . The image gets a sparse prior: most of its gradients are near zero and a few are large. The exact average over the image is not tractable, so the method fits an approximate posterior for the image by variational inference, and alternates between three steps: update for the image gradients, update for the hidden labels of the prior mixture, and set the kernel to the value that fits the data best on average under . Each step increases a lower bound on the log evidence of the kernel, the ELBO, so the bound never falls. The point of the averaging is to avoid a failure of the joint MAP estimate: with a sparse prior, the pair "sharp image equal to the data, no blur" often scores better than the true pair. Miskin and MacKay proposed the variational approach in 2000, and Fergus and coworkers made it work on real photos with camera shake in 2006. After the kernel is found, a non-blind method, such as Richardson-Lucy, recovers the image.
In plain words
A blurred photo can be explained in many ways: a sharp scene behind a wide blur, or a soft scene behind no blur at all. If you ask "which single scene and single blur are most likely together", the soft scene with no blur often wins, because blurring makes an image look smoother, and a prior that likes smooth images is happy with that. The variational method asks a different question: "which blur makes this photo most likely, when we average over all scenes that could be behind it". A blur that is too small needs scenes that are already soft, and few such scenes are typical, so the average penalizes it. The method keeps a cloud of plausible scenes and uses its spread when it picks the blur. Without the spread it is a joint fit again, and it can fall back to "no blur".
The problem
The grid is periodic with pixels and the method works on the gradient of the data. If , then with , because a convolution commutes with a difference. In the code is the forward difference on one dimension; on an image the same steps run on the two gradient images. The model is
- , with the circulant matrix of and ;
- each has a hidden label with , and : a Gaussian mixture with zero means, one narrow component for the flat regions and one wide component for the edges;
- the kernel lies in : , outside a known support of entries, and .
The goal is the kernel with the largest evidence . This is the marginal estimate. The joint MAP estimate instead minimizes over and together, with a data term and a sparse penalty .
The algorithm
The approximate posterior is , and the free energy is . The method maximizes by coordinate ascent over , and .
VB-BLIND(d, k0, T, π, v, σ², K)- 1
k ← k0, zero outside T - 2
w_i ← Σ_j π_j / v_j for every pixel i ▷ prior precision of g_i - 3
repeat K times - 4
S ← (KᵀK/σ² + diag(w))⁻¹; μ ← S Kᵀ d / σ² ▷ q(g) = N(μ, S) - 5
r_ij ∝ π_j v_j^(-1/2) exp(-(μ_i² + S_ii)/(2 v_j)); w_i ← Σ_j r_ij / v_j ▷ q(z) - 6
A, b ← the expected misfit E_q ||d - K g||² as k_Tᵀ A k_T - 2 bᵀ k_T + const - 7
k ← argmin of k_Tᵀ A k_T - 2 bᵀ k_T over k_T ≥ 0, Σ k_T = 1 - 8
return k, μ, S
In line L6, and for . The term with comes from the spread of . Line L7 is a convex quadratic program on the simplex. The code solves it exactly by trying each face of the simplex: on each set of positive entries it solves the KKT system with the sum constraint, keeps the solutions that are feasible, and returns the best one. This costs small solves and is only for small kernels. The "naive" option of the code drops in lines L5 and L6, which turns the method into an alternating joint fit of and with a reweighted quadratic penalty, in the style of iteratively reweighted least squares.
This is the form of Levin and coworkers (2011): a Gaussian for the image, the labels as in expectation maximization, and a point estimate of the kernel. Fergus and coworkers (2006), following Miskin and MacKay, put a prior on the kernel as well and used a fully factorized , with a diagonal covariance, for both. The code keeps the full covariance , which is exact for the step of line L4 but costs .
Example
Joint MAP prefers no blur, exactly. Take the bar on a periodic grid of 5 pixels. Its forward difference is , with norm . Blur it with : , whose difference is , with norm . With the Laplace prior and no noise, the true pair costs and the pair "the gradient is the data, the kernel is " costs . So joint MAP picks no blur, by a factor of 2. This is a special case of for every kernel in (a theorem, Claim 7 of the proof).
A measured run. On a periodic signal of samples with 4 random steps of random heights in , blurred by the kernel on the offsets to , plus Gaussian noise of standard deviation , both versions run 50 passes from the flat kernel , with , and . The table gives the relative error . These are measurements, with the generator of the tests.
| seed | variational (with ) | naive (without ) |
|---|---|---|
| 1 | 0.062 | 0.714 |
| 2 | 0.536 | 0.58 |
| 3 | 0.287 | 0.307 |
| 4 | 0.571 | 0.698 |
| 5 | 0.098 | 1.475 |
| 6 | 0.424 | 0.536 |
The delta kernel has the error 1.475, so on seed 5 the naive estimate ends exactly at "no blur". On seed 1 the variational kernel is . The variational estimate is better on all six seeds, but on seeds 2, 4 and 6 it is still far from the truth: 24 samples with 4 edges hold little information about a kernel of 5 entries. On signals of 36 samples with 5 steps and 30 passes it was better on 5 of 6 seeds. The free energy did not decrease in any run, as the theory says.
Correctness
The full proof is in the proofs file. Lines L4 and L5 are the exact maximizers of over and (Claims 1 and 2). The expected misfit in line L6 is a convex quadratic in the kernel (Claim 3), and the face enumeration of line L7 finds its exact minimizer on the simplex (Claim 4). So each line is an exact coordinate ascent step, never decreases, and it is bounded above by the largest log evidence, so the values converge (Claim 5). With one mixture component the bound is tight, (Claim 6). Joint MAP with a Laplace prior prefers to the true pair on noise-free data (Claim 7). When the covariance term is , which is largest at the delta kernels (Claim 8). The proof does not show that the kernel converges, or that it converges to the kernel of largest evidence: is not concave in jointly, and the bound is not tight for a mixture prior. That the covariance term keeps the estimate away from in general is a heuristic, supported by the measurements above.
Proof: Each step of the variational kernel estimate maximizes the free energy exactly, so the free energy never decreases, while joint MAP with a Laplace prior prefers no blurfull
Setting. On a periodic grid of points, with , where is the circulant matrix of the kernel , . The kernel lies in for a support set of offsets. Each has a hidden label with and , all independent. For a distribution the free energy is
The second form follows from . So , with equality exactly when is the posterior. The algorithm is lines L1 to L8 of the page.
Claim 1 (the step for ). For fixed with and fixed , the maximizer of over all densities is with
Proof. The terms of that depend on are with . This equals , which is largest exactly at . Up to terms free of , , a concave quadratic whose Hessian is and whose maximum is at . So is proportional to the density of . is positive definite because .
Claim 2 (the step for ). For fixed and , the maximizer over all is the product over of .
Proof. The same argument with and . The sum over makes a product, so the optimal factors over the pixels.
Claim 3 (the step for ). For fixed , depends on only through , and
where lists the values of on , and for . is positive semidefinite, so line L7 solves a convex quadratic program over the simplex.
Proof. With , and , , and . Writing and expanding gives the stated and . For any vector on , .
Claim 4 (the quadratic program is solved exactly). Let be symmetric positive semidefinite and the simplex. The routine simplex_qp returns a minimizer of over (with replaced by , , which makes it strictly convex and the minimizer unique).
Proof. is strictly convex, so it has one minimizer on the compact convex set . Let be the set of coordinates where . Then lies in the relative interior of the face , and it minimizes over the affine set : if some point of that affine set had a lower value, the segment from toward it would stay in for a short distance and, by convexity, lower there. The minimizer over the affine set is the solution of the KKT system that the routine solves for , and it is unique by strict convexity. So is one of the candidates. Every candidate that the routine keeps is a point of , so its value is at least , and the routine returns the candidate of least value, which is .
Claim 5 (the free energy never decreases). Along lines L4, L5 and L7, the value of never decreases, and it is bounded above by . So the values converge.
Proof. By Claims 1 to 4 each line replaces one block of by a maximizer of over that block with the others fixed; a maximizer is at least as good as the current value. The bound is . is continuous in on the compact set (it is a finite mixture of Gaussian densities whose covariances are at least ), so it has a maximum. A nondecreasing sequence that is bounded above converges.
This is a statement about the values of ; it does not say that the kernels converge, or that they converge to the kernel of largest evidence. The tests check the monotone values on a run.
Claim 6 (the bound is tight for a Gaussian prior). If , the step of Claim 1 makes .
Proof. With one component is fixed and is the Gaussian of Claim 1, so the KL term is . Integrating out of gives the stated Gaussian.
Claim 7 (joint MAP with a Laplace prior prefers no blur). For and every , . So if without noise, the joint MAP cost satisfies : the pair "the data are sharp and there is no blur" is at least as good as the true pair.
Proof. , by the triangle inequality, and . Then .
The inequality is strict as soon as the blur mixes values of opposite sign, for example at a thin bar.
Claim 8 (what the covariance term adds). If , then . On , , with equality only at the vertices, the delta kernels.
Proof. is the sum of the squares of all entries of the circulant , and each of its rows holds the values of once. On the simplex , with equality only when one entry is .
So in the simplest case the covariance term of Claim 3 is a penalty on , which is largest at the delta kernels. The "naive" estimate of the code sets in lines L5 and L6, which removes this penalty and also uses in place of . For a general the term is not a multiple of , and its effect is a heuristic explanation, not a theorem; the tests record, as a measurement, one run where the naive estimate ends at the delta kernel and the variational one does not.
Complexity
Line L4 factors a dense matrix, . Lines L5 and L6 cost and with the covariance entries that line L6 needs. Line L7 tries faces with a solve of size up to , . So passes cost , and the dense covariance needs space. This is for small tests only. Practical codes keep only the diagonal of , compute by conjugate gradients with FFT products in per product, solve the kernel step with a projected or active set QP solver in time polynomial in , and work from coarse to fine scales of the image.
Properties
- The free energy never decreases along the steps (theorem). The kernel sequence has no proved limit.
- The kernel is nonnegative, zero outside its support and of sum 1 after every pass.
- The estimate depends on the start kernel, on the prior , on and on the support.
- Without the covariance term the method is a joint fit, and it can end at the delta kernel (measured on seed 5).
- It estimates only the kernel. The image comes from a separate non-blind step.
Variants and improvements
- Fully factorized ensemble learning. Miskin and MacKay (2000) and Fergus and coworkers (2006) use a that factors over all pixels and kernel entries, with priors on both, and a coarse to fine scheme over image scales.
- EM with a point kernel. Levin and coworkers (2011) keep Gaussian and estimate as a point, as here, and approximate by its diagonal. They report that this is simpler than the fully factorized method and gives results of similar quality.
- Other sparse priors. A total variation prior in a variational frame (Babacan and coworkers, 2009), Student t priors, and priors learned from natural images.
- Joint MAP with tricks. Methods that alternate sharp image and kernel estimates can still work if they add edge prediction, shock filters or a careful schedule of the weight . Levin and coworkers (2009) discuss why these tricks are needed.
- Laplace and other approximations. The Laplace approximation and empirical Bayes give other ways to approximate the evidence of the kernel.
When to use it
Use it to estimate a camera shake or defocus kernel from one photo when no calibration is available and the scene has some strong edges. Estimate the kernel on a region with edges, then deblur the full image with a non-blind method. Do not use it when the kernel varies across the image, when the image has few edges, or when the noise is strong; and do not use the dense form of this page on images of more than a few hundred pixels. When a star or a calibration target is in the field, measure the PSF there instead.
Pitfalls
- Dropping the covariance term, even by accident through a diagonal approximation that is too crude, can send the estimate to the delta kernel.
- The support must contain the true kernel. A support that is too large makes the problem worse posed, so practical codes start small at a coarse scale and grow it.
- The gradient of white noise is not white; the model treats it as white. This is a modelling simplification, and is a tuning value rather than a known noise level.
- The kernel is found only up to a shift, together with an opposite shift of the image; compare kernels after centering them.
- The free energy rises, but a rising bound does not mean a better kernel. The measured runs on seeds 2, 4 and 6 end far from the truth with a monotone bound.
- The face enumeration of the code grows as ; use a real QP solver for larger kernels.
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
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).
A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""
import math
def _flat(x):
"""Flatten a list of rows (an image) into one list; a vector is returned as is."""
if x and isinstance(x[0], (list, tuple)):
return [v for row in x for v in row]
return x
def zeros(m, n):
"""The m x n zero matrix."""
return [[0.0] * n for _ in range(m)]
def eye(n):
"""The n x n identity matrix."""
out = zeros(n, n)
for i in range(n):
out[i][i] = 1.0
return out
def transpose(a):
"""A^T."""
return [list(col) for col in zip(*a)]
def conj_transpose(a):
"""A^H, the conjugate transpose."""
return [[v.conjugate() for v in col] for col in zip(*a)]
def matmul(a, b):
"""The product A B."""
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""The product A x."""
return [sum(v * w for v, w in zip(row, x)) for row in a]
def rmatvec(a, y):
"""The product A^H y."""
n = len(a[0]) if a else 0
out = [0.0] * n
for row, yi in zip(a, y):
if yi == 0:
continue
for j, v in enumerate(row):
out[j] += v.conjugate() * yi
return out
def dot(u, v):
"""<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))
def norm2(x):
"""The Euclidean norm. Images (lists of rows) are flattened."""
return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))
def solve(a, b):
"""Solve A x = b by Gaussian elimination with partial pivoting.
b is a vector or a matrix (a list of rows). A must be square and
nonsingular; a zero pivot raises ValueError. Fractions stay exact.
"""
n = len(a)
vec = not (b and isinstance(b[0], (list, tuple)))
rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
m = [list(row) + rhs[i] for i, row in enumerate(a)]
w = len(m[0])
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[p][c] == 0:
raise ValueError("singular matrix")
m[c], m[p] = m[p], m[c]
piv = m[c][c]
for r in range(c + 1, n):
f = m[r][c] / piv
if f != 0:
mr, mc = m[r], m[c]
for j in range(c, w):
mr[j] -= f * mc[j]
x = [[0.0] * (w - n) for _ in range(n)]
for r in range(n - 1, -1, -1):
for j in range(w - n):
s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
x[r][j] = s / m[r][r]
return [row[0] for row in x] if vec else x
def cholesky(a):
"""Lower triangular L with A = L L^H for a Hermitian positive definite A."""
n = len(a)
low = zeros(n, n)
for j in range(n):
d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
d = d.real if isinstance(d, complex) else d
if not d > 0:
raise ValueError("matrix is not positive definite")
ljj = math.sqrt(d)
low[j][j] = ljj
for i in range(j + 1, n):
s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
low[i][j] = s / ljj
return low
def cho_solve(low, b):
"""Solve (L L^H) x = b, with L from cholesky."""
n = len(low)
z = [0.0] * n
for i in range(n):
z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
x[i] = s / low[i][i].conjugate()
return x
def _rot_params(app, aqq, apq):
"""c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
theta = (aqq - app) / (2.0 * apq)
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(1.0 + t * t)
return c, c * t
def sym_eig(a, tol=1e-15, max_sweeps=100):
"""Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.
Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
"""
n = len(a)
m = [[float(v) for v in row] for row in a]
q = eye(n)
for _ in range(max_sweeps):
off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
scale = sum(m[i][i] ** 2 for i in range(n)) + off
if off <= (tol * tol) * scale or off == 0.0:
break
for p in range(n - 1):
for r in range(p + 1, n):
apq = m[p][r]
if apq == 0.0:
continue
c, s = _rot_params(m[p][p], m[r][r], apq)
for k in range(n):
mkp, mkr = m[k][p], m[k][r]
m[k][p] = c * mkp - s * mkr
m[k][r] = s * mkp + c * mkr
mp, mr = m[p], m[r]
for k in range(n):
mpk, mrk = mp[k], mr[k]
mp[k] = c * mpk - s * mrk
mr[k] = s * mpk + c * mrk
m[p][r] = m[r][p] = 0.0
for k in range(n):
qkp, qkr = q[k][p], q[k][r]
q[k][p] = c * qkp - s * qkr
q[k][r] = s * qkp + c * qkr
order = sorted(range(n), key=lambda i: m[i][i])
w = [m[i][i] for i in order]
qs = [[q[k][i] for i in order] for k in range(n)]
return w, qs
def _complete(cols, m):
"""Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
for idx, col in enumerate(cols):
if any(v != 0.0 for v in col):
continue
for e in range(m):
cand = [0.0] * m
cand[e] = 1.0
for _ in range(2):
for jdx, other in enumerate(cols):
if jdx == idx or not any(v != 0.0 for v in other):
continue
h = sum(a * b for a, b in zip(other, cand))
cand = [a - h * b for a, b in zip(cand, other)]
nrm = math.sqrt(sum(v * v for v in cand))
if nrm > 0.5:
cols[idx] = [v / nrm for v in cand]
break
return cols
def svd(a, tol=1e-15, max_sweeps=100):
"""Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).
Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
"""
m, n = len(a), len(a[0])
if m < n:
v, s, u = svd(transpose(a), tol, max_sweeps)
return u, s, v
cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
for _ in range(max_sweeps):
rotated = False
for p in range(n - 1):
for r in range(p + 1, n):
cp, cr = cols[p], cols[r]
alpha = sum(x * x for x in cp)
beta = sum(x * x for x in cr)
gamma = sum(x * y for x, y in zip(cp, cr))
if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
continue
rotated = True
c, s = _rot_params(alpha, beta, gamma)
cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
vp, vr = vcols[p], vcols[r]
vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
if not rotated:
break
sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
# A column below 1e-150 times the largest one is zero to working precision;
# its squares underflow, so its direction carries no information.
floor = max(sig) * 1e-150 if sig else 0.0
sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
order = sorted(range(n), key=lambda j: -sig[j])
s_out = [sig[j] for j in order]
ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
ucols = _complete(ucols, m)
u = [[ucols[j][i] for j in range(n)] for i in range(m)]
v = [[vcols[j][i] for j in order] for i in range(n)]
return u, s_out, v
def adjoint_gap(apply_a, apply_ah, x, y):
"""|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.
x and y may be vectors or images (lists of rows). If the denominator is
zero, the absolute gap is returned.
"""
ax = apply_a(x)
gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
den = norm2(ax) * norm2(y)
return gap / den if den > 0.0 else gap
variational_bayes_blind_deconvolution.py 188 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variational-bayes-blind-deconvolution/. The authors are listed in prov/JZ0W9B.jsonl.
"""Blind deconvolution by variational Bayes in the gradient domain.
The model follows Fergus et al. (2006) in one dimension, with the kernel as a
point estimate as in Levin et al. (2011). On a periodic grid of n points,
d = k * g + e, e ~ N(0, sigma2 I),
where d is the gradient of the blurred signal, g the unknown gradient of the
sharp signal and k the unknown kernel (centered at index 0, k >= 0, zero
outside a support, sum 1). Each g_i is drawn from a mixture of zero mean
Gaussians with weights pi_j and variances v_j, through a hidden label z_i.
The method maximizes the free energy (the evidence lower bound)
F(q, k) = E_q[log p(d, g, z | k)] + H[q], q(g, z) = q(g) q(z),
by exact coordinate steps: q(g) is a full Gaussian N(mu, S), q(z) is a table
of label probabilities r[i][j], and k minimizes the expected misfit
E_q ||d - k * g||^2, which includes the covariance S of g. Dropping S gives
the "naive" joint estimate, which the tests compare with.
"""
import math
from itertools import combinations
from imgla import cho_solve, cholesky, solve
def gradient(y):
"""Periodic forward difference: d_i = y_{i+1} - y_i."""
n = len(y)
return [y[(i + 1) % n] - y[i] for i in range(n)]
def conv(k, g):
"""(k * g)_r = sum_s k_s g_{r - s}, indices modulo n."""
n = len(g)
return [sum(k[s] * g[(r - s) % n] for s in range(n) if k[s] != 0) for r in range(n)]
def kernel_matrix(k):
"""The circulant matrix K with K g = k * g."""
n = len(k)
return [[k[(r - c) % n] for c in range(n)] for r in range(n)]
def update_q_g(d, k, w, sigma2):
"""The optimal Gaussian q(g) = N(mu, S) for fixed q(z) (precisions w) and k.
S^{-1} = K^T K / sigma2 + diag(w), mu = S K^T d / sigma2.
Returns (mu, S, logdet of S^{-1}).
"""
n = len(d)
km = kernel_matrix(k)
prec = [[sum(km[r][a] * km[r][b] for r in range(n)) / sigma2 for b in range(n)] for a in range(n)]
for i in range(n):
prec[i][i] += w[i]
low = cholesky(prec)
ktd = [sum(km[r][a] * d[r] for r in range(n)) / sigma2 for a in range(n)]
mu = cho_solve(low, ktd)
cols = [cho_solve(low, [1.0 if i == j else 0.0 for i in range(n)]) for j in range(n)]
cov = [[cols[j][i] for j in range(n)] for i in range(n)]
logdet = 2.0 * sum(math.log(low[i][i]) for i in range(n))
return mu, cov, logdet
def second_moments(mu, cov, use_cov=True):
"""E[g_i^2] = mu_i^2 + S_ii (or mu_i^2 alone for the naive estimate)."""
return [m * m + (cov[i][i] if use_cov else 0.0) for i, m in enumerate(mu)]
def update_q_z(m2, pi, v):
"""Label probabilities r[i][j] proportional to pi_j N-density with variance v_j at E[g_i^2].
Returns (r, w) with w_i = sum_j r[i][j] / v_j, the expected precision of g_i.
"""
r, w = [], []
for e in m2:
logs = [math.log(p) - 0.5 * math.log(vj) - e / (2.0 * vj) for p, vj in zip(pi, v)]
top = max(logs)
ex = [math.exp(t - top) for t in logs]
s = sum(ex)
ri = [t / s for t in ex]
r.append(ri)
w.append(sum(a / vj for a, vj in zip(ri, v)))
return r, w
def kernel_quadratic(d, mu, cov, support, use_cov=True):
"""A and b with E_q ||d - k * g||^2 = k^T A k - 2 b^T k + const over the support offsets."""
n = len(d)
a = [[0.0] * len(support) for _ in support]
b = [0.0] * len(support)
for p, s in enumerate(support):
b[p] = sum(d[r] * mu[(r - s) % n] for r in range(n))
for q, t in enumerate(support):
val = sum(mu[(r - s) % n] * mu[(r - t) % n] for r in range(n))
if use_cov:
val += sum(cov[(r - s) % n][(r - t) % n] for r in range(n))
a[p][q] = val
return a, b
def simplex_qp(a, b, ridge=1e-12):
"""Exact minimizer of k^T A k - 2 b^T k over k >= 0, sum k = 1 (A symmetric PSD).
The minimizer lies in the relative interior of some face of the simplex. For
each face (a nonempty subset T of the coordinates) solve the problem with the
equality constraints only, keep the solutions with k_T >= 0, and return the best.
"""
m = len(b)
best, best_val = None, math.inf
for size in range(1, m + 1):
for t in combinations(range(m), size):
# KKT system: 2 A_TT k_T + lam 1 = 2 b_T, 1^T k_T = 1.
mat = [[2.0 * a[i][j] + (2.0 * ridge if i == j else 0.0) for j in t] + [1.0] for i in t]
mat.append([1.0] * size + [0.0])
rhs = [2.0 * b[i] for i in t] + [1.0]
try:
sol = solve(mat, rhs)
except ValueError:
continue
if min(sol[:size]) < -1e-12:
continue
k = [0.0] * m
for i, v in zip(t, sol[:size]):
k[i] = max(v, 0.0)
tot = sum(k)
k = [v / tot for v in k]
val = sum(k[i] * a[i][j] * k[j] for i in range(m) for j in range(m)) - 2.0 * sum(bi * ki for bi, ki in zip(b, k))
if val < best_val:
best, best_val = k, val
return best
def free_energy(d, k, mu, cov, logdet_prec, r, pi, v, sigma2):
"""F = E_q[log p(d | g, k)] + E_q[log p(g | z)] + E_q[log p(z)] + H[q(g)] + H[q(z)]."""
n = len(d)
km = kernel_matrix(k)
res = [di - sum(km[i][j] * mu[j] for j in range(n)) for i, di in enumerate(d)]
ksk = sum(km[i][a] * cov[a][b] * km[i][b] for i in range(n) for a in range(n) for b in range(n) if km[i][a] and km[i][b])
lik = -0.5 * n * math.log(2 * math.pi * sigma2) - (sum(t * t for t in res) + ksk) / (2 * sigma2)
m2 = second_moments(mu, cov)
prior = 0.0
ent_z = 0.0
for e, ri in zip(m2, r):
for p, vj, rij in zip(pi, v, ri):
if rij > 0:
prior += rij * (math.log(p) - 0.5 * math.log(2 * math.pi * vj) - e / (2 * vj))
ent_z -= rij * math.log(rij)
ent_g = 0.5 * n * math.log(2 * math.pi * math.e) - 0.5 * logdet_prec
return lik + prior + ent_g + ent_z
def embed(kv, support, n):
"""The full length n kernel with values kv at the support offsets (taken modulo n)."""
k = [0.0] * n
for s, val in zip(support, kv):
k[s % n] += val
return k
def vb_blind(d, k0, support, pi, v, sigma2, iters=20, use_cov=True, history=None):
"""Variational EM for the kernel. Returns (k, mu, cov) with k of length n.
k0: the start kernel on the support offsets. use_cov=False gives the naive
estimate, which ignores the uncertainty of g. If history is a list, the
free energy after each of the three steps is appended (for use_cov=True).
"""
n = len(d)
track = history is not None and use_cov
k = embed(k0, support, n) # @line L1
w = [sum(p / vj for p, vj in zip(pi, v))] * n # @line L2
r = mu = cov = None
for it in range(iters): # @line L3
mu, cov, logdet = update_q_g(d, k, w, sigma2) # @line L4
if track and it > 0:
history.append(free_energy(d, k, mu, cov, logdet, r, pi, v, sigma2))
r, w = update_q_z(second_moments(mu, cov, use_cov), pi, v) # @line L5
if track:
history.append(free_energy(d, k, mu, cov, logdet, r, pi, v, sigma2))
a, b = kernel_quadratic(d, mu, cov, support, use_cov) # @line L6
k = embed(simplex_qp(a, b), support, n) # @line L7
if track:
history.append(free_energy(d, k, mu, cov, logdet, r, pi, v, sigma2))
return k, mu, cov # @line L8
test_variational_bayes_blind_deconvolution.py 186 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variational-bayes-blind-deconvolution/. The authors are listed in prov/JZ0W9B.jsonl.
import math
import random
from imgla import cholesky, cho_solve, matmul, transpose
from variational_bayes_blind_deconvolution import (
conv,
embed,
free_energy,
gradient,
kernel_matrix,
kernel_quadratic,
second_moments,
simplex_qp,
update_q_g,
update_q_z,
vb_blind,
)
SUPPORT = [-2, -1, 0, 1, 2]
K_TRUE = [0.1, 0.3, 0.35, 0.15, 0.1]
PI, V, SIGMA2 = (0.9, 0.1), (1e-3, 1.0), 2e-4
def problem(seed, n=24, jumps=4, noise=0.01):
"""A piecewise constant periodic signal with `jumps` steps, blurred by K_TRUE, plus noise."""
rng = random.Random(seed)
x = [0.0] * n
pos = sorted(rng.sample(range(n), jumps))
levels = [rng.uniform(0, 2) for _ in pos]
for idx, p in enumerate(pos):
q = pos[(idx + 1) % jumps]
i = p
while True:
x[(i + 1) % n] = levels[idx]
i = (i + 1) % n
if i == q:
break
k = embed(K_TRUE, SUPPORT, n)
y = [v + rng.gauss(0, noise) for v in conv(k, x)]
return x, k, y
def rel_err(a, b):
return math.sqrt(sum((p - q) ** 2 for p, q in zip(a, b)) / sum(q * q for q in b))
def random_state(seed, n=10):
rng = random.Random(seed)
d = [rng.gauss(0, 1) for _ in range(n)]
k = embed([rng.random() for _ in SUPPORT], SUPPORT, n)
s = sum(k)
k = [v / s for v in k]
w = [rng.uniform(0.5, 50.0) for _ in range(n)]
return d, k, w
def test_blur_commutes_with_the_gradient_and_matches_the_matrix():
rng = random.Random(1)
n = 12
x = [rng.random() for _ in range(n)]
k = embed([rng.random() for _ in SUPPORT], SUPPORT, n)
a, b = gradient(conv(k, x)), conv(k, gradient(x))
assert max(abs(p - q) for p, q in zip(a, b)) < 1e-13
km = kernel_matrix(k)
assert max(abs(sum(km[r][c] * x[c] for c in range(n)) - v) for r, v in enumerate(conv(k, x))) < 1e-13
def test_q_g_is_the_gaussian_with_the_right_mean_and_covariance():
d, k, w = random_state(2)
n = len(d)
mu, cov, logdet = update_q_g(d, k, w, SIGMA2)
km = kernel_matrix(k)
prec = matmul(transpose(km), km)
prec = [[prec[i][j] / SIGMA2 + (w[i] if i == j else 0.0) for j in range(n)] for i in range(n)]
eye = matmul(prec, cov)
assert max(abs(eye[i][j] - (1.0 if i == j else 0.0)) for i in range(n) for j in range(n)) < 1e-9
# mu minimizes ||d - K g||^2 / (2 sigma2) + sum w_i g_i^2 / 2: the gradient is zero.
res = [di - v for di, v in zip(d, conv(k, mu))]
grad = [-sum(km[r][a] * res[r] for r in range(n)) / SIGMA2 + w[a] * mu[a] for a in range(n)]
assert max(abs(t) for t in grad) < 1e-6 * max(abs(t) for t in d) / SIGMA2
low = cholesky(prec)
assert abs(logdet - 2 * sum(math.log(low[i][i]) for i in range(n))) < 1e-9
def test_label_probabilities_are_normalized_and_follow_bayes_rule():
m2 = [0.0, 1e-4, 0.01, 0.5, 3.0]
r, w = update_q_z(m2, PI, V)
for e, ri, wi in zip(m2, r, w):
dens = [p / math.sqrt(2 * math.pi * v) * math.exp(-e / (2 * v)) for p, v in zip(PI, V)]
assert abs(sum(ri) - 1.0) < 1e-12
assert all(abs(a - b / sum(dens)) < 1e-12 for a, b in zip(ri, dens))
assert abs(wi - sum(a / v for a, v in zip(ri, V))) < 1e-9 * wi
def test_kernel_quadratic_equals_the_expected_misfit():
d, k0, w = random_state(3)
n = len(d)
mu, cov, _ = update_q_g(d, k0, w, SIGMA2)
a, b = kernel_quadratic(d, mu, cov, SUPPORT)
rng = random.Random(4)
kv = [rng.random() for _ in SUPPORT]
k = embed(kv, SUPPORT, n)
km = kernel_matrix(k)
res = [di - v for di, v in zip(d, conv(k, mu))]
trace = sum(km[i][p] * cov[p][q] * km[i][q] for i in range(n) for p in range(n) for q in range(n))
expected = sum(t * t for t in res) + trace
quad = sum(kv[p] * a[p][q] * kv[q] for p in range(5) for q in range(5)) - 2 * sum(bp * kp for bp, kp in zip(b, kv))
assert abs(quad + sum(t * t for t in d) - expected) < 1e-9 * expected
def test_simplex_qp_beats_random_points_of_the_simplex():
rng = random.Random(5)
for _ in range(5):
m = rng.choice([2, 3, 5])
g = [[rng.gauss(0, 1) for _ in range(m + 1)] for _ in range(m)]
a = [[sum(g[i][t] * g[j][t] for t in range(m + 1)) for j in range(m)] for i in range(m)]
b = [rng.gauss(0, 1) for _ in range(m)]
k = simplex_qp(a, b)
assert min(k) >= 0 and abs(sum(k) - 1) < 1e-12
def f(z):
return sum(z[i] * a[i][j] * z[j] for i in range(m) for j in range(m)) - 2 * sum(p * q for p, q in zip(b, z))
best = f(k)
for _ in range(2000):
z = [rng.expovariate(1.0) for _ in range(m)]
if rng.random() < 0.5:
z[rng.randrange(m)] = 0.0
s = sum(z)
if s == 0:
continue
assert f([t / s for t in z]) >= best - 1e-10
def test_free_energy_equals_the_log_evidence_for_a_gaussian_prior():
# One mixture component: the model is linear and Gaussian, and the optimal
# q(g) makes the bound tight: F = log N(d; 0, v K K^T + sigma2 I).
d, k, _ = random_state(6, n=8)
n = len(d)
v = 0.7
mu, cov, logdet = update_q_g(d, k, [1.0 / v] * n, SIGMA2)
r, _ = update_q_z(second_moments(mu, cov), (1.0,), (v,))
f = free_energy(d, k, mu, cov, logdet, r, (1.0,), (v,), SIGMA2)
km = kernel_matrix(k)
c = matmul(km, transpose(km))
c = [[v * c[i][j] + (SIGMA2 if i == j else 0.0) for j in range(n)] for i in range(n)]
low = cholesky(c)
z = cho_solve(low, d)
log_ev = -0.5 * n * math.log(2 * math.pi) - sum(math.log(low[i][i]) for i in range(n)) - 0.5 * sum(p * q for p, q in zip(d, z))
assert abs(f - log_ev) < 1e-7 * abs(log_ev)
def test_free_energy_never_decreases():
_, _, y = problem(2)
hist = []
vb_blind(gradient(y), [0.2] * 5, SUPPORT, PI, V, SIGMA2, iters=10, history=hist)
assert len(hist) == 29
assert all(hist[i + 1] >= hist[i] - 1e-9 * abs(hist[i]) for i in range(len(hist) - 1))
def test_joint_map_with_a_laplace_prior_prefers_no_blur():
# ||k * g||_1 <= ||g||_1 for k >= 0 with sum 1, so with noise-free data the
# pair (d, delta) costs no more than the true pair under lam ||g||_1.
rng = random.Random(7)
for _ in range(200):
n = rng.randint(4, 16)
g = [rng.gauss(0, 1) if rng.random() < 0.4 else 0.0 for _ in range(n)]
kv = [rng.random() for _ in SUPPORT]
s = sum(kv)
k = embed([t / s for t in kv], SUPPORT, n)
d = conv(k, g)
assert sum(abs(t) for t in d) <= sum(abs(t) for t in g) + 1e-12
def test_measured_marginal_estimate_beats_the_naive_one_on_seed_5():
# A measurement: with the covariance term the kernel is close to the truth;
# without it the estimate collapses to the delta kernel.
_, kt, y = problem(5)
d = gradient(y)
k, _, _ = vb_blind(d, [0.2] * 5, SUPPORT, PI, V, SIGMA2, iters=50)
k_naive, _, _ = vb_blind(d, [0.2] * 5, SUPPORT, PI, V, SIGMA2, iters=50, use_cov=False)
assert rel_err(k, kt) < 0.15
assert k_naive[0] > 0.99
History
Blind deconvolution by alternating fits of image and kernel goes back to the 1980s, with methods such as Ayers-Dainty, which have no noise model and no prior. In 2000 Miskin and MacKay applied ensemble learning, a form of variational Bayes, to blind separation and deconvolution of images. In 2006 Fergus, Singh, Hertzmann, Roweis and Freeman used it with a mixture prior on image gradients and a coarse to fine scheme, and removed camera shake from real photos; this made the approach widely known. Levin, Weiss, Durand and Freeman (2009) analysed why the joint MAP estimate with a sparse prior prefers no blur, while the marginal estimate of the kernel does not, and in 2011 they gave a simpler EM form. Babacan, Molina and Katsaggelos (2009) and others extended the variational frame to other priors.
References
- Miskin and MacKay 2000, the chapter (the variational free energy for an unknown image and an unknown kernel)
- Fergus et al. 2006, pages 787 to 794 (the mixture prior on gradients, the variational kernel estimate and the coarse to fine scheme)
- Levin et al. 2009, pages 1964 to 1971 (why joint MAP of image and kernel prefers no blur, and why the marginal estimate of the kernel does not)
- Levin et al. 2011, the article (the EM form with a Gaussian q for the image and a point estimate of the kernel)
- Babacan et al. 2009, the article (a total variation prior in the same variational frame)
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 JZ0W9B Edit this page History Report an error Markdown