Inverse problems I: ill-posedness and regularization
Reconstruct causes from noisy observations in inverse problems such as deblurring and source recovery. Use the forward operator’s SVD and the Picard condition to explain noise amplification, then develop truncated SVD, Tikhonov and total variation regularization and learn how to choose their parameters.
After this lesson you can
- State Hadamard’s three criteria and explain why smoothing operators lead to ill-posed inverse problems.
- Diagnose noise amplification using singular-value decay and the discrete Picard condition.
- Implement truncated SVD and Tikhonov regularization in standard and general derivative-operator form, and interpret them as spectral filters.
- Choose a regularization parameter using the discrepancy principle, the L-curve and generalized cross-validation.
- Solve a reconstruction problem with total variation regularization and compare it with Tikhonov at sharp edges.
Before you start
- 29Finite difference stencils for PDEsTaxonomy of simulation uncertainty sourcesLocal sensitivity analysis
- 02Singular value decompositionMoore-Penrose pseudoinverse
- 09Conditioning of a problemNumerical least squares
- 06Proximal gradient methodSubgradient and subdifferential
- 11Ridge regressionLasso
- 13Bias-variance decomposition
Undoing smoothing
A camera turns a sharp scene into a blurred image; a heat equation takes an initial temperature to a smoother distribution; a tomograph turns an internal structure into measurements. The forward problem calculates data from a cause. The inverse problem asks what cause produced data that also contain noise.
If you write , the pseudoinverse seems an immediate solution. However, a smoothing operator attenuates fine oscillations. Inversion divides by those attenuations, and also divides the noise by them.
The four figures in this lesson share a reproducible model, not a real measurement. The periodic signal on equals plus on and plus on . It is sampled on a fine 128-point grid, spectral multiplier is applied and 32 observations are taken. Gaussian noise with fixed seed and adjustable standard deviation is added. Reconstruction uses a 32-point operator; generating on a different grid avoids reusing exactly the same discretization. This is a periodic diffusion and blur example, not a measured image or external benchmark.
What ill-posed means
A problem is well-posed in the Hadamard sense if a solution exists, is unique and depends continuously on the data in the chosen norms. Failure of any of these three conditions makes it ill-posed. In finite dimensions, an invertible square matrix has a continuous inverse, but can be very ill-conditioned: small perturbations give enormous errors. Genuine discontinuity appears in the infinite limit of many smoothing problems.
For example, on a periodic domain consider mode of the heat equation with . After time , its amplitude is multiplied by . To invert it you must multiply by , which grows without bound with . A data perturbation of amplitude tends to zero while its reconstruction has amplitude one. The inverse is not continuous in the norm.
This is also the intuition for infinite-rank compact operators between Hilbert spaces: their positive singular values decrease toward zero. In the corresponding directions, the unbounded inverse amplifies perturbations. Existence, uniqueness and stability must be discussed separately: a solution can be unique for exact data yet impossible to estimate stably from noisy data.
The SVD explains where information is lost
Let have positive singular values . For data , the minimum-norm solution is
Each noise coefficient is divided by . If is very small, even a tiny error becomes dominant. Directions in the nullspace of are not observed at all: no regularization can recover them without additional information.
The discrete Picard condition describes the favorable case where exact-data coefficients decay, on average, faster than in the meaningful region. With white noise, observed coefficients stop following that decline and reach a noise floor. Dividing that floor by decreasing singular values causes the explosion. The condition diagnoses a discretized problem: by itself it does not guarantee that the best cutoff is known or that every individual coefficient decreases monotonically.
For this circulant operator, Fourier modes are singular vectors and for , with positive and negative frequency pairs except zero and Nyquist. The chart groups each conjugate pair by frequency. A large ratio at one frequency does not prove all its content is noise: it identifies a sensitive direction where distinguishing signal from perturbation requires an additional assumption.
Filtering the inverse
Spectral filtering regularization replaces inversion with
Truncated SVD (TSVD) uses for retained modes and for the others. Its error has two parts: it discards signal in excluded directions and amplifies noise in included ones. A low cutoff biases reconstruction; a high cutoff reduces bias but can amplify the perturbation. If there is a nullspace, the component of the truth in it also remains undetermined by the data.
To make that tradeoff precise, write in singular coordinates. The error of a filter is
The first term is approximation error introduced by the filter even with exact data; the second is noise it lets through. Reducing dampens the second and increases the first. This identity is algebraic and does not depend on a noise distribution. To obtain expected squared error one must also specify its moments and, where appropriate, correlations.
Consider , truth and noise in left coordinates . Unfiltered inversion gives : the small noise becomes error in the second coordinate. With , Tikhonov gives approximately . The second coordinate is more stable against noise, but biased toward zero. The next cell recalculates both results.
Standard Tikhonov regularization balances fit and solution size:
Substitute the SVD and write . For each , minimizing gives
Tikhonov smoothly attenuates modes with ; TSVD removes them abruptly. The choice of depends on the scale of the operator and data, so an isolated number is not universal.
The general form penalizes . A first-difference matrix favors small variations; it does not penalize constant vectors if is a derivative. For the solution is unique if and only if . The numerically recommended formulation is the augmented system:
Solve it with QR or SVD, as in numerical least squares. Forming can worsen conditioning, especially with small regularization. For the pair with full-column-rank stacked matrix, generalized SVD (GSVD) provides common coordinates and factors , under normalized convention . These are not generally the ordinary singular vectors of .
Choosing λ without looking at the truth
Choosing the regularization parameter is part of the problem. Three criteria use different information:
- Morozov discrepancy. If you know a bound or estimate of the noise norm , seek a residual close to with . If the estimate is wrong, the criterion may overfit or oversmooth. Also check that this level lies within the attainable residual range.
- L-curve. Sweep and plot residual norm against solution norm or on logarithmic axes. The corner balances both quantities. Discrete curvature depends on the parameter grid and a corner may not be well defined.
- Generalized cross-validation (GCV). For a linear estimator , minimize , up to a constant factor that does not change the minimum. It does not need ; the usual interpretation assumes approximately white noise and comparable observations. If the noise covariance is known and correlated, whiten before applying these criteria.
The figure searches a finite grid; the corner is the maximum curvature estimated from consecutive points and may differ from a continuous estimate. The known noise level in the discrepancy is approximated by times its standard deviation, not the exact norm of one realization. None of the three criteria is an oracle: comparison with truth is only possible here because the signal was generated in the simulation.
For further reading, Hansen and O’Leary study the L-curve and Golub, Heath and Wahba formulate GCV for choosing regularization parameters.
Edges, total variation and early stopping
Discrete one-dimensional total variation is . The L1 norm of differences favors sparse gradients, allowing sharper edges than a quadratic difference penalty. It can also produce artificial plateaus, the staircase effect, and its parameter controls a tradeoff between noise and detail.
The total-variation denoising model of Rudin, Osher and Fatemi is a reference for this family of methods.
To minimize , ADMM introduces and alternates a quadratic problem in , soft thresholding in and a dual update. The Chambolle-Pock primal-dual method is another option separating operators and proximal steps. These are iterative algorithms: check primal and dual residuals or an appropriate gap, not only step count. The TV penalty uses , while in this lesson’s quadratic curves the parameter appears as ; numerically equal values do not represent equal strength.
You can also regularize by early stopping. Landweber starts from and applies . For , the filter for mode after steps is : large modes enter first and small ones take longer. Stopping too late reintroduces noise. Conjugate-gradient methods applied to least squares can also show this semiconvergence; their filter and stopping criterion are not identical to Landweber’s.
The rate is visible by expanding for small : on the order of steps are needed before that mode begins to enter substantially. If a frequency is noise-dominated, that delay helps only if iteration stops before fitting it. The training residual can keep falling after error relative to truth has started to rise. A practical rule must decide when to stop using available information, such as a reliable noise discrepancy, without consulting the unknown signal.
Avoiding the inverse crime
The inverse crime consists of generating data and reconstructing with the same discretization and assumptions in a way that makes the example artificially easy. Use a finer forward grid, compare measurement models and add noise according to an explicit process. A different grid alone does not eliminate every gap between simulation and reality: validation requires considering boundary conditions, calibration, correlated noise and other sources of uncertainty.
The regularized solution is an estimate conditioned on data, model, penalty and parameter choice. A small residual does not prove that the cause has been recovered: many vectors can generate nearly indistinguishable observations. Also compare stability against noise and sensitivity to the prior, and reserve known truth for synthetic experiments.
Lab: from diffusion to data
Construct a periodic heat operator using the discrete Fourier transform. Its multiplier is exactly that of the interactives, although the random-number generator and specific noise values here are NumPy’s. First we generate the signal and data on 128 points; then we observe every fourth point and reconstruct on 32. The observation restriction and inverse-problem grid are explicit.
import numpy as np
import matplotlib.pyplot as plt
def heat_matrix(n, tau=.04):
"""Difusión periódica espectral sobre n puntos en [0,1)."""
freq = np.fft.fftfreq(n, d=1/n)
attenuation = np.exp(-tau*freq**2)
return np.fft.ifft(attenuation[:,None]*np.fft.fft(np.eye(n),axis=0),axis=0).real
def signal(n):
t = np.arange(n)/n
return .15 + .8*((t>=.17)&(t<.37)) + .48*((t>=.55)&(t<.72))
fine, n = 128, 32
A_fine, A = heat_matrix(fine), heat_matrix(n)
truth = signal(n)
clean = (A_fine @ signal(fine))[::4]
noise_std = .02
noise = np.random.default_rng(42).normal(0,noise_std,n)
b = clean + noise
U, s, Vt = np.linalg.svd(A,full_matrices=False)
coef = U.T @ b
print("valores singulares extremos:", s[0], s[-1])
print("norma de ruido conocida en este experimento:", np.linalg.norm(noise))
print("diferencia entre modelos fino y grueso:", np.linalg.norm(clean-A@truth))The fine and coarse operators share the same equation but differ in discretization: this guards against an elementary inverse crime, not validates with physical data. The model residual printed by the cell adds to measurement uncertainty. The figures show different reproducible noise and use its theoretical standard deviation for discrepancy.
def tsvd(A,b,k):
U,s,Vt = np.linalg.svd(A,full_matrices=False)
if not 0 <= k <= len(s):
raise ValueError("k debe estar entre cero y el rango máximo")
if k and s[k-1] <= np.finfo(float).eps*max(A.shape)*s[0]:
raise ValueError("el corte incluye valores numéricamente nulos")
return Vt[:k].T @ ((U[:,:k].T @ b)/s[:k]) if k else np.zeros(A.shape[1])
for k in (3,9,17,31):
estimate = tsvd(A,b,k)
print("modos:", k, "RMSE:", np.sqrt(np.mean((estimate-truth)**2)))
fig,ax=plt.subplots(figsize=(7,3))
ax.semilogy(np.arange(1,n+1),s,label="σ")
ax.semilogy(np.arange(1,n+1),np.maximum(abs(coef),1e-14),label="|uᵢᵀb|")
ax.semilogy(np.arange(1,n+1),np.maximum(abs(coef/s),1e-14),label="cociente")
ax.set(xlabel="índice singular",ylabel="magnitud"); ax.legend(); plt.show()The lesson uses mathematical indices starting at one; NumPy arrays start at zero. TSVD retains columns of the ordered SVD, while the first interactive retains all Fourier modes up to a chosen frequency. A conjugate pair counts as two modes, except zero and Nyquist.
General Tikhonov and parameter criteria
The following function provides a reusable interface for any linear operator and compatible regularization matrix. Solving augmented least squares avoids forming normal equations. The GCV function uses the same augmented SVD to calculate the influence matrix and its trace, including when is a difference operator with a nullspace.
def tikhonov_general(A,b,L,lam):
A,b,L = np.asarray(A,float),np.asarray(b,float),np.asarray(L,float)
if lam <= 0:
raise ValueError("lam debe ser positivo")
aug = np.vstack((A,lam*L))
rhs = np.concatenate((b,np.zeros(L.shape[0])))
if np.linalg.matrix_rank(aug)<A.shape[1]:
raise ValueError("el sistema aumentado no tiene rango columna completo")
return np.linalg.lstsq(aug,rhs,rcond=None)[0]
def tikhonov_gcv(A,b,L,lambdas):
A,b,L = np.asarray(A,float),np.asarray(b,float),np.asarray(L,float)
m,n = A.shape
lambdas = np.asarray(lambdas,float)
if lambdas.size == 0 or np.any(lambdas <= 0):
raise ValueError("la rejilla debe contener lambdas positivos")
best, scores = None, []
for lam in lambdas:
aug = np.vstack((A,lam*L))
u,s,vh = np.linalg.svd(aug,full_matrices=False)
if s[-1] <= np.finfo(float).eps*max(aug.shape)*s[0]:
raise ValueError("el sistema aumentado no tiene rango columna completo")
# Mapea datos b a x; las filas añadidas al lado derecho son cero.
K = (vh.T/s) @ u[:m,:].T
x = K @ b
H = A @ K
denominator = (m-np.trace(H))**2
score = np.linalg.norm(A@x-b)**2/denominator if denominator > 1e-24 else np.inf
scores.append(score)
if best is None or score < best[0]:
best = (score,lam,x)
return best[1],best[2],np.asarray(scores)
D = np.roll(np.eye(n),-1,axis=1)-np.eye(n)
I = np.eye(n)
grid = np.logspace(-4,0,81)
lam_gcv,x_gcv,gcv = tikhonov_gcv(A,b,I,grid)
lam_gcv_d,x_gcv_d,_ = tikhonov_gcv(A,b,D,grid)
print("GCV orden 0 y 1:", lam_gcv,lam_gcv_d)
print("RMSE orden 0 y 1:",
np.sqrt(np.mean((x_gcv-truth)**2)),np.sqrt(np.mean((x_gcv_d-truth)**2)))
print("acuerdo SVD aumentada / lstsq:",
np.linalg.norm(x_gcv-tikhonov_general(A,b,I,lam_gcv)))The rows of take periodic differences. The function returns and searches only the proposed grid; a minimum at an endpoint signals that it should be expanded. In a real problem you do not know the truth and cannot directly minimize its RMSE.
GCV normalization divides by the square of effective residual degrees of freedom . If the fit interpolates almost all data, numerator and denominator can be very small and the ratio unstable; the code therefore guards a denominator close to zero. With singular , the augmented-matrix calculation remains valid if the rank condition holds. Do not replace its trace with the standard Tikhonov formula unless or the appropriate decomposition is available.
xs = [tikhonov_general(A,b,I,lam) for lam in grid]
residual = np.array([np.linalg.norm(A@x-b) for x in xs])
xnorm = np.array([np.linalg.norm(x) for x in xs])
target = np.linalg.norm(noise) # conocido solo porque se generó aquí
i_disc = np.argmin(abs(residual-target))
logcurve = np.column_stack((np.log(residual),np.log(xnorm)))
def corner(points):
curvature = np.zeros(len(points))
for i in range(1,len(points)-1):
a,bp,c = points[i-1:i+2]
ab,bc,ac = np.linalg.norm(bp-a),np.linalg.norm(c-bp),np.linalg.norm(c-a)
cross = (bp[0]-a[0])*(c[1]-a[1])-(bp[1]-a[1])*(c[0]-a[0])
curvature[i] = 2*abs(cross)/(ab*bc*ac) if ab*bc*ac > 0 else 0
return int(np.argmax(curvature))
i_l = corner(logcurve)
print("lambda discrepancia, GCV, esquina:", grid[i_disc],lam_gcv,grid[i_l])
print("residuo elegido y objetivo:", residual[i_disc],target)
small_s = np.array([1.,.01]); small_x = np.ones(2); small_noise = np.array([0.,.001])
small_b = small_s*small_x+small_noise
print("ejemplo sin filtro:", small_b/small_s,
"Tikhonov:", small_s*small_b/(small_s**2+.01**2))In this run, the difference between noise-free fine data and the coarse model prediction is greater than the norm of the generated noise. Using only the noise norm as therefore ignores part of the model error; a residual matching that target does not prove total uncertainty has been represented well. For a real application, estimate that discrepancy too and review observation assumptions.
TV with ADMM and backward heat
The periodic diffusion we built is also a backward heat problem: in the basis the heat multiplier is , so here . The same operator checks both deblurring and heat inversion under these boundaries. It is not the same problem as a heat equation on a fixed-boundary domain.
For TV, the following ADMM solves the quadratic subproblem using a single precomputed augmented SVD. It returns residuals and a convergence indicator. The comparison uses different penalties, so it explores each strength separately instead of treating their numbers as equivalent.
With scaled dual , its steps are: minimize over ; apply soft thresholding to with threshold to obtain ; and add to . The primal residual measures violation of and the dual measures change in propagated through . Here we use absolute tolerances for clarity; for variable-scale problems it is advisable to combine absolute and relative tolerances.
def tv_admm(A,b,D,alpha,rho=1.,max_iter=3000,tol=1e-5):
if alpha < 0 or rho <= 0:
raise ValueError("alpha debe ser no negativo y rho positivo")
m,n = A.shape
aug = np.vstack((A,np.sqrt(rho)*D))
u,s,vh = np.linalg.svd(aug,full_matrices=False)
if s[-1] <= np.finfo(float).eps*max(aug.shape)*s[0]:
raise ValueError("el sistema aumentado no tiene rango columna completo")
inverse = (vh.T/s) @ u.T
z = np.zeros(D.shape[0]); dual = np.zeros_like(z)
for iteration in range(1,max_iter+1):
x = inverse @ np.concatenate((b,np.sqrt(rho)*(z-dual)))
dx = D@x
old = z.copy()
v = dx+dual
z = np.sign(v)*np.maximum(abs(v)-alpha/rho,0)
dual += dx-z
primal = np.linalg.norm(dx-z)
dual_residual = rho*np.linalg.norm(D.T@(z-old))
if max(primal,dual_residual) < tol:
break
return x, {"iteraciones":iteration,"primal":primal,
"dual":dual_residual,"convergio":max(primal,dual_residual)<tol}
x_tv,diagnostic = tv_admm(A,b,D,.02)
print("TV:", diagnostic, "RMSE:", np.sqrt(np.mean((x_tv-truth)**2)))
fig,ax = plt.subplots(figsize=(7,3))
t = np.arange(n)/n
for values,label in [(truth,"verdad"),(x_gcv,"Tikhonov 0"),
(x_gcv_d,"Tikhonov 1"),(x_tv,"TV")]:
ax.plot(t,values,label=label)
ax.set(xlabel="posición",ylabel="señal"); ax.legend(); plt.show()The TV result must be judged by its residuals as well as the chart. In this example we know the original signal and can calculate RMSE. In a real reconstruction, do not tune by looking at truth; use criteria, independent data and sensitivity analysis appropriate to the noise and model.
The next experiment runs Landweber with step size one, allowed because this operator’s largest singular value is one. It prints residual and error at several times. Truth is used only to reveal the tradeoff in this experiment; it is not used to perform updates.
x_lw = np.zeros(n)
checkpoints = {1,10,100,1000,5000}
for step in range(1,max(checkpoints)+1):
x_lw += A.T@(b-A@x_lw)
if step in checkpoints:
print("paso:",step,"residuo:",np.linalg.norm(A@x_lw-b),
"RMSE:",np.sqrt(np.mean((x_lw-truth)**2)))The printed points sample the trajectory; they do not prove that the best step count among them is globally optimal. A larger step size can violate the stability condition and produce oscillation or divergence regardless of the stopping criterion.
Exercises
Step 1 of 3. How does the objective separate in singular coordinates?
Step 1 of 3. What happens to frequency-k mode in the forward problem?
import numpy as np
def tikhonov_gcv(A,b,L):
return 1.0, np.zeros(A.shape[1])