Algorithm Search⌘K

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.

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
Properties
deterministiciterativelocalmonotoneiterative
Origin
Kenneth Levenberg, Donald W. Marquardt, Jorge J. Moré, 1944

The Levenberg-Marquardt algorithm (LM) minimizes a sum of squares F(x)=12∥r(x)∥2F(x) = \tfrac12 \|r(x)\|^2 of smooth residuals. Like the Gauss-Newton algorithm, it linearizes the residuals at each step, but it solves the damped system (JTJ+μD)h=−JTr(J^{\mathsf T} J + \mu D) h = -J^{\mathsf T} r with a damping μ>0\mu > 0 and D=ID = I or D=diag⁡(JTJ)D = \operatorname{diag}(J^{\mathsf T} J). A step is accepted only if the cost goes down. After a failure μ\mu grows, which makes the step shorter and turns it toward the steepest descent direction −JTr-J^{\mathsf T} r. After a success μ\mu 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 JJ 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 r:Rn→Rmr: \mathbb{R}^n \to \mathbb{R}^m, its Jacobian J(x)J(x), a start x0x_0, a damping factor τ\tau for the first μ\mu, tolerances ε1\varepsilon_1 and ε2\varepsilon_2, and an iteration limit kmax⁡k_{\max}.

Output. A point xx with F(x)≤F(x0)F(x) \le F(x_0) at which the gradient g=JTrg = J^{\mathsf T} r is small, or the last iterate when a limit is reached.

Notation. A=JTJA = J^{\mathsf T} J, g=JTrg = J^{\mathsf T} r, L(h)=12∥r+Jh∥2L(h) = \tfrac12 \|r + J h\|^2 is the linear model of the residuals, and DD is II (Levenberg) or diag⁡(A)\operatorname{diag}(A) (Marquardt).

The algorithm

The version below is Algorithm 3.16 of Madsen, Nielsen and Tingleff (2004), with an option for the scaling DD.

  1. LEVENBERG-MARQUARDT(r, J, x_0, τ, ε_1, ε_2, k_max)
  2. 1x <- x_0 ; ν <- 2
  3. 2A <- J(x)^T J(x) ; g <- J(x)^T r(x)
  4. 3μ <- τ · max_i A_ii
  5. 4for k <- 1 to k_max
  6. 5if ||g||_∞ <= ε_1 then return x
  7. 6solve (A + μ D) h = -g by Cholesky
  8. 7if ||h|| <= ε_2 (||x|| + ε_2) then return x
  9. 8ρ <- (F(x) - F(x + h)) / (½ h^T (μ D h - g))
  10. 9if ρ > 0 then
  11. 10x <- x + h ; A <- J(x)^T J(x) ; g <- J(x)^T r(x)
  12. 11μ <- μ · max(1/3, 1 - (2ρ - 1)^3) ; ν <- 2
  13. 12else μ <- μ ν ; ν <- 2 ν
  14. 13return x

Line L3 scales the first damping to the size of AA; τ=10−6\tau = 10^{-6} suits a start close to the answer and τ=10−3\tau = 10^{-3} or 11 a start that is not (a rule of thumb of Madsen, Nielsen and Tingleff). Line L6 computes the damped step, which minimizes L(h)+12μhTDhL(h) + \tfrac12 \mu h^{\mathsf T} D h. Line L8 compares the actual decrease of FF with the decrease that the linear model predicts; the denominator is L(0)−L(h)L(0) - L(h), which is positive. Line L9 accepts any step that lowers FF. Line L11 lowers μ\mu by up to a factor 3 when the model is good (ρ\rho near 1) and raises it a little when ρ\rho is small. Line L12 raises μ\mu 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 μ→0\mu \to 0, hh tends to the Gauss-Newton step. As μ→∞\mu \to \infty, h≈−D−1g/μh \approx -D^{-1} g / \mu, a short step along the scaled steepest descent direction.

Example

The one-parameter example of Madsen, Nielsen and Tingleff is r(x)=(x+1,λx2+x−1)r(x) = (x + 1, \lambda x^2 + x - 1). For λ=−2\lambda = -2 the only minimizer is x∗=0x^* = 0 with F(0)=1F(0) = 1, and plain Gauss-Newton does not converge to it (see the Gauss-Newton page). Run LM from x0=0.1x_0 = 0.1 with τ=1\tau = 1 and D=ID = I. At x0x_0, r=(1.1,−0.92)r = (1.1, -0.92), J=(1,0.6)TJ = (1, 0.6)^{\mathsf T}, A=1.36A = 1.36, g=0.548g = 0.548 and F=1.0282F = 1.0282, so line L3 gives μ=1.36\mu = 1.36.

try xx μ\mu hh F(x+h)F(x + h) predicted ρ\rho result
1 0.10.1 1.36001.3600 −0.201471-0.201471 1.0331901.033190 0.0828040.082804 −0.0603-0.0603 rejected, μ←2μ\mu \leftarrow 2\mu
2 0.10.1 2.72002.7200 −0.134314-0.134314 1.0036161.003616 0.0613370.061337 0.40080.4008 accepted
3 −0.034314-0.034314 2.74122.7412 0.0423610.042361 1.0001931.000193 0.0069770.006977 0.49060.4906 accepted
4 0.0080470.008047 2.74132.7413 −0.010239-0.010239 1.0000141.000014 0.0003890.000389 0.45970.4597 accepted
5 −0.002192-0.002192 2.74272.7427 0.0027690.002769 1.0000011.000001 0.0000290.000029 0.46720.4672 accepted

The first try is the step that Gauss-Newton would almost take, and it raises FF. Doubling μ\mu gives a shorter step that lowers FF. After that, μ\mu stays near 2.742.74 and the error shrinks by a factor of about −0.266-0.266 per step: linear convergence, as expected with a nonzero residual. The run stops at x≈−7⋅10−10x \approx -7 \cdot 10^{-10} after 27 tries, 14 of them accepted. On the Rosenbrock residuals r=(10(x2−x12),1−x1)r = (10(x_2 - x_1^2), 1 - x_1) from (−1.2,1)(-1.2, 1), the reference code reaches (1,1)(1, 1) in 18 tries (15 accepted) with τ=10−3\tau = 10^{-3} and in 25 tries (22 accepted) with τ=1\tau = 1. These counts are measurements on this example only.

Correctness

For every μ>0\mu > 0 the matrix of line L6 is positive definite, so the step exists, also for a rank deficient JJ (theorem). The predicted reduction of line L8 is 12hT(μDh−g)>0\tfrac12 h^{\mathsf T} (\mu D h - g) > 0 whenever g≠0g \ne 0, so an accepted step lowers FF strictly and the costs of the accepted iterates decrease (theorem). At a point with g≠0g \ne 0, enough rejections make ρ\rho 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 μ\mu 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 JJ has full column rank and μ→0\mu \to 0, the steps approach Gauss-Newton steps, so the method inherits the quadratic rate for zero residual problems (a standard result when μk=O(∥gk∥)\mu_k = O(\|g_k\|); 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 r:Rn→Rmr: \mathbb{R}^n \to \mathbb{R}^m, F(x)=12∥r(x)∥2F(x) = \tfrac12 \|r(x)\|^2, JJ is the Jacobian at the current point xx, A=JTJA = J^{\mathsf T} J, g=JTrg = J^{\mathsf T} r, and L(h)=12∥r+Jh∥2L(h) = \tfrac12 \|r + J h\|^2 is the linear model. DD is the scaling matrix: D=ID = I (Levenberg) or D=diag⁡(A)D = \operatorname{diag}(A) (Marquardt). For the Marquardt form we assume that no column of JJ is zero, so DD has a positive diagonal.

Claim. (a) For every μ>0\mu > 0 the matrix A+μDA + \mu D is positive definite, so line L6 has a unique solution hh, also when JJ is rank deficient. (b) If g≠0g \ne 0, the predicted reduction of line L8 is L(0)−L(h)=12hT(μDh−g)>0L(0) - L(h) = \tfrac12 h^{\mathsf T} (\mu D h - g) > 0. (c) Every accepted step lowers FF strictly, so the stored costs decrease strictly. (d) If g≠0g \ne 0 and rr is continuously differentiable near xx, then after finitely many rejections at the same xx 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). AA is positive semidefinite, since vTAv=∥Jv∥2≥0v^{\mathsf T} A v = \|J v\|^2 \ge 0. μD\mu D is positive definite. So vT(A+μD)v≥μvTDv>0v^{\mathsf T} (A + \mu D) v \ge \mu v^{\mathsf T} D v > 0 for v≠0v \ne 0. A positive definite matrix has a Cholesky factorization, and the system of line L6 has one solution. □\square

Proof of (b). Expand L(h)=L(0)+hTg+12hTAhL(h) = L(0) + h^{\mathsf T} g + \tfrac12 h^{\mathsf T} A h. Line L6 gives Ah=−g−μDhA h = -g - \mu D h, so hTAh=−hTg−μhTDhh^{\mathsf T} A h = -h^{\mathsf T} g - \mu h^{\mathsf T} D h. Then

L(0)−L(h)=−hTg−12hTAh=−12hTg+12μ hTDh=12hT(μDh−g).L(0) - L(h) = -h^{\mathsf T} g - \tfrac12 h^{\mathsf T} A h = -\tfrac12 h^{\mathsf T} g + \tfrac12 \mu\, h^{\mathsf T} D h = \tfrac12 h^{\mathsf T} (\mu D h - g).

If g≠0g \ne 0 then h≠0h \ne 0, so μhTDh>0\mu h^{\mathsf T} D h > 0. Also −hTg=hT(A+μD)h>0-h^{\mathsf T} g = h^{\mathsf T} (A + \mu D) h > 0 by (a). Both terms are positive. □\square

Proof of (c). Line L9 accepts the step only when ρ=(F(x)−F(x+h))/(L(0)−L(h))>0\rho = (F(x) - F(x + h)) / (L(0) - L(h)) > 0. The denominator is positive by (b), because line L5 has already stopped the loop if g=0g = 0 (in exact arithmetic). So F(x+h)<F(x)F(x + h) < F(x). Line L10 stores the new cost, so the stored costs decrease strictly. □\square

Proof of (d). Each rejection in line L12 multiplies μ\mu by ν≥2\nu \ge 2 and doubles ν\nu, so after jj rejections μ≥2jμ0\mu \ge 2^j \mu_0 and μ→∞\mu \to \infty. Write hμh_\mu for the step. From (A+μD)hμ=−g(A + \mu D) h_\mu = -g,

μhμ=−(D+A/μ)−1g→−D−1g(μ→∞),\mu h_\mu = -(D + A / \mu)^{-1} g \to -D^{-1} g \quad (\mu \to \infty),

so ∥hμ∥=O(1/μ)\|h_\mu\| = O(1/\mu). Put c=gTD−1g>0c = g^{\mathsf T} D^{-1} g > 0. Then −gThμ=(c+o(1))/μ-g^{\mathsf T} h_\mu = (c + o(1))/\mu and μhμTDhμ=(c+o(1))/μ\mu h_\mu^{\mathsf T} D h_\mu = (c + o(1))/\mu, so by (b) the predicted reduction is (c+o(1))/μ(c + o(1))/\mu. Because FF is differentiable at xx with gradient gg, F(x)−F(x+hμ)=−gThμ+o(∥hμ∥)=(c+o(1))/μF(x) - F(x + h_\mu) = -g^{\mathsf T} h_\mu + o(\|h_\mu\|) = (c + o(1))/\mu. Hence ρ→1\rho \to 1 as μ→∞\mu \to \infty, and for μ\mu large enough ρ>0\rho > 0, which is an accepted step. □\square

The step as a trust region step. By (a) the step of line L6 minimizes L(h)+12μhTDhL(h) + \tfrac12 \mu h^{\mathsf T} D h. So it is also the minimizer of LL over the ellipsoid hTDh≤Δ2h^{\mathsf T} D h \le \Delta^2 with Δ2=hTDh\Delta^2 = h^{\mathsf T} D h: if some h′h' in that set had L(h′)<L(h)L(h') < L(h), then L(h′)+12μh′TDh′<L(h)+12μhTDhL(h') + \tfrac12 \mu h'^{\mathsf T} D h' < L(h) + \tfrac12 \mu h^{\mathsf T} D h, which contradicts the minimality. This is why a large μ\mu gives a short step, and why the method is a trust region method with the radius controlled through μ\mu.

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 Δ\Delta and computes μ\mu from it, that the gradients gkg_k tend to zero at least along a subsequence when rr is continuously differentiable, and that the iterates converge to a stationary point under further conditions stated there. The μ\mu 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 r(x)=(x+1,−2x2+x−1)r(x) = (x + 1, -2x^2 + x - 1) the Gauss-Newton matrix at x∗=0x^* = 0 is A∗=2A_* = 2 and the second derivative term is S∗=4S_* = 4. With a fixed μ\mu, the step near 00 is h=−(A+μ)−1gh = -(A + \mu)^{-1} g with g=(A∗+S∗)e+O(e2)g = (A_* + S_*) e + O(e^2), so e+=μ−S∗A∗+μ e+O(e2)=μ−4μ+2 e+O(e2)e_+ = \frac{\mu - S_*}{A_* + \mu}\, e + O(e^2) = \frac{\mu - 4}{\mu + 2}\, e + O(e^2). For μ≈2.74\mu \approx 2.74, the value of the run on the page, the factor is about −0.266-0.266, which explains the linear convergence with alternating signs that the run shows.

Complexity

In the real RAM model, a try costs one evaluation of rr, Θ(n3)\Theta(n^3) for the dense Cholesky factorization of line L6, and Θ(n)\Theta(n) for the test of line L8. An accepted step also costs one evaluation of JJ and Θ(mn2)\Theta(m n^2) to form AA in line L10. So each try costs Θ(mn2+n3)\Theta(m n^2 + n^3) plus one evaluation, and the extra space is Θ(mn)\Theta(m n) for JJ and Θ(n2)\Theta(n^2) for AA. 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 x0x_0. 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 JJ (theorem). For μ>0\mu > 0 and D=ID = I the damped matrix is positive definite for every JJ. This matters in bundle adjustment, where the gauge freedom makes JTJJ^{\mathsf T} J singular.
  • A trust region method (theorem). The step of line L6 minimizes LL over the ellipsoid hTDh≤∥h∥D2h^{\mathsf T} D h \le \|h\|_D^2, so μ\mu controls the radius indirectly.
  • Scale dependence. With D=ID = I the step depends on the units of the parameters. With D=diag⁡(A)D = \operatorname{diag}(A) 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. D=diag⁡(A)D = \operatorname{diag}(A) 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 μ\mu 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 Δ\Delta and finds the μ\mu for which ∥Dh∥=Δ\|D h\| = \Delta 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 rr, 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 L(0)−L(h)L(0) - L(h), not by F(x)F(x) or by ∥g∥\|g\|. With the wrong value, ρ\rho has the wrong scale and line L11 adapts μ\mu badly.
  • μ\mu that only grows. If line L11 is left out, μ\mu never falls and the method becomes slow gradient descent. Check that μ\mu decreases near the solution.
  • Rounding near convergence. Close to the minimum, F(x)−F(x+h)F(x) - F(x + h) is a difference of nearly equal numbers and ρ\rho is noisy. Rely on the stopping rules of lines L5 and L7.
  • Scaling. With D=ID = I, 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 D=ID = I 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.

levenberg_marquardt.pyI0RawGitHub
# 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 JTJJ^{\mathsf T} J, and a simple rule for μ\mu. 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

  1. 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)
  2. 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)
  3. 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)
  4. 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)
  5. 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)
  6. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per_iteration
  • a full proof of space.extra
  • a full proof of evaluations.per_iteration
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
  • a scene preset for the example