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.
- 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 iterations; m = the number of residuals; n = the number of parameters, with m >= n
- Model
- Real RAM
- Properties
- deterministicnot globally convergentiterativelocaliterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Carl Friedrich Gauss, 1809
The Gauss-Newton algorithm minimizes a sum of squares of smooth residuals of a parameter vector . At each step it replaces each residual by its linear approximation , where is the Jacobian, and moves to the minimizer of that linear least squares model: it solves the normal equations and sets . It is Newton's method on with the second derivative term of the Hessian dropped, so it needs only first derivatives. Near a solution where the residuals are zero and 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 with , its Jacobian (an matrix), a start , a tolerance and an iteration limit .
Output. A point that is close to a stationary point of , that is, . The method finds a local minimizer only when it converges. It does not find the global one in general.
Notation. and . The Hessian of is with . Gauss-Newton uses in place of .
The algorithm
GAUSS-NEWTON(r, J, x_0, ε, k_max)- 1
x <- x_0 - 2
for k <- 1 to k_max - 3
r <- r(x) ; J <- J(x) - 4
A <- J^T J ; g <- J^T r - 5
if ||g||_∞ <= ε then return x - 6
solve A h = -g by Cholesky - 7
x <- x + h - 8
if ||h|| <= ε (||x|| + ε) then return x - 9
return x
Line L3 evaluates the residual and the Jacobian at the current point. Line L4 forms the normal equations of the linear model , whose gradient is . Line L5 stops at a point where the gradient of is small. Line L6 finds the minimizer of by a Cholesky factorization of ; it fails when 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 . A numerically safer form of line L6 solves the linear least squares problem by a QR decomposition of , which does not square the condition number.
Example
Fit to the four exact values at , so the residuals are and the solution is with . Start at . Then , has rows , and . Line L6 gives .
| 0 | |||
| 1 | |||
| 2 | |||
| 3 | |||
| 4 |
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 with one parameter. Its minimizer is for every , with , and near it the Gauss-Newton error obeys . From :
| behavior | ||
|---|---|---|
| linear, the ratio tends to | ||
| no convergence |
For , is the only stationary point and the global minimizer of , 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 has full column rank, and that step is a descent direction for . The local behavior follows from the error recursion at a stationary point with of full column rank and smooth residuals. If , which holds when , the convergence is quadratic (theorem). If it is linear (theorem). If in one dimension, the iterates leave every small neighborhood of (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 bounded away from zero, (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 with , the cost is , is the Jacobian of , and . The second derivative term is . Then and .
Claim. (a) If has full column rank, line L6 is well defined, its step is the unique minimizer of the linear model , and is a descent direction of whenever . (b) Let be a stationary point () such that has full column rank, and let be twice differentiable with Lipschitz continuous first and second derivatives near . Then the error satisfies
(c) As a consequence, if (in particular if ), the iteration converges quadratically from every start close enough to . If in some operator norm, it converges at least linearly. If and , no start gives iterates that stay in a small neighborhood of , so the full step method does not converge to except by landing on it exactly.
Proof of (a). is a quadratic in with Hessian . If has full column rank, then for , so is positive definite, its Cholesky factorization exists, and has the unique minimizer given by , which is the system of line L6. If , then and , so is a descent direction.
Proof of (b). Let be a closed ball around in which the derivatives of up to order 2 are Lipschitz. Then , and are Lipschitz on . Because is positive definite and is continuous, we can shrink so that is invertible on with . Then .
Taylor's theorem with a Lipschitz Hessian gives , with . Lines L6 and L7 give , so
In the second step we replaced by at the cost .
Proof of (c). By (b) there are and with for , where .
If , then . For , induction gives , so every iterate stays in the ball and the convergence is quadratic. If , then every and .
If in an operator norm, pick with (with taken for this norm). For , , which is linear convergence.
If and , let and pick with . For , . So while the iterates stay in and differ from , their distance to grows by the factor at each step, and after finitely many steps an iterate leaves the interval.
The example of Madsen, Nielsen and Tingleff. Take , and . At , , and , so is stationary, and . So and . Also , so is a strict local minimizer for every . For , , and has a negative discriminant, so is the only stationary point and the global minimizer, with . Yet , so by (c) the full step method does not converge to it. The tests of the reference code check both the linear rate for and the escape for .
Stopping rules. Line L5 stops at an approximate stationary point. Line L8 stops when the step is small relative to . Neither guarantees a minimizer. The method has no globalization, so far from 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, (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 and , to form , to form , and for the dense Cholesky factorization. So the cost per iteration is plus the evaluation, and the extra space is for . 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, iterations reach accuracy . When is sparse, as in bundle adjustment, is sparse too and a sparse factorization replaces the dense one; see the reduced camera system.
Properties
- Only first derivatives. The method needs and , not the second derivatives of . The cost is that only approximates the Hessian.
- Descent direction (theorem). If has full column rank and , then . A full step can still increase .
- 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 , because 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 with 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 and adapt . This handles rank deficient 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 , for example by a quasi-Newton update of only (Dennis and Schnabel, chapter 10), or switch to full Newton.
- Inexact steps. For very large , 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 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 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 . Monitor and add a line search or switch to Levenberg-Marquardt if it rises.
- Rank deficient . Line L6 fails when 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 in line L4 squares the condition number of . 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 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 . Check 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.
# 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
- 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)
- 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)
- 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)
- 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
- Direct image alignment
- Fast global registration
- Geiger's method
- Least-squares fitting of spheres, cylinders, cones and tori
- GraphSLAM
- Incremental 4D-Var
- Inverse compositional image alignment
- Iteratively regularized Gauss-Newton method
- Levenberg-Marquardt algorithm
- Point-to-plane ICP
- Powell's dog leg method
- Prediction error method
- Randomize-then-optimize
- Real-time iteration
- Weak-constraint 4D-Var
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 77QE67 Edit this page History Report an error Markdown