Gauss-Newton and Levenberg-Marquardt
Curve fitting, camera calibration, GPS positioning and robot localization all minimize a sum of squared residuals,
where each residual 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 of the residual vector ():
Near a good fit the residuals are small, so the second term is small and alone is an excellent Hessian approximation, built only from first derivatives.
Gauss-Newton
Drop the second term and take the Newton step with :
This is exactly the normal equation of the linear least-squares problem : linearize the residuals, solve a linear fit, repeat. In code, solve it with lstsq (QR/SVD) instead of forming , which squares the condition number.
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:
break1: 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: 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 is rank deficient or the start is far away, because nothing controls the step length.
Levenberg-Marquardt
Levenberg-Marquardt (LM) adds a damping term:
with or . Large gives a short gradient-descent-like step; small gives Gauss-Newton. After each step, decrease if dropped, increase it if not. This is a trust-region method in which plays the role of the radius.
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
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_fitis LM (or TRF with bounds) behind a friendlier interface; MINPACK'slmderis 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 and , compute with at .
Answer
Solution
and , so . Directly: has , equal to 4 at .
Exercise 2: Linear residuals
What does Gauss-Newton do when the residuals are linear, ?
Answer
It solves the problem in one step.
Solution
Then and the second-order term vanishes, so is the exact Hessian and the step solves the normal equations .
Exercise 3: Fit a circle (code)
Points lie near a circle. Fit centre and radius with residuals using least_squares.
Answer
Close to the true centre and radius 3.
Solution
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 by…
In Levenberg-Marquardt, a very large damping makes the step behave like…
- Gauss-Newton
- a short gradient-descent step
- Newton's method
- a random search
Why solve the Gauss-Newton step with lstsq instead of forming ?
- It is shorter to type
- Forming squares the condition number
- is not symmetric
- lstsq uses the exact Hessian