Chapter 6: Orthogonality and least squares

Previous: LA 05 Subspaces Basis and Rank | LA 00 Course Map | Next: LA 07 Determinants

The big idea

When has no solution, aim for the closest reachable point instead. The closest point in the column space is the projection of , and “closest” means the leftover error is perpendicular to every column. That one condition gives the normal equations , which is linear regression.

In this chapter you will learn to
  1. Explain why noisy data gives systems with no exact solution.
  2. Derive and solve the normal equations.
  3. Fit lines and curves to data by least squares.
  4. Work with orthonormal vectors and orthogonal matrices.
  5. Build an orthonormal basis with Gram-Schmidt, and understand .
Before you start

You need projection onto a vector (LA 02 Dot Product Length and Angle, section 2.6), column space (LA 05 Subspaces Basis and Rank), and transposes (LA 03 Matrices as Linear Maps).


6.1 The problem: too many equations

Where it comes from

You measure a spring: hang a weight, record the stretch. Theory says stretch weight. With 2 measurements you could solve exactly. With 20 noisy measurements, no single fits them all exactly.

In matrix form, you have more equations than unknowns (a tall ), and is almost never in the column space. has no solution.

Giving up is not an option. Instead we ask for the best .

What “best” means

For any guess , the residual is the error vector

Each entry is how far off one equation is. We choose to make the residual as short as possible:

Least squares problem

"" means “the that minimizes”. “Least squares” because we minimize a sum of squared errors.

Why squares? Squares make every error positive, so errors cannot cancel; they punish big errors more than small ones; and, most importantly, they lead to a linear system you can solve exactly. (In probability terms, squared error is the right choice when noise is Gaussian: see PS 09 Estimation and Maximum Likelihood.)


6.2 The geometric solution

The picture

  • As varies, sweeps out the column space : a flat subspace (a plane, say) inside .
  • sits somewhere off that plane.
  • We want the point in the plane closest to .

From chapter 2: the closest point on a line is found by dropping a perpendicular. The same is true for a plane. The closest point is the projection of onto , and the error sticks straight out of the plane.

                 b
                 |
                 |  r = b - p   (perpendicular to the plane)
                 |
     ____________●______________
    /            p              /
   /     column space C(A)     /
  /___________________________/

Why perpendicular means closest

Let be the point where is perpendicular to the plane, and let be any other point in the plane. Then lies in the plane, so it is perpendicular to . By Pythagoras (chapter 2):

So is never closer than . Equality only when .

From perpendicular to equations

“The residual is perpendicular to the column space” means it is perpendicular to every column of . Each column gives one equation:

Stacking all of these: the columns of are the rows of , so

Rearranged:

The normal equations

( is square, , even though is tall.) They are called “normal” because “normal” is another word for perpendicular.

If the columns of are independent, is invertible (chapter 5, exercise C4) and

Compare with projection onto one vector

In chapter 2, projecting onto a single vector gave , that is . The normal equations are exactly the same equation, with the single vector replaced by the matrix , and division replaced by solving a system. Least squares is projection, nothing more.


6.3 Worked examples

Worked example 6.1: fitting a line

Fit to the three points , , .

Step 1: write one equation per point. We want :

The column of ones multiplies (the intercept); the column of values multiplies (the slope). The points are not on one line ( is a rise of 1, a rise of 2), so there is no exact solution.

Step 2: compute and .

Notice what the entries mean: is the number of points, is , is , is , is .

Step 3: solve.

Best line: .

Step 4: look at the residual. Fitted values . Residual .

Step 5: verify perpendicularity.

  • ✓
  • ✓

The residual is perpendicular to both columns, exactly as the theory promised. Its squared length, , is the smallest possible.

Worked example 6.2: least squares generalizes averaging

You measure the same quantity three times: , , . Best single value?

The mean. Least squares, applied to “one unknown measured several times”, gives the average. Everything in this chapter is a generalization of averaging.

Worked example 6.3: fitting a parabola

Fit to , , , . The model is linear in the unknowns , even though it is curved in , so least squares still applies. Just add a column of :

Solving gives , , : the parabola , which passes through all four points exactly. When the data fits the model perfectly, least squares finds the exact answer and the residual is zero.

What “linear” means in linear regression

The word refers to the unknown coefficients, not the input. , , and are all fitted by linear least squares. is not (the unknown is inside the exponential).


6.4 The projection matrix

The projected point is . The matrix in front of is the projection matrix:

It takes any to its shadow in the column space. Two properties:

  • : projecting twice is the same as projecting once (the shadow of a shadow is itself).
  • : it is symmetric.

And projects onto the perpendicular complement: it gives the residual .


6.5 Orthonormal vectors and orthogonal matrices

Definitions

Definition: orthonormal

Vectors are orthonormal if each has length 1 and each pair is perpendicular:

Put them as the columns of a matrix . Then entry of is , so

If is also square, it is called an orthogonal matrix, and then . The inverse costs nothing: just transpose.

What orthogonal matrices do

They preserve lengths and angles:

So they are exactly the rotations and reflections. Every rotation matrix in robotics is orthogonal, and checking is a standard sanity test on a computed rotation.

Examples. from chapter 3. Permutation matrices (which reorder coordinates). .

Why orthonormal bases are so convenient

Coordinates become dot products. If is an orthonormal basis, then for any ,

Why: write and dot both sides with . Every term vanishes except . So . No system of equations to solve.

Worked example 6.4. , , and .

and .

Check: ✓.

Least squares becomes trivial. If has orthonormal columns, the normal equations become simply


6.6 Gram-Schmidt: making vectors orthonormal

The idea

Given independent vectors we want orthonormal spanning the same space. Process them one at a time: take the next vector, remove its components along the directions already found, and normalize what is left.

The procedure

Each subtraction removes a projection (chapter 2). What remains is perpendicular to everything before it.

Worked example 6.5

, .

Step 1. , so .

Step 2. Remove the component from . , so

Step 3. Normalize: , so .

Check: ✓.

QR factorization

Gram-Schmidt can be recorded as

where has orthonormal columns and is upper triangular (because each is built only from ).

Least squares then becomes:

solved by back-substitution. This is how software actually solves least squares, because it avoids forming , which squares the sensitivity to rounding error (chapter 12).


6.7 Pitfalls of least squares

  • Outliers. Squaring errors means one wild point can drag the whole fit. If your data has outliers, look at them, or use a robust loss (absolute error, Huber loss).
  • Dependent columns. If two features are copies or combinations of each other, is singular and there is no unique answer. Remove the redundancy or add regularization (ridge regression, chapter 9 exercise C4).
  • Extrapolation. A fit is trustworthy only near the data. A parabola fitted on may be wildly wrong at .
  • Overfitting. With as many parameters as data points you can fit every point exactly, including the noise. More parameters is not always better.

Summary

IdeaFormula
residual
least squaresminimize
conditionresidual every column
normal equations
projection matrix,
orthogonal matrix, , preserves length
coordinates in an orthonormal basis
QR least squares

Three facts to remember:

  1. Closest point = projection = perpendicular error.
  2. Least squares is the matrix version of averaging.
  3. Orthonormal columns turn every hard step into a dot product.

Exercises

Part A: warm-up

A1. Project onto the line through . Give the residual and check it is perpendicular to .

A2. Find the least squares solution of , , .

A3. Is orthogonal? What is its inverse?

A4. Write the coordinates of in the orthonormal basis , .

Part B: core

B1. Fit to , , , . Give the fitted values and the residual, and verify perpendicularity.

B2. Fit (a line through the origin) to the same data. Why is this a different answer from B1?

B3. Apply Gram-Schmidt to , , .

B4. A spring stretches 2.1 cm, 3.9 cm and 6.2 cm under weights of 1, 2 and 3 kg. Fit stretch weight by least squares.

B5. Compute the projection matrix onto the line through , and check that .

Part C: explain and prove

C1. Prove that satisfies and .

C2. Prove that if is orthogonal, then . What does this say about angles?

C3. Explain why the least squares residual must sum to zero whenever the model includes an intercept (a column of ones).

C4. Prove that the product of two orthogonal matrices is orthogonal. Interpret for rotations.

Part D: practise with code

D1. Solve B1 with np.linalg.lstsq(A, b, rcond=None). Compare with solving the normal equations by np.linalg.solve(A.T @ A, A.T @ b).

D2. Generate 50 points from with . Fit a line, plot the data and the fit, and plot the residuals against . What should a good residual plot look like?

D3. Fit polynomials of degree 1, 3 and 15 to 20 noisy points from . Plot them. Which one overfits? Compute the error on 100 fresh points.

D4. Use np.linalg.qr(A) on a random matrix. Check that Q.T @ Q is the identity and that R is upper triangular.


Where this is used

  • Calibration. Camera intrinsics, hand-eye calibration and sensor offsets are fitted by (often nonlinear) least squares (04 Perception and State).
  • Kalman filter. Each update is a weighted least squares problem balancing prediction and measurement.
  • Training networks. Minimizing squared loss with gradient descent is the nonlinear version of this chapter (05 Training Neural Policies).

Next: LA 07 Determinants: one number that says how much a matrix scales volume.