Three noisy ranges, one robot. From the corner of the room, Gauss-Newton finds the best spot in 4 steps, but its first step climbs uphill. Levenberg-Marquardt takes 5 steps, every one downhill. Plain gradient descent takes 58.
Pick a solver and press Run. Tap the floor to start somewhere else. Then we build, piece by piece, the cost, the Jacobian, the Gauss-Newton step, the damping knob, the robust kernel and the error ellipse.
You need a little algebra, what a vector is and some Python for the code. We build the rest from zero.
A foundation lesson for the estimation and robotics track. It sits between Jacobians and Linearization and the SLAM back ends in Factor Graphs and AA274A SLAM.
Illustrative toy. Beacons sit at (0, 0), (10, 0) and (0, 10) m, and the robot at (3, 4). The measured ranges 5.2, 8.0 and 6.9 m carry made-up noise. Darker purple is lower cost. Gradient descent uses a fixed step of 0.1; Levenberg-Marquardt starts with damping 1. Step counts are to within 1 cm of the best spot; NumPy gives the same counts.
Chapter 0
See why noisy ranges have no exact answer, and name the best one
A small robot sits in a room. Three beacons hang on the walls at known spots. The robot pings each one and turns the echo time into a distance: 5.2 m, 8.0 m and 6.9 m. Where is the robot?
With perfect distances, draw a circle around each beacon. The circles cross at one point, and that point is the robot. This is trilateration: finding a position from distances to known points. GPS does the same with satellites.
Real distances carry noise. An echo bounces off a wall, a clock drifts. So the circles miss each other and leave a small triangle of near misses. You want the one point that disagrees least with all three readings.
Blue circles are the three measured ranges. Pink lines are how far your orange guess misses each circle. Drag the guess and make the total as small as you can.
Illustrative toy: the same room as the hero. The best spot is (3.21, 4.02) m with a total squared miss of 0.0277 m²; NumPy and scipy.optimize.least_squares agree.
The hard part is the shape of the link between position and range. Call the robot's position p = (x, y). Call the position of beacon i (ui, vi). The range the robot would read from p, with no noise, is the predicted range hi(p).
h-i of p equals the square root of, x minus u-i squared, plus y minus v-i squared.
Subtract the beacon's x from your x, and its y from your y. Square both gaps, add them, take the square root. That is h-i.
With made-up numbers: test p = (5, 5) against beacon one at (0, 0). The gaps are 5 and 5, so h-1 = √50 = 7.07 m. The beacon reported 5.2 m, so this guess misses by 1.87 m.
The square root bends the link. Move 1 m and the range changes by anything from 0 to 1 m, depending on direction. So you cannot stack three straight equations and solve. You search instead, for the position that makes the total squared miss smallest. That search is nonlinear least squares.
Failure to watch for: the symptom is a "position" that jumps between runs. Measure it by printing the total squared miss at the answer. If it is far above the noise you expect, the search stopped early or a reading is bad. Chapters 5 and 7 fix those two cases.
Chapter 1
Fit a line to three noisy points in one shot, and see the right angle behind it
Master the straight case first. You calibrate a cheap sensor at three known temperatures, 0, 1 and 2 degrees. It reads 1.0, 2.0 and 2.0 volts. You expect voltage = a + b × temperature. Which intercept a and slope b fit best?
Write one row per reading. Put the unknowns in a vector θ = (a, b). Put the readings in y = (1, 2, 2). The design matrix A has one row per reading: a 1 for the intercept and the temperature for the slope. So A has rows (1, 0), (1, 1), (1, 2).
Three equations, two unknowns: no line passes through all three points. The prediction Aθ always lies on the flat sheet of what A can produce. The best fit is the point on that sheet closest to y. There, the leftover miss stands at a right angle to every column of A. Write that right angle as algebra and you get the normal equations.
A-transpose A times theta equals A-transpose times y.
Dot each column of A with every column of A: that gives a 2 by 2 matrix. Dot each column of A with y: that gives 2 numbers. Solve the 2 by 2 system for theta.
A-transpose A = [[3, 3], [3, 5]] and A-transpose y = (5, 6). So 3a + 3b = 5 and 3a + 5b = 6. Subtract: 2b = 1, so b = 0.5 and a = 7/6 = 1.167. The line is volts = 1.167 + 0.5 × temperature.
Pink bars are the misses at each point. Move the two sliders and watch the total squared miss. Then press the snap button.
Illustrative toy data. The least-squares line is a = 1.167, b = 0.5, with a total squared miss of 0.167 V².
Check the misses, prediction minus reading: +0.167, −0.333, +0.167. They add to zero. That always happens when the model has an intercept, because the first normal equation forces it.
pythonimport numpy as np A = np.array([[1, 0], [1, 1], [1, 2]], dtype=float) # [3, 2] y = np.array([1.0, 2.0, 2.0]) # [3] theta = np.linalg.solve(A.T @ A, A.T @ y) # [1.1667, 0.5] theta2, *_ = np.linalg.lstsq(A, y, rcond=None) # same answer, safer route
Failure: the symptom is a fit that changes wildly when one reading moves a little. Measure the condition number of A-transpose A with np.linalg.cond. Forming A-transpose A squares it, so 104 becomes 108. Fix: use lstsq, which works on A directly.
Chapter 2
Turn three misses into one cost, and see which noise makes squares the right choice
A residual is the signed miss of one reading: the predicted value minus the measured value. One guess gives three residuals. You need one number to rank guesses.
Adding the residuals fails: +3 and −3 cancel to zero, yet both are wrong. Absolute values or squares both fix the sign. Squares win for a reason. Assume each reading has bell-shaped Gaussian noise with the same spread for every beacon. Then the likelihood of the readings falls as the sum of squared residuals grows. So the smallest sum of squares is the maximum likelihood answer: the position that makes the readings most probable.
A check with numbers. Let the noise spread be 0.3 m. A residual of 0.1 m has a bell-curve density of 1.26. A residual of 0.6 m has 0.18. The smaller residual is seven times more likely, and its square, 0.01, is smaller than 0.36. The two rankings always agree.
Now name the cost. Call the measured range from beacon i zi. The residual is ri = hi(p) − zi. The cost F(p) is the sum of the squared residuals.
F of p equals the sum over i of, h-i of p minus z-i, squared.
For each beacon, subtract the measured range z-i from the predicted range h-i. Square that residual. Add the squares. The total is F.
At p = (5, 5) the residuals are 1.871, −0.929 and 0.171 m. F = 3.501 + 0.863 + 0.029 = 4.393 m². At the best spot F falls to 0.028.
Pink is the squared cost, grey the absolute cost. Drag the residual and watch the gap open.
Pure arithmetic: the squared cost is r times r, the absolute cost is the size of r.
Squares punish big misses hard: a residual twice as large costs four times as much. That is right for Gaussian noise. It is wrong for a reading that is broken. Failure: the symptom is one residual far larger than the rest at the answer. Measure each residual divided by the noise spread; above 3 is suspect. The fix is Chapter 7.
Chapter 3
Replace the curved range by a straight slope at the current guess, and check how good that is
Zoom in far enough on any smooth curve and it looks straight. Near a guess p, each range changes almost in proportion to a small move. The numbers of that proportion form the Jacobian J: one row per beacon, one column per unknown. Row i says how fast h-i grows when you nudge x or y. Jacobians and Linearization builds the idea in full; here we need one row.
J-i equals the pair: x minus u-i over h-i, and y minus v-i over h-i.
Draw the arrow from beacon i to the guess. Shrink it to length 1. Its two parts are row J-i. Moving along the arrow changes the range at full rate; moving across it changes the range hardly at all.
At p = (5, 5), beacon two sits at (10, 0) and h-2 = 7.071. J-2 = (−5/7.071, 5/7.071) = (−0.707, 0.707). Nudge 0.5 m east: the row predicts a change of −0.354 m. The true change is −0.344 m.
Orange arrows are the three Jacobian rows at the guess; the thick plain arrow is the nudge. Turn its direction and size. Drag the guess to move the test point.
Illustrative toy room. Predicted change is the row dotted with the nudge; true change is the new range minus the old one.
Stack the three rows and you get J, 3 by 2. Near the guess, the change in all three residuals is J times the move. That straight model is what the next chapter solves.
Failure: the symptom is a step that lands worse than it started. Measure it as above: compare the predicted change with the true one. A big nudge or a guess near a beacon breaks the straight model. The fix is a shorter step, which is Chapter 5.
Chapter 4
Solve the straight model with the normal equations, step, and rebuild it at the new guess
Chapter 1 solved a straight problem in one shot. Chapter 3 made the curved problem straight near a guess. Gauss-Newton joins them in a loop:
Call the step Δ (delta), a 2-vector in metres. The straight model says the new residuals are r + JΔ. Make their squares smallest, exactly as in Chapter 1.
J-transpose J times delta equals minus J-transpose r.
Build J-transpose J and J-transpose r from the rows and residuals. Solve the 2 by 2 system for delta. Add delta to the guess.
At (5, 5): J-transpose J = [[1.5, −0.5], [−0.5, 1.5]] and J-transpose r = (2.101, 0.545). The determinant is 2.0, so delta = (−1.712, −0.934). The new guess is (3.288, 4.066), and F drops from 4.393 to 0.038.
Pick a start, then press Step. The table shows each guess, its cost and its step. Red marks a step that raised the cost.
Illustrative toy room. Every number matches a NumPy run of the same loop.
From (5, 5) the steps are 1.95 m, 0.093 m, then 0.002 m. The guess settles at (3.205, 4.019), 0.21 m from the true robot, because the readings are noisy. Near the answer each step cuts the remaining error about 40 times, because the residuals there are small.
Failure: pick Start (12, 0). The symptom: the first step jumps to (11.6, 13.1) and F rises from 158 to 206. Measure it by printing F after every step. The straight model was poor that far out. Gauss-Newton has no brake; the fix is damping.
Chapter 5
Add one number to the diagonal and slide between a bold step and a careful one
Gauss-Newton trusts its straight model fully. Far from the answer, that trust sends it uphill. Levenberg-Marquardt adds a damping number λ (lambda) to the diagonal before it solves. Think of λ as a trust knob. I is the 2 by 2 identity matrix.
J-transpose J plus lambda I, times delta, equals minus J-transpose r.
Add lambda to both diagonal entries of J-transpose J. Solve for delta. A large lambda makes delta short and points it straight downhill.
At (5, 5) with lambda = 5: the matrix is [[6.5, −0.5], [−0.5, 6.5]], determinant 42. Delta = (−0.332, −0.109), length 0.35 m. The Gauss-Newton step was 1.95 m.
The faint arrow is the Gauss-Newton step, the yellow dashes point straight downhill, and the orange arrow is the damped step. Green means the step lowers the cost; red means it raises it.
Illustrative toy room. The slider is on a log scale from 0 to 100.
| λ | Step from (5, 5) | Length | Angle off downhill |
|---|---|---|---|
| 0 (Gauss-Newton) | (−1.712, −0.934) | 1.95 m | 14.1° |
| 5 | (−0.332, −0.109) | 0.35 m | 3.7° |
| 20 | (−0.098, −0.028) | 0.10 m | 1.2° |
The solver turns the knob itself. If a step lowers F, accept it and divide λ by 3. If it raises F, reject it and multiply λ by 3. From (12, 0) with λ = 1, the first step lands at (10.4, 3.4) and F falls from 158 to 83. Five accepted steps reach the answer.
Failure: the symptom is a solver that stalls far from the answer with λ huge. Measure by logging λ and F each step. A wrong Jacobian makes every step fail, so λ climbs forever. Fix: check J against finite differences.
Chapter 6
Solve the same step for thousands of cameras and points by skipping the zeros
A drone maps a building site. It estimates 200 camera poses, 6 numbers each, and 50,000 landmark points, 3 numbers each. That is 151,200 unknowns. Fitting all of them to the pixel measurements is bundle adjustment: the same least-squares step, at scale. A dense J-transpose J would hold 23 billion entries.
Most entries are zero. One pixel measurement involves one camera and one landmark.
So call the step matrix H = J-transpose J and split it into blocks. Hcc joins cameras with cameras. Hll joins landmarks with landmarks, and it is block diagonal, because two landmarks never share a measurement. Hcl joins each camera to the landmarks it saw. Eliminate the landmarks first. What is left is the Schur complement S, a system over the cameras only.
S equals H-c-c minus H-c-l times H-l-l inverse times H-l-c.
For each landmark, invert its small block. Use it to remove that landmark's pull from the cameras. Solve S for the camera steps. Then solve each landmark's step on its own.
With made-up numbers: one camera unknown, two landmark unknowns. H-c-c = 4, H-c-l = (1, 2), H-l-l = diag(2, 3). S = 4 − (1 × 1/2 + 2 × 2/3) = 2.167. With right side (1, 2, 3), the camera step is −2/2.167 = −0.923. The landmark steps are 1.462 and 1.615, the same as a full solve.
Each filled cell is a block that is not zero. Slide the counts. Toggle the Schur view to see the small camera system that remains.
Illustrative toy: 2 or 3 nearby cameras see each landmark. The drone counts are a made-up example.
Cost of a dense solve grows as n cubed. For 151,200 unknowns that is about 3.5 × 1015 operations. The camera system has 1,200 unknowns, about 1.7 × 109, plus 50,000 tiny 3 by 3 solves. That is two million times less work in the expensive part.
Failure: the symptom is a solver that runs out of memory or takes hours. Measure the fraction of nonzero blocks. If a dense solver meets a sparse matrix, switch to a Schur or sparse Cholesky solver; Ceres, g2o and GTSAM do this.
Chapter 7
Give each reading a weight that falls as its residual grows, and watch one echo lose its grip
Add a fourth beacon at (10, 10). Its true range is 9.22 m, but an echo off a metal cabinet makes it read 13.22 m: 4 m too long. Squares give that one reading a huge say. Plain least squares lands 1.78 m from the robot.
A robust kernel keeps the square for small residuals and grows slower for large ones. The Huber kernel is the square up to a threshold δ (delta), then a straight line. At a residual of 10 with δ = 1, half the square is 50; Huber is 9.5. The Cauchy kernel grows only as a logarithm.
Solvers apply a kernel by iteratively reweighted least squares (IRLS). Each step gives reading i a weight wi. It scales that reading's share of J-transpose J and J-transpose r by the weight, then solves as before.
w-i equals 1 if the size of r-i is at most delta; otherwise delta over the size of r-i.
If reading i misses by less than delta, give it full weight 1. If it misses by more, give it delta over the miss. The worse the miss, the smaller its vote.
With delta = 1 m: a residual of 4 m gets weight 0.25. At the Huber answer the echo's residual is 3.30 m, so its weight is 0.30. The answer lands 0.70 m from the robot instead of 1.78 m.
Beacon four (red when it lies) reads too long. Pick a kernel and drag the echo error. Bars show each beacon's weight.
Illustrative toy. With a 4 m echo, scipy.optimize.least_squares lands 1.78 m off with plain squares. It lands 0.70 m off with loss="huber" and 0.13 m with loss="cauchy", both with f_scale=1.
| Kernel | Echo weight at the answer | Distance from robot |
|---|---|---|
| Plain squares | 1 | 1.78 m |
| Huber, δ = 1 | 0.30 | 0.70 m |
| Cauchy, c = 1 (weight 1/(1 + r²)) | 0.06 | 0.13 m |
Failure: a kernel can bury a good reading if the start is poor, because every residual looks large. The symptom is an answer that ignores a beacon you trust. Measure the final weights. Fix: start from a plain fit or a good prior, and pick δ near three noise spreads.
Chapter 8
Invert the curvature you already built and draw the ellipse of likely positions
An answer without an error bar is risky. A planner should act one way when the robot is sure to 3 cm and another when it is sure to 60 cm. The matrix J-transpose J holds that answer. A steep bowl pins the answer down; a flat bowl lets it wander.
Call the noise spread of one range σ (sigma), in metres. Evaluate J at the answer. The covariance C of the estimate is the 2 by 2 matrix of how far the answer would scatter if you repeated the readings.
C equals sigma squared times the inverse of J-transpose J.
Build J-transpose J at the answer. Invert it. Multiply by sigma squared. The square roots of its diagonal are the error bars in x and y.
At (3.205, 4.019): J-transpose J = [[1.353, −0.367], [−0.367, 1.647]], its inverse is [[0.787, 0.175], [0.175, 0.646]]. Times 0.09 and take roots: 0.27 m in x and 0.24 m in y.
The purple ellipse holds the likely positions, drawn 5 times larger so you can see it. Drag any beacon, or pick a layout.
Illustrative toy with sigma = 0.3 m. The ellipse is one standard deviation along each axis, evaluated at the true position (3, 4).
Geometry matters as much as noise. Put the three beacons at (0, 0), (2, 0) and (0, 2), all on one side. The long axis grows from 0.29 m to 0.59 m with the same sensor. GPS calls this dilution of precision.
Failure: the symptom is an ellipse that looks tight around a wrong answer. Measure the residuals against σ: if they are far larger, the model is wrong and C is too small. Fix: correct the model, or scale C by the cost per degree of freedom, F/(m − n). Here m is the number of readings and n the number of unknowns.
Chapter 9
Run every piece at once, and break it on purpose
The lab has four beacons, a robot and a start. Drag any of them. The shading is the cost F over the floor. The solver walks from the start toward the darkest spot and leaves a trail.
Drag beacons (blue), the robot (teal) and the start (orange). Step or run the solver. Turn on the echo and a kernel.
Illustrative toy. Noise is a fixed pseudo-random draw scaled by the slider, so a run repeats. The echo adds 4 m to beacon four. We draw the ellipse 5 times larger.
Try these in order:
Failure on purpose: push the noise to 1 m and cluster all four beacons. The bowl turns flat and wide. No solver can recover information the readings never held; an honest solver reports a big ellipse instead of a confident wrong answer.
Chapter 10
Keep the terms, the numbers, the loop and the next steps in one place
Nonlinear least squares finds the parameters that make the sum of squared residuals smallest. Gauss-Newton linearizes and solves the normal equations. Levenberg-Marquardt damps that step. Sparsity makes it scale, kernels make it robust, and the inverse curvature says how far to trust it.
| Term | What it is | Number in this lesson |
|---|---|---|
| Residual r-i | Predicted minus measured | 1.871 m for beacon one at (5, 5) |
| Cost F | Sum of squared residuals | 4.393 at (5, 5); 0.0277 at the answer |
| Jacobian row J-i | Unit vector from beacon to guess | (−0.707, 0.707) for beacon two at (5, 5) |
| Gauss-Newton step | Solve J-transpose J delta = minus J-transpose r | (−1.712, −0.934) from (5, 5) |
| Damping lambda | Trust knob added to the diagonal | lambda 5 shortens the step to 0.35 m |
| Schur complement S | Camera-only system after removing landmarks | 1,200 of 151,200 unknowns |
| Huber weight | 1 inside delta, delta over the miss outside | 0.25 for a 4 m miss |
| Covariance C | sigma squared times (J-transpose J) inverse | 0.27 m in x, 0.24 m in y |
| Situation | Reach for |
|---|---|
| Model is linear in the unknowns | Normal equations or lstsq, one shot |
| Curved model, good start | Gauss-Newton |
| Curved model, rough start | Levenberg-Marquardt (the usual default) |
| Thousands of unknowns in small groups | Sparse solver with the Schur complement |
| Some readings are wrong | Huber or Cauchy kernel through IRLS |
| A consumer needs an error bar | sigma squared times (J-transpose J) inverse at the answer |
pythonimport numpy as np from scipy.optimize import least_squares B = np.array([[0, 0], [10, 0], [0, 10]], dtype=float) # beacons [3, 2] z = np.array([5.2, 8.0, 6.9]) # measured ranges [3] def residuals(p): return np.linalg.norm(p - B, axis=1) - z # [3] def jacobian(p): d = p - B; return d / np.linalg.norm(d, axis=1)[:, None] # [3, 2] def lm(p, lam=1.0, iters=50): cost = sum(residuals(p)**2) for _ in range(iters): J, r = jacobian(p), residuals(p) step = np.linalg.solve(J.T @ J + lam * np.eye(2), -J.T @ r) new = sum(residuals(p + step)**2) if new < cost: p, cost, lam = p + step, new, lam / 3 # accept, trust more else: lam = lam * 3 # reject, trust less J = jacobian(p) return p, 0.3**2 * np.linalg.inv(J.T @ J) # answer, covariance p, C = lm(np.array([12.0, 0.0])) # [3.2052, 4.0187] sol = least_squares(residuals, [12, 0], jac=jacobian, method="lm") # same answer rob = least_squares(residuals, [5, 5], loss="huber", f_scale=1.0) # robust version
Now press Present or Teach. Explain from memory the cost, one Jacobian row, the Gauss-Newton step, lambda and the error ellipse. Then go back to the hero and race the three solvers from the corner again. Say why Gauss-Newton climbs first.