Algorithm Search⌘K

Algorithmcore

Gauss-Newton algorithm

Also called Gauss-Newton method.

Minimize a sum of squares by linearizing the residuals at each step and solving the normal equations J^T J dx = -J^T r for the update.

Time
Θ(m n^2 + n^3) per_iteration
Space
Θ(m n) extra
Counts
evaluations 1 per_iteration
Where
k = the number of iterations; m = the number of residuals; n = the number of parameters, with m >= n
Properties
deterministicnot globally convergentiterativelocaliterative
Origin
Carl Friedrich Gauss, 1809

The Gauss-Newton algorithm minimizes a sum of squares F(x)=12∑iri(x)2F(x) = \tfrac12 \sum_i r_i(x)^2 of smooth residuals rir_i of a parameter vector xx. At each step it replaces each residual by its linear approximation r+Jhr + J h, where JJ is the Jacobian, and moves to the minimizer of that linear least squares model: it solves the normal equations JTJ h=−JTrJ^{\mathsf T} J\, h = -J^{\mathsf T} r and sets x←x+hx \leftarrow x + h. It is Newton's method on ∇F=0\nabla F = 0 with the second derivative term of the Hessian dropped, so it needs only first derivatives. Near a solution where the residuals are zero and JJ has full column rank it converges quadratically. With nonzero residuals the rate is linear at best, and the method can fail to converge even from a start close to the minimizer. The nonlinear least squares page states the problem. Levenberg-Marquardt adds a damping term so that every accepted step lowers the cost, and Powell's dog leg method mixes the Gauss-Newton step with the steepest descent step inside a trust region. Both of those methods reduce to Gauss-Newton near a good solution. In computer vision, Gauss-Newton is the step inside bundle adjustment, camera calibration and image alignment.

In plain words

You have a model with a few unknown numbers, and many measurements. Each measurement gives an error, and you want to make the sum of the squared errors as small as you can. The errors depend on the unknowns in a curved way, so you cannot solve for the best numbers in one go. Gauss-Newton guesses, then pretends that near the guess every error changes in a straight line. For straight lines, the best change of the numbers is easy to compute. You apply that change and repeat. If the model can fit the data almost exactly, each round roughly doubles the number of correct digits. If the fit stays poor, the rounds can help slowly or not at all.

The problem

Input. A residual function r:Rn→Rmr: \mathbb{R}^n \to \mathbb{R}^m with m≥nm \ge n, its Jacobian J(x)=∂r/∂xJ(x) = \partial r / \partial x (an m×nm \times n matrix), a start x0x_0, a tolerance ε\varepsilon and an iteration limit kmax⁡k_{\max}.

Output. A point xx that is close to a stationary point of F(x)=12∥r(x)∥2F(x) = \tfrac12 \|r(x)\|^2, that is, g(x)=J(x)Tr(x)≈0g(x) = J(x)^{\mathsf T} r(x) \approx 0. The method finds a local minimizer only when it converges. It does not find the global one in general.

Notation. A=JTJA = J^{\mathsf T} J and g=JTrg = J^{\mathsf T} r. The Hessian of FF is ∇2F=A+S\nabla^2 F = A + S with S=∑iri∇2riS = \sum_i r_i \nabla^2 r_i. Gauss-Newton uses AA in place of ∇2F\nabla^2 F.

The algorithm

  1. GAUSS-NEWTON(r, J, x_0, ε, k_max)
  2. 1x <- x_0
  3. 2for k <- 1 to k_max
  4. 3r <- r(x) ; J <- J(x)
  5. 4A <- J^T J ; g <- J^T r
  6. 5if ||g||_∞ <= ε then return x
  7. 6solve A h = -g by Cholesky
  8. 7x <- x + h
  9. 8if ||h|| <= ε (||x|| + ε) then return x
  10. 9return x

Line L3 evaluates the residual and the Jacobian at the current point. Line L4 forms the normal equations of the linear model L(h)=12∥r+Jh∥2L(h) = \tfrac12 \|r + J h\|^2, whose gradient is g+Ahg + A h. Line L5 stops at a point where the gradient of FF is small. Line L6 finds the minimizer of LL by a Cholesky factorization of AA; it fails when JJ is rank deficient, and then the method is not defined. Line L7 takes the full step, with no line search and no damping. Line L8 stops when the step is small relative to xx. A numerically safer form of line L6 solves the linear least squares problem min⁡∥r+Jh∥\min \|r + J h\| by a QR decomposition of JJ, which does not square the condition number.

Example

Fit y=x1ex2ty = x_1 e^{x_2 t} to the four exact values y=2e−0.5ty = 2 e^{-0.5 t} at t=0,1,2,3t = 0, 1, 2, 3, so the residuals are ri=x1ex2ti−yir_i = x_1 e^{x_2 t_i} - y_i and the solution is x∗=(2,−0.5)x^* = (2, -0.5) with F(x∗)=0F(x^*) = 0. Start at x0=(1,0)x_0 = (1, 0). Then r=(−1,−0.213061,0.264241,0.553740)r = (-1, -0.213061, 0.264241, 0.553740), JJ has rows (1,ti)(1, t_i), A=(46614)A = \begin{pmatrix} 4 & 6 \\ 6 & 14 \end{pmatrix} and g=(−0.395080,1.976641)g = (-0.395080, 1.976641). Line L6 gives h=(0.869548,−0.513852)h = (0.869548, -0.513852).

kk xkx_k F(xk)F(x_k) ∥xk−x∗∥\|x_k - x^*\|
0 (1,0)(1, 0) 7.109⋅10−17.109 \cdot 10^{-1} 1.1181.118
1 (1.869548,−0.513852)(1.869548, -0.513852) 1.629⋅10−21.629 \cdot 10^{-2} 1.312⋅10−11.312 \cdot 10^{-1}
2 (1.999955,−0.498807)(1.999955, -0.498807) 3.787⋅10−63.787 \cdot 10^{-6} 1.193⋅10−31.193 \cdot 10^{-3}
3 (2.000000,−0.499998)(2.000000, -0.499998) 5.671⋅10−125.671 \cdot 10^{-12} 1.575⋅10−61.575 \cdot 10^{-6}
4 (2.000000,−0.500000)(2.000000, -0.500000) 1.293⋅10−231.293 \cdot 10^{-23} 2.403⋅10−122.403 \cdot 10^{-12}

The error is roughly squared at each step, as the theorem for zero residuals says. A nonzero residual changes this. Madsen, Nielsen and Tingleff use r(x)=(x+1,λx2+x−1)r(x) = (x + 1, \lambda x^2 + x - 1) with one parameter. Its minimizer is x∗=0x^* = 0 for every λ<1\lambda < 1, with F(0)=1F(0) = 1, and near it the Gauss-Newton error obeys ek+1=λek+O(ek2)e_{k+1} = \lambda e_k + O(e_k^2). From x0=0.1x_0 = 0.1:

λ\lambda x0,x1,x2,…x_0, x_1, x_2, \dots behavior
0.50.5 0.1,0.047738,0.023326,0.011530,0.005732,0.0028580.1, 0.047738, 0.023326, 0.011530, 0.005732, 0.002858 linear, the ratio tends to 0.50.5
−2-2 0.1,−0.302941,0.136764,−0.467990,0.066387,−0.176704,0.1533850.1, -0.302941, 0.136764, -0.467990, 0.066387, -0.176704, 0.153385 no convergence

For λ=−2\lambda = -2, 00 is the only stationary point and the global minimizer of FF, yet the iteration jumps around it. Levenberg-Marquardt and the dog leg method converge on the same problem.

Correctness

Line L6 returns the exact minimizer of the linear model when JJ has full column rank, and that step is a descent direction for FF. The local behavior follows from the error recursion ek+1=−A∗−1S∗ek+O(∥ek∥2)e_{k+1} = -A_*^{-1} S_* e_k + O(\|e_k\|^2) at a stationary point x∗x^* with J(x∗)J(x^*) of full column rank and smooth residuals. If S∗=0S_* = 0, which holds when r(x∗)=0r(x^*) = 0, the convergence is quadratic (theorem). If ∥A∗−1S∗∥<1\|A_*^{-1} S_*\| < 1 it is linear (theorem). If ∣A∗−1S∗∣>1|A_*^{-1} S_*| > 1 in one dimension, the iterates leave every small neighborhood of x∗x^* (theorem, shown on the example above). The proof is in the proof file below. A global result needs a globalization: with a line search that satisfies the Wolfe conditions and singular values of JJ bounded away from zero, JkTrk→0J_k^{\mathsf T} r_k \to 0 (Nocedal and Wright, Theorem 10.1).

Proof: The Gauss-Newton step minimizes the linear model and converges locally, quadratically when the residual at the solution is zerofull

We use the notation of the page. The residual is r:Rn→Rmr: \mathbb{R}^n \to \mathbb{R}^m with m≥nm \ge n, the cost is F(x)=12∥r(x)∥2F(x) = \tfrac12 \|r(x)\|^2, J(x)J(x) is the m×nm \times n Jacobian of rr, A(x)=J(x)TJ(x)A(x) = J(x)^{\mathsf T} J(x) and g(x)=J(x)Tr(x)g(x) = J(x)^{\mathsf T} r(x). The second derivative term is S(x)=∑i=1mri(x)∇2ri(x)S(x) = \sum_{i=1}^m r_i(x) \nabla^2 r_i(x). Then ∇F=g\nabla F = g and ∇2F=A+S\nabla^2 F = A + S.

Claim. (a) If J(x)J(x) has full column rank, line L6 is well defined, its step hh is the unique minimizer of the linear model L(h)=12∥r+Jh∥2L(h) = \tfrac12 \|r + J h\|^2, and hh is a descent direction of FF whenever g≠0g \ne 0. (b) Let x∗x^* be a stationary point (g(x∗)=0g(x^*) = 0) such that J(x∗)J(x^*) has full column rank, and let rr be twice differentiable with Lipschitz continuous first and second derivatives near x∗x^*. Then the error ek=xk−x∗e_k = x_k - x^* satisfies

ek+1=−A∗−1S∗ ek+O(∥ek∥2),A∗=A(x∗),  S∗=S(x∗).e_{k+1} = -A_*^{-1} S_* \, e_k + O(\|e_k\|^2), \qquad A_* = A(x^*), \; S_* = S(x^*).

(c) As a consequence, if S∗=0S_* = 0 (in particular if r(x∗)=0r(x^*) = 0), the iteration converges quadratically from every start close enough to x∗x^*. If ∥A∗−1S∗∥<1\|A_*^{-1} S_*\| < 1 in some operator norm, it converges at least linearly. If n=1n = 1 and ∣A∗−1S∗∣>1|A_*^{-1} S_*| > 1, no start x0≠x∗x_0 \ne x^* gives iterates that stay in a small neighborhood of x∗x^*, so the full step method does not converge to x∗x^* except by landing on it exactly.

Proof of (a). L(h)=12rTr+hTg+12hTAhL(h) = \tfrac12 r^{\mathsf T} r + h^{\mathsf T} g + \tfrac12 h^{\mathsf T} A h is a quadratic in hh with Hessian AA. If JJ has full column rank, then hTAh=∥Jh∥2>0h^{\mathsf T} A h = \|J h\|^2 > 0 for h≠0h \ne 0, so AA is positive definite, its Cholesky factorization exists, and LL has the unique minimizer given by ∇L=g+Ah=0\nabla L = g + A h = 0, which is the system of line L6. If g≠0g \ne 0, then h≠0h \ne 0 and ∇FTh=gTh=−hTAh<0\nabla F^{\mathsf T} h = g^{\mathsf T} h = -h^{\mathsf T} A h < 0, so hh is a descent direction. □\square

Proof of (b). Let BB be a closed ball around x∗x^* in which the derivatives of rr up to order 2 are Lipschitz. Then AA, SS and ∇2F=A+S\nabla^2 F = A + S are Lipschitz on BB. Because A∗A_* is positive definite and AA is continuous, we can shrink BB so that A(x)A(x) is invertible on BB with ∥A(x)−1∥≤2∥A∗−1∥\|A(x)^{-1}\| \le 2 \|A_*^{-1}\|. Then A(x)−1−A∗−1=A(x)−1(A∗−A(x))A∗−1=O(∥e∥)A(x)^{-1} - A_*^{-1} = A(x)^{-1} (A_* - A(x)) A_*^{-1} = O(\|e\|).

Taylor's theorem with a Lipschitz Hessian gives g(x)=g(x∗)+(A∗+S∗)e+O(∥e∥2)=(A∗+S∗)e+O(∥e∥2)g(x) = g(x^*) + (A_* + S_*) e + O(\|e\|^2) = (A_* + S_*) e + O(\|e\|^2), with e=x−x∗e = x - x^*. Lines L6 and L7 give x+=x−A(x)−1g(x)x_+ = x - A(x)^{-1} g(x), so

e+=e−A(x)−1(A∗+S∗)e+O(∥e∥2)=e−A∗−1(A∗+S∗)e+O(∥e∥2)=−A∗−1S∗e+O(∥e∥2).e_+ = e - A(x)^{-1} (A_* + S_*) e + O(\|e\|^2) = e - A_*^{-1} (A_* + S_*) e + O(\|e\|^2) = -A_*^{-1} S_* e + O(\|e\|^2).

In the second step we replaced A(x)−1A(x)^{-1} by A∗−1A_*^{-1} at the cost O(∥e∥)⋅O(∥e∥)O(\|e\|) \cdot O(\|e\|). □\square

Proof of (c). By (b) there are δ>0\delta > 0 and CC with ∥e+−Me∥≤C∥e∥2\|e_+ - M e\| \le C \|e\|^2 for ∥e∥≤δ\|e\| \le \delta, where M=−A∗−1S∗M = -A_*^{-1} S_*.

If S∗=0S_* = 0, then ∥e+∥≤C∥e∥2\|e_+\| \le C \|e\|^2. For ∥e0∥≤min⁡(δ,1/(2C))\|e_0\| \le \min(\delta, 1/(2C)), induction gives ∥ek+1∥≤C∥ek∥2≤12∥ek∥\|e_{k+1}\| \le C \|e_k\|^2 \le \tfrac12 \|e_k\|, so every iterate stays in the ball and the convergence is quadratic. If r(x∗)=0r(x^*) = 0, then every ri(x∗)=0r_i(x^*) = 0 and S∗=0S_* = 0.

If ∥M∥=c<1\|M\| = c < 1 in an operator norm, pick ϵ\epsilon with c+Cϵ<1c + C \epsilon < 1 (with CC taken for this norm). For ∥e0∥≤min⁡(δ,ϵ)\|e_0\| \le \min(\delta, \epsilon), ∥ek+1∥≤(c+C∥ek∥)∥ek∥≤(c+Cϵ)∥ek∥\|e_{k+1}\| \le (c + C \|e_k\|) \|e_k\| \le (c + C\epsilon) \|e_k\|, which is linear convergence.

If n=1n = 1 and ∣M∣>1|M| > 1, let q=(∣M∣+1)/2>1q = (|M| + 1)/2 > 1 and pick ϵ≤δ\epsilon \le \delta with Cϵ≤∣M∣−qC \epsilon \le |M| - q. For 0<∣e∣≤ϵ0 < |e| \le \epsilon, ∣e+∣≥∣M∣∣e∣−C∣e∣2≥q∣e∣|e_+| \ge |M| |e| - C |e|^2 \ge q |e|. So while the iterates stay in (x∗−ϵ,x∗+ϵ)(x^* - \epsilon, x^* + \epsilon) and differ from x∗x^*, their distance to x∗x^* grows by the factor qq at each step, and after finitely many steps an iterate leaves the interval. □\square

The example of Madsen, Nielsen and Tingleff. Take n=1n = 1, m=2m = 2 and r(x)=(x+1,λx2+x−1)r(x) = (x + 1, \lambda x^2 + x - 1). At x∗=0x^* = 0, r=(1,−1)r = (1, -1), J=(1,1)TJ = (1, 1)^{\mathsf T} and g=1−1=0g = 1 - 1 = 0, so 00 is stationary, A∗=2A_* = 2 and S∗=1⋅0+(−1)⋅2λ=−2λS_* = 1 \cdot 0 + (-1) \cdot 2\lambda = -2\lambda. So M=λM = \lambda and ek+1=λek+O(ek2)e_{k+1} = \lambda e_k + O(e_k^2). Also F′′(0)=A∗+S∗=2−2λF''(0) = A_* + S_* = 2 - 2\lambda, so 00 is a strict local minimizer for every λ<1\lambda < 1. For λ=−2\lambda = -2, F′(x)=(x+1)+(−2x2+x−1)(1−4x)=x(8x2−6x+6)F'(x) = (x + 1) + (-2x^2 + x - 1)(1 - 4x) = x (8x^2 - 6x + 6), and 8x2−6x+68x^2 - 6x + 6 has a negative discriminant, so 00 is the only stationary point and the global minimizer, with F(0)=1F(0) = 1. Yet ∣M∣=2>1|M| = 2 > 1, so by (c) the full step method does not converge to it. The tests of the reference code check both the linear rate 0.50.5 for λ=0.5\lambda = 0.5 and the escape for λ=−2\lambda = -2.

Stopping rules. Line L5 stops at an approximate stationary point. Line L8 stops when the step is small relative to xx. Neither guarantees a minimizer. The method has no globalization, so far from x∗x^* the cost can increase. With a line search that satisfies the Wolfe conditions and a Jacobian whose singular values are bounded away from zero on the level set, JkTrk→0J_k^{\mathsf T} r_k \to 0 (Nocedal and Wright, Theorem 10.1); that variant is not the one in the reference code.

Complexity

In the real RAM model, one iteration costs one evaluation of rr and JJ, Θ(mn2)\Theta(m n^2) to form AA, Θ(mn)\Theta(m n) to form gg, and Θ(n3)\Theta(n^3) for the dense Cholesky factorization. So the cost per iteration is Θ(mn2+n3)\Theta(m n^2 + n^3) plus the evaluation, and the extra space is Θ(mn)\Theta(m n) for JJ. The number of iterations is not bounded in general, since the method can diverge. With zero residual and a start inside the region of quadratic convergence, O(log⁡log⁡(1/ε))O(\log \log (1/\varepsilon)) iterations reach accuracy ε\varepsilon. When JJ is sparse, as in bundle adjustment, AA is sparse too and a sparse factorization replaces the dense one; see the reduced camera system.

Properties

  • Only first derivatives. The method needs rr and JJ, not the second derivatives of rr. The cost is that AA only approximates the Hessian.
  • Descent direction (theorem). If JJ has full column rank and g≠0g \ne 0, then gTh=−∥Jh∥2<0g^{\mathsf T} h = -\|J h\|^2 < 0. A full step can still increase FF.
  • Local rate (theorem). Quadratic for zero residual problems, linear for small residual problems, possibly divergent for large residual problems.
  • Invariance (theorem). The iterates do not change under an invertible linear change of the parameters x=Byx = B y, because hh is the minimizer of a model that does not depend on the coordinates. Gradient descent does not have this property.
  • Not robust. Each residual enters squared, so one gross outlier can move the solution far. Use an M-estimator through iteratively reweighted least squares.

Variants and improvements

  • Damped Gauss-Newton. Take x←x+αhx \leftarrow x + \alpha h with α\alpha from a line search, for example a backtracking line search with the Armijo condition. This gives global convergence to a stationary point under the full rank condition.
  • Levenberg-Marquardt. Solve (A+μI)h=−g(A + \mu I) h = -g and adapt μ\mu. This handles rank deficient JJ and keeps the cost decreasing.
  • Powell's dog leg method. Combine the Gauss-Newton step and the steepest descent step inside a trust region.
  • Large residual problems. Add an approximation of SS, for example by a quasi-Newton update of SS only (Dennis and Schnabel, chapter 10), or switch to full Newton.
  • Inexact steps. For very large nn, solve line L6 approximately by the conjugate gradient method. This is the base of inexact Newton bundle adjustment.
  • Use in bundle adjustment. The Jacobian of the reprojection error has one block per observation, and the Gauss-Newton matrix AA has an arrow structure. Eliminating the points gives the reduced camera system, and sparse bundle adjustment wraps it in Levenberg-Marquardt.

When to use it

Use plain Gauss-Newton when the model fits the data well (small residuals), when JJ has full rank, and when you start close to the answer, for example when refining a pose or a homography from a good linear estimate. Each step is then cheap and the convergence is fast. When the start may be far, when some directions are poorly determined, or when residuals at the solution are large, use Levenberg-Marquardt or the dog leg method, which keep the cost decreasing. When the residuals are not small and second derivatives are available, Newton's method with a line search can be better.

Pitfalls

  • Divergence. Line L7 takes the full step even when it increases FF. Monitor FF and add a line search or switch to Levenberg-Marquardt if it rises.
  • Rank deficient JJ. Line L6 fails when JJ does not have full column rank, which happens in bundle adjustment because of the gauge freedom. Fix the gauge or add damping.
  • Squaring the condition number. Forming A=JTJA = J^{\mathsf T} J in line L4 squares the condition number of JJ. For ill conditioned problems solve the linear least squares problem by QR.
  • Wrong Jacobian. A Jacobian with a sign or scale error still gives a direction, but the fast rate is lost and line L5 may never be met. Check JJ against finite differences.
  • Stopping too early. Line L8 can stop at a point that is not stationary if the steps become small for another reason, such as a very ill conditioned AA. Check ∥g∥\|g\| at the end.

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.

gauss_newton_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gauss-newton-algorithm/. The authors are listed in prov/77QE67.jsonl.

"""The Gauss-Newton algorithm for nonlinear least squares.

The problem is to minimize F(x) = 1/2 ||r(x)||^2 for a residual function
r: R^n -> R^m with m >= n. The caller gives r and its Jacobian J (an m x n
matrix as a list of rows). Each step solves the normal equations
(J^T J) h = -J^T r by a Cholesky factorization and sets x <- x + h, with no
line search and no damping (the classical, full-step method).
"""

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.

    Raises ValueError when a pivot is not positive, that is when J does not
    have full column rank (to working precision)."""
    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("J^T J is not positive definite: J is rank deficient")
        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 gauss_newton(residual: Callable[[Vector], Vector],
                 jacobian: Callable[[Vector], Matrix],
                 x0: Sequence[float], max_iter: int = 50,
                 eps: float = 1e-12) -> Tuple[Vector, List[Vector]]:
    """Run the Gauss-Newton iteration from x0.

    Returns (x, path), where path holds x0 and every iterate. Stops when
    ||J^T r||_inf <= eps, when the step is small relative to x, or after
    max_iter steps. The iteration can diverge; the caller checks the cost."""
    x = [float(v) for v in x0]  # @line L1
    path = [list(x)]
    for _ in range(max_iter):  # @line L2
        r, jac = residual(x), jacobian(x)  # @line L3
        a, g = normal_equations(jac, r)  # @line L4
        if max(abs(v) for v in g) <= eps:  # @line L5
            break
        h = cholesky_solve(a, [-v for v in g])  # @line L6
        x = [xi + hi for xi, hi in zip(x, h)]  # @line L7
        path.append(list(x))
        if math.sqrt(sum(v * v for v in h)) <= eps * (math.sqrt(sum(v * v for v in x)) + eps):  # @line L8
            break
    return x, path  # @line L9
test_gauss_newton_algorithm.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gauss-newton-algorithm/. The authors are listed in prov/77QE67.jsonl.

import math
import random

import pytest

from gauss_newton_algorithm import cholesky_solve, cost, gauss_newton, 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 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 = list(x)
        xm = 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_jacobian_against_finite_differences():
    rng = random.Random(5)
    for _ in range(20):
        x = [rng.uniform(0.5, 3.0), rng.uniform(-1.0, 0.5)]
        a, b = exp_j(x), fd_jacobian(exp_r, x)
        for ra, rb in zip(a, b):
            for u, v in zip(ra, rb):
                assert abs(u - v) <= 1e-6 * max(1.0, abs(u))


def test_zero_residual_exact_recovery_and_quadratic_rate():
    x, path = gauss_newton(exp_r, exp_j, [1.0, 0.0], eps=1e-15)
    assert abs(x[0] - 2.0) < 1e-10 and abs(x[1] + 0.5) < 1e-10
    errs = [math.hypot(p[0] - 2.0, p[1] + 0.5) for p in path]
    # quadratic: e_{k+1} <= C e_k^2 once e_k is small
    for e0, e1 in zip(errs[1:], errs[2:]):
        if 1e-9 < e0 < 0.2:
            assert e1 <= 2.0 * e0 * e0


def test_linear_residual_one_step_is_least_squares():
    rng = random.Random(11)
    ts = [rng.uniform(-2, 2) for _ in range(12)]
    ys = [0.7 * t - 1.3 + rng.gauss(0, 0.1) for t in ts]
    r = lambda x: [x[0] * t + x[1] - y for t, y in zip(ts, ys)]
    j = lambda x: [[t, 1.0] for t in ts]
    x, path = gauss_newton(r, j, [5.0, 5.0], eps=1e-13)
    # closed form of the line fit
    n = len(ts)
    st, sy = sum(ts), sum(ys)
    stt, sty = sum(t * t for t in ts), sum(t * y for t, y in zip(ts, ys))
    a = (n * sty - st * sy) / (n * stt - st * st)
    b = (sy - a * st) / n
    assert abs(path[1][0] - a) < 1e-10 and abs(path[1][1] - b) < 1e-10
    assert abs(x[0] - a) < 1e-10 and abs(x[1] - b) < 1e-10


def test_nonzero_residual_linear_rate():
    lam = 0.5
    _, path = gauss_newton(mnt_r(lam), mnt_j(lam), [0.1], max_iter=12, eps=1e-300)
    ratios = [p1[0] / p0[0] for p0, p1 in zip(path[3:], path[4:])]
    for q in ratios:
        assert abs(q - lam) < 0.01  # e_{k+1} / e_k tends to lambda


def test_nonzero_residual_failure_near_a_minimum():
    lam = -2.0  # x* = 0 is a strict minimizer (F''(0) = 2 - 2 lambda > 0)
    _, path = gauss_newton(mnt_r(lam), mnt_j(lam), [0.1], max_iter=8, eps=1e-300)
    expect = [0.1, -0.302941, 0.136764, -0.467990, 0.066387]
    for p, e in zip(path, expect):
        assert abs(p[0] - e) < 1e-6
    _, path = gauss_newton(mnt_r(lam), mnt_j(lam), [1e-3], max_iter=40, eps=1e-300)
    assert max(abs(p[0]) for p in path) > 0.1  # the iterates leave the neighborhood


def test_against_grid_minimum_on_one_parameter():
    rate = -0.5
    r = lambda x: [2.0 * math.exp(x[0] * t) - y + 0.01 * (k % 2) for k, (t, y) in enumerate(zip(T, Y))]
    j = lambda x: [[2.0 * t * math.exp(x[0] * t)] for t in T]
    x, _ = gauss_newton(r, j, [-0.3], eps=1e-14)
    grid = min((cost(r([rate + i * 1e-5])), rate + i * 1e-5) for i in range(-3000, 3001))
    assert abs(x[0] - grid[1]) < 2e-5
    assert cost(r(x)) <= grid[0] + 1e-12


def test_rank_deficient_jacobian_raises():
    r = lambda x: [x[0] + x[1] - 1.0, 2 * x[0] + 2 * x[1] - 2.5]
    j = lambda x: [[1.0, 1.0], [2.0, 2.0]]
    with pytest.raises(ValueError):
        gauss_newton(r, j, [0.0, 0.0])


def test_cholesky_solve_and_normal_equations():
    jac = [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]
    a, g = normal_equations(jac, [1.0, 0.0, -1.0])
    assert a == [[35.0, 44.0], [44.0, 56.0]] and g == [-4.0, -4.0]
    x = cholesky_solve(a, g)
    assert abs(35 * x[0] + 44 * x[1] + 4) < 1e-12 and abs(44 * x[0] + 56 * x[1] + 4) < 1e-12

History

Gauss used least squares with linearized orbit equations to find the orbits of planets and published the least squares method in his Theoria motus of 1809. The iteration takes its name from him and from Newton's method, of which it is the version without second derivatives. It was used in geodesy and photogrammetry long before the theory of its convergence was written down. Levenberg (1944) and Marquardt (1963) added damping to fix its failures far from the solution. The local analysis with the second derivative term, and the difference between small and large residual problems, is in Dennis and Schnabel (1983) and in Nocedal and Wright (1999). Madsen, Nielsen and Tingleff (2004) give the one-parameter example on which the method fails.

References

  1. Jorge Nocedal and Stephen J. Wright, Numerical Optimization, second edition, Springer, 2006, Chapter 10, Least-squares problems (the Gauss-Newton method and Theorem 10.1, its global convergence with a Wolfe line search when the singular values of J are bounded away from zero)
  2. J. E. Dennis Jr. and Robert B. Schnabel, Numerical Methods for Unconstrained Optimization and Nonlinear Equations, SIAM Classics in Applied Mathematics 16, 1996, Chapter 10, Nonlinear least squares (Theorem 10.2.1, the local convergence of Gauss-Newton and the role of the second derivative term)
  3. 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.1, The Gauss-Newton method (Example 3.3, the residual (x + 1, λx^2 + x - 1), on which the method converges linearly or fails)
  4. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Appendix 6, Iterative estimation methods (Newton iteration and the Gauss-Newton method, and their use for 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