---
title: Least squares and curve fitting
heading: Fitting a model to noisy data, linear and nonlinear
eyebrow: A13 · Lesson 37 · Least squares and curve fitting
xp: 40
---

::: hook
A capacitor discharges and a scope records eight noisy points. What's the time constant? A thermistor is measured at a dozen temperatures; what are its B and $R_{25}$? Fitting a model to data means choosing parameters that make the misfit small, and the standard measure of misfit is the sum of squared residuals. When the model is linear in its parameters (a line, a polynomial), that's a linear least-squares problem, solved stably by QR (A7). When it isn't (an exponential, a resonance curve), **Gauss–Newton** linearizes and repeats, and **Levenberg–Marquardt** adds a safety brake. Both are what `scipy.optimize.curve_fit` runs.
:::

::: play
- Eight points from an RC discharge with noise, and the model $Ae^{-t/\tau}$. Move A and τ to make the sum of squared residuals as small as you can.
- The two parameters trade off: a larger A with a shorter τ can fit the early points similarly. The minimum, 0.0352 V², is at A = 5.050 V and τ = 1.980 ms.
- Starting from A = 4, τ = 1.5 (SSR 5.66), Gauss–Newton reaches it in three steps: 0.050, 0.0352, 0.0352.
:::
:::

```sim plot
view: graph
x: t = 0..4 ms
y: v = 0..6 V
slider: A = 3..7 step 0.01 = 4
slider: tau = 0.8..3 step 0.01 = 1.5 ms
plot: A*exp(-t/tau) | label: model A e^(−t/τ)
point: 0, 5.08
point: 0.5, 3.844
point: 1, 3.143
point: 1.5, 2.272
point: 2, 1.869
point: 2.5, 1.493
point: 3, 1.046
point: 3.5, 0.889
readout: sum of squared residuals, V² = (5.08 - A*exp(-0/tau))^2 + (3.844 - A*exp(-0.5/tau))^2 + (3.143 - A*exp(-1/tau))^2 + (2.272 - A*exp(-1.5/tau))^2 + (1.869 - A*exp(-2/tau))^2 + (1.493 - A*exp(-2.5/tau))^2 + (1.046 - A*exp(-3/tau))^2 + (0.889 - A*exp(-3.5/tau))^2
readout: best possible (Gauss–Newton), V² = 0.03519
```

::: predict
## You solve a least-squares fit through the normal equations $A^TAx = A^Tb$, and $\kappa(A) = 10^6$. About how many digits can you trust?

- [ ] About 10
- [x] About 4
- [ ] About 16
- [ ] About 6

::: reveal
About 4: $\kappa(A^TA) = \kappa(A)^2 = 10^{12}$, so forming $A^TA$ throws away twice the digits. A QR factorization of A works with κ(A) itself and keeps about 10.
:::
:::

::: nameit
## Linear least squares

For a model linear in its parameters, $\min_x\lVert Ax - b\rVert^2$. Three ways to solve it:

| Method | Conditioning | Notes |
|---|---|---|
| normal equations $A^TAx = A^Tb$ | $\kappa(A)^2$ | cheap; fine when κ is small |
| QR: $A = QR$, solve $Rx = Q^Tb$ | $\kappa(A)$ | the standard choice |
| SVD | $\kappa(A)$ | handles rank deficiency; most expensive |

For a straight line through $(x_i, y_i)$: slope $= \frac{\sum(x_i - \bar x)(y_i - \bar y)}{\sum(x_i - \bar x)^2}$, intercept $= \bar y - \text{slope}\cdot\bar x$, and with noise σ on each y the slope's standard error is $\frac{\sigma}{\sqrt{\sum(x_i - \bar x)^2}}$.

## Nonlinear least squares

For residuals $r_i(p) = y_i - f(t_i; p)$ with Jacobian $J_{ij} = \partial f(t_i)/\partial p_j$:

- **Gauss–Newton:** solve the linear least-squares problem $J\Delta \approx r$ (that is, $J^TJ\Delta = J^Tr$, preferably by QR) and set $p \leftarrow p + \Delta$. Near a good fit it converges almost quadratically.
- **Levenberg–Marquardt:** solve $(J^TJ + \lambda D)\Delta = J^Tr$. A large λ gives short, safe steps downhill; a small λ is Gauss–Newton. Raise λ when a step makes things worse, lower it when steps succeed.

At the solution, the parameters' covariance is about $\sigma^2(J^TJ)^{-1}$, with σ² estimated as SSR/(m − n) for m points and n parameters.

## Don't linearize by transforming the data

Fitting a line to $\ln v$ does give an exponential, but it weights the noisy small values far more heavily and biases the result. Use it for a starting guess, then fit the real model.
:::

::: example
## Fit $Ae^{-t/\tau}$ to the eight points above by Gauss–Newton from A = 4 V, τ = 1.5 ms.

::: solution
1. **The start.** At A = 4 V and τ = 1.5 ms the SSR is 5.663 V².
2. **Iterate.** Gauss–Newton takes (A, τ) to (5.023, 2.049), (5.050, 1.979) and (5.050, 1.980), and the SSR falls to 0.0501, 0.03520 and 0.035191 V².
3. **Compare with the log-linear fit.** It gives A = 5.038 V and τ = 1.987 ms: close, but not the least-squares answer for the actual data.

**Answer:** A = 5.050 V and τ = 1.980 ms, with an SSR of 0.035191 V².
:::
:::

::: example
## A line is fitted to 11 points with x = 0, 1, ..., 10 and noise σ = 0.2 on each y. What's the slope's standard error?

::: solution
1. **The spread of x.**
   $$\begin{aligned} \sum(x_i - \bar x)^2 &= \frac{n(n^2 - 1)}{12} \\ &= \frac{11 \times 120}{12} \\ &= 110 \end{aligned}$$
2. **The standard error.**
   $$0.2/\sqrt{110} = 0.019$$

**Answer:** about 0.019.
:::
:::

::: example
## Fit a line to (0, 1), (1, 3), (2, 4), (3, 4) and estimate the noise.

::: solution
1. **The sums.** n = 4, Σx = 6, Σx² = 14, Σy = 12 and Σxy = 23.
2. **Slope.**
   $$\begin{aligned} m &= \frac{4 \times 23 - 6 \times 12}{4 \times 14 - 36} \\ &= \frac{20}{20} \\ &= 1 \end{aligned}$$
3. **Intercept.**
   $$\begin{aligned} b &= \frac{12 - 6}{4} \\ &= 1.5 \end{aligned}$$
4. **Residuals.** They are −0.5, 0.5, 0.5, −0.5, so SSR = 1.
5. **Noise.** With two fitted parameters the noise variance estimate is
   $$\frac{1}{4 - 2} = 0.5$$
   a standard deviation of 0.71.
6. **A hint in the residuals.** Their pattern, negative at the ends and positive in the middle, hints that a straight line isn't the right model; with more points, a plot of the residuals would show it.

**Answer:** the line is $y = 1.5 + x$, and the noise's standard deviation is about 0.71.
:::
:::

::: check
given: k = 3 | 5 | 7
answer: 15.95 - 2*k
tolerance: 1%

## Least squares by the normal equations with $\kappa(A) = 10^{\given{k}}$: about how many digits survive?

::: right
Right. $15.95 - 2\log_{10}\kappa$ = {answer}.
:::

::: misses
- [15.95 - k] That's QR's; the normal equations square κ.
- [any] Not yet. $\kappa(A^TA) = \kappa(A)^2$.
:::
:::

::: check
given: a = 1 | 2; b = 3 | 4; c = 3 | 9
answer: (a + b + c)/3 - (c - a)/2
tolerance: 0.1%

## What's the intercept of the least-squares line through (0, {a}), (1, {b}), (2, {c})?

::: right
Right. $\bar y - \text{slope}\cdot\bar x$ = {answer}, with slope $(c - a)/2$.
:::

::: misses
- [a] That's the first point; the fitted line needn't pass through it.
- [any] Not yet. Slope $= \frac{c - a}{2}$, and the line passes through $(\bar x, \bar y) = (1, \frac{a + b + c}{3})$.
:::
:::

::: check
given: s = 0.1 | 0.5; n = 6 | 11 | 21
answer: s/sqrt(n*(n^2 - 1)/12)
tolerance: 0.5%

## A line is fitted to {n} points at x = 0, 1, 2, ..., each y with noise σ = {s}. What's the slope's standard error?

::: right
Right. $\frac{\sigma}{\sqrt{n(n^2 - 1)/12}}$ = {answer}.
:::

::: misses
- [s/sqrt(n)] That's the error of a mean; a slope also depends on how spread out the x's are.
- [any] Not yet. $\sum(x_i - \bar x)^2 = \frac{n(n^2 - 1)}{12}$.
:::
:::

::: check
given: A = 5 | 2; tau = 2 | 1; t = 1 | 3
answer: A*t/tau^2*exp(-t/tau)
tolerance: 0.1%

## For the model $Ae^{-t/\tau}$ with A = {A}, τ = {tau}, what's the Jacobian entry $\partial f/\partial\tau$ at t = {t}?

::: right
Right. $\frac{At}{\tau^2}e^{-t/\tau}$ = {answer}.
:::

::: misses
- [-A*t/tau^2*exp(-t/tau)] $\frac{d}{d\tau}(-t/\tau) = +t/\tau^2$.
- [any] Not yet. Differentiate $e^{-t/\tau}$ with respect to τ.
:::
:::

::: check
given: S = 0.035 | 0.8; m = 8 | 20; n = 2 | 3
answer: S/(m - n)
tolerance: 0.5%

## A fit of {n} parameters to {m} points leaves SSR = {S}. What's the estimated noise variance σ²?

::: right
Right. $\frac{\text{SSR}}{m - n}$ = {answer}.
:::

::: misses
- [S/m] Each fitted parameter uses up a degree of freedom: divide by m − n.
- [any] Not yet. $\sigma^2 \approx \text{SSR}/(m - n)$.
:::
:::

::: check
kind: choice

## In Levenberg–Marquardt, a step just increased the SSR. What should happen to λ?

- [x] Increase it, for a shorter step closer to steepest descent, and retry
- [ ] Decrease it, toward Gauss–Newton
- [ ] Set it to zero
- [ ] Leave it and accept the step

::: misses
- [2] That's what to do after a successful step.
- [3] That's pure Gauss–Newton, which just failed.
- [4] A step that makes the fit worse should be rejected.
:::
:::

::: check
kind: parts
given: a = 1 | 2; b = 3 | 2; c = 4 | 5; d = 4 | 7

## Fit a line to (0, {a}), (1, {b}), (2, {c}), (3, {d}).

::: part
answer: (-1.5*a - 0.5*b + 0.5*c + 1.5*d)/5
tolerance: 0.5%

### What is its slope?

::: misses
- [any] $\frac{\sum(x - \bar x)(y - \bar y)}{\sum(x - \bar x)^2}$, with $\bar x = 1.5$.
:::
:::

::: part
answer: (a + b + c + d)/4 - 1.5*(-1.5*a - 0.5*b + 0.5*c + 1.5*d)/5
tolerance: 0.5%

### What is its intercept?

::: misses
- [any] The line passes through $(\bar x, \bar y)$.
:::
:::
:::

::: check
kind: derivation
vars: p = -3..3, q = -3..3

## Fit $y = kx$ through the origin to the points (1, p) and (2, q).

::: step
answer: (p + 2*q)/5

### What is k, $\frac{\sum xy}{\sum x^2}$?
:::

::: step
answer: (p - (p + 2*q)/5)^2 + (q - 2*(p + 2*q)/5)^2

### What is the sum of squared residuals?
:::

::: right
Right. The residual vector is orthogonal to x = (1, 2), which is what the normal equation says.
:::
:::

::: explain
## Why is solving least squares through the normal equations less accurate than through QR?

::: model
Forming $A^TA$ squares the condition number: if A's columns are nearly dependent, with $\kappa(A) = 10^6$, then $A^TA$ has $\kappa = 10^{12}$, and solving with it loses about 12 digits instead of 6. The information that distinguishes the nearly parallel columns is in the small singular values, which get squared and pushed toward the level of rounding error when $A^TA$ is formed. QR works on A directly with orthogonal transformations, which don't amplify errors, so its accuracy is governed by κ(A) alone. The normal equations are fine when A is well-conditioned, which is why they're still used for small, well-posed fits.
:::
:::

::: practice

::: check
given: k = 1..7 int
answer: 15.95 - 2*k
tolerance: 1%

## Digits left by normal equations, $\kappa = 10^{\given{k}}$?

::: misses
- [any] $15.95 - 2k$.
:::
:::

::: check
given: s = 0.05 | 2; n = 5 | 51
answer: s/sqrt(n*(n^2 - 1)/12)
tolerance: 0.5%

## Slope standard error, {n} points, σ = {s}?

::: misses
- [any] $\sigma/\sqrt{n(n^2 - 1)/12}$.
:::
:::

::: check
given: a = 0 | 3; b = 2 | 1; c = 5 | 8
answer: (a + b + c)/3 - (c - a)/2
tolerance: 0.1%

## Intercept of the fit through (0, {a}), (1, {b}), (2, {c})?

::: misses
- [any] $\bar y - \frac{c - a}{2}$.
:::
:::
:::
