Algorithm Search⌘K

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 y=Ax+ey = Ax + e without any training data. Take a convolutional generator GθG_\theta with weights θ\theta, fix a random input zz, and run a gradient method on

min⁡θ ∥AGθ(z)−y∥2,\min_\theta\ \|AG_\theta(z) - y\|^2,

starting from random weights. Stop after a chosen number of steps KK and return x^=GθK(z)\hat x = G_{\theta_K}(z). 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 yy. 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 AA with its adjoint, data yy, a generator Gθ(z)G_\theta(z) that is differentiable in θ\theta, and a fixed input zz. The cost of one step is one call to GG, one backpropagation through GG, one call to AA and one to ATA^T.

Fact 1 (a linear generator is Landweber). Let GW(z)=WzG_W(z) = Wz with a weight matrix WW. The gradient of ∥AWz−y∥2\|AWz - y\|^2 in WW is 2AT(AWz−y)zT2A^T(AWz - y)z^T. A gradient step with step η\eta changes the image x=Wzx = Wz to

xk+1=xk−2η∥z∥2AT(Axk−y),x_{k+1} = x_k - 2\eta\|z\|^2A^T(Ax_k - y),

which is the Landweber iteration with step ω=2η∥z∥2\omega = 2\eta\|z\|^2. This is a theorem, and it shows the mechanism in its simplest form: with W0=0W_0 = 0 the iterates stay in the range of ATA^T, and the number of steps acts as the regularization parameter, with semi-convergence when yy 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 KK 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 AA and ATA^T. Do not use it when a trained method is available and fast reconstruction matters: each image needs thousands of network steps.

The template

  1. DIP(A, y, G, z, θ_0, η, K)
  2. 1θ ← θ_0
  3. 2for k = 1 to K ▷ hole: the stopping step K
  4. 3x ← G_θ(z) ▷ hole: the generator, a given function
  5. 4r ← A x - y
  6. 5g ← ∇_θ ⟨2 A^T r, G_θ(z)⟩ ▷ one backpropagation through G
  7. 6θ ← θ - η g ▷ hole: the optimizer
  8. 7return 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 KK 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 GG and its vector-Jacobian product as arguments and runs lines L1 to L7 around them. The tests build GG by hand as one linear layer, GW(z)=ϕ(Wz)G_W(z) = \phi(Wz) with ϕ=tanh⁡\phi = \tanh 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 tanh⁡\tanh generator.

Classic examples

Check value. One pixel, A=1A = 1, y=1y = 1, z=1z = 1, W0=0W_0 = 0 and η=0.005\eta = 0.005. By Fact 1, this is Landweber with ω=0.01\omega = 0.01, so xk=1−0.99kx_k = 1 - 0.99^k and x100=0.63397x_{100} = 0.63397.

Semi-convergence on a blur. Take n=16n = 16 pixels, the periodic blur with kernel (0.2,0.6,0.2)(0.2, 0.6, 0.2), the true signal xi=sin⁡(2πi/16)+12cos⁡(4πi/16)x_i = \sin(2\pi i/16) + \tfrac12\cos(4\pi i/16) with ∥x∥=10≈3.16\|x\| = \sqrt{10} \approx 3.16, and Gaussian noise with standard deviation 0.1 from seed 3. Use the linear generator with z=1z = 1, W0=0W_0 = 0 and η=0.05\eta = 0.05, so ω=0.1\omega = 0.1. The error ∥xk−x∥\|x_k - x\| 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 10−310^{-3}. 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 zz; DIP uses an untrained generator and optimizes the weights.

Pitfalls

  • Stopping. The result depends strongly on KK, and the best KK 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.

deep_image_prior.pyI0RawGitHub
# 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

  1. Prove Fact 1. What happens if W0≠0W_0 \neq 0?
  2. Verify the check value x100=0.63397x_{100} = 0.63397.
  3. For the blur in the example, find the eigenvalues of ATAA^TA and write the Landweber iterate in the Fourier basis. Explain why the error first goes down and then up.
  4. For the generator GW(z)=tanh⁡(Wz)G_W(z) = \tanh(Wz), write the gradient of ∥AGW(z)−y∥2\|AG_W(z) - y\|^2 in WW, and check it by finite differences.
  5. Run the example with noise of standard deviation 0.05 and 0.2. How does the best stopping step change?

References

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • three classic examples