Projections and the Geometry of Least Squares
See least squares as dropping a perpendicular onto the space your features can reach, with a worked fit and what the geometry explains.
Key takeaways
- Predictions Xw can only land in the column space of X, the set of all weighted sums of the feature columns.
- The least squares fit is the orthogonal projection of y onto that space.
- The residual is orthogonal to every feature column, which gives the normal equations XᵀXw = Xᵀy.
- Collinear features leave the projection unique but the weights undetermined.
- Perpendicularity holds on the data used for fitting and says nothing about new data.
Least squares regression finds the closest point to your target vector among all the predictions your features can produce. That closest point is the orthogonal projection of the targets onto the space spanned by the feature columns, and the leftover error is perpendicular to every one of those columns.
This single picture explains the normal equations, why adding a feature never increases training error, what collinearity does and why a model with as many parameters as examples can fit anything.
Projection onto a single direction
Start with one feature column a and a target y, both vectors with n entries. You want the multiple c·a nearest to y. The error y − c·a is shortest when it is perpendicular to a.
a · (y − c a) = 0
c = (a · y) / (a · a) For a = (1, 1, 1), a constant column, c = (y₁ + y₂ + y₃)/3. The best constant prediction under squared error is the mean, and here you can see it as a projection. The residuals y minus the mean sum to zero because they are orthogonal to the column of ones.
Many columns
With X of shape (n, d), the predictions ŷ = Xw fill a flat subspace of n-dimensional space, called the column space. Its dimension is the rank of X, at most d. The target y usually lies outside it.
Minimizing ‖y − Xw‖² means finding the nearest point in the subspace. At that point the residual r = y − Xw is orthogonal to all columns.
Xᵀ (y − Xw) = 0
XᵀX w = Xᵀy the normal equations You can also reach this by setting the gradient of the squared error to zero. The gradient is −2Xᵀ(y − Xw). The geometric and calculus routes agree.
A worked fit
Fit a line ŷ = w₀ + w₁x to the points (0, 1), (1, 2) and (2, 2).
X = [[1, 0], [1, 1], [1, 2]] y = (1, 2, 2)
XᵀX = [[3, 3], [3, 5]] Xᵀy = (5, 6)
determinant = 3·5 − 3·3 = 6
w₀ = (5·5 − 3·6)/6 = 7/6
w₁ = (3·6 − 3·5)/6 = 1/2
ŷ = (7/6, 5/3, 13/6)
r = y − ŷ = (−1/6, 1/3, −1/6) Check orthogonality. The residuals sum to zero, so r is perpendicular to the column of ones. Their dot product with (0, 1, 2) is 0 + 1/3 − 2/6 = 0.
Because ŷ and r are perpendicular, Pythagoras applies: ‖y‖² = ‖ŷ‖² + ‖r‖². Here ‖y‖² = 9, ‖r‖² = 1/6 and ‖ŷ‖² = 318/36 = 53/6, which sum correctly.
Removing one feature's influence
Projection explains what a single coefficient means in a multiple regression. Pick one column, say x_j. First regress x_j on all the other columns and keep the residual, the part of x_j they cannot reproduce. Do the same for y. Then regress the y residual on the x_j residual.
The slope you get equals the coefficient of x_j in the full regression. This result is known as the Frisch-Waugh-Lovell theorem.
It makes "holding the other features fixed" concrete, in a linear sense. The coefficient measures the relationship between y and whatever is new in x_j. If the other features reproduce x_j almost completely, that leftover is tiny, the slope rests on very little variation and its estimate is noisy.
Subtracting the means is the simplest case. Regressing on the column of ones leaves each variable minus its mean, which is why centering the data and fitting without an intercept gives the same slopes as fitting with one.
None of this makes a coefficient causal. Features you did not record can still drive both x_j and y.
R² as a statement about angles
When the model includes an intercept, Pythagoras also works after subtracting the mean of y from everything. The total variation splits into explained and residual parts.
In the example, the mean of y is 5/3 and the total sum of squares is 2/3. The residual sum of squares is 1/6. So R² = 1 − (1/6)/(2/3) = 0.75.
Geometrically, R² is the squared cosine of the angle between the centered targets and the centered predictions. A value of 0.75 corresponds to an angle of 30°. Without an intercept, or on held-out data, this decomposition need not hold, and R² on test data can be negative. See regression scores.
The projection matrix
When X has full column rank, the predictions are ŷ = Hy, with
H = X (XᵀX)⁻¹ Xᵀ shape (n, n) H is called the hat matrix. It is symmetric, and H·H = H, since projecting something already in the subspace changes nothing. Its trace equals the number of columns.
Its diagonal entries are leverages: how strongly each example's own target pulls its prediction. In the line fit above they are 5/6, 1/3 and 5/6, summing to 2. The end points have high leverage. An unusual feature value combined with an unusual target can swing the whole fit, which residual plots and leverage values help you find.
Collinearity and rank
If two columns are identical, the column space is no larger than with one of them. The projection ŷ is still unique. The weights are not: you can move any amount from one copy to the other without changing a prediction.
Near-collinearity is the practical version. The columns point in almost the same direction, so small changes in y cause large swings in the weights. The matrix XᵀX is then close to singular, a matter of condition numbers.
For computation, avoid inverting XᵀX explicitly. Solvers based on QR or SVD work with X directly and are more accurate.
import numpy as np
X = np.array([[1.0, 0], [1, 1], [1, 2]]) # (3, 2)
y = np.array([1.0, 2, 2])
w, *_ = np.linalg.lstsq(X, y, rcond=None)
r = y - X @ w
print(w) # about [1.1667, 0.5]
print(X.T @ r) # about [0, 0] When columns are exactly dependent, this routine returns the solution with the smallest L2 norm. That is a tie-breaking rule, not evidence about which feature matters.
Weighted fits
Sometimes errors on certain rows should count more. Minimizing the sum of wᵢ-weighted squares, with positive weights cᵢ, changes the meaning of perpendicular. The normal equations become XᵀCXw = XᵀCy, where C is the diagonal matrix of those weights.
You can reuse an ordinary solver by multiplying each row of X and each entry of y by √cᵢ. The fit is then an ordinary projection in the rescaled space. A weight of 2 has the same effect as listing a row twice.
What adding features does
A new column can only enlarge the column space or leave it unchanged. The nearest point in a larger space is never farther away, so training squared error cannot rise. That is true even for a column of random numbers.
With n linearly independent columns for n examples, the column space is all of n-dimensional space. The projection of y is y itself and the training error is zero, whatever the targets are. Training fit alone therefore cannot justify a feature. Compare models on validation data, or use cross-validation with all fitting steps inside each fold.
Training error against new data
The perpendicularity of the residual is a property of the fitted sample. On new rows, errors can lean in the direction of a feature, and they usually are larger.
A projection argument shows why under a simple assumption. Suppose the targets are a fixed signal inside the column space plus independent noise of variance s² in each entry, and X has full column rank d. Projecting keeps the part of the noise that lies in the d-dimensional subspace.
expected training error per example: s² · (n − d) / n
expected error on fresh targets, same rows: s² · (n + d) / n With n = 100, d = 20 and s² = 1, training error averages 0.8 while error on new targets averages 1.2. The gap, 2ds²/n, grows with the number of columns and shrinks with more data. New rows with different feature values typically add further error.
If the true signal lies outside the column space, there is an additional error that more rows of the same kind will not remove. Only different features or a more flexible model can.
How ridge changes the picture
Adding a penalty λ‖w‖² gives w = (XᵀX + λI)⁻¹Xᵀy. For λ > 0 this is no longer a projection. Using the singular value decomposition of X, ordinary least squares keeps the component of y along each left singular direction in full, while ridge multiplies it by σ²/(σ² + λ).
Directions with large singular values are barely affected. Weak directions, where noise is most amplified, are shrunk strongly. Ridge regression develops this further.
Common questions
Does the geometry need Gaussian noise?
No. Projection is pure linear algebra. Assumptions about noise matter when you interpret the weights statistically, for instance to build confidence intervals or to say least squares is the maximum likelihood estimate.
Why is the residual uncorrelated with the features?
With an intercept, residuals have mean zero and zero dot product with each column, so their sample correlation with each feature is zero. Curved relationships can remain, such as residuals that follow x².
Is gradient descent doing the same thing?
For squared error, gradient descent heads toward the same projection. Starting from zero weights with a small enough step size, it approaches the smallest-norm solution when many exist. A NumPy implementation lets you watch this.