The Geometry of Least Squares
Least squares has a picture that explains all its algebra. The targets are one point in ; the predictions can only reach a subspace, the column space of . The best fit is the foot of the perpendicular from to that subspace, and the residual is what sticks out.
Predictions live in the column space
is a combination of the columns of , each a vector in (one entry per example). With examples and features, we look for the point of a 3-dimensional subspace of closest to . By Orthogonal Projections, it is
is the hat matrix (it puts the hat on ). The residual is orthogonal to every column of .
Pythagoras gives
Including an intercept column, and are orthogonal, so the total sum of squares splits exactly:
is the squared cosine of the angle between the centred and the centred fit.
import numpy as np
rng = np.random.default_rng(0)
N = 50
X = np.column_stack([np.ones(N), rng.normal(size=N), rng.normal(size=N)])
y = X @ np.array([1.0, 2.0, 0.0]) + rng.normal(size=N)
P = X @ np.linalg.solve(X.T @ X, X.T)
y_hat = P @ y; r = y - y_hat
print("P symmetric and idempotent:", np.allclose(P, P.T), np.allclose(P @ P, P))
print("trace of P (= number of columns):", round(np.trace(P), 6))
print("X^T r = 0:", np.allclose(X.T @ r, 0))
tot = np.sum((y - y.mean())**2); exp_ = np.sum((y_hat - y.mean())**2); res = r @ r
print(f"total {tot:.4f} = explained {exp_:.4f} + residual {res:.4f}: {np.isclose(tot, exp_ + res)}")
yc, fc = y - y.mean(), y_hat - y.mean()
print("R^2:", round(1 - res / tot, 6), " cos^2 of angle:", round((yc @ fc)**2 / (yc @ yc * fc @ fc), 6))P symmetric and idempotent: True True
trace of P (= number of columns): 3.0
X^T r = 0: True
total 212.8279 = explained 168.4088 + residual 44.4191: True
R^2: 0.791291 cos^2 of angle: 0.791291
Degrees of freedom and leverage
, the number of parameters: the fit "uses up" dimensions, leaving for the residual. That is why the unbiased noise estimate divides by . The diagonal entries are the leverages: how much example pulls the fit towards itself. Points with extreme inputs have high leverage.
import numpy as np
x = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 20.0]) # one extreme input
X = np.column_stack([np.ones_like(x), x])
P = X @ np.linalg.solve(X.T @ X, X.T)
print("leverages:", np.round(np.diag(P), 3), " sum:", round(np.trace(P), 6))leverages: [0.26 0.225 0.199 0.18 0.169 0.967] sum: 2.0
The point at has leverage close to 1: the fitted line passes almost through it whatever its value.
When columns are dependent
If the columns of are linearly dependent, the column space is the same with fewer columns. The projection is still unique, but is not: many coefficient vectors give the same point. The pseudo-inverse picks the shortest one (SVD).
In software
statsmodelsreports leverages and Cook's distances (influence measures) built on .- Residual plots check the orthogonality assumptions visually: residuals should show no pattern against the fitted values.
- Adjusted and the divisor both come from the dimension count above.
Exercises
Exercise 1: Trace of the hat matrix
A regression with an intercept and 4 features is fitted to 30 points. What is , and how many residual degrees of freedom remain?
Answer
5 and 25.
Solution
columns, so and .
Exercise 2: Perfect fit
If already lies in the column space of , what are , and ?
Answer
, , .
Solution
The projection of a vector already in the subspace is the vector itself.
Exercise 3: Project onto the ones vector (code)
For (intercept only), show that is the mean of in every entry, for .
Answer
.
Solution
, which averages.
import numpy as np
one = np.ones((3, 1)); y = np.array([2.0, 4.0, 9.0])
print(one @ np.linalg.solve(one.T @ one, one.T @ y))[5. 5. 5.]
Test yourself
The least-squares fit is…
- the projection of onto the column space of
- the projection of onto the null space of
- the mean of
- any vector in
The trace of the hat matrix equals…
- the number of columns
- 1
A training point with leverage close to 1…
- has no effect on the fit
- pulls the fitted value almost onto itself
- must be an outlier in
- is automatically removed