Algorithmcore
Levenberg-Marquardt algorithm
Also called Levenberg-Marquardt, damped least squares method.
Gauss-Newton with a damping term added to J^T J, raised when a step fails and lowered when it succeeds, moving between Gauss-Newton and gradient descent.
- Solves
- Nonlinear least squares
- Time
- Θ(m n^2 + n^3) per_iteration
- Space
- Θ(m n) extra
- Counts
- evaluations 1 per_iteration
- Where
- k = the number of steps tried, accepted or rejected; m = the number of residuals; n = the number of parameters
- Model
- Real RAM
- Properties
- deterministiciterativelocalmonotoneiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Kenneth Levenberg, Donald W. Marquardt, Jorge J. Moré, 1944
The Levenberg-Marquardt algorithm (LM) minimizes a sum of squares of smooth residuals. Like the Gauss-Newton algorithm, it linearizes the residuals at each step, but it solves the damped system with a damping and or . A step is accepted only if the cost goes down. After a failure grows, which makes the step shorter and turns it toward the steepest descent direction . After a success shrinks, so near a good solution the method becomes Gauss-Newton and inherits its fast local rate. The damping also makes the system solvable when is rank deficient. The nonlinear least squares page states the problem. Plain Gauss-Newton has no safeguard, and Powell's dog leg method controls a trust region radius directly and, after a rejected step, reuses the Gauss-Newton step it already has, where LM must factor a new damped matrix. LM is the standard solver for small and medium nonlinear least squares problems in computer vision, such as camera calibration, homography and pose refinement, and, in its sparse form, bundle adjustment.
In plain words
You want the best values of some unknown numbers, where "best" means the sum of the squared errors is smallest. The fast method (Gauss-Newton) jumps to where a straight line approximation says the best values are, but if you start far away, that jump can make things worse. Levenberg-Marquardt adds a brake. It tries a jump, and if the error goes down, it keeps the jump and loosens the brake a little. If the error goes up, it throws the jump away, tightens the brake and tries a shorter, more careful jump in the downhill direction. So it is careful when things go badly and fast when they go well.
The problem
Input. A residual function , its Jacobian , a start , a damping factor for the first , tolerances and , and an iteration limit .
Output. A point with at which the gradient is small, or the last iterate when a limit is reached.
Notation. , , is the linear model of the residuals, and is (Levenberg) or (Marquardt).
The algorithm
The version below is Algorithm 3.16 of Madsen, Nielsen and Tingleff (2004), with an option for the scaling .
LEVENBERG-MARQUARDT(r, J, x_0, τ, ε_1, ε_2, k_max)- 1
x <- x_0 ; ν <- 2 - 2
A <- J(x)^T J(x) ; g <- J(x)^T r(x) - 3
μ <- τ · max_i A_ii - 4
for k <- 1 to k_max - 5
if ||g||_∞ <= ε_1 then return x - 6
solve (A + μ D) h = -g by Cholesky - 7
if ||h|| <= ε_2 (||x|| + ε_2) then return x - 8
ρ <- (F(x) - F(x + h)) / (½ h^T (μ D h - g)) - 9
if ρ > 0 then - 10
x <- x + h ; A <- J(x)^T J(x) ; g <- J(x)^T r(x) - 11
μ <- μ · max(1/3, 1 - (2ρ - 1)^3) ; ν <- 2 - 12
else μ <- μ ν ; ν <- 2 ν - 13
return x
Line L3 scales the first damping to the size of ; suits a start close to the answer and or a start that is not (a rule of thumb of Madsen, Nielsen and Tingleff). Line L6 computes the damped step, which minimizes . Line L8 compares the actual decrease of with the decrease that the linear model predicts; the denominator is , which is positive. Line L9 accepts any step that lowers . Line L11 lowers by up to a factor 3 when the model is good ( near 1) and raises it a little when is small. Line L12 raises after a failure by a factor that doubles with each failure in a row, so a run of failures quickly gives a short steepest descent step. Lines L5 and L7 are the stopping rules for a small gradient and a small step.
The two limits of line L6 explain the method. As , tends to the Gauss-Newton step. As , , a short step along the scaled steepest descent direction.
Example
The one-parameter example of Madsen, Nielsen and Tingleff is . For the only minimizer is with , and plain Gauss-Newton does not converge to it (see the Gauss-Newton page). Run LM from with and . At , , , , and , so line L3 gives .
| try | predicted | result | |||||
|---|---|---|---|---|---|---|---|
| 1 | rejected, | ||||||
| 2 | accepted | ||||||
| 3 | accepted | ||||||
| 4 | accepted | ||||||
| 5 | accepted |
The first try is the step that Gauss-Newton would almost take, and it raises . Doubling gives a shorter step that lowers . After that, stays near and the error shrinks by a factor of about per step: linear convergence, as expected with a nonzero residual. The run stops at after 27 tries, 14 of them accepted. On the Rosenbrock residuals from , the reference code reaches in 18 tries (15 accepted) with and in 25 tries (22 accepted) with . These counts are measurements on this example only.
Correctness
For every the matrix of line L6 is positive definite, so the step exists, also for a rank deficient (theorem). The predicted reduction of line L8 is whenever , so an accepted step lowers strictly and the costs of the accepted iterates decrease (theorem). At a point with , enough rejections make tend to 1, so a step is accepted after finitely many tries (theorem). The proof file below proves these three facts. They do not by themselves show convergence of the iterates. For a version that controls a trust region radius and derives from it, Moré (1978) proves that the gradients tend to zero along a subsequence, and convergence to a stationary point under further conditions (theorem, not proved here). Near a minimizer where has full column rank and , the steps approach Gauss-Newton steps, so the method inherits the quadratic rate for zero residual problems (a standard result when ; the update of line L11 is a heuristic that usually achieves it).
Proof: The Levenberg-Marquardt step always exists, its model decrease is positive, accepted steps lower the cost and a rejected step is followed by an accepted onefull
We use the notation of the page. The residual is , , is the Jacobian at the current point , , , and is the linear model. is the scaling matrix: (Levenberg) or (Marquardt). For the Marquardt form we assume that no column of is zero, so has a positive diagonal.
Claim. (a) For every the matrix is positive definite, so line L6 has a unique solution , also when is rank deficient. (b) If , the predicted reduction of line L8 is . (c) Every accepted step lowers strictly, so the stored costs decrease strictly. (d) If and is continuously differentiable near , then after finitely many rejections at the same a step is accepted. So the loop of lines L4 to L12 cannot reject forever at a point that is not stationary.
Proof of (a). is positive semidefinite, since . is positive definite. So for . A positive definite matrix has a Cholesky factorization, and the system of line L6 has one solution.
Proof of (b). Expand . Line L6 gives , so . Then
If then , so . Also by (a). Both terms are positive.
Proof of (c). Line L9 accepts the step only when . The denominator is positive by (b), because line L5 has already stopped the loop if (in exact arithmetic). So . Line L10 stores the new cost, so the stored costs decrease strictly.
Proof of (d). Each rejection in line L12 multiplies by and doubles , so after rejections and . Write for the step. From ,
so . Put . Then and , so by (b) the predicted reduction is . Because is differentiable at with gradient , . Hence as , and for large enough , which is an accepted step.
The step as a trust region step. By (a) the step of line L6 minimizes . So it is also the minimizer of over the ellipsoid with : if some in that set had , then , which contradicts the minimality. This is why a large gives a short step, and why the method is a trust region method with the radius controlled through .
What this proof does not show. It shows monotone decrease and that the method never stalls in rejections at a non-stationary point. It does not show that the iterates converge. Moré (1978) proves, for a version that controls a trust region radius and computes from it, that the gradients tend to zero at least along a subsequence when is continuously differentiable, and that the iterates converge to a stationary point under further conditions stated there. The update of line L11 follows Madsen, Nielsen and Tingleff (2004, Algorithm 3.16); they report its good behavior in tests, which is a benchmark result, not a theorem.
The example of the page. For the Gauss-Newton matrix at is and the second derivative term is . With a fixed , the step near is with , so . For , the value of the run on the page, the factor is about , which explains the linear convergence with alternating signs that the run shows.
Complexity
In the real RAM model, a try costs one evaluation of , for the dense Cholesky factorization of line L6, and for the test of line L8. An accepted step also costs one evaluation of and to form in line L10. So each try costs plus one evaluation, and the extra space is for and for . A rejected step costs a new factorization but no new Jacobian. The number of tries has no useful general bound; it depends on the problem and on . In bundle adjustment the dense factorization is replaced by the reduced camera system, which brings the cost of a try down to that of sparse bundle adjustment.
Properties
- Monotone (theorem). The accepted costs decrease strictly.
- Defined for rank deficient (theorem). For and the damped matrix is positive definite for every . This matters in bundle adjustment, where the gauge freedom makes singular.
- A trust region method (theorem). The step of line L6 minimizes over the ellipsoid , so controls the radius indirectly.
- Scale dependence. With the step depends on the units of the parameters. With it does not change when a parameter is rescaled.
- Same weakness against outliers as Gauss-Newton. The cost is a plain sum of squares.
Variants and improvements
- Marquardt scaling. makes the method invariant to a diagonal rescaling of the parameters. On the Rosenbrock example the reference code needs 35 tries with it, against 18 without, which shows that the scaling is not always better.
- Nielsen's update. Lines L11 and L12 are the update of Nielsen, used by Madsen, Nielsen and Tingleff. The older rule multiplies by a fixed factor, for example 10, after a failure and divides by it after a success.
- Trust region form. Moré (1978) controls a radius and finds the for which by a scalar iteration. This is the form in MINPACK and the one with the convergence proof.
- Geodesic acceleration. A second order correction along the step, computed from a directional second derivative of , helps on problems with long curved valleys.
- Sparse LM. For bundle adjustment, the damped normal equations have the same block structure as the undamped ones, and the points can be eliminated by the Schur complement. See sparse bundle adjustment, and inexact Newton bundle adjustment for the iterative solve.
- Robust costs. With an M-estimator the residuals and the Jacobian are reweighted at each step, as in iteratively reweighted least squares.
When to use it
Use LM for small and medium nonlinear least squares problems when the start may be poor or some directions are poorly determined, which is the usual case in calibration, pose estimation, homography refinement and small bundle adjustments. It is a safe default: it never raises the cost, and near a good solution it is as fast as Gauss-Newton. For problems where one factorization is expensive and many steps are rejected, the dog leg method can be cheaper, since it can shrink the radius without a new factorization (Lourakis and Argyros 2005 report this for bundle adjustment). For very large problems, solve the damped system iteratively.
Pitfalls
- Wrong predicted reduction. Line L8 must divide by , not by or by . With the wrong value, has the wrong scale and line L11 adapts badly.
- that only grows. If line L11 is left out, never falls and the method becomes slow gradient descent. Check that decreases near the solution.
- Rounding near convergence. Close to the minimum, is a difference of nearly equal numbers and is noisy. Rely on the stopping rules of lines L5 and L7.
- Scaling. With , parameters in very different units, such as a focal length in pixels and a rotation in radians, get the same damping. Normalize the parameters or use the Marquardt scaling.
- Rank deficiency hidden by damping. With a gauge freedom no longer breaks line L6, but the iterates can drift along the gauge directions. Fix the gauge when you need a unique answer.
Implementations
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/levenberg-marquardt/. The authors are listed in prov/MSS87Z.jsonl.
"""The Levenberg-Marquardt algorithm for nonlinear least squares.
The problem is to minimize F(x) = 1/2 ||r(x)||^2 for r: R^n -> R^m. Each
step solves the damped normal equations (J^T J + mu D) h = -J^T r, with
D = I (Levenberg) or D = diag(J^T J) (Marquardt). The damping mu is updated
from the gain ratio rho by the rule of Madsen, Nielsen and Tingleff (2004,
Algorithm 3.16): after an accepted step mu <- mu max(1/3, 1 - (2 rho - 1)^3),
after a rejected step mu <- mu nu and nu <- 2 nu.
"""
import math
from typing import Callable, List, Sequence, Tuple
Vector = List[float]
Matrix = List[List[float]]
def cost(r: Sequence[float]) -> float:
"""F = 1/2 ||r||^2."""
return 0.5 * sum(v * v for v in r)
def normal_equations(jac: Sequence[Sequence[float]], r: Sequence[float]) -> Tuple[Matrix, Vector]:
"""Return A = J^T J and g = J^T r."""
m, n = len(jac), len(jac[0])
a = [[sum(jac[k][i] * jac[k][j] for k in range(m)) for j in range(n)] for i in range(n)]
g = [sum(jac[k][i] * r[k] for k in range(m)) for i in range(n)]
return a, g
def cholesky_solve(a: Sequence[Sequence[float]], b: Sequence[float]) -> Vector:
"""Solve a x = b for a symmetric positive definite a by a = L L^T."""
n = len(a)
low = [[0.0] * n for _ in range(n)]
for j in range(n):
d = a[j][j] - sum(low[j][k] ** 2 for k in range(j))
if d <= 0.0:
raise ValueError("matrix is not positive definite")
low[j][j] = math.sqrt(d)
for i in range(j + 1, n):
low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
y = [0.0] * n
for i in range(n):
y[i] = (b[i] - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
return x
def damped_step(a: Matrix, g: Vector, mu: float, marquardt: bool = False) -> Vector:
"""Solve (A + mu D) h = -g, with D = I or D = diag(A)."""
n = len(a)
b = [row[:] for row in a]
for i in range(n):
b[i][i] += mu * (a[i][i] if marquardt else 1.0)
return cholesky_solve(b, [-v for v in g])
def levenberg_marquardt(residual: Callable[[Vector], Vector],
jacobian: Callable[[Vector], Matrix],
x0: Sequence[float], tau: float = 1e-3,
eps1: float = 1e-12, eps2: float = 1e-14,
max_iter: int = 200, marquardt: bool = False):
"""Run Levenberg-Marquardt from x0.
Returns (x, info). info["costs"] holds F at x0 and after each accepted
step, info["mus"] the damping used at each step, info["iterations"] the
number of steps tried (accepted or rejected)."""
x = [float(v) for v in x0] # @line L1
nu = 2.0
r = residual(x)
a, g = normal_equations(jacobian(x), r) # @line L2
f = cost(r)
mu = tau * max(a[i][i] for i in range(len(x))) # @line L3
info = {"costs": [f], "mus": [], "iterations": 0}
for k in range(max_iter): # @line L4
if max(abs(v) for v in g) <= eps1: # @line L5
break
info["iterations"] = k + 1
h = damped_step(a, g, mu, marquardt) # @line L6
info["mus"].append(mu)
if math.sqrt(sum(v * v for v in h)) <= eps2 * (math.sqrt(sum(v * v for v in x)) + eps2): # @line L7
break
x_new = [xi + hi for xi, hi in zip(x, h)]
r_new = residual(x_new)
f_new = cost(r_new)
dmu = [mu * (a[i][i] if marquardt else 1.0) * h[i] for i in range(len(h))]
predicted = 0.5 * sum(hi * (di - gi) for hi, di, gi in zip(h, dmu, g)) # L(0) - L(h)
rho = (f - f_new) / predicted # @line L8
if rho > 0: # @line L9
x, r, f = x_new, r_new, f_new # @line L10
a, g = normal_equations(jacobian(x), r)
info["costs"].append(f)
mu *= max(1.0 / 3.0, 1.0 - (2.0 * rho - 1.0) ** 3) # @line L11
nu = 2.0
else:
mu *= nu # @line L12
nu *= 2.0
return x, info # @line L13
test_levenberg_marquardt.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/levenberg-marquardt/. The authors are listed in prov/MSS87Z.jsonl.
import math
import random
from levenberg_marquardt import cost, damped_step, levenberg_marquardt, normal_equations
T = [0.0, 1.0, 2.0, 3.0]
Y = [2.0 * math.exp(-0.5 * t) for t in T]
def exp_r(x):
return [x[0] * math.exp(x[1] * t) - y for t, y in zip(T, Y)]
def exp_j(x):
return [[math.exp(x[1] * t), x[0] * t * math.exp(x[1] * t)] for t in T]
def rosen_r(x):
return [10.0 * (x[1] - x[0] ** 2), 1.0 - x[0]]
def rosen_j(x):
return [[-20.0 * x[0], 10.0], [-1.0, 0.0]]
def mnt_r(lam):
return lambda x: [x[0] + 1.0, lam * x[0] ** 2 + x[0] - 1.0]
def mnt_j(lam):
return lambda x: [[1.0], [2.0 * lam * x[0] + 1.0]]
def fd_jacobian(f, x, h=1e-6):
cols = []
for i in range(len(x)):
xp, xm = list(x), list(x)
xp[i] += h
xm[i] -= h
cols.append([(a - b) / (2 * h) for a, b in zip(f(xp), f(xm))])
return [[cols[i][k] for i in range(len(x))] for k in range(len(cols[0]))]
def test_jacobians_against_finite_differences():
rng = random.Random(3)
for f, jf in ((exp_r, exp_j), (rosen_r, rosen_j)):
for _ in range(10):
x = [rng.uniform(-1.5, 2.0), rng.uniform(-1.0, 1.0)]
for ra, rb in zip(jf(x), fd_jacobian(f, x)):
for u, v in zip(ra, rb):
assert abs(u - v) <= 1e-5 * max(1.0, abs(u))
def test_rosenbrock_from_standard_start():
for tau in (1e-3, 1.0):
for marq in (False, True):
x, info = levenberg_marquardt(rosen_r, rosen_j, [-1.2, 1.0], tau=tau, marquardt=marq)
assert abs(x[0] - 1.0) < 1e-6 and abs(x[1] - 1.0) < 1e-6
costs = info["costs"]
assert all(c1 < c0 for c0, c1 in zip(costs, costs[1:]))
def test_zero_residual_exact_recovery():
x, info = levenberg_marquardt(exp_r, exp_j, [1.0, 0.0])
assert abs(x[0] - 2.0) < 1e-8 and abs(x[1] + 0.5) < 1e-8
assert info["costs"][-1] < 1e-20
def test_converges_where_gauss_newton_fails():
# with lambda = -2 the full Gauss-Newton step does not converge to x* = 0
x, info = levenberg_marquardt(mnt_r(-2.0), mnt_j(-2.0), [0.1], tau=1.0)
assert abs(x[0]) < 1e-6
costs = info["costs"]
assert all(c1 < c0 for c0, c1 in zip(costs, costs[1:]))
assert abs(costs[-1] - 1.0) < 1e-10 # F(0) = 1, the residual is not zero
def test_step_limits():
# large mu: the step tends to -g / mu (steepest descent); mu -> 0: Gauss-Newton
x = [-1.2, 1.0]
a, g = normal_equations(rosen_j(x), rosen_r(x))
h = damped_step(a, g, 1e8)
for hi, gi in zip(h, g):
assert abs(hi * 1e8 + gi) < 1e-4 * max(1.0, abs(gi))
h0 = damped_step(a, g, 0.0)
h1 = damped_step(a, g, 1e-12)
assert all(abs(u - v) < 1e-8 for u, v in zip(h0, h1))
def test_step_length_decreases_with_mu_and_model_decrease_is_positive():
rng = random.Random(17)
for _ in range(20):
x = [rng.uniform(-2, 2), rng.uniform(-1, 3)]
a, g = normal_equations(rosen_j(x), rosen_r(x))
last = float("inf")
for mu in (1e-3, 1e-1, 1.0, 10.0, 100.0):
h = damped_step(a, g, mu)
n = math.sqrt(sum(v * v for v in h))
assert n <= last + 1e-12
last = n
pred = 0.5 * sum(hi * (mu * hi - gi) for hi, gi in zip(h, g))
jh = [sum(row[i] * h[i] for i in range(2)) for row in rosen_j(x)]
lin = cost([ri + ji for ri, ji in zip(rosen_r(x), jh)])
assert pred > 0 and abs(pred - (cost(rosen_r(x)) - lin)) < 1e-9 * max(1.0, pred)
def test_against_grid_minimum():
x, _ = levenberg_marquardt(mnt_r(0.5), mnt_j(0.5), [0.7], tau=1e-2)
f = lambda v: cost(mnt_r(0.5)([v]))
best = min((f(-1.0 + i * 1e-4), -1.0 + i * 1e-4) for i in range(20001))
assert abs(x[0] - best[1]) < 2e-4 and f(x[0]) <= best[0] + 1e-12
History
Kenneth Levenberg published damped least squares in 1944: add a multiple of the identity, or of a diagonal matrix, to the normal equations so that the step stays in the region where the linear approximation holds. Donald Marquardt, at DuPont, published the same idea in 1963, with a geometric argument that the damped step interpolates between the Gauss-Newton step and the gradient step, the scaling by the diagonal of , and a simple rule for . His paper made the method widely used. Jorge Moré (1978) described it as a trust region method, gave a robust implementation, which became part of MINPACK, and proved its convergence. In computer vision, Hartley and Zisserman made LM the standard refinement step, and Lourakis and Argyros built their sparse bundle adjustment package on it.
References
- Kenneth Levenberg, A method for the solution of certain non-linear problems in least squares, Quarterly of Applied Mathematics 2(2), 1944, 164-168, the whole note (the damped least squares step and its relation to the Taylor series method)
- Donald W. Marquardt, An algorithm for least-squares estimation of nonlinear parameters, Journal of the Society for Industrial and Applied Mathematics 11(2), 1963, 431-441, the whole paper (the interpolation between the Gauss-Newton and the gradient step, the scaling by the diagonal of J^T J and the rule for the damping)
- Jorge J. Moré, The Levenberg-Marquardt algorithm, implementation and theory, in G. A. Watson (ed.), Numerical Analysis, Lecture Notes in Mathematics 630, Springer, 1978, 105-116, the whole paper (the trust region form, the computation of the damping from the radius and the convergence theorem)
- Kaj Madsen, Hans Bruun Nielsen and Ole Tingleff, Methods for Non-Linear Least Squares Problems, second edition, Informatics and Mathematical Modelling, Technical University of Denmark, 2004, Section 3.2, The Levenberg-Marquardt method (Algorithm 3.16, the start value of the damping, the update rule and the stopping rules)
- Jorge Nocedal and Stephen J. Wright, Numerical Optimization, second edition, Springer, 2006, Chapter 10, Least-squares problems (Section 10.3, the Levenberg-Marquardt method as a trust region method, its implementation and its convergence)
- Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Appendix 6, Iterative estimation methods (the Levenberg-Marquardt iteration, its sparse form and its application to bundle adjustment)
Where this leads
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag MSS87Z Edit this page History Report an error Markdown