Least Squares Fitting#
Week 7 showed that when does not lie in the column space , the equation has no exact solution. The closest you can get is the orthogonal projection of onto : find so that
minimizes the residual length over all . That is the least-squares problem
The geometry is the same as last week: the residual must be orthogonal to every column of , which forces the normal equations
When is with and full column rank , the Gram matrix is , symmetric, and invertible, so a unique least-squares solution exists:
The fitted values are ; the residual lives in the left null space .
When this shows up. Overdetermined systems are the everyday case: more measurements than parameters. Fitting a line through noisy sensor readings, estimating robot pose from many landmarks, regressing a policy on a batch of trajectories — all are least squares.
Worked example: fit a line. Suppose we want for three data points
Stack the model as with (slope first, then intercept):
The first column is the -values; the second is the constant column of ones. No exact line hits all three points (check: the slopes between consecutive pairs differ). Form the normal equations:
Solve :
Divide the second equation by to get . Subtract three times this from : the -terms cancel, leaving , so ; then . So
The fitted values are , and the residual is orthogonal to both columns of (dot products zero). Among all lines, this one minimizes the sum of squared vertical errors.
Connection to Week 7. The normal equations are exactly the subspace-projection equations . Least squares is projection of onto , rephrased as “best fit in the 2-norm.”
Gram-Schmidt Orthogonalization#
Projections become cleanest when the basis is orthonormal: vectors with
(unit length, pairwise orthogonal). The projection of onto collapses to a sum of line projections:
with no matrix inverse. Gram-Schmidt turns any independent set into such an orthonormal set.
Algorithm. Start with independent vectors .
- , then .
- For :
- Subtract projections onto the previous 's:
- Normalize: .
Each is the component of orthogonal to . Independence of the 's guarantees , so normalization is always defined.
Worked example: two vectors in . Take
First vector: , so
Second vector: the coefficient of is
Then
Norm: . So
Check: , and both have unit length. The pair is an orthonormal basis for .
Failure mode. If the input vectors are linearly dependent, some is zero and you cannot normalize — Gram-Schmidt is ill-defined (or you drop that vector and reduce rank). Independent vectors that are already orthogonal are no trouble: their coefficients are zero, so the subtraction step vanishes and only the normalization remains.
Apply the first step of Gram-Schmidt to a1 = (1, 1, 0): normalize it to get q1. What is the first (x) component of q1, rounded to 3 decimals?
The QR Factorization#
Pack the independent columns of as and the Gram-Schmidt outputs as . By construction, each is a linear combination of only (earlier 's appear with coefficient ; later ones do not appear). In matrix form that is the QROrthogonal-Upper (matrix factorization) factorization
where
- is with orthonormal columns (),
- is upper triangular.
Explicitly, the entries of are the Gram-Schmidt coefficients:
Column of reads , which is exactly the reverse of the Gram-Schmidt subtractions.
Example continued. With from above,
Check , , , and . Multiplying recovers .
Full vs thin QR. When is with and full column rank, the form above is the thin (or reduced) QR: is , is . A full QR extends to an orthogonal matrix by adding an orthonormal basis for the left null space; the extra rows of are zero. For least squares the thin form is enough.
Why care. is a stable way to encode “orthonormal basis for the column space” plus “change-of-basis coefficients.” Week 13 reuses orthonormal columns in the SVD construction; Gram-Schmidt is the constructive prototype for that idea.
Least Squares via QR#
Substitute into the normal equations :
Since and is invertible (upper triangular with positive diagonal entries from full column rank), multiply both sides by :
That is a triangular system. Solve it by back-substitution — no need to form or invert it.
Why this is better numerically. Forming squares the condition number: in the 2-norm, — a standard result in numerical linear algebra (Trefethen & Bau, Numerical Linear Algebra, see Further Reading). If is already moderately ill-conditioned, can lose all accurate digits before you solve. Working with keeps the condition number of order , not . Library routines (numpy.linalg.lstsq, np.linalg.qr followed by a triangular solve) use QR or related orthogonal factorizations for this reason. The conditioning and stability of least-squares problems are treated at length in Optimization Week 4: Least Squares and Conditioning.
Algorithm summary.
- Compute thin QR: .
- Form the projected right-hand side .
- Solve by back-substitution.
- Fitted values: ; residual is orthogonal to .
For the line-fit design matrix from the first section, the same appears whether you solve normal equations or use QR; the QR path is the one you should prefer on real data.
Knowledge check#
In A = QR, what property do the columns of Q have?
Browser lab: least squares line fit#
Fit a noisy line with least squares, solved via QR.
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
x = np.linspace(0, 10, 20)
y_true = 2.0 * x + 1.0
y = y_true + rng.normal(scale=2.0, size=x.shape)
A = np.column_stack([x, np.ones_like(x)])
Q, R = np.linalg.qr(A)
x_hat = np.linalg.solve(R, Q.T @ y)
print("slope, intercept =", x_hat)
fig, ax = plt.subplots(figsize=(6, 4))
ax.scatter(x, y, color="tab:blue", label="data")
ax.plot(x, A @ x_hat, color="tab:orange", label="least-squares fit")
ax.legend()
ax.set_title("Least squares line fit via QR")
plt.show()
print("Notice: slope, intercept ≈ [1.9, 1.2]; the fitted line tracks the true 2.0x + 1.0 trend through the noise.")
Done when#
You can form the normal equations for an overdetermined system, solve for a least-squares line, and explain how Gram-Schmidt produces the orthonormal in . Check it against the browser lab: set the noise to scale=0.0 and the printed slope, intercept becomes [2. 1.] (within floating-point error), recovering .
Further Reading#
- Trefethen & Bau, Numerical Linear Algebra — Chapters 7–11 cover QR factorization, Gram-Schmidt variants (classical, modified), Householder reflectors, and least squares with detailed numerical analysis.
- Strang, Linear Algebra and Its Applications — Chapter 3 on orthogonal projections and least squares; clear geometric intuition for the normal equations and QR.
- Golub & Van Loan, Matrix Computations — Chapters 5–6 on orthogonalization and the least squares problem, including weighted least squares and the singular value decomposition connection.