A robot's camera measures the bearing to four landmarks, each about 2° off. Start the guess by the far wall: Gauss-Newton's steps leave the room, and after 5 steps the guess is 169 km away. Levenberg-Marquardt, from the same guess, is within 1 cm of the best point after 5 steps, and every step goes downhill.
Run Gauss-Newton, then Levenberg-Marquardt. Then drag the warm start ring anywhere on the floor. Then we build it piece by piece: the squares, the linear case, the Jacobian, both solvers, where each fails, and how sure the answer is.
You need Lecture 7 (bearings, triangulation), Lecture 8 (RANSAC hands over clean matches), a little matrix algebra and a little Python. We build the rest from zero.
Lecture 9 of 14 in our follow-along of MIT 16.485, Visual Navigation for Autonomous Vehicles (VNAV, taught by Luca Carlone). Every idea is re-taught here in our own words and devices. Previous: Lecture 8, RANSAC. Next: Lecture 10, optimization on manifolds.
Illustrative toy floor: bearings with 2° of Gaussian noise drawn once from a seed; the robot knows its heading. Levenberg-Marquardt starts with λ equal to the largest diagonal entry of J⊤J and divides or multiplies it by 10. It runs in your browser; scipy.optimize.least_squares finds the same best point.
Chapter 0
Drag a guess across the floor and watch four small angle errors pull against each other
A robot stands on a 10 m × 8 m floor. Its camera sees four landmarks on the far wall. For each one it measures a bearing: the direction to the landmark, as an angle in the world frame. The IMU gives the robot's heading, so the only unknowns are its position x and y.
Each bearing says "you stand somewhere on this ray". With perfect bearings the four rays would cross at one point. With 2° of noise they do not. No point satisfies all four. So the question changes: which point disagrees with the measurements least?
Blue rays run back from each landmark along its measured bearing. Drag the purple guess. At the guess, yellow arcs show the gap between each measured direction and the direction the guess predicts.
Illustrative toy floor: the same four noisy bearings as the hero. Bars show each residual divided by its 2° noise, squared.
Name the measured bearing to landmark i zi. Name the bearing a guess x predicts hi(x): the angle of the line from x to landmark i. Their gap is the residual.
r-i of x equals z-i minus h-i of x.
Pick a guess x. Work out the bearing h-i it predicts to landmark i. Subtract it from the measured z-i. The answer r-i is small when x agrees with that measurement.
Landmark 3 stands at (6.5, 7.0) and the camera measured z3 = 70.0°. A guess at the true spot (5, 2) predicts 73.3°, so r3 = −3.3°. Even the truth has residuals: the noise put them there.
Four residuals pull in different directions, and the guess must trade them off. In the device, the true robot position leaves residuals of −1.6°, 0.5°, −3.3° and 1.3°. The best point, 0.13 m away, leaves −0.4°, 1.7°, −2.4° and 1.7°: a fairer share. Chapter 1 shows why squaring and adding is the right way to score the trade.
Symptom: an estimator that trusts one bearing and ignores the rest, so one noisy reading moves the answer.
Measure: the residuals at the answer. One large residual and three tiny ones means the trade was not fair.
Fix: score every residual by its noise (Chapter 1) and minimise the total.
Chapter 1
Blur one landmark and watch the right weights keep the estimate on the robot
Treat each measurement as the truth plus noise: zi = hi(x) + εi. Assume the noise εi is Gaussian, a bell curve with mean zero and standard deviation σi ("sigma-i"). Then the chance of residual ri at a guess x is a bell:
Read it as "the chance of z-i given x is proportional to e to the minus r-i squared over two sigma-i squared". The four noises are independent, so the chance of all four readings is the product of four bells. That product is the likelihood. The maximum likelihood estimate is the guess that makes it largest.
Take the logarithm: the product becomes a sum. Add a minus sign: "largest" becomes "smallest". What is left is a sum of squares, each over its noise squared.
x-hat equals the arg min over x of the sum over i of r-i of x squared, over sigma-i squared.
Divide each residual r-i by its noise sigma-i, square it, and add the four. Call the total the cost C. The guess x-hat with the smallest C is the most likely position. A noisy landmark, with a big sigma-i, counts less.
At the best point, landmark 3 leaves r3 = −2.43° with σ = 2°: (2.43 / 2)2 = 1.48. The four terms add to C = 2.94. Blur landmark 3 to σ = 8° and its weight falls 16 times.
This is weighted least squares. Its weight is also called the information. Here each residual is one number, so the weight is a number. For a 2-D pixel residual it becomes the matrix Σi−1, and the term becomes ri⊤Σi−1ri. The squares are the logarithm of the bell, not a habit.
Slide landmark 3's real noise up: its blue ray swings further off. Then switch between equal weights and weights 1/σ2, and compare each estimate with the robot.
Illustrative: the same standard-normal draw for every slider position, scaled by each landmark's σ. The averages come from 500 seeded redraws, solved in your browser.
At σ3 = 8°, equal weights miss the robot by 0.57 m on this draw and the weighted estimate by 0.21 m. Over 500 redraws the average miss is 0.41 m against 0.27 m. The weights help only if the σ's are right. Combining Two Measurements builds this rule from two thermometers.
Symptom: one known-noisy sensor drags every estimate.
Measure: each residual divided by its σ. Above 3 means a σ is too small, or an outlier.
Fix: give each sensor its own σ. Remove outliers first with RANSAC (Lecture 8); the Gaussian model does not cover them.
Chapter 2
Turn each bearing into a straight line and find the point closest to all four at once
The bearing model has an atan2 in it, so the cost is not a simple bowl. Lecture 7's triangulation trick still works. A bearing zi says the robot lies on the line through landmark i with direction (cos zi, sin zi). That line is linear in x and y.
A point lies on a line when its offset from the landmark has no part across the line. The cross direction is (sin zi, −cos zi). So the condition is one equation per landmark:
Sine z-i times l-x-i minus x, minus cosine z-i times l-y-i minus y, equals zero.
Move the known parts to the right. Each landmark gives one row: sin z-i times x minus cos z-i times y equals sin z-i times l-x-i minus cos z-i times l-y-i. Stack the four rows as A x = b, with A a 4 × 2 matrix.
Landmark 1 at (1.5, 7.2), measured z1 = 122.3°: sin z1 = 0.845, cos z1 = −0.535. Its row is 0.845 x + 0.535 y = 0.845 × 1.5 + 0.535 × 7.2 = 5.12.
Four equations and two unknowns make an overdetermined system: the noisy lines share no point. Linear least squares picks the point that makes the sum of squared row errors Σ(aix − bi)2 smallest. Each row error is the perpendicular distance from the point to that bearing line, in metres.
The hollow purple ring is the linear answer; yellow segments are its distances to each line. The solid purple dot is the best point from Chapter 1. Slide landmark 1 further away along its line.
Illustrative: landmark 1 moves along its true ray, keeping its 1.6° noise. The floor view widens as it moves.
On the hero's bearings the linear point lands at (4.92, 1.89), 4.0 cm from the best point. Close, not equal. A line distance is the range times the angle error, so a far landmark's line errors count more than its angle deserves. Push landmark 1 to three times its distance and the gap grows to 32 cm. The linear point then misses the robot by 0.42 m, the best point by 0.13 m.
Symptom: a linear answer that drifts toward the far landmarks as you add range.
Measure: its bearing residuals against those of a nonlinear fit.
Fix: use it only as the start for Gauss-Newton (Chapter 5), as Lecture 7 did with triangulation.
Chapter 3
Bunch the landmarks together and watch one direction of the answer go soft
The cost ‖Ax − b‖2 is a bowl in x. At the bottom of a bowl the slope is zero in every direction. Write the cost out, (Ax − b)⊤(Ax − b), take its gradient 2A⊤Ax − 2A⊤b, and set it to zero.
A transpose A, times x-hat, equals A transpose b.
Multiply A by its own transpose to get a 2 × 2 matrix. Multiply b by A's transpose to get a 2-vector. Solve the 2 × 2 system for x-hat. Geometrically, the leftover b − A x-hat is then at right angles to every column of A.
The smallest case by hand: fit y = a t + c to (1, 2.1), (2, 3.9), (3, 6.2), (4, 7.8). A⊤A = [[30, 10], [10, 4]], A⊤b = [59.7, 20.0]. The determinant is 30 × 4 − 10 × 10 = 20. So a = (4 × 59.7 − 10 × 20) / 20 = 1.94, and c = (30 × 20 − 10 × 59.7) / 20 = 0.15. The residuals are 0.01, −0.13, 0.23 and −0.11.
For the four bearings, A⊤A = [[3.253, −0.151], [−0.151, 0.747]] and A⊤b = [15.704, 0.673], which gives (4.92, 1.89). The two numbers on the diagonal already tell a story: 3.25 for x, 0.75 for y. The rows constrain left-right more than toward-the-wall.
The purple ellipse is the shape of (A⊤A)−1: long where the lines pin the point weakly. Slide the landmarks toward the middle of the wall and watch the lines turn parallel.
Illustrative: landmarks keep their wall height; their x positions shrink toward x = 5 m. Bearings keep the same angle noise. The ellipse is scaled for visibility.
The eigenvalues of A⊤A measure how strongly the data pin each direction. Their ratio is the condition number: 4.4 at full spread. Bunch the landmarks and the lines turn parallel; the small eigenvalue heads to zero. At 4% spread the condition number is 945 and the linear point lands 3.9 m off. Depth becomes unobservable: no amount of data along those parallel lines fixes it.
Symptom: estimates that jump far along one direction from frame to frame.
Measure: the condition number of A⊤A (or J⊤J). Above about 106, solve by QR or SVD, not by inverting.
Fix: add a measurement that sees the weak direction: a landmark off to one side, a prior, a second view.
Chapter 4
Slide a step along the floor and watch the straight-line guess part from the true curve
Back to the true bearing cost, which has no straight-line form. Near any guess x̄ ("x-bar"), though, a smooth curve looks straight. Know how each residual changes when x and y move a little, and you can swap the curve for its tangent and solve a linear problem.
Name the small move δ ("delta"), a 2-vector in metres. The Jacobian Ji is the row of rates: how much ri changes per metre of x and per metre of y.
r-i at x-bar plus delta is about r-i at x-bar, plus J-i times delta.
Stand at x-bar. Multiply the move delta by the rates in J-i and add the result to today's residual. That is the residual you predict after the move. It is good while delta is small next to the range rho.
From x̄ = (1, 1), landmark 2 at (4.0, 7.6) is 3.0 m right and 6.6 m up, so ρ2 = 52.6 m2. Its bearing turns 6.6 / 52.6 = 0.126 rad, or 7.2°, per metre of x. A 0.1 m step predicts 0.72°; the true change is 0.72° too.
The purple curve is the bearing a robot would see as it slides along x from (1, 1). The dashed line is the Jacobian's tangent. Slide the step and pick a landmark; the yellow gap is the linearization error.
Exact geometry; the start (1, 1) is the hero's near-corner start. The Jacobian here is analytic; a finite difference with a 10−6 m step agrees to six digits.
For landmark 2 a 1 m step predicts 7.20° and the truth is 7.59°, 5% more. A 2 m step predicts 14.4° against 15.8°. The rates scale as 1/ρ: a near landmark has a steep, fast-bending curve, so its tangent fails sooner. The Jacobian is also an observability test: if no row of J changes with some direction, no data can fix that direction.
Symptom: a solver that stalls or steps the wrong way although the model is right.
Measure: compare J with a finite difference, (r(x + ε) − r(x − ε)) / 2ε, at a few random points.
Fix: fix the sign or the chain-rule factor. The most common bug is the Jacobian of h instead of r: they differ by a minus sign.
Chapter 5
Step the solver from a corner and watch the cost fall by a factor of ten each step
Put the two ideas together. Replace each residual by its tangent, ri + Jiδ, and the cost becomes ‖r + Jδ‖2: a linear least-squares problem in δ. Chapter 3 solves it in one line. Take the step, stand at the new point, and do it again.
Here J stacks the four rows Ji into a 4 × 2 matrix and r stacks the four residuals. The weights 1/σi2 sit in a diagonal matrix W.
J transpose W J, times delta, equals minus J transpose W r.
From (1, 1): J⊤WJ = [[44.0, −17.7], [−17.7, 13.3]] per m2 and J⊤Wr = [−192.2, 80.7] per m. Solving gives δ = (4.15, −0.54) m, so the guess jumps to (5.15, 0.46). The cost falls from 845.7 to 31.1.
Choose a start and press Step. Each warm arrow is one Gauss-Newton step; the bars below show the cost after each, on a log scale.
The hero's bearings. Cost C = Σ(ri/σi)2, unitless.
From the near corner the costs run 845.7, 31.1, 4.4, 2.94: within 1 cm of the best point after 4 steps. Near the answer each step shrinks the error many times over, so the last steps are fast. Why does this work without second derivatives? Newton's method would use the full curvature J⊤WJ + Σri∇2ri/σi2. Gauss-Newton drops the second part, which is small when the residuals are small or nearly linear. That holds near a good fit.
Symptom: the cost goes up after a step, or the guess leaves the room.
Measure: the cost before and after each step, and the step length against the distance to the landmarks.
Fix: the solver trusted the tangent too far. Damp the step (Chapter 6) or start closer, from the linear answer of Chapter 2.
Chapter 6
Turn the damping and watch the step shrink from a leap out of the room to a careful step downhill
From the far wall, Gauss-Newton's first step is 12.7 m long. It lands at (−9.35, −0.94), outside the room. The cost did fall, from 5,738 to 3,699, but the tangent model is now useless. The next full step is 45 m long and the cost jumps to 9,029. After five steps the guess is 169 km away.
Levenberg (1944) gave the fix and Marquardt (1963) rediscovered it: add a number λ ("lambda"), the damping, to the diagonal of the Gauss-Newton matrix.
J transpose W J plus lambda I, times delta, equals minus J transpose W r.
With lambda at zero, delta is the full Gauss-Newton step. As lambda grows, lambda I dominates, and delta becomes minus J transpose W r divided by lambda: a short step straight downhill. Lambda slides the step between the two.
At the wall start the largest diagonal entry of J⊤WJ is 894, so we start with λ = 894. The step is 1.02 m, to (1.09, 5.78), and the cost falls from 5,738 to 3,079: accept, and divide λ by 10.
The run sets λ itself, by a simple form of Marquardt's rule:
The thin warm curve is every damped step from this start, from λ = 0 (its far end) to huge λ (at the start). The arrow is the step for your λ; the dashed circle has the step's length as radius.
The hero's bearings. Accept means the cost after the step is lower than before.
Two readings of λ help. The first is a trust region. Among all steps no longer than itself, the damped step is the best one for the tangent model (Nocedal and Wright, Chapter 10). Big λ, small circle. As a blend: small λ gives Gauss-Newton's speed near the answer, big λ gives gradient descent's caution far away.
From where Gauss-Newton landed, λ = 0 asks for a 45 m step. The cost rises from 3,699 to 9,029: reject. λ = 1 asks for 16 m, and the cost falls to 382: accept. The same knob saves both starts.
Symptom: Levenberg-Marquardt crawls: hundreds of tiny accepted steps.
Measure: λ over the run. If it never falls, the steps are pure gradient descent.
Fix: check J (Chapter 4) and the scale of the unknowns. Mixed units, metres and radians, call for damping by diag(J⊤WJ) instead of I, as Ceres and MINPACK (SciPy's method 'lm') do.
Chapter 7
Run both solvers from 315 starts and paint the floor by where each one ends
Both solvers are local: they see only the slope and curvature where they stand. Whether they reach the best point depends on the start. The set of starts that reach it is the basin of convergence.
Each half-metre cell is one start. Green: the solver reaches the best point. Red: it diverges. Tap a cell to draw that run.
A 0.5 m grid of starts over the 10 m × 8 m floor, skipping 5 cells within 0.3 m of a landmark. Up to 30 Gauss-Newton steps or 300 LM tries. Computed in your browser; our NumPy script gets the same counts.
Gauss-Newton reaches the best point from 301 of the 315 starts, in a median of 3 steps. All 14 failures start within 1.8 m of the far wall, where a step of a metre swings a bearing by tens of degrees. Levenberg-Marquardt reaches it from all 315, in a median of 4 steps. It pays one step of caution for a basin that covers the floor.
This toy has one valley, so every failure is a runaway. Many real problems have several valleys, called local minima. Even two-view triangulation in reprojection error can have more than one (Hartley and Sturm, 1997), and bundle adjustment over many frames has many. No local solver escapes a wrong valley; only a better start does.
That is why the pipeline runs in this order. A linear or minimal solver gives a start: Chapter 2's lines, Lecture 7's 8-point algorithm. RANSAC (Lecture 8) makes sure that start comes from inliers. Then Gauss-Newton or Levenberg-Marquardt polishes it.
Symptom: the solver converges, but to a pose that is plainly wrong.
Measure: the final cost against what the noise predicts. With m residuals and n unknowns the cost should be near m − n; here 2.94 against 2.
Fix: a better start: the linear solution, a RANSAC inlier set, the previous frame's pose.
Chapter 8
Redraw the noise hundreds of times and watch the cloud of answers fill the predicted ellipse
An estimate without an error bar cannot be fused with anything. A Kalman filter, a factor graph or a planner needs to know how far to trust (4.89, 1.93). The same matrix that drove Gauss-Newton answers it.
Near the best point the cost is a bowl, and the bowl's curvature is J⊤WJ: the information matrix of the estimate. Steep sides mean the data pin that direction hard. Call the uncertainty of the estimate its covariance Σx̂ ("sigma x-hat").
Sigma x-hat is about the inverse of J transpose W J.
At the final estimate x-hat, build J transpose W J and invert it. The square roots of its diagonal are the standard deviations of x and y. Its eigenvectors give the axes of the uncertainty ellipse.
At (4.89, 1.93), J⊤WJ = [[77.4, −3.6], [−3.6, 15.5]] per m2. Its inverse is [[0.0131, 0.0030], [0.0030, 0.0653]] m2, so x has a spread of ±0.11 m and y of ±0.26 m. Depth toward the wall is the soft direction.
The purple ellipse is the 95% region predicted by (J⊤WJ)−1. Press Run: 300 times, the page draws new 2° noise and localizes the robot again. Slide the robot toward the wall.
Illustrative: seeded noise, each trial solved from the linear start. The page draws the ellipse at the true position; its half-axes are 2.45 standard deviations, the 95% point of a chi-square with 2 degrees of freedom.
We ran 2,000 trials at the hero's robot position. 95.3% of the estimates fell inside the predicted 95% ellipse. Their spread was ±0.113 m in x and ±0.249 m in y, against ±0.113 and ±0.251 predicted. Slide the robot up to y = 6 m, near the landmarks, and the bearings fan out: the predicted y spread shrinks to ±0.05 m.
The formula is a first-order result. It assumes the noise is Gaussian with the right σ, and that the model is close to linear over the size of the ellipse. Both hold here; with a far robot or a big σ the cloud bends into a banana shape and the ellipse is only a sketch.
Symptom: a filter that fuses this estimate grows overconfident and then jumps.
Measure: how often the truth falls inside the 95% ellipse, in simulation or on ground truth. It should be near 95%.
Fix: correct the σ's, or inflate the covariance. An ellipse that is too small is worse than none.
Chapter 9
Choose the landmarks, the noise and the start, and watch both solvers run with their cost curves
Everything at once. Choose three, four or six landmarks, set the bearing noise, drag the warm start anywhere, and run either solver. The left panel shows the floor, the path and the final 95% ellipse. The right panel shows the cost after each try on a log scale. For Levenberg-Marquardt, a green dot is an accepted step and a red dot a rejected one.
Drag the warm ring to set the start. Press Run; then change the landmarks, the noise, or the solver.
Illustrative toy floor; the first draw is the hero's. Extra landmarks stand at (0.4, 3.5) and (9.6, 4.0). The solver knows the true σ.
Things to try. With three landmarks on the wall, the predicted spread toward the wall grows to ±0.33 m. With six, two on the side walls, it falls to ±0.12 m: the side bearings cross the wall bearings at a wide angle. Put Gauss-Newton by the far wall and it runs away; switch to Levenberg-Marquardt and it comes home. Raise the noise to 8° and the ellipse swells, but the solvers still agree.
Chapter 10
Keep the formulas, the numbers and the code side by side
Gaussian noise turns the most likely state into weighted least squares. A linear model solves in one step by the normal equations. A nonlinear model is linearized with its Jacobian and solved again and again: Gauss-Newton takes full steps, Levenberg-Marquardt damps them so the cost never rises. At the end, the inverse of J⊤WJ says how sure the answer is.
| Piece | Formula | Number on this page | Watch out |
|---|---|---|---|
| Residual | ri = zi − hi(x) | truth: −1.6°, 0.5°, −3.3°, 1.3° | wrap angles to ±180° |
| Maximum likelihood | argmin Σ ri2/σi2 | best point (4.89, 1.93), C = 2.94 | only for Gaussian noise |
| Linear rows | sin zi x − cos zi y = bi | (4.92, 1.89), 4.0 cm from best | weights by range |
| Normal equations | (A⊤A)x̂ = A⊤b | condition number 4.4; 945 bunched | solve, do not invert |
| Jacobian of a bearing | [−(ly − y), lx − x] / ρ2 | 7.2° per metre at (1, 1) | r versus h: a minus sign |
| Gauss-Newton | (J⊤WJ)δ = −J⊤Wr | 301 of 315 starts; median 3 steps | runs away near the wall |
| Levenberg-Marquardt | (J⊤WJ + λI)δ = −J⊤Wr | 315 of 315 starts; median 4 steps | local, not global |
| Covariance | Σx̂ ≈ (J⊤WJ)−1 | ±0.11 m, ±0.26 m; 95.3% inside | first order, right σ |
python import numpy as np from scipy.optimize import least_squares L = np.array([[1.5, 7.2], [4.0, 7.6], [6.5, 7.0], [8.8, 7.4]]) # landmarks, metres z = np.array([2.1352, 1.7560, 1.2215, 0.9805]) # measured bearings, rad sig = np.deg2rad(2.0) * np.ones(4) wrap = lambda a: (a + np.pi) % (2 * np.pi) - np.pi def res(x): # whitened residuals r_i / sigma_i, shape (4,) return wrap(z - np.arctan2(L[:, 1] - x[1], L[:, 0] - x[0])) / sig def jac(x): # shape (4, 2) d = L - x; q = (d**2).sum(1) return np.stack([-d[:, 1] / q, d[:, 0] / q], 1) / sig[:, None] def levenberg_marquardt(x, tau=1.0, iters=100): J = jac(x); lam = tau * np.max(np.diag(J.T @ J)); c = res(x) @ res(x) for _ in range(iters): J, r = jac(x), res(x) d = np.linalg.solve(J.T @ J + lam * np.eye(2), -J.T @ r) # lam = 0: Gauss-Newton cn = res(x + d) @ res(x + d) if cn < c: x, c, lam = x + d, cn, lam / 10 # accept, trust more else: lam *= 10 # reject, damp more if np.linalg.norm(d) < 1e-9: break return x, np.linalg.inv(jac(x).T @ jac(x)) # estimate and covariance x_hat, cov = levenberg_marquardt(np.array([0.75, 6.75])) # about (4.893, 1.927) x_sp = least_squares(res, [0.75, 6.75], jac=jac, method='lm').x # the same point
Our hand loop and scipy.optimize.least_squares, both with method 'lm' (MINPACK) and the default 'trf', agree on (4.8929, 1.9269) to the printed digits. In 2-D the state is a vector, so x + δ is fine. A 3-D rotation is not: the next lecture applies the step on the manifold, R ← R exp(δ∧), with the tools of Lecture 2.
Lecture 7 gave linear and minimal solvers. Lecture 8 kept only the matches that agree. This lecture refines the answer by nonlinear least squares and reports its covariance. Lecture 10 does the same with rotations and poses as unknowns. Visual-inertial odometry (Lecture 11) and SLAM (Lecture 13) are this solver on thousands of unknowns, where the sparsity of J⊤WJ makes it fast.
Now press Present or Teach. Derive weighted least squares from the Gaussian, write a bearing as a line, derive the normal equations, and say what λ does at 0 and at infinity. Then go back to the hero and explain why Gauss-Newton leaves the room from the far wall while Levenberg-Marquardt comes home.