Techniqueresearch
Bilevel learning of regularizers
Also called bilevel parameter learning.
Learn the parameters of a variational regularizer by minimizing the error of its reconstructions on training data, a bilevel optimization problem.
Bilevel learning chooses the parameters of a variational reconstruction method from training pairs , with . The lower level is the reconstruction itself, and the upper level scores it against the true images:
The parameters can be one regularization weight, weights of several penalties, filters inside the regularizer, or weights of the data terms. Haber and Tenorio (2003) set this up for inverse problems, and Kunisch and Pock (2013) and De los Reyes and Schönlieb (2013) developed it for variational image models. The gradient of comes from the implicit function theorem and one adjoint solve per pair.
In plain words
A variational method has knobs, such as how strongly to smooth. Normally a person sets them by hand or by a rule that uses only the measured data. Bilevel learning sets them from examples where the true image is known. For each candidate setting, it runs the reconstruction on the examples and measures how far the results are from the true images. Then it changes the setting in the direction that makes this error smaller. The inner reconstruction is an optimization problem, and the outer search is another one, which is why it is called bilevel.
When it applies
Setting. The lower-level energy is twice differentiable in and differentiable in , and has a unique minimizer with an invertible Hessian . The training pairs come from the same source as the data to be reconstructed.
Fact 1 (the gradient, by the implicit function theorem). The minimizer satisfies . Differentiating in gives
So for the upper loss , solve the adjoint system , and then
This is a theorem under the conditions above. Each pair needs one lower-level solve and one linear solve with , whatever the number of parameters.
Fact 2 (Tikhonov). For , the minimizer solves , and Fact 1 gives
Both levels are then exact, which makes Tikhonov the test case.
Fact 3 (what is learned). In the scalar model , with , the expected upper loss of is
which is smallest at , with the value , the posterior variance. So with many pairs, bilevel learning recovers the weight of the Bayes estimator for a linear Gaussian problem. With few pairs, it fits those pairs.
Use bilevel learning when there are training pairs and the regularizer has few, meaningful parameters, so that the learned method stays a variational method that can be analyzed. If the regularizer is nonsmooth, such as total variation, smooth it first or use a nonsmooth analysis; Kunisch and Pock and De los Reyes and Schönlieb treat such cases.
The template
BILEVEL-LEARN(pairs (x_i, y_i), LOWER, α_0, η, K)- 1
α ← α_0 - 2
for k = 1 to K - 3
g ← 0 - 4
for each pair (x_i, y_i), i = 1 to N - 5
x ← LOWER(α, y_i) ▷ hole: the lower-level solver, a given function - 6
g ← g + (2/N) ⟨dx/dα, x - x_i⟩ ▷ adjoint solve, Fact 1 - 7
α ← max(α - η g, 0) ▷ projected gradient step - 8
return α
The holes are the lower-level energy and its solver, the parameters, the upper loss and the outer optimizer. The template learns one weight by projected gradient descent; for many parameters, becomes a vector and the outer optimizer is often a quasi-Newton method. Each outer step costs lower-level solves and adjoint solves. If the lower level is solved only approximately, the gradient is approximate too, and the outer method needs a solve accuracy that grows as it converges.
The lower-level solver and the product are given functions: the code takes them as arguments and runs lines L1 to L8 around them. The tests build them by hand, for Tikhonov in closed form by Fact 2 or as for a scalar problem, and draw the training pairs from fixed seeds; no network is trained. They check the hand example below, that the projection keeps at 0 when the data asks for less than no smoothing, the adjoint gradient against finite differences, that the learned weight matches a grid search on a seeded problem, and Fact 3 on 2000 seeded pairs.
Classic examples
One pair by hand. Let , and . Then and . At : , , by Fact 2, and . The minimizer is , where and ; projected gradient descent with reaches it from . With instead, every shrinks the estimate further from 1, so the learned weight is , with .
Many scalar pairs. Draw 2000 pairs with and (seed 6). Fact 3 predicts and a loss of 0.2 for infinitely many pairs. The learned weight is 0.2677, which equals the exact minimizer for this sample. The difference from 0.25 is sampling error, a measurement for this seed.
A seeded matrix problem. A Gaussian matrix, four training pairs and noise of standard deviation 0.5 (seed 5). Projected gradient descent from with lowers the loss from 0.340 to 0.255 and stops at , which matches a grid search with spacing .
Image models. Kunisch and Pock learn the weights of filter-based regularizers for denoising, and De los Reyes and Schönlieb learn the weights of the data terms for mixed noise. Their results on test images are measurements.
Variations
- Many parameters. Learn filters and penalty functions inside the regularizer, as in Kunisch and Pock. Fact 1 still needs only one adjoint solve per pair.
- Unrolled lower level. Replace the exact minimizer by steps of a solver and backpropagate through them. This is algorithm unrolling, and the learned parameters may then depend on .
- Learning the data term. Learn the weights of several noise models, as De los Reyes and Schönlieb do.
- Without true images. Replace the upper loss by an unbiased estimate of the error, such as the Stein unbiased risk estimate, or by cross-validation on the data.
Pitfalls
- Nonsmooth lower levels. With total variation or an penalty, is not differentiable everywhere and Fact 1 does not apply as written. Smooth the penalty, or use a nonsmooth calculus.
- Inexact lower-level solves. An inaccurate gives an inaccurate gradient. Check the gradient against finite differences on a small case.
- Nonconvex upper level. is not convex in general, so the outer method can stop at a local minimizer.
- Overfitting. With few pairs and many parameters, the learned method fits the training images. Keep test pairs apart.
- Positivity. Weights such as must stay nonnegative. Project, or learn instead.
Code
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/bilevel-learning-of-regularizers/. The authors are listed in prov/VE2JDY.jsonl.
"""Bilevel learning of a regularization weight.
Upper level: L(alpha) = (1/N) sum_i ||x_alpha(y_i) - x_i||^2 over training
pairs (x_i, y_i). Lower level: x_alpha(y) minimizes the variational energy
with weight alpha. The lower-level solver and the derivative of its solution
in alpha are given functions. For Tikhonov regularization both are exact.
Matrices are lists of rows; vectors are lists of floats.
"""
def bilevel_learn(pairs, lower, lower_vjp, alpha0, step, iters):
"""Projected gradient descent on alpha >= 0. Return (alpha, losses).
lower(alpha, y) returns x_alpha(y).
lower_vjp(alpha, y, x, v) returns <dx_alpha(y)/dalpha, v> for x = x_alpha(y).
Each step calls lower and lower_vjp once per pair.
"""
n_pairs = len(pairs)
alpha = alpha0 # @line L1
losses = []
for _ in range(iters): # @line L2
g, loss = 0.0, 0.0 # @line L3
for x_true, y in pairs: # @line L4
x = lower(alpha, y) # @line L5
r = [p - q for p, q in zip(x, x_true)]
loss += sum(v * v for v in r) / n_pairs
g += 2.0 * lower_vjp(alpha, y, x, r) / n_pairs # @line L6
losses.append(loss)
alpha = max(alpha - step * g, 0.0) # @line L7
return alpha, losses # @line L8
def solve(m, b):
"""Solve m x = b by Gaussian elimination with partial pivoting."""
n = len(b)
a = [list(row) + [bi] for row, bi in zip(m, b)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(a[r][c]))
a[c], a[p] = a[p], a[c]
for r in range(c + 1, n):
f = a[r][c] / a[c][c]
for k in range(c, n + 1):
a[r][k] -= f * a[c][k]
x = [0.0] * n
for r in range(n - 1, -1, -1):
x[r] = (a[r][n] - sum(a[r][k] * x[k] for k in range(r + 1, n))) / a[r][r]
return x
def rmatvec(a, y):
return [sum(a[r][j] * y[r] for r in range(len(a))) for j in range(len(a[0]))]
def tikhonov(a):
"""Return (lower, lower_vjp) for x_alpha = argmin ||Ax - y||^2 + alpha ||x||^2.
x_alpha solves (A^T A + alpha I) x = A^T y. Differentiating in alpha gives
(A^T A + alpha I) dx/dalpha = -x_alpha, so <dx/dalpha, v> = -<p, x_alpha>
with the adjoint solve (A^T A + alpha I) p = v.
"""
n = len(a[0])
ata = [[sum(a[r][i] * a[r][j] for r in range(len(a))) for j in range(n)]
for i in range(n)]
def system(alpha):
return [[ata[i][j] + (alpha if i == j else 0.0) for j in range(n)]
for i in range(n)]
def lower(alpha, y):
return solve(system(alpha), rmatvec(a, y))
def lower_vjp(alpha, y, x, v):
p = solve(system(alpha), v)
return -sum(pi * xi for pi, xi in zip(p, x))
return lower, lower_vjp
def upper_loss(pairs, lower, alpha):
"""L(alpha), the mean squared reconstruction error on the pairs."""
total = 0.0
for x_true, y in pairs:
x = lower(alpha, y)
total += sum((p - q) ** 2 for p, q in zip(x, x_true))
return total / len(pairs)
test_bilevel_learning_of_regularizers.py 83 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bilevel-learning-of-regularizers/. The authors are listed in prov/VE2JDY.jsonl.
import random
from bilevel_learning_of_regularizers import bilevel_learn, tikhonov, upper_loss
def seeded_pairs(seed, m=5, n=4, count=4, noise=0.5):
rng = random.Random(seed)
a = [[rng.gauss(0.0, 1.0) for _ in range(n)] for _ in range(m)]
pairs = []
for _ in range(count):
x = [rng.gauss(0.0, 1.0) for _ in range(n)]
y = [sum(a[r][j] * x[j] for j in range(n)) + rng.gauss(0.0, noise)
for r in range(m)]
pairs.append((x, y))
return a, pairs
def upper_gradient(pairs, lower, lower_vjp, alpha):
g = 0.0
for x_true, y in pairs:
x = lower(alpha, y)
g += 2.0 * lower_vjp(alpha, y, x, [p - q for p, q in zip(x, x_true)])
return g / len(pairs)
def test_hand_example():
lower, vjp = tikhonov([[1.0]])
pairs = [([1.0], [1.2])]
assert abs(lower(1.0, [1.2])[0] - 0.6) < 1e-15
assert abs(upper_loss(pairs, lower, 1.0) - 0.16) < 1e-15
assert abs(upper_gradient(pairs, lower, vjp, 1.0) - 0.24) < 1e-15
alpha, losses = bilevel_learn(pairs, lower, vjp, 1.0, 0.5, 60)
assert abs(alpha - 0.2) < 1e-10 and losses[-1] < 1e-18
def test_projection_keeps_alpha_nonnegative():
lower, vjp = tikhonov([[1.0]])
alpha, losses = bilevel_learn([([1.0], [0.8])], lower, vjp, 1.0, 0.5, 60)
assert alpha == 0.0 and abs(losses[-1] - 0.04) < 1e-12
def test_adjoint_gradient_matches_finite_differences():
a, pairs = seeded_pairs(5)
lower, vjp = tikhonov(a)
h = 1e-6
for alpha in (0.05, 0.4, 2.0):
fd = (upper_loss(pairs, lower, alpha + h) - upper_loss(pairs, lower, alpha - h)) / (2 * h)
assert abs(fd - upper_gradient(pairs, lower, vjp, alpha)) < 1e-8
def test_learned_weight_matches_a_grid_search():
a, pairs = seeded_pairs(5)
lower, vjp = tikhonov(a)
alpha, losses = bilevel_learn(pairs, lower, vjp, 1.0, 0.5, 300)
assert all(l2 <= l1 + 1e-15 for l1, l2 in zip(losses, losses[1:]))
assert abs(upper_gradient(pairs, lower, vjp, alpha)) < 1e-9
best = min((upper_loss(pairs, lower, k / 1000), k / 1000) for k in range(0, 2001))
assert abs(alpha - best[1]) < 1e-3 and upper_loss(pairs, lower, alpha) <= best[0] + 1e-15
assert abs(alpha - 0.36527) < 1e-5
def test_many_scalar_pairs_give_the_noise_to_signal_ratio():
rng = random.Random(6)
pairs = []
for _ in range(2000):
x = rng.gauss(0.0, 1.0)
pairs.append(([x], [x + rng.gauss(0.0, 0.5)]))
def lower(alpha, y): # Tikhonov with A = 1, written by hand
return [y[0] / (1.0 + alpha)]
def vjp(alpha, y, x, v):
return -x[0] * v[0] / (1.0 + alpha)
alpha, _ = bilevel_learn(pairs, lower, vjp, 1.0, 1.0, 100)
sxy = sum(x[0] * y[0] for x, y in pairs)
syy = sum(y[0] * y[0] for _, y in pairs)
assert abs(alpha - (syy / sxy - 1.0)) < 1e-9 # the exact minimizer
assert abs(alpha - 0.25) < 0.05 # sigma^2 / sigma_x^2 for large N
assert abs(lower(0.3, [0.7])[0] - tikhonov([[1.0]])[0](0.3, [0.7])[0]) < 1e-15
Exercises
- Derive Fact 1 from the implicit function theorem, and Fact 2 from Fact 1.
- Verify the hand example, and show that is the minimizer when .
- Prove Fact 3 and compare the minimum with the posterior variance of given .
- For the lower level with a matrix , find and write the adjoint gradient.
- For a vector of weights on the penalties , show that one adjoint solve per pair gives the gradient in all .
References
- Eldad Haber and Luis Tenorio, Learning regularization functionals, a supervised training approach, Inverse Problems 19(3), 2003, pages 611 to 626 (learning the regularization functional from training models by minimizing the reconstruction error)
- Karl Kunisch and Thomas Pock, A bilevel optimization approach for parameter learning in variational models, SIAM Journal on Imaging Sciences 6(2), 2013, pages 938 to 983 (the bilevel problem for learning the weights of variational denoising models, and its solution by gradient methods)
- Juan Carlos De los Reyes and Carola-Bibiane Schönlieb, Image denoising, learning the noise model via nonsmooth PDE-constrained optimization, Inverse Problems and Imaging 7(4), 2013, pages 1183 to 1214 (learning the weights of the data terms for mixed noise by a bilevel problem)
- Simon Arridge, Peter Maass, Ozan Öktem and Carola-Bibiane Schönlieb, Solving inverse problems using data-driven models, Acta Numerica 28, 2019, the section on learning the regularizer by bilevel optimization
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag VE2JDY Edit this page History Report an error Markdown