---
title: Fitting lines to noisy data
heading: Least squares, residuals and the error in a slope
eyebrow: A11 · Lesson 39 · Least-squares fitting
xp: 50
---

::: hook
You measure the current through a resistor at eight voltages. The points almost line up, but not quite, because the meter is noisy. The resistance is one over the slope of the line through them. Which line, exactly? And how precisely do eight noisy points pin down the slope? Least squares picks the line, and the scatter of the points around it tells you how far to trust the answer. It's how sensors are calibrated, how device parameters are extracted, and, in matrix form, the projection of A7.
:::

::: play
- The dots are eight measured currents. The solid line is your trial line, $I = a + bV$; the dashed one is the least-squares line.
- Adjust $a$ and $b$ to make the sum of squared vertical misses as small as you can. Can you beat the dashed line?
- The readout also gives the resistance your slope implies, $1/b$.
:::
:::

```sim plot
view: graph
x: V = 0..8 V
y: I = -0.5..4.5 mA
slider: a = -0.5..0.5 step 0.01 = 0.3 mA
slider: b = 0.3..0.7 step 0.002 = 0.45 mA/V
plot: a + b*V | label: trial line
plot: 0.015 + 0.49679*V | label: least squares | dashed | color: ch2
point: 0, 0.08
point: 1, 0.38
point: 2, 1.05
point: 3, 1.60
point: 4, 1.94
point: 5, 2.41
point: 6, 3.11
point: 7, 3.46
readout: sum of squared misses = (0.08 - a)^2 + (0.38 - a - b)^2 + (1.05 - a - 2*b)^2 + (1.6 - a - 3*b)^2 + (1.94 - a - 4*b)^2 + (2.41 - a - 5*b)^2 + (3.11 - a - 6*b)^2 + (3.46 - a - 7*b)^2 | digits: 4
readout: least-squares sum = 0.05815 | digits: 4
readout: resistance from your slope, kΩ = 1/b | digits: 4
```

::: predict
## The best line through these points has slope 0.497 mA/V, and the points scatter about 0.1 mA from it. Roughly how well is the resistance determined?

- [ ] Exactly: 2.013 kΩ
- [x] To about 3%
- [ ] To about 20%
- [ ] Not at all, with only eight points

::: reveal
To about 3%. The slope's standard error is the scatter divided by the spread of the voltages, $\frac{0.098}{\sqrt{42}} = 0.015$ mA/V, which is 3% of the slope. So $R = 2.01 \pm 0.06$ kΩ. More points, or a wider voltage range, would shrink it.
:::
:::

::: nameit
## The least-squares line

For data $(x_i, y_i)$ and a model $y = a + bx$, the **residuals** are $r_i = y_i - a - bx_i$. Least squares chooses $a$ and $b$ to minimize $\text{SSE} = \sum r_i^2$. Setting both partial derivatives to zero (A9.10) gives

$$b = \frac{S_{xy}}{S_{xx}} \qquad a = \bar y - b\bar x$$

with $S_{xx} = \sum (x_i - \bar x)^2$ and $S_{xy} = \sum (x_i - \bar x)(y_i - \bar y)$. The line passes through the point of averages $(\bar x, \bar y)$.

**Matrix form.** Stack the equations as $A\theta \approx y$, with a column of ones and a column of $x$ values in $A$ and $\theta = (a, b)$. The least-squares $\theta$ solves the normal equations $A^TA\,\theta = A^Ty$: it projects $y$ onto the columns of $A$ (A7.27). The same works for any model that's linear in its unknowns, such as polynomials. In NumPy, `np.polyfit(x, y, 1)` returns $(b, a)$ and `np.linalg.lstsq(A, y)` solves the general case.

**Why squares?** If the noise is Gaussian and independent, minimizing the squared residuals is exactly maximum likelihood (lesson 35).

## How good is the fit

- **Noise estimate:** $s_e = \sqrt{\frac{\text{SSE}}{n - 2}}$, dividing by $n - 2$ because two parameters were fitted (Bessel's correction again).
- **Slope uncertainty:** $s_b = \frac{s_e}{\sqrt{S_{xx}}}$. Spreading the $x$ values out shrinks it as much as adding points.
- **$R^2$:** $1 - \frac{\text{SSE}}{\sum(y_i - \bar y)^2}$, the fraction of the variation the line explains.
- **Look at the residuals.** A curve or a trend in them means the model is wrong, whatever $R^2$ says.

## Straightening curves

Many EE laws become lines after a transformation. An RC decay $v = V_0e^{-t/\tau}$ gives $\ln v = \ln V_0 - \frac{t}{\tau}$, a line in $t$ with slope $-\frac{1}{\tau}$. A diode's $I = I_Se^{V/nV_T}$ is a line in $\ln I$ versus $V$. Fit the line, then convert back. (Taking logs also reshapes the noise, so points near zero get too much weight; use only points well above the noise.)
:::

::: example
## Find the least-squares line for the eight points in the sim, the resistance and its uncertainty.

::: solution
1. **Center the data.** $\bar V = 3.5$ V and $S_{xx} = 42$ V².
2. **Fit the line.** The fit gives $b = 0.4968$ mA/V and $a = 0.015$ mA, so
   $$\begin{aligned} R &= \frac{1}{b} \\ &= 2.013\ \text{k}\Omega \end{aligned}$$
3. **Noise from the residuals.** The residuals give SSE $= 0.0582$ mA², so
   $$\begin{aligned} s_e &= \sqrt{0.0582/6} \\ &= 0.098\ \text{mA} \end{aligned}$$
4. **Slope uncertainty.**
   $$\begin{aligned} s_b &= \frac{0.098}{\sqrt{42}} \\ &= 0.0152\ \text{mA/V} \end{aligned}$$
   a relative error of 3.1%.

**Answer:** the line is $I = 0.015 + 0.4968V$ (mA), and $R = 2.01 \pm 0.06$ kΩ.
:::
:::

::: example
## An RC decay reads 3.0 V at 1 ms and 1.1 V at 3 ms. Estimate τ by straightening the curve.

::: solution
1. **Slope of the straightened curve.** On a plot of $\ln v$ against $t$,
   $$\begin{aligned} \text{slope} &= \frac{\ln 1.1 - \ln 3.0}{3 - 1} \\ &= -\frac{1.003}{2}\ \text{per ms} \end{aligned}$$
2. **Time constant.**
   $$\begin{aligned} \tau &= \frac{2}{1.003} \\ &= 1.99\ \text{ms} \end{aligned}$$
3. **With more points.** You'd fit a line to all the $(t, \ln v)$ pairs.

**Answer:** $\tau$ is about 1.99 ms.
:::
:::

::: check
given: sxy = 21 | 30; sxx = 42 | 50
answer: sxy/sxx
tolerance: 0.5%

## For some data, $S_{xy}$ = {sxy} and $S_{xx}$ = {sxx}. What is the least-squares slope?

::: right
Right. $\frac{S_{xy}}{S_{xx}}$ = {answer}.
:::

::: misses
- [sxx/sxy] Upside down.
- [any] Not yet. $b = S_{xy}/S_{xx}$.
:::
:::

::: check
given: yb = 2 | 3.5; xb = 3 | 4; b = 0.5 | 0.8
answer: yb - b*xb
tolerance: 0.5%

## A fit has slope {b}, and the data average $\bar x$ = {xb}, $\bar y$ = {yb}. What is the intercept?

::: right
Right. The line goes through $(\bar x, \bar y)$: $a = \bar y - b\bar x$ = {answer}.
:::

::: misses
- [yb] The intercept is at $x = 0$, not at $\bar x$.
- [any] Not yet. $a = \bar y - b\bar x$.
:::
:::

::: check
given: sse = 0.06 | 0.2; n = 8 | 12
answer: sqrt(sse/(n - 2))
tolerance: 0.5%

## A straight-line fit to {n} points leaves SSE = {sse}. What is the estimated noise per point?

::: right
Right. $\sqrt{\text{SSE}/(n - 2)}$ = {answer}.
:::

::: misses
- [sqrt(sse/n)] Two parameters were fitted: divide by $n - 2$.
- [sqrt(sse/(n - 1))] A line has two fitted parameters, so $n - 2$.
- [any] Not yet. $s_e = \sqrt{\text{SSE}/(n - 2)}$.
:::
:::

::: check
given: se = 0.1 | 0.05; sxx = 42 | 160
answer: se/sqrt(sxx)
tolerance: 0.5%

## A fit has noise estimate $s_e$ = {se} and $S_{xx}$ = {sxx}. What is the standard error of the slope?

::: right
Right. $\frac{s_e}{\sqrt{S_{xx}}}$ = {answer}.
:::

::: misses
- [se/sxx] Divide by the square root of $S_{xx}$.
- [any] Not yet. $s_b = s_e/\sqrt{S_{xx}}$.
:::
:::

::: check
given: sse = 0.5 | 2; sst = 20 | 40
answer: 1 - sse/sst
tolerance: 0.5%

## A fit leaves SSE = {sse}, and the data's total sum of squares about their mean is {sst}. What is $R^2$?

::: right
Right. $1 - \frac{\text{SSE}}{\text{SST}}$ = {answer}.
:::

::: misses
- [sse/sst] That's the fraction left unexplained.
- [any] Not yet. $R^2 = 1 - \text{SSE}/\text{SST}$.
:::
:::

::: check
given: m = -0.5 | -0.2 | -2
answer: -1/m
unit: ms
tolerance: 0.5%

## A line fitted to $\ln v$ against $t$ (in ms) for an RC decay has slope {m} per ms. What is τ?

::: right
Right. The slope is $-1/\tau$, so $\tau$ = {answer}.
:::

::: misses
- [-m] τ is the reciprocal of the slope's size.
- [any] Not yet. $\ln v = \ln V_0 - t/\tau$.
:::
:::

::: check
kind: python

## Write `fit_line(x, y)` returning `(a, b)` for the least-squares line $y = a + bx$, using $b = S_{xy}/S_{xx}$ and $a = \bar y - b\bar x$ (no `polyfit`). The test compares with NumPy on random data.

```python starter
import numpy as np

def fit_line(x, y):
    return 0.0, 0.0

x = np.arange(8.0)
y = np.array([0.08, 0.38, 1.05, 1.60, 1.94, 2.41, 3.11, 3.46])
print(fit_line(x, y))
```

```python solution
import numpy as np

def fit_line(x, y):
    x, y = np.asarray(x, float), np.asarray(y, float)
    dx = x - x.mean()
    b = np.sum(dx * (y - y.mean())) / np.sum(dx * dx)
    return y.mean() - b * x.mean(), b

x = np.arange(8.0)
y = np.array([0.08, 0.38, 1.05, 1.60, 1.94, 2.41, 3.11, 3.46])
print(fit_line(x, y))
```

```python tests
import numpy as np
a, b = fit_line(np.arange(8.0), [0.08, 0.38, 1.05, 1.60, 1.94, 2.41, 3.11, 3.46])
assert abs(b - 0.496786) < 1e-5 and abs(a - 0.015) < 1e-5, f"For the sim's data expect a = 0.015, b = 0.4968; got {a:.5f}, {b:.5f}."
rng = np.random.default_rng(5)
x = rng.uniform(0, 10, 30); y = 1.5 - 0.3 * x + rng.normal(0, 0.2, 30)
bb, aa = np.polyfit(x, y, 1)
a, b = fit_line(x, y)
assert abs(a - aa) < 1e-9 and abs(b - bb) < 1e-9, "Your line should match np.polyfit on random data."
```

::: right
Right. The closed form and NumPy agree to rounding.
:::
:::

::: check
kind: python

## Write `slope_se(x, y)` returning the standard error of the least-squares slope: fit the line, compute $s_e = \sqrt{\text{SSE}/(n - 2)}$ from the residuals, and return $s_e/\sqrt{S_{xx}}$.

```python starter
import numpy as np

def slope_se(x, y):
    return 0.0

x = np.arange(8.0)
y = np.array([0.08, 0.38, 1.05, 1.60, 1.94, 2.41, 3.11, 3.46])
print(slope_se(x, y))
```

```python solution
import numpy as np

def slope_se(x, y):
    x, y = np.asarray(x, float), np.asarray(y, float)
    b, a = np.polyfit(x, y, 1)
    r = y - (a + b * x)
    se = np.sqrt(np.sum(r**2) / (len(x) - 2))
    return se / np.sqrt(np.sum((x - x.mean())**2))

x = np.arange(8.0)
y = np.array([0.08, 0.38, 1.05, 1.60, 1.94, 2.41, 3.11, 3.46])
print(slope_se(x, y))
```

```python tests
import numpy as np
s = slope_se(np.arange(8.0), [0.08, 0.38, 1.05, 1.60, 1.94, 2.41, 3.11, 3.46])
assert abs(s - 0.015191) < 1e-5, f"For the sim's data the slope's standard error is about 0.01519; got {s:.5f}. Divide SSE by n − 2."
rng = np.random.default_rng(0)
V = np.linspace(0, 10, 21)
est = [slope_se(V, V / 2.2 + rng.normal(0, 0.05, V.size)) for _ in range(300)]
assert abs(np.mean(est) - 0.0036) / 0.0036 < 0.1, f"On simulated data with 0.05 noise, expect about 0.0036; got {np.mean(est):.5f}."
```

::: right
Right. Across many simulated data sets, the slopes really do scatter by about this much, so the formula's error bar is honest.
:::
:::

::: explain
## Why does spreading the $x$ values out make the slope more precise?

::: model
The slope is set by how $y$ changes between points far apart in $x$. Noise moves each point up or down by about the same amount wherever it is, so its effect on the slope is that error divided by how far apart the points are. Points bunched together let a small vertical error swing the line a lot; points spread wide pin it down. That's why $S_{xx}$, the spread of the $x$ values, sits in the denominator of the slope's standard error, and why you should measure across the widest range you trust the model over.
:::
:::

::: practice

::: check
given: b = 0.25 | 0.5 | 0.8
answer: 1/b
unit: kΩ
tolerance: 0.5%

## An I–V fit (mA against V) has slope {b} mA/V. What is the resistance?

::: misses
- [b] Resistance is one over the slope.
- [any] $R = 1/b$.
:::
:::

::: check
given: n = 5..50 int
answer: n - 2
tolerance: 0.01%

## A straight line is fitted to {n} points. How many degrees of freedom remain for estimating the noise?

::: misses
- [n - 1] Two parameters were fitted.
- [any] $n - 2$.
:::
:::

::: check
given: k = 2..10 int
answer: k
tolerance: 0.5%

## The $x$ values of an experiment are spread {k} times wider, with the same number of points and the same noise. By what factor does the slope's standard error shrink?

::: misses
- [k^2] $S_{xx}$ grows by $k^2$, and the error goes as $1/\sqrt{S_{xx}}$.
- [any] $\sqrt{S_{xx}}$ grows by $k$.
:::
:::
:::
