---
title: Least squares and projection
heading: The best answer when there's no exact one
eyebrow: A7 · Lesson 27 · Least squares and projection
xp: 40
---

::: hook
Six measurements of current at six voltages give six equations for one unknown, the resistance. With measurement noise they can't all be true at once: the system has no exact solution. Yet there's clearly a best answer. Least squares finds it, and its geometry, dropping a perpendicular, is one of the most useful pictures in all of engineering.

::: play
- The dots are six noisy measurements. The line $I = sV$ goes through the origin with slope $s$, the conductance.
- Move $s$ to make the line fit the dots as well as you can. The strip shows the sum of the squared vertical misses.
- Find the smallest total you can. Compare your slope with the least-squares slope in the strip.
:::
:::

```sim plot
view: graph
x: V = 0..12 V
y: I = 0..14 mA
slider: s = 0.5..1.5 step 0.005 = 0.8
plot: s*V | label: I = sV
point: 2, 2.3
point: 4, 3.7
point: 6, 6.6
point: 8, 7.8
point: 10, 10.9
point: 12, 11.6
readout: squared misses = (2.3 - 2*s)^2 + (3.7 - 4*s)^2 + (6.6 - 6*s)^2 + (7.8 - 8*s)^2 + (10.9 - 10*s)^2 + (11.6 - 12*s)^2
readout: least-squares slope = (2*2.3 + 4*3.7 + 6*6.6 + 8*7.8 + 10*10.9 + 12*11.6)/(4 + 16 + 36 + 64 + 100 + 144)
```

::: predict
## The best slope minimizes the sum of squared misses. At that slope, what is true of the misses?

- [ ] They're all zero
- [ ] They're all positive
- [x] Weighted by the voltages, they add up to zero: $\sum V_k(I_k - sV_k) = 0$
- [ ] The largest one is as small as possible

::: reveal
The voltage-weighted misses add to zero. That's what setting the derivative of the total to zero gives, and it says the vector of misses is perpendicular to the vector of voltages. Least squares is a projection: the best fit is the point in the reachable set closest to the data, and the leftover miss sticks out at right angles.
:::
:::

::: nameit
## Least squares is a projection

Write the measurements as an overdetermined system $A\mathbf{x} \approx \mathbf{b}$: more equations than unknowns. For the line through the origin, $A$ is the column of voltages, $\mathbf{x}$ is the single unknown $s$, and $\mathbf{b}$ is the column of currents.

No $\mathbf{x}$ makes $A\mathbf{x} = \mathbf{b}$ exactly, so choose the one that makes the **residual** $\mathbf{r} = \mathbf{b} - A\mathbf{x}$ as short as possible. The closest point $A\mathbf{x}$ to $\mathbf{b}$ is where $\mathbf{r}$ is perpendicular to every column of $A$:

$$A^{\mathsf T}(\mathbf{b} - A\mathbf{x}) = 0 \quad\Longrightarrow\quad A^{\mathsf T}A\,\mathbf{x} = A^{\mathsf T}\mathbf{b}$$

These are the **normal equations**. For a single column they reduce to

$$s = \frac{\sum V_kI_k}{\sum V_k^2}$$

the formula in the strip. For a line with an intercept, $A$ has a second column of ones, and the normal equations are 2 × 2. This is exactly what `np.polyfit` solved in A4.

**Projection.** $A\mathbf{x}$ is the projection of $\mathbf{b}$ onto the space the columns of $A$ can reach. In two dimensions, projecting $\mathbf{b}$ onto the direction of $\mathbf{a}$ gives $\frac{\mathbf{a}\cdot\mathbf{b}}{\mathbf{a}\cdot\mathbf{a}}\mathbf{a}$: the same formula as $s$.

**In practice.** Solve least-squares problems with `np.linalg.lstsq(A, b)`, which avoids forming $A^{\mathsf T}A$ (that step squares the condition number and loses accuracy). The same mathematics fits curves, estimates channels in a radio receiver and locates you from GPS satellites.
:::

::: example
## Fit $y = sx$ to $(1, 2.1)$, $(2, 3.9)$, $(3, 6.2)$.

::: solution
1. **The formula.**
   $$s = \frac{\sum xy}{\sum x^2}$$
2. **Plug in.**
   $$\begin{aligned} s &= \frac{2.1 + 7.8 + 18.6}{1 + 4 + 9} \\ &= \frac{28.5}{14} \\ &= 2.036 \end{aligned}$$

**Answer:** the best slope is $s = 2.036$.
:::
:::

::: example
## Fit $y = c + mx$ to $(0, 1)$, $(1, 3)$, $(2, 4)$, and check the residuals.

::: solution
1. **Normal equations.**
   $$\begin{bmatrix}3 & 3\\3 & 5\end{bmatrix}\begin{bmatrix}c\\m\end{bmatrix} = \begin{bmatrix}8\\11\end{bmatrix}$$
2. **Solve.** They give $m = 1.5$ and $c = 1.167$.
3. **Residuals.**
   $$1 - 1.167 = -0.167$$
   $$3 - 2.667 = 0.333$$
   $$4 - 4.167 = -0.167$$
4. **Check them.** They add to zero and are perpendicular to $(0, 1, 2)$ too, as the projection requires.

**Answer:** $y = 1.167 + 1.5x$, with residuals $-0.167$, 0.333 and $-0.167$.
:::
:::

::: example
## A capacitor's voltage is measured as 10, 6.1 and 3.6 V at $t$ = 0, 1 and 2 s. Fit $v = V_0e^{-t/\tau}$.

::: solution
1. **Take logarithms.** $\ln v = \ln V_0 - t/\tau$ is a straight line in $t$, so fit $\ln v$ = 2.3026, 1.8083, 1.2809 by least squares.
2. **Slope.** With $\bar t = 1$:
   $$\begin{aligned} m &= \frac{\sum(t - \bar t)(\ln v - \overline{\ln v})}{\sum(t - \bar t)^2} \\ &= \frac{-1.0217}{2} \\ &= -0.5108 \end{aligned}$$
3. **Intercept.** The intercept is 2.3081.
4. **Back to the exponential.**
   $$\begin{aligned} \tau &= 1/0.5108 \\ &= 1.958\ \text{s} \\ V_0 &= e^{2.3081} \\ &= 10.06\ \text{V} \end{aligned}$$
5. **A caution.** Fitting the logarithm weights the small late readings more heavily than a direct fit would.

**Answer:** $V_0$ = 10.06 V and $\tau$ = 1.958 s.
:::
:::

::: check
given: V1 = 1..3 int; V2 = 4..6 int; k = 1..3 int; let I1 = k*V1; let I2 = k*V2 + 2
answer: (V1*I1 + V2*I2)/(V1^2 + V2^2)
unit: mA/V
tolerance: 0.5%

## Two measurements: {I1} mA at {V1} V and {I2} mA at {V2} V. What is the least-squares slope $s$ (in mA per volt) of a line $I = sV$ through the origin?

::: right
Right. $s = \sum V_kI_k / \sum V_k^2$ = {answer} mA/V.
:::

::: misses
- [(I1/V1 + I2/V2)/2] That averages the two slopes. Least squares weights the larger voltage more.
- [(I1 + I2)/(V1 + V2)] That's the ratio of the sums, not least squares.
- [any] Not yet. Use $s = \sum V_kI_k / \sum V_k^2$.
:::
:::

::: check
given: a1 = 2..5 int; a2 = 1..5 int; b1 = 1..9 int; b2 = 1..9 int
answer: (a1*b1 + a2*b2)/(a1^2 + a2^2)*a1
tolerance: 0.5%

## Project $\mathbf{b} = (\given{b1}, \given{b2})$ onto the direction of $\mathbf{a} = (\given{a1}, \given{a2})$. What is the first component of the projection?

::: right
Right. $\frac{\mathbf{a}\cdot\mathbf{b}}{\mathbf{a}\cdot\mathbf{a}}\mathbf{a}$, first component {answer}.
:::

::: misses
- [(a1*b1 + a2*b2)/(a1^2 + a2^2)] That's the multiplier. Multiply it by $\mathbf{a}$'s first component.
- [(a1*b1 + a2*b2)/sqrt(a1^2 + a2^2)] That's the projection's length. The question asks for its first component.
- [any] Not yet. Compute $\frac{\mathbf{a}\cdot\mathbf{b}}{\mathbf{a}\cdot\mathbf{a}}$ and multiply by $a_1$.
:::
:::

::: check
kind: python

## Fit a line with an intercept, $I = sV + c$, to the six measurements in the sim using `np.linalg.lstsq`. Set `s` and `c`.

```python starter
import numpy as np

V = np.array([2, 4, 6, 8, 10, 12], dtype=float)
I = np.array([2.3, 3.7, 6.6, 7.8, 10.9, 11.6])
A = np.zeros((6, 2))   # replace: columns of V and of ones
s, c = 0, 0
print(s, c)
```

```python solution
import numpy as np

V = np.array([2, 4, 6, 8, 10, 12], dtype=float)
I = np.array([2.3, 3.7, 6.6, 7.8, 10.9, 11.6])
A = np.column_stack([V, np.ones_like(V)])
(s, c), *rest = np.linalg.lstsq(A, I, rcond=None)
print(s, c)
```

```python tests
import numpy as np
A2 = np.column_stack([V, np.ones_like(V)])
want = np.linalg.solve(A2.T @ A2, A2.T @ I)
assert abs(s - want[0]) < 1e-9 and abs(c - want[1]) < 1e-9, "s and c should be the least-squares fit: build A with a column of V and a column of ones, then use np.linalg.lstsq(A, I, rcond=None)."
```

::: right
Right. The intercept comes out small but not zero: the noise doesn't know the true line passes through the origin.
:::
:::

::: check
kind: parts
given: y1 = 1 | 2; y2 = 3 | 4; y3 = 6 | 7

## Fit lines to $(1, \given{y1})$, $(2, \given{y2})$, $(3, \given{y3})$.

::: part
answer: (y1 + 2*y2 + 3*y3)/14
tolerance: 0.5%

### What slope does $y = sx$, through the origin, get?

::: misses
- [any] $s = \frac{\mathbf{x}\cdot\mathbf{y}}{\mathbf{x}\cdot\mathbf{x}}$, with $\mathbf{x}\cdot\mathbf{x} = 14$.
:::
:::

::: part
answer: (y3 - y1)/2
tolerance: 0.5%

### What slope does $y = c + mx$ get?

::: misses
- [any] For equally spaced points, $m = \frac{\sum(x - \bar x)(y - \bar y)}{\sum(x - \bar x)^2}$, with $\sum(x - \bar x)^2 = 2$.
:::
:::
:::

::: check
kind: derivation
vars: a = 0.5..5, b = 0.5..5

## Fit $y = sx$ to $(1, a)$ and $(2, b)$.

::: step
answer: a + 2*b

### With $A = (1, 2)$, what is $A^T\mathbf{y}$?
:::

::: step
answer: (a + 2*b)/5

### $A^TA = 5$. What is $s$?
:::

::: right
Right. $s = \frac{a + 2b}{5}$: the normal equation in one unknown.
:::
:::

::: check
given: y1 = 1.9 | 2.2; y2 = 3.8 | 4.3; y3 = 6.1 | 5.7
answer: y1^2 + y2^2 + y3^2 - (y1 + 2*y2 + 3*y3)^2/14
tolerance: 1%

## Fit $y = sx$ by least squares to $(1, \given{y1})$, $(2, \given{y2})$ and $(3, \given{y3})$. What is the sum of the squared residuals at the best $s$?

::: right
Right. The best slope is $s = \sum xy/\sum x^2$, and because the residual is perpendicular to $\mathbf{x}$, the squared residual is $|\mathbf{y}|^2 - (\mathbf{x}\cdot\mathbf{y})^2/|\mathbf{x}|^2$ = {answer}: Pythagoras, with the projection as one leg.
:::

::: misses
- [(y1 + 2*y2 + 3*y3)/14] That's the best slope $s$. Now square each residual $y_i - sx_i$ and add.
- [y1^2 + y2^2 + y3^2] That's $|\mathbf{y}|^2$, the error with $s = 0$. Subtract the squared length of the projection.
- [any] Not yet. Find $s = \sum xy/\sum x^2$, then add up $(y_i - sx_i)^2$.
:::
:::

::: explain
## Why is the least-squares residual perpendicular to the columns of A?

::: model
The fitted values $A\mathbf{x}$ can only lie in the space the columns of A reach, and least squares picks the point there closest to the data $\mathbf{b}$. The closest point to $\mathbf{b}$ in a line or plane is the foot of the perpendicular from $\mathbf{b}$, like dropping a plumb line. If the residual leaned along any column, you could move a little in that column's direction and get closer, so at the best fit the residual has no component along any column: it's perpendicular to all of them.
:::
:::

::: practice

::: check
given: k = 2..6 int; n = 3..6 int
answer: k
tolerance: 0.5%

## Measurements lie exactly on $y = \given{k}x$ at $x = 1, 2, \ldots, \given{n}$. What least-squares slope (through the origin) do you get?

::: misses
- [any] With no noise, the residual is zero at the true slope, so least squares returns it exactly.
:::
:::

::: check
given: x1 = 1..3 int; x2 = 4..6 int; k = 1..3 int; let y1 = k*x1; let y2 = k*x2 + 1
answer: (x1*y1 + x2*y2)/(x1^2 + x2^2)
tolerance: 0.5%

## Fit $y = sx$ through the origin to $(\given{x1}, \given{y1})$ and $(\given{x2}, \given{y2})$. What is $s$?

::: misses
- [(y1 + y2)/(x1 + x2)] Use $\sum xy/\sum x^2$.
- [any] $s = \sum x_ky_k/\sum x_k^2$.
:::
:::
:::
