Simple Algorithm
Machine Learning · Convergence · 28 min

The Geometry of Least Squares

Projections, the hat matrix, leverage and numerically stable solvers.

Least squares is a projection, and a projection has a matrix. That matrix tells you how strongly each point steers its own fitted value, which points can move the whole fit on their own, how to strip one variable's influence out of another, and why the textbook formula (X⊤X)−1X⊤y(X^\top X)^{-1}X^\top\mathbf y is the wrong way to compute anything.

What you’ll learn

  • Prove that the hat matrix is symmetric, idempotent and of trace dd, and derive the covariances of the fitted values and residuals.
  • Compute leverages and Cook's distances, and derive the exact change in the coefficients when one observation is deleted.
  • State and prove the Frisch–Waugh–Lovell theorem, and use it to explain variance inflation under collinearity.
  • Quantify why QR and the SVD are numerically safer than the normal equations, in terms of the condition number.

The hat matrix

Throughout, X∈Rn×dX \in \R^{n\times d} has full column rank and y=Xw+ε\mathbf y = X\mathbf w + \boldsymbol\varepsilon with Eε=0\E\boldsymbol\varepsilon = \mathbf 0 and Cov⁡ε=σ2I\Cov\boldsymbol\varepsilon = \sigma^2 I. The fitted values are y^=Hy\hat{\mathbf y} = H\mathbf y with the hat matrix H=X(X⊤X)−1X⊤H = X(X^\top X)^{-1}X^\top, and the residuals are e=(I−H)y\mathbf e = (I - H)\mathbf y.

DerivationProof
  1. H⊤=X((X⊤X)−1)⊤X⊤=H,H2=X(X⊤X)−1X⊤X(X⊤X)−1⏟IX⊤=HH^\top = X\big((X^\top X)^{-1}\big)^\top X^\top = H, \qquad H^2 = X(X^\top X)^{-1}\underbrace{X^\top X(X^\top X)^{-1}}_{I}X^\top = H

    Symmetry, because X⊤XX^\top X is symmetric and so is its inverse; idempotence, because the middle factor cancels:

  2. Tr⁡H=Tr⁡((X⊤X)−1X⊤X)=Tr⁡Id=d\Tr H = \Tr\big((X^\top X)^{-1}X^\top X\big) = \Tr I_d = d

    If Hv=λvH\mathbf v = \lambda\mathbf v with v≠0\mathbf v \ne \mathbf 0, then λv=H2v=λ2v\lambda\mathbf v = H^2\mathbf v = \lambda^2\mathbf v, so λ∈{0,1}\lambda \in \{0, 1\}. A symmetric matrix is diagonalizable, so its rank is the number of unit eigenvalues, which is its trace. The cyclic property of the trace gives

  3. e=(I−H)y=(I−H)ε,Cov⁡e=σ2(I−H)(I−H)⊤=σ2(I−H)\mathbf e = (I - H)\mathbf y = (I - H)\boldsymbol\varepsilon, \qquad \Cov\mathbf e = \sigma^2(I - H)(I - H)^\top = \sigma^2(I - H)

    Since HXw=XwHX\mathbf w = X\mathbf w, the residuals see only the noise. With Cov⁡ε=σ2I\Cov\boldsymbol\varepsilon = \sigma^2 I and (I−H)(I-H) symmetric and idempotent,

  4. Var⁡y^i=σ2hii,Var⁡ei=σ2(1−hii),1n∑i=1nVar⁡y^i=σ2dn\Var\hat y_i = \sigma^2 h_{ii}, \qquad \Var e_i = \sigma^2(1 - h_{ii}), \qquad \frac1n\sum_{i=1}^n \Var\hat y_i = \frac{\sigma^2 d}{n}

    Likewise Cov⁡y^=σ2HH⊤=σ2H\Cov\hat{\mathbf y} = \sigma^2 HH^\top = \sigma^2 H. In particular Var⁡y^i=σ2hii\Var\hat y_i = \sigma^2 h_{ii} and Var⁡ei=σ2(1−hii)\Var e_i = \sigma^2(1 - h_{ii}), and the fitted values have average variance σ2Tr⁡H/n=σ2d/n\sigma^2\Tr H/n = \sigma^2 d/n.

With a thin QR factorization X=QRX = QR (Q∈Rn×dQ \in \R^{n\times d} with orthonormal columns, RR upper triangular and invertible), the inverse disappears: H=QR(R⊤R)−1R⊤Q⊤=QQ⊤H = QR(R^\top R)^{-1}R^\top Q^\top = QQ^\top. That is the computational form, and it shows that hii=∥qi∥2h_{ii} = \norm{\mathbf q_i}^2, the squared length of row ii of QQ.

Leverage

The diagonal entry hii=xi⊤(X⊤X)−1xih_{ii} = \mathbf x_i^\top(X^\top X)^{-1}\mathbf x_i is the leverage of observation ii. Since y^i=∑jhijyj\hat y_i = \sum_j h_{ij}y_j, it is the derivative ∂y^i/∂yi\partial\hat y_i/\partial y_i: how strongly a point pulls its own fitted value toward itself. Leverage depends on XX alone, never on y\mathbf y. A high-leverage point is a potential problem; it becomes an actual one only if its response disagrees with the rest.

  • Range. From H=H2H = H^2 and symmetry, hii=∑jhij2≥hii2h_{ii} = \sum_j h_{ij}^2 \ge h_{ii}^2, so 0≤hii≤10 \le h_{ii} \le 1. With an intercept column, hii≥1/nh_{ii} \ge 1/n.
  • Average. ∑ihii=d\sum_i h_{ii} = d, so the average leverage is d/nd/n. Hoaglin & Welsch (1978) suggest a second look at points with hii>2d/nh_{ii} > 2d/n.
  • The extreme. If hii=1h_{ii} = 1 then ∑j≠ihij2=0\sum_{j\ne i}h_{ij}^2 = 0, so y^i=yi\hat y_i = y_i: the fit is forced through the point and its residual is zero however wrong yiy_i is.
  • Distance from the center. With an intercept, hii=1n+(x~i−xˉ)⊤S−1(x~i−xˉ)h_{ii} = \frac1n + (\tilde{\mathbf x}_i - \bar{\mathbf x})^\top S^{-1}(\tilde{\mathbf x}_i - \bar{\mathbf x}), where x~i\tilde{\mathbf x}_i omits the constant and SS is the centered cross-product matrix of the features: a Mahalanobis distance from the centroid. For one feature, hii=1n+(xi−xˉ)2∑j(xj−xˉ)2h_{ii} = \frac1n + \frac{(x_i - \bar x)^2}{\sum_j (x_j - \bar x)^2}.
Predict before you look

Simple regression (intercept and slope) on the four inputs x=0,1,2,3x = 0, 1, 2, 3. What is the leverage of the point at x=3x = 3?

Show the answer

0.7

xˉ=1.5\bar x = 1.5 and ∑j(xj−xˉ)2=5\sum_j(x_j - \bar x)^2 = 5, so h=14+1.525=0.25+0.45=0.7h = \tfrac14 + \tfrac{1.5^2}{5} = 0.25 + 0.45 = 0.7. The inner points get 0.25+0.05=0.30.25 + 0.05 = 0.3, and the four leverages sum to 0.7+0.3+0.3+0.7=2=d0.7 + 0.3 + 0.3 + 0.7 = 2 = d. Its residual has variance only 0.3 σ20.3\,\sigma^2: the line is pulled hard toward it.

Influence: what one point does to the fit

Leverage measures potential; influence measures effect. The cleanest way to measure the effect of observation ii is to delete it and refit. No refitting is needed: one rank-one update gives the answer in closed form.

DerivationDeleting one observation
  1. (A−xixi⊤)−1=A−1+A−1xixi⊤A−11−h(A - \mathbf x_i\mathbf x_i^\top)^{-1} = A^{-1} + \frac{A^{-1}\mathbf x_i\mathbf x_i^\top A^{-1}}{1 - h}

    Write A=X⊤XA = X^\top X and h=hii<1h = h_{ii} < 1. Deleting row ii subtracts xixi⊤\mathbf x_i\mathbf x_i^\top from AA and xiyi\mathbf x_i y_i from X⊤yX^\top\mathbf y, and the Sherman–Morrison formula inverts the rank-one update:

  2. w^(−i)=w^−A−1xiyi+A−1xi y^i−h yi1−h=w^−A−1xi yi(1−h)−y^i+h yi1−h\hat{\mathbf w}_{(-i)} = \hat{\mathbf w} - A^{-1}\mathbf x_i y_i + A^{-1}\mathbf x_i\,\frac{\hat y_i - h\,y_i}{1 - h} = \hat{\mathbf w} - A^{-1}\mathbf x_i\,\frac{y_i(1-h) - \hat y_i + h\,y_i}{1 - h}

    Multiply by X⊤y−xiyiX^\top\mathbf y - \mathbf x_i y_i, using A−1X⊤y=w^A^{-1}X^\top\mathbf y = \hat{\mathbf w}, xi⊤w^=y^i\mathbf x_i^\top\hat{\mathbf w} = \hat y_i and xi⊤A−1xi=h\mathbf x_i^\top A^{-1}\mathbf x_i = h:

  3. w^−w^(−i)=(X⊤X)−1xi ei1−hii\hat{\mathbf w} - \hat{\mathbf w}_{(-i)} = \frac{(X^\top X)^{-1}\mathbf x_i\,e_i}{1 - h_{ii}}

    The bracket collapses to the residual ei=yi−y^ie_i = y_i - \hat y_i. The change in the coefficients is the residual, amplified by 1/(1−hii)1/(1 - h_{ii}):

  4. yi−xi⊤w^(−i)=ei1−hiiy_i - \mathbf x_i^\top\hat{\mathbf w}_{(-i)} = \frac{e_i}{1 - h_{ii}}

    Multiplying by xi⊤\mathbf x_i^\top shows that deleting the point moves its own fitted value by hiiei/(1−hii)h_{ii}e_i/(1-h_{ii}), so its leave-one-out residual is ei/(1−hii)e_i/(1 - h_{ii}): the identity behind one-fit leave-one-out cross-validation.

Check your understanding

For the four points (0,1)(0,1), (1,3)(1,3), (2,4)(2,4), (3,8)(3,8), the least-squares residuals are 0.3,0.1,−1.1,0.70.3, 0.1, -1.1, 0.7, the leverages 0.7,0.3,0.3,0.70.7, 0.3, 0.3, 0.7, and σ^2=1.8/2=0.9\hat\sigma^2 = 1.8/2 = 0.9. Which point has the largest Cook's distance?

  1. (0,1)(0, 1)
  2. (1,3)(1, 3)
  3. (2,4)(2, 4), which has the largest residual
  4. (3,8)(3, 8)
Show the answer

D. (3,8)(3, 8)

Di=ei2dσ^2⋅hii(1−hii)2D_i = \frac{e_i^2}{d\hat\sigma^2}\cdot\frac{h_{ii}}{(1-h_{ii})^2} with dσ^2=1.8d\hat\sigma^2 = 1.8. For (3,8)(3,8): 0.491.8⋅0.70.09≈2.12\frac{0.49}{1.8}\cdot\frac{0.7}{0.09} \approx 2.12. For (2,4)(2,4): 1.211.8⋅0.30.49≈0.41\frac{1.21}{1.8}\cdot\frac{0.3}{0.49} \approx 0.41. For (0,1)(0,1): about 0.390.39; for (1,3)(1,3): about 0.0030.003. A moderate residual at high leverage beats a large residual at low leverage.

Partialling out: the Frisch–Waugh–Lovell theorem

DerivationProof
  1. M1y=M1X1w^1+M1X2w^2+M1e=M1X2 w^2+eM_1\mathbf y = M_1X_1\hat{\mathbf w}_1 + M_1X_2\hat{\mathbf w}_2 + M_1\mathbf e = M_1X_2\,\hat{\mathbf w}_2 + \mathbf e

    Apply M1M_1 to the full fit. It annihilates X1X_1, and it leaves e\mathbf e alone because e⊥col(X1)\mathbf e \perp \mathrm{col}(X_1):

  2. (M1X2)⊤e=X2⊤M1e=X2⊤e=0(M_1X_2)^\top\mathbf e = X_2^\top M_1\mathbf e = X_2^\top\mathbf e = \mathbf 0

    The residual is also orthogonal to the regressors of the reduced problem, since M1M_1 is symmetric and X2⊤e=0X_2^\top\mathbf e = \mathbf 0:

  3. (M1X2)⊤(M1y−M1X2w^2)=0⟹w^2=(X2⊤M1X2)−1X2⊤M1y(M_1X_2)^\top(M_1\mathbf y - M_1X_2\hat{\mathbf w}_2) = \mathbf 0 \quad\Longrightarrow\quad \hat{\mathbf w}_2 = (X_2^\top M_1X_2)^{-1}X_2^\top M_1\mathbf y

    So w^2\hat{\mathbf w}_2 and e\mathbf e satisfy the normal equations of regressing M1yM_1\mathbf y on M1X2M_1X_2. Full column rank of XX makes M1X2M_1X_2 of full column rank, so that solution is unique, and solving gives the formula. Since M1M_1 is idempotent, regressing the raw y\mathbf y on M1X2M_1X_2 gives the same coefficient, though not the same residuals.

What a coefficient means. Take X2X_2 to be a single column xj\mathbf x_j: its coefficient is the slope of y\mathbf y on the part of xj\mathbf x_j that the other features cannot explain. Plotting M−jyM_{-j}\mathbf y against M−jxjM_{-j}\mathbf x_j (an added-variable plot) shows that slope and the points that drive it. Centering is the special case X1=1X_1 = \mathbf 1, and including one indicator per group is the same as subtracting group means (the "within" estimator for panel data).

Why collinearity hurts. The theorem also gives the variance: Var⁡w^j=σ2/∥M−jxj∥2\Var\hat w_j = \sigma^2/\norm{M_{-j}\mathbf x_j}^2. With an intercept in the model, ∥M−jxj∥2=Sjj(1−Rj2)\norm{M_{-j}\mathbf x_j}^2 = S_{jj}(1 - R_j^2), where Sjj=∑i(xij−xˉj)2S_{jj} = \sum_i (x_{ij} - \bar x_j)^2 and Rj2R_j^2 is the R2R^2 of regressing xj\mathbf x_j on the other features. So

Var⁡w^j=σ2Sjj⋅11−Rj2,\Var\hat w_j = \frac{\sigma^2}{S_{jj}}\cdot\frac{1}{1 - R_j^2},

and 1/(1−Rj2)1/(1 - R_j^2) is the variance inflation factor: the price of feature jj being predictable from the others.

Predict before you look

A feature can be predicted from the other features with Rj2=0.9R_j^2 = 0.9. Compared with a design where it is uncorrelated with them (same SjjS_{jj} and σ\sigma), by what factor is the standard error of its coefficient multiplied?

Show the answer

3.16

The variance is multiplied by 1/(1−0.9)=101/(1 - 0.9) = 10, so the standard error by 10≈3.16\sqrt{10} \approx 3.16. To get it back you would need ten times as much data. At Rj2=0.99R_j^2 = 0.99 the factor is 10 for the standard error and 100 for the variance.

Computing least squares stably

Let κ=κ(X)=σ1/σd\kappa = \kappa(X) = \sigma_1/\sigma_d, the condition number of XX (the ratio of its largest to smallest singular value), and u≈1.1×10−16u \approx 1.1\times10^{-16} the unit roundoff of double precision. The least-squares problem has an intrinsic sensitivity: perturbing XX and y\mathbf y by relative amounts of order uu moves w^\hat{\mathbf w} by a relative amount of order

u (κ+κ2tan⁡θ),sin⁡θ=∥e∥∥y∥,u\,\big(\kappa + \kappa^2\tan\theta\big), \qquad \sin\theta = \frac{\norm{\mathbf e}}{\norm{\mathbf y}},

so the κ2\kappa^2 term matters only when the residual is large (Golub & Van Loan, 2013, §5.3). Backward-stable algorithms, Householder QR (introduced for least squares by Golub, 1965) and the SVD, achieve errors of this order. Forming X⊤XX^\top X instead squares the condition number whatever the residual: the normal equations behave like u κ2u\,\kappa^2, losing about twice as many digits as necessary when the fit is good.

Think first Take X=(11ϵ00ϵ)X = \begin{pmatrix}1 & 1\\ \epsilon & 0\\ 0 & \epsilon\end{pmatrix} with ϵ=10−8\epsilon = 10^{-8}. XX has full rank. What happens to the normal equations in double precision?

X⊤X=(1+ϵ2111+ϵ2)X^\top X = \begin{pmatrix}1+\epsilon^2 & 1\\ 1 & 1+\epsilon^2\end{pmatrix}, and 1+10−161 + 10^{-16} rounds to exactly 11 in double precision. The computed X⊤XX^\top X is the all-ones matrix, which is singular, so the normal equations break down, although κ(X)=2+ϵ2/ϵ≈1.4×108\kappa(X) = \sqrt{2+\epsilon^2}/\epsilon \approx 1.4\times10^8 is comfortably below 1/u1/u, and a QR factorization of XX still delivers about eight correct digits (uκ≈10−8u\kappa \approx 10^{-8} when the residual is small). This is Läuchli's classic example.

MethodFlops (n≫dn \gg d)Error scaleRank deficient?
Normal equations + Choleskynd2+d3/3nd^2 + d^3/3u κ2u\,\kappa^2breaks down
Householder QR, Rw^=Q⊤yR\hat{\mathbf w} = Q^\top\mathbf y2nd2−23d32nd^2 - \tfrac23 d^3u(κ+κ2tan⁡θ)u(\kappa + \kappa^2\tan\theta)with column pivoting
SVD, w^=VΣ+U⊤y\hat{\mathbf w} = V\Sigma^+U^\top\mathbf ya few times QRu(κ+κ2tan⁡θ)u(\kappa + \kappa^2\tan\theta)yes: zero out tiny σj\sigma_j
LSQR (Krylov iterations)O(nd)\order{nd} per iterationdepends on stoppingconverges to the minimum-norm solution from w0=0\mathbf w_0 = \mathbf 0
For the SVD, a singular value is treated as zero when it falls below a tolerance such as max⁡(n,d) ϵmach σ1\max(n, d)\,\epsilon_{\text{mach}}\,\sigma_1 with machine epsilon ϵmach=2u≈2.2×10−16\epsilon_{\text{mach}} = 2u \approx 2.2\times10^{-16} (NumPy's default in lstsq); this truncated solution is the stable version of the pseudoinverse. The normal equations remain a reasonable choice when κ\kappa is small and speed matters.

Key takeaways

  • H=X(X⊤X)−1X⊤=QQ⊤H = X(X^\top X)^{-1}X^\top = QQ^\top is the orthogonal projection onto col(X)\mathrm{col}(X): symmetric, idempotent, eigenvalues 0 and 1, trace dd. Fitted values have covariance σ2H\sigma^2H and residuals σ2(I−H)\sigma^2(I - H).
  • Leverage hii=∂y^i/∂yih_{ii} = \partial\hat y_i/\partial y_i depends only on XX, lies in [1/n,1][1/n, 1] with an intercept and averages d/nd/n. Deleting point ii moves the coefficients by (X⊤X)−1xiei/(1−hii)(X^\top X)^{-1}\mathbf x_ie_i/(1-h_{ii}), and Cook's distance ri2dhii1−hii\frac{r_i^2}{d}\frac{h_{ii}}{1-h_{ii}} combines outlyingness with leverage.
  • Frisch–Waugh–Lovell: a coefficient is the slope of y\mathbf y on the part of its feature orthogonal to the others, so collinearity multiplies its variance by 1/(1−Rj2)1/(1 - R_j^2).
  • The normal equations square the condition number. Householder QR and the SVD are backward stable, and the SVD also handles rank deficiency; randomized sketches speed up very tall problems.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A regression has n=500n = 500 observations and d=10d = 10 columns (intercept included). What is the average leverage?

  1. 0.0020.002
  2. 0.020.02
  3. 0.20.2
  4. It depends on y\mathbf y
Show the answer

B. 0.020.02

∑ihii=Tr⁡H=d=10\sum_i h_{ii} = \Tr H = d = 10, so the average is 10/500=0.0210/500 = 0.02, and the Hoaglin–Welsch screen 2d/n2d/n flags points above 0.040.04.

Question 2

Why can raw residuals hide a bad observation that has high leverage?

  1. Because high-leverage points always have large residuals
  2. Because leverage changes the noise variance σ2\sigma^2
  3. Because residuals are not defined at high-leverage points
  4. Because its residual has variance σ2(1−hii)\sigma^2(1 - h_{ii}): the fit is pulled toward the point, which shrinks its residual
Show the answer

D. Because its residual has variance σ2(1−hii)\sigma^2(1 - h_{ii}): the fit is pulled toward the point, which shrinks its residual

Cov⁡e=σ2(I−H)\Cov\mathbf e = \sigma^2(I - H), so a point with hiih_{ii} near 1 has a residual near zero even if yiy_i is far off. Studentizing, ei/(σ^1−hii)e_i/(\hat\sigma\sqrt{1-h_{ii}}), puts residuals on a common scale, and Cook's distance combines them with leverage.

Question 3

κ(X)=106\kappa(X) = 10^6 and the fit is good (small residual). Working in double precision (about 16 significant digits), roughly how many digits of w^\hat{\mathbf w} can the normal equations lose?

  1. About 12, since κ(X⊤X)=κ(X)2=1012\kappa(X^\top X) = \kappa(X)^2 = 10^{12}
  2. About 6, the same as QR
  3. About 24, so nothing survives
  4. None: (X⊤X)−1X⊤y(X^\top X)^{-1}X^\top\mathbf y is an exact formula
Show the answer

A. About 12, since κ(X⊤X)=κ(X)2=1012\kappa(X^\top X) = \kappa(X)^2 = 10^{12}

Forming X⊤XX^\top X squares the condition number, so errors of order uκ2=10−16⋅1012=10−4u\kappa^2 = 10^{-16}\cdot10^{12} = 10^{-4} leave about 4 correct digits. With a small residual, QR or the SVD lose only about log⁡10κ=6\log_{10}\kappa = 6 digits.

Question 4

You regress wages on education and experience. By the Frisch–Waugh–Lovell theorem, the coefficient on education equals the slope from which regression?

  1. Wages on education alone
  2. Education on wages
  3. The residuals of wages-on-experience on the residuals of education-on-experience
  4. The average of the two single-variable slopes
Show the answer

C. The residuals of wages-on-experience on the residuals of education-on-experience

Partial experience (and the intercept) out of both sides, then regress. The coefficient uses only the variation in education that experience does not explain, which is what "holding experience fixed" means for a linear fit.

Further reading

  • D. C. Hoaglin & R. E. Welsch, "The hat matrix in regression and ANOVA," The American Statistician 32(1), 17–22 (1978).
  • R. D. Cook, "Detection of influential observation in linear regression," Technometrics 19(1), 15–18 (1977).
  • M. C. Lovell, "Seasonal adjustment of economic time series and multiple regression analysis," Journal of the American Statistical Association 58(304), 993–1010 (1963).
  • G. H. Golub & C. F. Van Loan, Matrix Computations, 4th ed. (Johns Hopkins University Press, 2013), chapter 5.
  • P. Drineas, M. W. Mahoney, S. Muthukrishnan & T. Sarlós, "Faster least squares approximation," Numerische Mathematik 117, 219–249 (2011).