TExcelTAD
Home › Math for Machine Learning › The Geometry of Least Squares

The Geometry of Least Squares

Least squares has a picture that explains all its algebra. The targets y\mathbf{y} are one point in RN\mathbb{R}^N; the predictions XθX\boldsymbol{\theta} can only reach a subspace, the column space of XX. The best fit is the foot of the perpendicular from y\mathbf{y} to that subspace, and the residual is what sticks out.

Predictions live in the column space

y^=Xθ=θ1c1+⋯+θDcD\hat{\mathbf{y}} = X\boldsymbol{\theta} = \theta_1\mathbf{c}_1 + \cdots + \theta_D\mathbf{c}_D is a combination of the DD columns of XX, each a vector in RN\mathbb{R}^N (one entry per example). With N=100N = 100 examples and D=3D = 3 features, we look for the point of a 3-dimensional subspace of R100\mathbb{R}^{100} closest to y\mathbf{y}. By Orthogonal Projections, it is

y^=Py,P=X(XTX)−1XT\hat{\mathbf{y}} = P\mathbf{y}, \qquad P = X(X^TX)^{-1}X^T

PP is the hat matrix (it puts the hat on y\mathbf{y}). The residual r=(I−P)y\mathbf{r} = (I - P)\mathbf{y} is orthogonal to every column of XX.

Pythagoras gives R2R^2

Including an intercept column, y^−yˉ1\hat{\mathbf{y}} - \bar{y}\mathbf{1} and r\mathbf{r} are orthogonal, so the total sum of squares splits exactly:

∥y−yˉ1∥2⏟total=∥y^−yˉ1∥2⏟explained+∥r∥2⏟residual,R2=1−∥r∥2∥y−yˉ1∥2\underbrace{\lVert \mathbf{y} - \bar{y}\mathbf{1} \rVert^2}_{\text{total}} = \underbrace{\lVert \hat{\mathbf{y}} - \bar{y}\mathbf{1} \rVert^2}_{\text{explained}} + \underbrace{\lVert \mathbf{r} \rVert^2}_{\text{residual}}, \qquad R^2 = 1 - \frac{\lVert \mathbf{r} \rVert^2}{\lVert \mathbf{y} - \bar{y}\mathbf{1} \rVert^2}

R2R^2 is the squared cosine of the angle between the centred y\mathbf{y} and the centred fit.

python · try it yourself
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

tr⁡(P)=D\operatorname{tr}(P) = D, the number of parameters: the fit "uses up" DD dimensions, leaving N−DN - D for the residual. That is why the unbiased noise estimate divides by N−DN - D. The diagonal entries PnnP_{nn} are the leverages: how much example nn pulls the fit towards itself. Points with extreme inputs have high leverage.

python · try it yourself
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 x=20x = 20 has leverage close to 1: the fitted line passes almost through it whatever its yy value.

When columns are dependent

If the columns of XX are linearly dependent, the column space is the same with fewer columns. The projection y^\hat{\mathbf{y}} is still unique, but θ\boldsymbol{\theta} is not: many coefficient vectors give the same point. The pseudo-inverse picks the shortest one (SVD).

In software

  • statsmodels reports leverages and Cook's distances (influence measures) built on PP.
  • Residual plots check the orthogonality assumptions visually: residuals should show no pattern against the fitted values.
  • Adjusted R2R^2 and the N−DN - D 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 tr⁡(P)\operatorname{tr}(P), and how many residual degrees of freedom remain?

Answer

5 and 25.

Solution

D=1+4=5D = 1 + 4 = 5 columns, so tr⁡(P)=5\operatorname{tr}(P) = 5 and N−D=25N - D = 25.

Exercise 2: Perfect fit

If y\mathbf{y} already lies in the column space of XX, what are y^\hat{\mathbf{y}}, r\mathbf{r} and R2R^2?

Answer

y^=y\hat{\mathbf{y}} = \mathbf{y}, r=0\mathbf{r} = \mathbf{0}, R2=1R^2 = 1.

Solution

The projection of a vector already in the subspace is the vector itself.

Exercise 3: Project onto the ones vector (code)

For X=1X = \mathbf{1} (intercept only), show that y^\hat{\mathbf{y}} is the mean of y\mathbf{y} in every entry, for y=(2,4,9)\mathbf{y} = (2, 4, 9).

Answer

y^=(5,5,5)\hat{\mathbf{y}} = (5, 5, 5).

Solution

P=1(1T1)−11T=1N11TP = \mathbf{1}(\mathbf{1}^T\mathbf{1})^{-1}\mathbf{1}^T = \frac{1}{N}\mathbf{1}\mathbf{1}^T, which averages.

python · try it yourself
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 y^\hat{\mathbf{y}} is…

  1. the projection of y\mathbf{y} onto the column space of XX
  2. the projection of y\mathbf{y} onto the null space of XX
  3. the mean of XX
  4. any vector in RN\mathbb{R}^N

The trace of the hat matrix P=X(XTX)−1XTP = X(X^TX)^{-1}X^T equals…

  1. NN
  2. the number of columns DD
  3. 1
  4. R2R^2

A training point with leverage close to 1…

  1. has no effect on the fit
  2. pulls the fitted value almost onto itself
  3. must be an outlier in yy
  4. is automatically removed