Techniqueresearch
Deep image prior
Also called DIP.
Fit an untrained convolutional network with random input to the measured data and stop early, using the network structure itself as the prior.
The deep image prior (DIP) reconstructs an image from data without any training data. Take a convolutional generator with weights , fix a random input , and run a gradient method on
starting from random weights. Stop after a chosen number of steps and return . Ulyanov, Vedaldi and Lempitsky (2018) observed that such a network fits the structure of a natural image in fewer steps than it fits noise. So the iterates first become a plausible image and only later fit the noise in . The prior is the network architecture together with the stopping step; there is no explicit regularizer.
In plain words
Take a network that turns a fixed random pattern into an image, and that has never seen an image. Adjust its weights, step by step, so that the image it makes, when blurred or masked in the same way as the measurement, matches the measurement. Such a network finds it easy to make smooth regions and edges, and hard to make random speckle. So it makes the clean parts of the picture first. If you stop at the right time, you have the picture without most of the noise. If you go on, the network learns the noise too.
When it applies
Setting. A forward map with its adjoint, data , a generator that is differentiable in , and a fixed input . The cost of one step is one call to , one backpropagation through , one call to and one to .
Fact 1 (a linear generator is Landweber). Let with a weight matrix . The gradient of in is . A gradient step with step changes the image to
which is the Landweber iteration with step . This is a theorem, and it shows the mechanism in its simplest form: with the iterates stay in the range of , and the number of steps acts as the regularization parameter, with semi-convergence when is noisy.
Fact 2 (the network bias). For convolutional networks of the kind used by Ulyanov et al., fitting a natural image takes fewer steps than fitting noise or a scrambled image. This is a measurement on their images. Later analyses prove a version of it for simple models, such as a two-layer convolutional generator in a regime where it behaves like a linear model, but there is no theorem for the networks used in practice. Treat the choice of as a heuristic.
Use DIP when there is no training data for the task, when the forward map changes from case to case, or as a baseline that needs only and . Do not use it when a trained method is available and fast reconstruction matters: each image needs thousands of network steps.
The template
DIP(A, y, G, z, θ_0, η, K)- 1
θ ← θ_0 - 2
for k = 1 to K ▷ hole: the stopping step K - 3
x ← G_θ(z) ▷ hole: the generator, a given function - 4
r ← A x - y - 5
g ← ∇_θ ⟨2 A^T r, G_θ(z)⟩ ▷ one backpropagation through G - 6
θ ← θ - η g ▷ hole: the optimizer - 7
return G_θ(z)
The holes are the generator and its input, the initial weights, the optimizer and the stopping step. Ulyanov et al. use an encoder-decoder network with skip connections, a uniform random input, and the Adam optimizer; plain gradient steps are the simplest case and the one shown. They fix for each task by hand. They also add small fresh noise to the input at each step in some tasks, as a further regularizer.
The generator is a given function: the code takes and its vector-Jacobian product as arguments and runs lines L1 to L7 around them. The tests build by hand as one linear layer, with or the identity and seeded weights, and write its gradient by hand; no convolutional network is trained. They check the gradient against finite differences, Fact 1 step by step on a periodic blur, the check value below, and the semi-convergence example below, and that the loss goes down for the generator.
Classic examples
Check value. One pixel, , , , and . By Fact 1, this is Landweber with , so and .
Semi-convergence on a blur. Take pixels, the periodic blur with kernel , the true signal with , and Gaussian noise with standard deviation 0.1 from seed 3. Use the linear generator with , and , so . The error is 2.87 after 1 step, 1.20 after 10, 0.48 after 20, smallest at step 32 with 0.316, and then grows again: 0.38 after 50, 0.55 after 100, 0.72 after 200 and 0.87 after 500 steps, when the data misfit is below . The late iterates fit the noise. This is a measurement for one seed; seeds 4 and 5 also give the smallest error near step 32 to 35. With a real network, the same shape of curve is what Ulyanov et al. report, but the best step is not known without the true image.
Image tasks. Ulyanov et al. apply DIP to denoising, super-resolution, inpainting with large holes, and other restoration tasks, and report results close to those of trained methods on some of them. These are measurements on their test images.
Variations
- Extra regularizers. Add a total variation term or another explicit penalty to the loss, which makes the result less sensitive to the stopping step.
- Smaller networks. Decoders with fewer weights than pixels, such as the deep decoder of Heckel and Hand, cannot fit all of the noise, so they need less care with stopping.
- Bayesian DIP. Add noise to the weight updates, as in Langevin dynamics, and average the images over the run to get an estimate and an uncertainty.
- Pretrained start. Start from weights trained on related images, which reduces the number of steps.
- Related generative methods. CSGM uses a trained generator and optimizes the input ; DIP uses an untrained generator and optimizes the weights.
Pitfalls
- Stopping. The result depends strongly on , and the best depends on the image, the noise level and the network. Without a rule, the late iterates fit the noise, as in the example.
- Cost. Each reconstruction is a full network optimization, many times the cost of a trained method at test time.
- Randomness. The result depends on the random input and initial weights. Two runs can give different images, and the method gives no measure of this unless you run it several times.
- No guarantee. Fact 1 is the only exact statement, and it is for a linear generator. For real networks, the claim that the network prefers natural images is an observation about the architecture, not a property of the data.
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/deep-image-prior/. The authors are listed in prov/E31RHQ.jsonl.
"""Deep image prior (DIP) of Ulyanov, Vedaldi and Lempitsky.
The generator is given: gen(theta) returns the image x = G_theta(z) for the
fixed input z, and gen_vjp(theta, v) returns the gradient of <v, G_theta(z)>
in the weights theta. DIP fits the weights to the data by gradient steps on
||A G_theta(z) - y||^2 and stops after a chosen number of steps.
Vectors and flat weight lists are lists of floats.
"""
import math
def dip(apply_a, apply_at, y, gen, gen_vjp, theta0, step, iters, on_step=None):
"""Run iters gradient steps on the weights. Return (x, theta, losses).
on_step(k, x), if given, is called with the image after step k.
Each step calls gen once, gen_vjp once, A once and A^T once.
"""
theta = list(theta0) # @line L1
losses = []
for k in range(1, iters + 1): # @line L2
x = gen(theta) # @line L3
r = [p - q for p, q in zip(apply_a(x), y)] # @line L4
losses.append(sum(v * v for v in r))
g = gen_vjp(theta, [2.0 * v for v in apply_at(r)]) # @line L5
theta = [t - step * gi for t, gi in zip(theta, g)] # @line L6
if on_step is not None:
on_step(k, gen(theta))
return gen(theta), theta, losses # @line L7
def one_layer_generator(z, n, activation="tanh"):
"""G_W(z) = phi(W z) with W an n by q matrix stored row by row in theta.
The gradient of <v, phi(W z)> in W is (v * phi'(W z)) z^T.
"""
q = len(z)
def pre(theta):
return [sum(theta[i * q + j] * z[j] for j in range(q)) for i in range(n)]
if activation == "tanh":
def gen(theta):
return [math.tanh(s) for s in pre(theta)]
def slope(theta):
return [1.0 - math.tanh(s) ** 2 for s in pre(theta)]
else:
def gen(theta):
return pre(theta)
def slope(theta):
return [1.0] * n
def gen_vjp(theta, v):
d = [vi * si for vi, si in zip(v, slope(theta))]
return [d[i] * z[j] for i in range(n) for j in range(q)]
return gen, gen_vjp
def periodic_blur(kernel, n):
"""Return (apply_a, apply_at) for periodic convolution with a centered kernel."""
half = len(kernel) // 2
def apply_a(x):
return [sum(kernel[k] * x[(i + k - half) % n] for k in range(len(kernel)))
for i in range(n)]
def apply_at(r):
return [sum(kernel[k] * r[(j - k + half) % n] for k in range(len(kernel)))
for j in range(n)]
return apply_a, apply_at
test_deep_image_prior.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deep-image-prior/. The authors are listed in prov/E31RHQ.jsonl.
import math
import random
from deep_image_prior import dip, one_layer_generator, periodic_blur
def identity(x):
return list(x)
def test_blur_adjoint():
rng = random.Random(0)
a, at = periodic_blur([0.2, 0.5, 0.3], 9)
x = [rng.gauss(0.0, 1.0) for _ in range(9)]
r = [rng.gauss(0.0, 1.0) for _ in range(9)]
lhs = sum(p * q for p, q in zip(a(x), r))
rhs = sum(p * q for p, q in zip(x, at(r)))
assert abs(lhs - rhs) < 1e-12
def test_weight_gradient_matches_finite_differences():
rng = random.Random(1)
n, q = 5, 3
z = [rng.uniform(0.0, 0.1) * 10 for _ in range(q)]
gen, vjp = one_layer_generator(z, n, "tanh")
theta = [rng.gauss(0.0, 0.5) for _ in range(n * q)]
v = [rng.gauss(0.0, 1.0) for _ in range(n)]
g = vjp(theta, v)
h = 1e-6
for j in range(n * q):
tp, tm = list(theta), list(theta)
tp[j] += h
tm[j] -= h
fd = sum(vi * (p - m) for vi, p, m in zip(v, gen(tp), gen(tm))) / (2 * h)
assert abs(fd - g[j]) < 1e-8
def test_linear_generator_is_landweber_check_value():
gen, vjp = one_layer_generator([1.0], 1, "identity")
x, _, _ = dip(identity, identity, [1.0], gen, vjp, [0.0], 0.005, 100)
assert abs(x[0] - (1.0 - 0.99 ** 100)) < 1e-12
assert abs(x[0] - 0.63397) < 1e-5
def test_linear_generator_follows_landweber_on_a_blur():
n = 8
a, at = periodic_blur([0.2, 0.6, 0.2], n)
rng = random.Random(2)
y = [rng.gauss(0.0, 1.0) for _ in range(n)]
z = [0.6, 0.8, 0.0] # norm 1, so the Landweber step is 2 * eta
gen, vjp = one_layer_generator(z, n, "identity")
eta = 0.1
seen = []
dip(a, at, y, gen, vjp, [0.0] * (3 * n), eta, 25, lambda k, x: seen.append(x))
x = [0.0] * n
for k in range(25):
r = [p - q for p, q in zip(a(x), y)]
x = [xi - 2.0 * eta * gi for xi, gi in zip(x, at(r))]
assert max(abs(p - q) for p, q in zip(x, seen[k])) < 1e-12
def test_early_stopping_beats_the_fitted_end():
n = 16
a, at = periodic_blur([0.2, 0.6, 0.2], n)
rng = random.Random(3)
truth = [math.sin(2 * math.pi * i / n) + 0.5 * math.cos(4 * math.pi * i / n)
for i in range(n)]
y = [v + rng.gauss(0.0, 0.1) for v in a(truth)]
gen, vjp = one_layer_generator([1.0], n, "identity")
errs = []
_, _, losses = dip(a, at, y, gen, vjp, [0.0] * n, 0.05, 500,
lambda k, x: errs.append(math.dist(x, truth)))
best = min(range(500), key=lambda i: errs[i]) + 1
assert best == 32 and abs(errs[best - 1] - 0.3157) < 1e-4
assert errs[-1] > 2.5 * errs[best - 1]
assert losses[-1] < 1e-3 # the end fits the noise (16 * 0.1^2 = 0.16 expected)
def test_tanh_generator_decreases_the_loss():
rng = random.Random(4)
n, q = 6, 4
z = [rng.uniform(0.0, 1.0) for _ in range(q)]
gen, vjp = one_layer_generator(z, n, "tanh")
a = lambda x: [x[0] + x[1], x[2] - x[3], x[4] + 0.5 * x[5]]
at = lambda r: [r[0], r[0], r[1], -r[1], r[2], 0.5 * r[2]]
y = [0.3, -0.2, 0.5]
theta0 = [rng.gauss(0.0, 0.3) for _ in range(n * q)]
_, _, losses = dip(a, at, y, gen, vjp, theta0, 0.05, 300)
assert all(l2 <= l1 + 1e-15 for l1, l2 in zip(losses, losses[1:]))
assert losses[-1] < 1e-3 * losses[0]
Exercises
- Prove Fact 1. What happens if ?
- Verify the check value .
- For the blur in the example, find the eigenvalues of and write the Landweber iterate in the Fourier basis. Explain why the error first goes down and then up.
- For the generator , write the gradient of in , and check it by finite differences.
- Run the example with noise of standard deviation 0.05 and 0.2. How does the best stopping step change?
References
- Dmitry Ulyanov, Andrea Vedaldi and Victor Lempitsky, Deep image prior, IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), 2018, pages 9446 to 9454 (the method, the observation that the network fits natural images faster than noise, and the denoising, super-resolution and inpainting experiments)
- Dmitry Ulyanov, Andrea Vedaldi and Victor Lempitsky, Deep image prior, International Journal of Computer Vision 128(7), 2020, pages 1867 to 1888 (the journal version of the method and experiments)
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 E31RHQ Edit this page History Report an error Markdown