---
title: "Lab: least squares and QR in code"
heading: Fitting data, and doing it accurately
eyebrow: A7 · Lesson 29 · Lab: least squares and QR in code
xp: 60
---

::: hook
Least squares is the workhorse of measurement: calibrating sensors, fitting time constants, estimating parameters from noisy data. The normal equations $A^TA\hat{\mathbf{x}} = A^T\mathbf{b}$ give the answer in one line, and for many problems they're fine. For badly conditioned ones they throw away half the available digits, because forming $A^TA$ squares the condition number. In this lab you'll fit an RTD's calibration curve, watch classical Gram-Schmidt lose orthogonality where the modified version keeps it, compare the normal equations with QR on a fit that punishes the shortcut, and weight measurements by how much you trust them.
:::

::: play
- The three points are $(0, 1)$, $(1, 3)$ and $(2, 4)$, the data from lesson 27. The solid line has the slope you choose, with the intercept that suits it best.
- The readout is the sum of squared residuals. Find the slope that makes it smallest.
- The dashed line is the least-squares fit, $y = 1.167 + 1.5x$. At its slope the readout bottoms out at 0.167.
:::

```sim plot
view: graph
x: x = -0.5..2.5
y: y = 0..5.5
slider: m = 0..3 step 0.05 = 0.8
plot: 8/3 - m + m*x | label: trial line
plot: 8/3 - 1.5 + 1.5*x | dashed | color: ch2 | label: least squares
point: 0, 1
point: 1, 3
point: 2, 4
readout: sum of squared residuals = 42/9 - 6*m + 2*m^2 | digits: 4
```

::: predict
## A fitting matrix has condition number $10^6$. About how many significant digits can the normal equations deliver in double precision?

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

::: reveal
About 4. $A^TA$ has condition number $10^{12}$, and double precision carries about 16 digits, so only about 4 survive. QR works with $A$ itself and keeps about 10. For a well-conditioned fit, say condition number 10, both are fine; the difference matters as the columns become nearly dependent, as powers of $t$ do on a short interval.
:::
:::

::: nameit
## Three ways to solve least squares

- **Normal equations:** `np.linalg.solve(A.T @ A, A.T @ b)`. Fast and simple; condition number squared.
- **QR:** `Q, R = np.linalg.qr(A)`, then solve $R\hat{\mathbf{x}} = Q^T\mathbf{b}$ by back substitution. About twice the work; condition number unchanged.
- **SVD**, through `np.linalg.lstsq`: the most robust, and it handles rank-deficient $A$ with the pseudoinverse.

## Classical and modified Gram-Schmidt

Both subtract projections onto the $\mathbf{q}$'s found so far. Classical computes every coefficient $\mathbf{q}_i\cdot\mathbf{a}_j$ from the original column; modified updates the column after each subtraction and computes the next coefficient from what's left. In exact arithmetic they agree. In floating point, the modified version's $\mathbf{q}$'s stay orthogonal to about the rounding level times the condition number, while the classical version's can lose orthogonality entirely.

## Weighted least squares

When measurement $i$ has standard deviation $\sigma_i$, minimize $\sum\left(\frac{r_i}{\sigma_i}\right)^2$. Dividing row $i$ of $A$ and entry $i$ of $\mathbf{b}$ by $\sigma_i$ turns it into ordinary least squares. The normal equations become $A^TWA\hat{\mathbf{x}} = A^TW\mathbf{b}$ with $W = \text{diag}(1/\sigma_i^2)$. Precise points pull the fit harder.
:::

::: example
## Why does the trial line's error bottom out at slope 1.5?

::: solution
1. **The error with the best intercept.** With the best intercept for each slope, the sum of squared residuals is
   $$S_{yy} - 2mS_{xy} + m^2S_{xx}$$
2. **The sums.** They are sums of products of deviations from the means:
   $$S_{xx} = 2, \quad S_{xy} = 3, \quad S_{yy} = \tfrac{42}{9}$$
3. **Minimize the parabola.** That's a parabola in $m$, smallest at
   $$\begin{aligned} m &= \frac{S_{xy}}{S_{xx}} \\ &= 1.5 \end{aligned}$$
   where it equals
   $$\begin{aligned} &\tfrac{42}{9} - 9 + 4.5 \\ &= 0.167 \end{aligned}$$
4. **Intercept.**
   $$\begin{aligned} \bar y - m\bar x &= \tfrac83 - 1.5 \\ &= 1.167 \end{aligned}$$

**Answer:** the error is a parabola in the slope, lowest at $m = 1.5$ (with intercept 1.167), where the sum of squares is 0.167.
:::
:::

::: example
## A degree-9 polynomial is fitted to 20 equally spaced points on $[0, 1]$. How do the normal equations and QR compare?

::: solution
1. **Condition number.** The Vandermonde matrix's condition number is $3.8 \times 10^6$.
2. **Normal equations.** With data generated from coefficients that are all 1, the normal equations recover them with a largest error of $1.6 \times 10^{-4}$.
3. **QR.** It recovers them with a largest error of $3.7 \times 10^{-10}$, about 400 000 times better.
4. **Why.** That's roughly the factor of $\kappa$ the normal equations give away by squaring it.

**Answer:** QR is about 400 000 times more accurate, a largest error of $3.7 \times 10^{-10}$ against $1.6 \times 10^{-4}$.
:::
:::

::: check
given: k = 100 | 1000 | 10000
answer: 16 - 2*log(k)
tolerance: 2%

## A fit's matrix has condition number {k}. About how many digits can the normal equations keep, out of 16?

::: right
Right. $A^TA$ has condition number $\kappa^2$, which costs $2\log_{10}\kappa$ digits: about {answer} remain.
:::

::: misses
- [16 - log(k)] That's what QR keeps; the normal equations square the condition number.
- [any] Not yet. Forming $A^TA$ squares $\kappa$.
:::
:::

::: check
given: s1 = 0.1 | 0.2; s2 = 0.5 | 1
answer: (s2/s1)^2
tolerance: 0.5%

## Two measurements have standard deviations {s1} and {s2}. How many times more weight does the first get in weighted least squares?

::: right
Right. Weights go as $1/\sigma^2$, so the ratio is {answer}.
:::

::: misses
- [s2/s1] Square it: the weights are $1/\sigma^2$.
- [any] Not yet. $W = \text{diag}(1/\sigma_i^2)$.
:::
:::

::: check
kind: python

## An RTD's resistance follows $R = c_0 + c_1T + c_2T^2$. Fit the data in the starter by the normal equations, set `c` to the three coefficients, and set `alpha = c[1] / c[0]`, the temperature coefficient.

```python starter
import numpy as np

T = np.arange(0, 101, 10.0)
R = 100 * (1 + 3.9083e-3 * T - 5.775e-7 * T**2) + 0.01 * np.sin(7 * T)
c = np.zeros(3)
alpha = 0
print(c, alpha)
```

```python solution
import numpy as np

T = np.arange(0, 101, 10.0)
R = 100 * (1 + 3.9083e-3 * T - 5.775e-7 * T**2) + 0.01 * np.sin(7 * T)
A = np.column_stack([np.ones_like(T), T, T**2])
c = np.linalg.solve(A.T @ A, A.T @ R)
alpha = c[1] / c[0]
print(c, alpha)
```

```python tests
import numpy as np
A = np.column_stack([np.ones_like(T), T, T**2])
ref = np.linalg.lstsq(A, R, rcond=None)[0]
assert np.allclose(c, ref, rtol=1e-8), f"The normal equations should match lstsq here; got {c} against {ref}."
assert abs(alpha - 3.9083e-3) < 0.01 * 3.9083e-3, f"The fitted coefficient should be within 1% of 0.0039083 per degree; got {alpha}."
```

::: right
Right. With only 11 points on $[0, 100]$ and three columns, the normal equations are well within their accuracy.
:::
:::

::: check
kind: python

## Write `cgs(A)` (classical Gram-Schmidt) and `mgs(A)` (modified). On the matrix in the starter, set `loss_c` and `loss_m` to $|\mathbf{q}_2\cdot\mathbf{q}_3|$ from each.

```python starter
import numpy as np

e = 1e-8
A = np.array([[1, 1, 1], [e, 0, 0], [0, e, 0], [0, 0, e]])

def cgs(A):
    return A / np.linalg.norm(A, axis=0)

def mgs(A):
    return A / np.linalg.norm(A, axis=0)

Qc, Qm = cgs(A), mgs(A)
loss_c = abs(Qc[:, 1] @ Qc[:, 2])
loss_m = abs(Qm[:, 1] @ Qm[:, 2])
print(loss_c, loss_m)
```

```python solution
import numpy as np

e = 1e-8
A = np.array([[1, 1, 1], [e, 0, 0], [0, e, 0], [0, 0, e]])

def cgs(A):
    Q = np.zeros_like(A, dtype=float)
    for j in range(A.shape[1]):
        v = A[:, j].astype(float)
        for i in range(j):
            v = v - (Q[:, i] @ A[:, j]) * Q[:, i]
        Q[:, j] = v / np.linalg.norm(v)
    return Q

def mgs(A):
    Q = A.astype(float)
    for j in range(A.shape[1]):
        Q[:, j] /= np.linalg.norm(Q[:, j])
        for k in range(j + 1, A.shape[1]):
            Q[:, k] -= (Q[:, j] @ Q[:, k]) * Q[:, j]
    return Q

Qc, Qm = cgs(A), mgs(A)
loss_c = abs(Qc[:, 1] @ Qc[:, 2])
loss_m = abs(Qm[:, 1] @ Qm[:, 2])
print(loss_c, loss_m)
```

```python tests
import numpy as np
assert loss_c > 0.4, f"Classical Gram-Schmidt should leave q2 and q3 about 60 degrees apart (dot product near 0.5); got {loss_c}."
assert loss_m < 1e-10, f"Modified Gram-Schmidt should keep them orthogonal; got {loss_m}."
B = np.array([[3.0, 1], [4, 0]])
assert np.allclose(mgs(B).T @ mgs(B), np.eye(2)) and np.allclose(cgs(B).T @ cgs(B), np.eye(2)), "On a well-conditioned matrix both give orthonormal columns."
```

::: right
Right. The same arithmetic in a different order: the modified version subtracts each projection from what's left, so earlier rounding errors get projected out too.
:::
:::

::: check
kind: python

## Fit a degree-9 polynomial to 20 points on $[0, 1]$ whose true coefficients are all 1. Solve by the normal equations and by QR, and set `err_normal` and `err_qr` to each one's largest coefficient error.

```python starter
import numpy as np

t = np.linspace(0, 1, 20)
A = np.vander(t, 10, increasing=True)
y = A @ np.ones(10)
err_normal = err_qr = 1.0
print(err_normal, err_qr)
```

```python solution
import numpy as np

t = np.linspace(0, 1, 20)
A = np.vander(t, 10, increasing=True)
y = A @ np.ones(10)
x_normal = np.linalg.solve(A.T @ A, A.T @ y)
Q, R = np.linalg.qr(A)
x_qr = np.linalg.solve(R, Q.T @ y)
err_normal = np.max(np.abs(x_normal - 1))
err_qr = np.max(np.abs(x_qr - 1))
print(err_normal, err_qr)
```

```python tests
assert err_qr < 1e-7, f"QR should recover the coefficients to about 1e-9; got an error of {err_qr}."
assert err_normal > 100 * err_qr, f"The normal equations should be far worse; got {err_normal} against {err_qr}."
```

::: right
Right. Same data, same answer in exact arithmetic, and about five orders of magnitude apart in floating point.
:::
:::

::: check
kind: python

## Four measurements in the starter have standard deviations `sg`. Fit $y = b_0 + b_1x$ by weighted least squares, scaling each row by $1/\sigma_i$, and set `b0` and `b1`.

```python starter
import numpy as np

xs = np.array([0, 1, 2, 3.0])
ys = np.array([1.1, 2.9, 5.2, 6.8])
sg = np.array([0.1, 0.1, 0.5, 0.5])
b0, b1 = np.polyfit(xs, ys, 1)[::-1]
print(b0, b1)
```

```python solution
import numpy as np

xs = np.array([0, 1, 2, 3.0])
ys = np.array([1.1, 2.9, 5.2, 6.8])
sg = np.array([0.1, 0.1, 0.5, 0.5])
A = np.column_stack([np.ones_like(xs), xs]) / sg[:, None]
b0, b1 = np.linalg.lstsq(A, ys / sg, rcond=None)[0]
print(b0, b1)
```

```python tests
import numpy as np
X = np.column_stack([np.ones(4), xs]); W = np.diag(1 / sg**2)
ref = np.linalg.solve(X.T @ W @ X, X.T @ W @ ys)
assert np.allclose([b0, b1], ref), f"The weighted fit should be {ref}; got {(b0, b1)}."
assert abs(b1 - 1.8695) < 1e-3, "The two precise points dominate: the slope is close to theirs, 1.8, not the unweighted 1.94."
```

::: right
Right. The first two points, five times more precise, carry 25 times the weight, and the slope moves toward the line through them.
:::
:::

::: explain
## Why does QR give a more accurate least-squares answer than the normal equations when the columns are nearly dependent?

::: model
Nearly dependent columns make $A$ ill conditioned, with condition number $\kappa$, so any method loses about $\log_{10}\kappa$ digits to the problem itself. The normal equations form $A^TA$ first, whose condition number is $\kappa^2$, and solving it loses $2\log_{10}\kappa$ digits: the information that separates the nearly dependent columns is partly rounded away the moment the products are summed. QR never forms $A^TA$. It rotates $A$ into triangular form with orthogonal transformations, which don't change lengths or amplify errors, so it loses only what the problem's own conditioning demands. For $\kappa = 10^6$, that's about 10 digits kept instead of 4.
:::
:::

::: practice

::: check
given: k = 10..10000000
answer: 16 - 2*log(k)
tolerance: 2%

## Digits left by the normal equations for $\kappa$ = {k}?

::: misses
- [any] $16 - 2\log_{10}\kappa$.
:::
:::

::: check
given: s1 = 0.01..1; s2 = 0.01..1
answer: (s2/s1)^2
tolerance: 0.5%

## Weight ratio for standard deviations {s1} and {s2}?

::: misses
- [any] $(\sigma_2/\sigma_1)^2$.
:::
:::
:::
