TExcelTAD
Home › Optimization › Gauss-Newton and Levenberg-Marquardt

Gauss-Newton and Levenberg-Marquardt

Curve fitting, camera calibration, GPS positioning and robot localization all minimize a sum of squared residuals,

f(x)=12∑i=1mri(x)2=12∥r(x)∥2f(\mathbf{x}) = \frac{1}{2}\sum_{i=1}^m r_i(\mathbf{x})^2 = \frac{1}{2}\lVert \mathbf{r}(\mathbf{x}) \rVert^2

where each residual rir_i is a smooth, nonlinear function of the parameters. This structure gives a free, positive semidefinite approximation of the Hessian, and two classic methods are built on it.

The structure of the derivatives

With the Jacobian J(x)J(\mathbf{x}) of the residual vector (Jij=∂ri/∂xjJ_{ij} = \partial r_i/\partial x_j):

∇f=JTr,∇2f=JTJ+∑iri∇2ri\nabla f = J^T\mathbf{r}, \qquad \nabla^2 f = J^TJ + \sum_i r_i\nabla^2 r_i

Near a good fit the residuals rir_i are small, so the second term is small and JTJJ^TJ alone is an excellent Hessian approximation, built only from first derivatives.

Gauss-Newton

Drop the second term and take the Newton step with JTJJ^TJ:

JTJ p=−JTrJ^TJ\,\mathbf{p} = -J^T\mathbf{r}

This is exactly the normal equation of the linear least-squares problem min⁡p∥Jp+r∥2\min_{\mathbf{p}}\lVert J\mathbf{p} + \mathbf{r} \rVert^2: linearize the residuals, solve a linear fit, repeat. In code, solve it with lstsq (QR/SVD) instead of forming JTJJ^TJ, which squares the condition number.

python · try it yourself
import numpy as np

# fit y = a * exp(-b t) + c to noisy decay data
rng = np.random.default_rng(0)
t = np.linspace(0, 4, 30)
y = 2.5 * np.exp(-1.3 * t) + 0.5 + 0.02 * rng.normal(size=t.size)

def residual(x):
    a, b, c = x
    return a * np.exp(-b * t) + c - y
def jacobian(x):
    a, b, c = x
    e = np.exp(-b * t)
    return np.column_stack([e, -a * t * e, np.ones_like(t)])

x = np.array([1.0, 0.5, 0.0])
for k in range(1, 20):
    r, J = residual(x), jacobian(x)
    p = np.linalg.lstsq(J, -r, rcond=None)[0]
    x = x + p
    print(f"{k}: a, b, c = {np.round(x, 5)},  f = {0.5 * residual(x) @ residual(x):.6f}")
    if np.linalg.norm(p) < 1e-10:
        break
1: a, b, c = [1.57939 2.18608 1.29529],  f = 5.094623
2: a, b, c = [2.39665 0.33905 0.54982],  f = 12.359421
3: a, b, c = [-0.17213  1.26872  2.97552],  f = 63.811575
4: a, b, c = [2.51049 0.70361 0.49841],  f = 2.216065
5: a, b, c = [2.21507 1.20467 0.72614],  f = 0.702063
6: a, b, c = [2.50733 1.3182  0.50063],  f = 0.003972
7: a, b, c = [2.51081 1.30739 0.49797],  f = 0.003806
8: a, b, c = [2.51088 1.30758 0.49798],  f = 0.003806
9: a, b, c = [2.51088 1.30757 0.49798],  f = 0.003806
10: a, b, c = [2.51088 1.30757 0.49798],  f = 0.003806
11: a, b, c = [2.51088 1.30757 0.49798],  f = 0.003806
12: a, b, c = [2.51088 1.30757 0.49798],  f = 0.003806

Look at steps 2 and 3: ff jumped from 5.09 to 63.8 before the iterates found the right basin, and nothing in the method prevents such jumps. Gauss-Newton converges fast when the residuals at the solution are small and the start is reasonable. It can fail when JJ is rank deficient or the start is far away, because nothing controls the step length.

Levenberg-Marquardt

Levenberg-Marquardt (LM) adds a damping term:

(JTJ+λD) p=−JTr(J^TJ + \lambda D)\,\mathbf{p} = -J^T\mathbf{r}

with D=ID = I or D=diag⁡(JTJ)D = \operatorname{diag}(J^TJ). Large λ\lambda gives a short gradient-descent-like step; small λ\lambda gives Gauss-Newton. After each step, decrease λ\lambda if ff dropped, increase it if not. This is a trust-region method in which λ\lambda plays the role of the radius.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
t = np.linspace(0, 4, 30)
y = 2.5 * np.exp(-1.3 * t) + 0.5 + 0.02 * rng.normal(size=t.size)
res = lambda x: x[0] * np.exp(-x[1] * t) + x[2] - y
jac = lambda x: np.column_stack([np.exp(-x[1] * t), -x[0] * t * np.exp(-x[1] * t), np.ones_like(t)])

def gauss_newton(x, steps=10):
    for _ in range(steps):
        x = x + np.linalg.lstsq(jac(x), -res(x), rcond=None)[0]
    return x
def levenberg_marquardt(x, lam=1e-2, steps=100):
    f = lambda x: 0.5 * res(x) @ res(x)
    for _ in range(steps):
        J, r = jac(x), res(x)
        A = J.T @ J
        p = np.linalg.solve(A + lam * np.diag(np.diag(A)), -J.T @ r)
        if f(x + p) < f(x):
            x, lam = x + p, lam / 3
        else:
            lam *= 2
    return x

x0 = np.array([1.0, 10.0, 0.0])                  # a poor start: decay rate far too high
with np.errstate(all="ignore"):
    gn = gauss_newton(x0)
print("Gauss-Newton:        f =", f"{0.5 * res(gn) @ res(gn):.3g}", " a =", round(abs(float(gn[0])), 4), "(stuck: the model has lost its decay term)")
lm = levenberg_marquardt(x0)
print("Levenberg-Marquardt:", np.round(lm, 4), " f =", f"{0.5 * res(lm) @ res(lm):.6f}")
Gauss-Newton:        f = 7.12  a = 0.0 (stuck: the model has lost its decay term)
Levenberg-Marquardt: [2.5109 1.3076 0.498 ]  f = 0.003806

In practice: scipy.optimize.least_squares

python · try it yourself
import numpy as np
from scipy.optimize import least_squares

rng = np.random.default_rng(0)
t = np.linspace(0, 4, 30)
y = 2.5 * np.exp(-1.3 * t) + 0.5 + 0.02 * rng.normal(size=t.size)
res = lambda x: x[0] * np.exp(-x[1] * t) + x[2] - y
for method in ("lm", "trf"):
    r = least_squares(res, x0=[1.0, 10.0, 0.0], method=method)
    print(f"{method}: {np.round(r.x, 4)}  cost = {r.cost:.6f}  evaluations = {r.nfev}")
lm: [2.5109 1.3076 0.498 ]  cost = 0.003806  evaluations = 35
trf: [2.5109 1.3076 0.498 ]  cost = 0.003806  evaluations = 13

least_squares also supports bounds (trf), robust losses (loss="huber", "soft_l1") that down-weight outliers, and sparse Jacobians.

In software

  • scipy.optimize.curve_fit is LM (or TRF with bounds) behind a friendlier interface; MINPACK's lmder is the classic implementation.
  • Bundle adjustment in photogrammetry and SLAM (Ceres Solver, g2o, GTSAM) solves sparse nonlinear least squares with millions of residuals using LM with sparse Cholesky.

Exercises

Exercise 1: Gradient of the sum of squares

For residuals r1=x−1r_1 = x - 1 and r2=2xr_2 = 2x, compute ∇f\nabla f with JTrJ^T\mathbf{r} at x=1x = 1.

Answer
Solution

J=(1,2)TJ = (1, 2)^T and r=(0,2)\mathbf{r} = (0, 2), so JTr=0+4=4J^T\mathbf{r} = 0 + 4 = 4. Directly: f=12((x−1)2+4x2)f = \frac{1}{2}((x - 1)^2 + 4x^2) has f′(x)=(x−1)+4xf'(x) = (x - 1) + 4x, equal to 4 at x=1x = 1.

Exercise 2: Linear residuals

What does Gauss-Newton do when the residuals are linear, r(x)=Ax−b\mathbf{r}(\mathbf{x}) = A\mathbf{x} - \mathbf{b}?

Answer

It solves the problem in one step.

Solution

Then J=AJ = A and the second-order term vanishes, so JTJJ^TJ is the exact Hessian and the step solves the normal equations ATAx=ATbA^TA\mathbf{x} = A^T\mathbf{b}.

Exercise 3: Fit a circle (code)

Points lie near a circle. Fit centre (cx,cy)(c_x, c_y) and radius RR with residuals ri=(xi−cx)2+(yi−cy)2−Rr_i = \sqrt{(x_i - c_x)^2 + (y_i - c_y)^2} - R using least_squares.

Answer

Close to the true centre (2,−1)(2, -1) and radius 3.

Solution
python · try it yourself
import numpy as np
from scipy.optimize import least_squares
rng = np.random.default_rng(1)
ang = rng.uniform(0, 2 * np.pi, 40)
px = 2 + 3 * np.cos(ang) + 0.05 * rng.normal(size=40)
py = -1 + 3 * np.sin(ang) + 0.05 * rng.normal(size=40)
res = lambda p: np.hypot(px - p[0], py - p[1]) - p[2]
r = least_squares(res, x0=[0.0, 0.0, 1.0])
print(np.round(r.x, 3))
[ 1.987 -1.004  2.984]

Geometric fitting like this is used in metrology and computer vision; it is nonlinear because the distance is.

Test yourself

Gauss-Newton approximates the Hessian of 12∥r(x)∥2\frac{1}{2}\lVert \mathbf{r}(\mathbf{x}) \rVert^2 by…

  1. II
  2. JTJJ^TJ
  3. JTrJ^T\mathbf{r}
  4. ∑i∇2ri\sum_i \nabla^2 r_i

In Levenberg-Marquardt, a very large damping λ\lambda makes the step behave like…

  1. Gauss-Newton
  2. a short gradient-descent step
  3. Newton's method
  4. a random search

Why solve the Gauss-Newton step with lstsq instead of forming JTJJ^TJ?

  1. It is shorter to type
  2. Forming JTJJ^TJ squares the condition number
  3. JTJJ^TJ is not symmetric
  4. lstsq uses the exact Hessian