Training a linear regression model means searching for a w that satisfies y≈Xw as well as possible for an observed vector y. The intercept b can be absorbed into the weights by appending a column of all ones to the design matrix X.
Minimising the sum of squared errors L(w)=∥y−Xw∥2 is exactly equivalent to solving the normal equationsXTXw=XTy, and no differentiation is needed to see this (Theorem 3.3). That learning collapses into a system of linear equations is the whole point of the model.
The prediction Xw^ produced by a solution w^ of the normal equations is nothing other than the orthogonal projection of y onto the column space ImX (Theorem 4.2). The residual is orthogonal to every explanatory variable.
The normal equations always have a solution, whatever X and y may be. The solution is unique precisely when rankX=p (the columns are linearly independent), and then w^=(XTX)−1XTy. Even when the rank drops, the prediction Xw^ remains uniquely determined.
In an implementation, never form (XTX)−1 explicitly. Since κ2(XTX)=κ2(X)2 squares the condition number, going through a QR decomposition or a singular value decomposition is safer.
As one learns in school, there is exactly one line through two distinct points in the plane. So which line “passes through” 100 points contaminated by measurement error? The answer is: none. There are only two unknowns, the slope and the intercept, but there are 100 equations. Such an overdetermined system — a system of linear equations with more equations than unknowns — has no solution in the ordinary sense.
This situation was entirely routine in the astronomy and geodesy of the early nineteenth century. An orbit is described by six elements, yet observations are made dozens of times. Practitioners of the day resorted to ad hoc procedures: selecting a few observations and writing down equations, or grouping observations and averaging them. What was wanted was a procedure that uses all the observations impartially and still returns a unique answer.
That procedure is the method of least squares. On 1 January 1801 Giuseppe Piazzi discovered the asteroid Ceres, but after 41 days of observation it moved towards the Sun and was lost. Gauss, then 24, computed an orbit from the scanty data and predicted where it would reappear; at the end of the same year astronomers recovered Ceres exactly where he had said it would be. The episode made the power of least squares widely known. The method itself was published in 1805 by Legendre, as “méthode des moindres carrés” in an appendix to his Nouvelles méthodes pour la détermination des orbites des comètes, whereupon Gauss claimed in his Theoria Motus of 1809 that he had been using it since 1795 — the origin of a famous priority dispute.
The sum of squares is not the only way to measure error. The sum of absolute values ∑i∣yi−y^i∣ or the maximum error maxi∣yi−y^i∣ would do just as well. There are nevertheless clear reasons why the sum of squares became standard.
It is differentiable. The absolute value is not differentiable at the origin, whereas the square is smooth everywhere and, moreover, a quadratic in w. The condition for a stationary point of a quadratic is a linear equation.
It connects directly with geometry. The sum of squares is the square of the Euclidean norm, that is, the distance coming from an inner product. Hence “minimise the error” means the same as “drop a perpendicular onto a subspace”, and the Pythagorean theorem applies verbatim (Theorem 4.2).
There is a weakness on the other side. Squaring emphasises large errors still further, so a single outlier can move the solution a long way. Remedies for this weakness (robust regression, regularisation) are touched on in the later sections and in the exercises.
As we saw in Why Does Machine Learning Need Mathematics?, machine learning algorithms become suddenly transparent once written in the language of mathematics. Among supervised learning models, linear regression is essentially the only one whose learning problem admits a closed-form solution. For logistic regression or neural networks the loss ceases to be a quadratic in w, the closed form disappears, and one falls back on iterative methods such as Gradient Descent. It is precisely because a closed form exists here that it is worth understanding completely what is going on. The triple that appears here — orthogonal projection, rank condition, condition number — carries over unchanged to Principal Component Analysis and to the iteratively reweighted least squares of Logistic Regression.
The data consist of n observations (xi,yi) for i=1,…,n. Here xi∈Rd is the vector of explanatory variables (features) and yi∈R is the response. The relationship we wish to predict has the form
y^=w1x1+w2x2+⋯+wdxd+b
where b is the intercept (bias term). To handle these d+1 unknowns together we set up the following notation.
Definition 2.1(Design matrix and the linear regression model)
Given n observations (xi,yi) with xi=(xi1,…,xid)T∈Rd and yi∈R, put p=d+1 and set
The matrix X is called the design matrix. Its first column is the vector 1 all of whose entries are 1. Writing the parameters as w=(b,w1,…,wd)T∈Rp, the n predicted values are collected into Xw∈Rn. This is the linear regression model.
By placing 1 in the first column, the intercept becomes “the weight attached to the constant feature 1”. From now on the intercept needs no special treatment. The i-th row of X is the i-th data point, and the j-th column is the j-th feature recorded across all data. We shall use the correspondence rows are data, columns are features throughout.
Let us make the meaning of “linear” precise. The “linear” in linear regression means linear in the parameters w, not in the explanatory variables. This distinction widens the range of applications enormously.
Fix an arbitrary map φ:Rd→Rp and let Φ∈Rn×p be the matrix obtained by replacing the i-th row of the design matrix with φ(xi)T. The model y^=wTφ(x) is called the linear model with feature map φ. However nonlinear φ may be, the model is linear in w.
For instance, taking d=1 and φ(x)=(1,x,x2,x3)T gives a cubic polynomial fit, yet the model is still linear in the unknown w. Everything we build below therefore applies directly to polynomial regression, trigonometric expansions and radial basis function models. A concrete numerical instance appears in Example 6.2.
3. The least squares problem and the normal equations
When n>p, there is in general no w satisfying Xw=y exactly. We therefore give up on exactness and choose the w that makes the discrepancy as small as possible.
For X∈Rn×p and y∈Rn, define the residual vectorr(w)=y−Xw and the sum of squared errors (residual sum of squares)
L(w)=∥y−Xw∥2=i=1∑n(yi−(Xw)i)2.
A vector w^ minimising L over all of Rp, that is, one satisfying
w^∈w∈Rpargmin∥y−Xw∥2,
is called a least squares solution.
L is a quadratic in each component of w and is bounded below (always L≥0). As we shall see, the minimum is always attained. The minimiser need not be unique, however. Capturing this “exists but need not be unique” structure precisely is the goal of this section and the next.
Let A∈Rp×p be symmetric (AT=A), let b∈Rp and c∈R, and define f:Rp→R by
f(w)=wTAw−2bTw+c.
Then f is of class C∞, and its gradient and Hessian are
∇f(w)=2Aw−2b,∇2f(w)=2A.
Proof(Lemma 3.2)
In components, f(w)=∑i=1p∑j=1paijwiwj−2∑i=1pbiwi+c, a polynomial in w1,…,wp, hence of class C∞. Differentiate with respect to the k-th component. The product wiwj involves wk when i=k and when j=k; the term akkwk2 with i=j=k differentiates to 2akkwk, which agrees with the sum of the two counts. Therefore
By the hypothesis AT=A the right-hand side equals 2(Aw)k−2bk, which gives the first formula. Differentiating once more with respect to wl gives ∂2f/∂wl∂wk=2akl, so the Hessian is 2A.
We come to the central theorem. Note that it can be proved without any differentiation at all. Because the proof needs nothing but an algebraic identity, it simultaneously establishes that we have a minimum, and not merely a stationary point.
By the transpose rule ⟨u,Av⟩=⟨ATu,v⟩, the middle term can be written
⟨r^,Xv⟩=⟨XTr^,v⟩=vT(XTy−XTXw^).
So, setting g=XTy−XTXw^=XTr^, we obtain for every v
L(w^+v)=L(w^)−2vTg+∥Xv∥2.
Both implications follow from this single identity.
(2) ⇒ (1). If the normal equations hold then g=0, so the identity becomes L(w^+v)=L(w^)+∥Xv∥2. Since ∥Xv∥2≥0, we get L(w^+v)≥L(w^) for every v; that is, w^ is a minimiser. Substituting w=w^+v gives exactly the asserted identity. Equality holds if and only if ∥Xv∥=0, that is, Xv=0, so the set of minimisers is w^+KerX.
(1) ⇒ (2). We prove the contrapositive. Suppose g=0 and substitute v=tg with t>0:
L(w^+tg)−L(w^)=−2t∥g∥2+t2∥Xg∥2=t(t∥Xg∥2−2∥g∥2).
If Xg=0 the right-hand side equals −2t∥g∥2<0 for every t>0. If Xg=0, taking for example t=∥g∥2/∥Xg∥2>0 makes the right-hand side −∥g∥4/∥Xg∥2<0. In either case L(w^+tg)<L(w^), so w^ is not a minimiser. Hence a minimiser must satisfy g=0, that is, the normal equations.
∎
The normal equations XTXw=XTy form a system of p linear equations. However large n may be — even hundreds of millions of data points — the size of the system to be solved is governed solely by the number of features p. What actually happens behind the word “learning” is the solution of a p×p linear system.
Let us also record the derivation using calculus. Expanding,
L(w)=∥y∥2−2yTXw+wTXTXw,
so applying Lemma 3.2 with A=XTX (symmetric, since (XTX)T=XTX), b=XTy and c=∥y∥2 gives
∇L(w)=2XTXw−2XTy.
The condition ∇L(w^)=0 is the normal equations. Being a stationary point does not in general imply being a minimum. Here, however, the Hessian is 2XTX, and vT(XTX)v=∥Xv∥2≥0 for every v, so it is positive semidefinite; L is therefore convex and a stationary point is a global minimum. The proof of Theorem 3.3 can be viewed as replacing this convexity argument by a single identity.
4. Geometry: the least squares solution is an orthogonal projection
Rewrite the normal equations as XT(y−Xw^)=0, that is, XTr^=0. The j-th component of XTr^ is the inner product of the j-th column of X with r^, so the equation reads:
the residual vector is orthogonal to every column of X, that is, to every feature.
In statistical terms, “the residual contains nothing further that could be explained by a linear combination of the available features”. Least squares is a procedure that stops exactly when everything the explanatory variables can account for has been used up. Let us turn this reading into a theorem.
Lemma 4.1(Orthogonal complement of the column space)
For any X∈Rn×p we have (ImX)⊥=KerXT.
Proof(Lemma 4.1)
That u∈(ImX)⊥ means ⟨u,Xv⟩=0 for every v∈Rp. By the transpose rule ⟨u,Xv⟩=⟨XTu,v⟩, this is equivalent to ⟨XTu,v⟩=0 for every v. Taking in particular v=XTu gives ∥XTu∥2=0, hence XTu=0. Conversely, if XTu=0 then the inner product vanishes for every v. The two conditions are therefore equivalent, and the sets coincide.
∎
Theorem 4.2(Existence of least squares solutions and their projection form)
Let X∈Rn×p and y∈Rn be arbitrary. Then the following hold.
The normal equations XTXw=XTy have at least one solution. In particular a least squares solution always exists.
If w^ is any least squares solution, then Xw^ equals the orthogonal projection of y onto the subspace ImX. In particular Xw^ is uniquely determined, independently of which least squares solution is chosen.
y^=Xw^ is the unique point of ImX closest to y: if z∈ImX and z=y^, then ∥y−z∥>∥y−y^∥.
Proof(Theorem 4.2)
(1). Since W=ImX is a subspace of Rn, the orthogonal decomposition Rn=W⊕W⊥ gives a unique decomposition y=y^+s with y^∈W and s∈W⊥. As y^∈ImX, there is a w^ with y^=Xw^. By Lemma 4.1, s∈W⊥=KerXT, that is, XTs=0. Hence
XTXw^=XTy^=XT(y−s)=XTy,
so this w^ solves the normal equations. By Theorem 3.3 it is a least squares solution.
(2). Let w^ be any least squares solution. By Theorem 3.3, XT(y−Xw^)=0, hence by Lemma 4.1 we have y−Xw^∈W⊥. On the other hand Xw^∈W, so y=Xw^+(y−Xw^) is a decomposition along W⊕W⊥. Such a decomposition is unique, so Xw^ equals the y^ constructed in (1), namely the orthogonal projection of y onto W, and does not depend on the choice of least squares solution.
If z=y^ the second term is positive, giving the strict inequality.
∎
The geometry of least squares. The observed vector y generally lies outside the column space Im X; the fitted vector is the foot of the perpendicular dropped from y onto Im X (the orthogonal projection). The residual r is orthogonal to the whole column space.
4.2. The hat matrix and the coefficient of determination
Suppose X∈Rn×p satisfies rankX=p (so that XTX is invertible by Corollary 5.2). Put
P=X(XTX)−1XT∈Rn×n.
Then the following hold.
PT=P and P2=P (symmetric idempotent).
For every y∈Rn, Py is the orthogonal projection of y onto ImX, and Py=Xw^.
In−P is the orthogonal projection onto (ImX)⊥=KerXT, and the residual is r^=(In−P)y.
trP=p.
Proof(Proposition 4.3)
1.(XTX)−1 is the inverse of a symmetric matrix, hence symmetric (substitute AT=A into (A−1)T=(AT)−1). Therefore PT=X((XTX)−1)TXT=P. Also
P2=X(XTX)−1=IpXTX(XTX)−1XT=X(XTX)−1XT=P.
2.w^=(XTX)−1XTy solves the normal equations (multiply both sides by XTX to check), so Py=Xw^, and by part (2) of Theorem 4.2 this is the orthogonal projection.
3. We have r^=y−Py=(In−P)y, and the proof of Theorem 4.2 shows r^∈(ImX)⊥. Since (In−P)T=In−P and (In−P)2=In−2P+P2=In−P, this matrix is also symmetric idempotent; and for u∈(ImX)⊥ we have XTu=0 by Lemma 4.1, hence Pu=0 and (In−P)u=u, so In−P is the identity on (ImX)⊥.
4. Using the cyclic property of the trace, tr(AB)=tr(BA), with A=X and B=(XTX)−1XT,
trP=tr((XTX)−1XTX)=trIp=p.∎
Because y^=Py “puts a hat on y”, P is called the hat matrix. In statistics the diagonal entries Pii measure “how strongly the i-th observation pulls its own fitted value” (the leverage), and trP=p can be read as ”p degrees of freedom have been spent on n observations”.
Corollary 4.4(Decomposition of the sum of squares and the coefficient of determination)
Assume that the columns of X include the all-ones vector 1. Put y^=Xw^, r^=y−y^ and yˉ=n1∑iyi. Then the following hold.
∑i=1nr^i=0, and consequently n1∑iy^i=yˉ.
The decomposition of the sum of squares
total Stoti=1∑n(yi−yˉ)2=explainedi=1∑n(y^i−yˉ)2+residual Sresi=1∑nr^i2
holds. In particular, when Stot=0 the coefficient of determinationR2=1−Sres/Stot satisfies 0≤R2≤1.
Proof(Corollary 4.4)
1. By Theorem 3.3 we have XTr^=0, and the component corresponding to 1 is ⟨1,r^⟩=∑ir^i=0. Dividing by n gives yˉ−n1∑iy^i=0.
2. Decompose y−yˉ1=(y^−yˉ1)+r^. Since 1∈ImX and y^∈ImX, we have y^−yˉ1∈ImX, while r^∈(ImX)⊥ by Theorem 4.2; the two are therefore orthogonal. The asserted identity follows from the Pythagorean theorem. Finally R2=(explained)/Stot, and both terms are non-negative with sum Stot, so 0≤R2≤1.
∎
Example 4.5(Fitting a line to three points, seen as a projection)
Take n=3, d=1 and the data (xi,yi)=(0,1),(1,1),(2,4). The design matrix and observation vector are
X=111012,y=114.
Here ImX is a two-dimensional plane in R3, and y does not lie on it (the three points are not collinear). Computing the ingredients of the normal equations,
that is, y^=0.5+1.5x. The fitted values and residuals are
y^=Xw^=(0.5,2.0,3.5)T,r^=y−y^=(0.5,−1.0,0.5)T.
Let us verify orthogonality: ⟨1,r^⟩=0.5−1.0+0.5=0 and ⟨(0,1,2)T,r^⟩=0⋅0.5+1⋅(−1.0)+2⋅0.5=0, so the residual is indeed orthogonal to both columns of X. The Pythagorean theorem also checks out:
By Theorem 4.2 the prediction y^=Xw^ is always unique. Whether the coefficient vector w^ itself is unique is another matter. The last assertion of Theorem 3.3 says the solution set is w^+KerX, so uniqueness is equivalent to KerX={0}. Let us translate this into the language of XTX.
If Xv=0, multiplying on the left by XT gives XTXv=0, so KerX⊆Ker(XTX). Conversely, suppose XTXv=0 and multiply on the left by vT:
0=vTXTXv=(Xv)T(Xv)=∥Xv∥2.
Only the zero vector has zero norm, so Xv=0, giving Ker(XTX)⊆KerX. The two kernels therefore coincide. As for the ranks, both X and XTX have p columns, so applying the rank–nullity theorem
rankA=p−dimKerA
to each and using the equality of the kernel dimensions gives the equality of the ranks.
∎
Corollary 5.2(Uniqueness of the least squares solution)
Let X∈Rn×p and y∈Rn. The following three conditions are equivalent.
The p columns of X are linearly independent, that is, rankX=p.
XTX is invertible.
There is exactly one least squares solution.
In that case the least squares solution is
w^=(XTX)−1XTy.
Furthermore, n≥p is necessary for these conditions to hold.
Proof(Corollary 5.2)
1 ⇔ 2.XTX is a p×p square matrix, so invertibility is equivalent to rank(XTX)=p. By Lemma 5.1 this is equivalent to rankX=p, which is exactly linear independence of the columns.
1 ⇔ 3. By Theorem 4.2 a least squares solution always exists, and by Theorem 3.3 the solution set is w^+KerX. Hence there is exactly one solution if and only if KerX={0}, which by the rank–nullity theorem is equivalent to rankX=p.
The formula. Under condition 2, setting w=(XTX)−1XTy gives XTXw=XTy, so this solves the normal equations and is therefore a least squares solution by Theorem 3.3. Uniqueness has just been shown.
Necessity of n≥p. Since rankX≤min(n,p), the equality rankX=p forces p≤n.
∎
When there are fewer data points than features (n<p), the solution is in this sense never unique. The situation of “more parameters than data”, an everyday occurrence in deep learning, already shows its face at the level of linear regression.
Example 5.3(When features are duplicated (multicollinearity))
Take the same data (xi,yi)=(0,1),(1,1),(2,4) as in Example 4.5 and add the pointless feature x′=2x, “twice x”. The design matrix becomes
X=111012024,
whose third column is exactly twice the second, so rankX=2<3=p. The kernel is
KerX={t(0,2,−1)T:t∈R}
(indeed 0⋅1+2x−1⋅(2x)=0). Appending a third coordinate 0 to the (0.5,1.5) found in Example 4.5 gives the least squares solution w^0=(0.5,1.5,0)T, so by Theorem 3.3 the solution set is the whole line
{(0.5,1.5−2t,t)T:t∈R}.
For example t=0.75 gives (0.5,0,0.75) and t=−1 gives (0.5,3.5,−1); the coefficients look completely different. Whether “the effect of x is 1.5” or “the effect of x is 0 and that of x′ is 0.75” cannot be decided from the data. The prediction, however, is
The second component is (n∑ixiyi−nyˉ∑ixi)/(nSxx)=(∑ixiyi−nxˉyˉ)/Sxx=Sxy/Sxx. Computing the first component in the same way gives (yˉ∑ixi2−xˉ∑ixiyi)/Sxx, which agrees with yˉSxx−xˉSxy=yˉ∑ixi2−nxˉ2yˉ−xˉ∑ixiyi+nxˉ2yˉ=yˉ∑ixi2−xˉ∑ixiyi. In summary we recover the formula familiar from school:
w^1=SxxSxy,b^=yˉ−w^1xˉ.
The second equation says that the regression line always passes through the centroid (xˉ,yˉ). It is also a restatement of part 1 of Corollary 4.4 (that the residuals sum to 0).
Example 6.1(Carrying a five-point simple regression through to the end)
Take the data (xi,yi)=(1,2),(2,3),(3,5),(4,4),(5,6). With n=5,
that is, y^=1.3+0.9x. Let us check with the formula as well: Sxx=4+1+0+1+4=10 and Sxy=(−2)(−2)+(−1)(−1)+0⋅1+1⋅0+2⋅2=9, so w^1=9/10=0.9 and b^=4−0.9⋅3=1.3, in agreement.
The fitted values are y^=(2.2,3.1,4.0,4.9,5.8)T and the residuals are
r^=(−0.2,−0.1,1.0,−0.9,0.2)T.
Verifying the orthogonality conditions, ∑ir^i=−0.2−0.1+1.0−0.9+0.2=0 and ∑ixir^i=−0.2−0.2+3.0−3.6+1.0=0, both zero. The sums of squares are Sres=0.04+0.01+1.00+0.81+0.04=1.90 and Stot=4+1+1+0+4=10, so by Corollary 4.4 the explained variation is 10−1.9=8.1, which matches Sxy2/Sxx=81/10=8.1. The coefficient of determination is R2=1−1.9/10=0.81.
The same computation in NumPy looks as follows. Note that it solves a linear system rather than forming an inverse.
import numpy as np
x = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
y = np.array([2.0, 3.0, 5.0, 4.0, 6.0])
X = np.column_stack([np.ones_like(x), x]) # design matrix (5, 2)
# solve the normal equations X^T X w = X^T y directly
The second row immediately gives w^1=−0.2. The first and third rows form a system in w0 and w2 alone; doubling the first row and subtracting it from the third gives
(34−20)w2=48−34,that is14w2=14,
so w^2=1, and then the first row gives w^0=(17−10)/5=1.4. The fitted curve is
y^=1.4−0.2x+x2.
The fitted values are y^=(5.8,2.6,1.4,2.2,5.0)T and the residuals are r^=(0.2,−0.6,0.6,−0.2,0)T. Checking the orthogonality conditions again, all three hold:
The residual sum of squares is Sres=0.04+0.36+0.36+0.04+0=0.8, and since yˉ=3.4 the total is Stot=6.76+1.96+1.96+1.96+2.56=15.2, so R2=1−0.8/15.2≈0.947. We fitted a curve, yet all we solved was a 3×3 linear system. That is the power of being linear in the parameters.
Let us gather the results so far onto a single page.
flowchart TD
A["data X, y"] --> B["minimise the sum of squared errors L"]
B --> C["normal equations X^T X w = X^T y"]
C --> D{"is rank X = p?"}
D -- "yes" --> E["unique solution; implement via Cholesky or QR"]
D -- "no" --> F["solution set is w0 + Ker X; choose the minimum-norm one"]
E --> G["the prediction Xw is the orthogonal projection of y onto Im X"]
F --> G
From the least squares problem to the solution. The branch is the rank condition, and the vector of predictions is uniquely determined along either branch.
When rankX=p, the matrix XTX is symmetric and positive definite. Indeed, by Lemma 5.1, if v=0 then Xv=0, so vTXTXv=∥Xv∥2>0. A positive definite symmetric matrix admits a Cholesky decomposition XTX=LLT with L lower triangular, so the implementation reduces to: form XTX and XTy, compute the Cholesky factor, and solve two triangular systems.
The normal equations, clean as they are in theory, have a numerical drawback. Measuring the condition number of a matrix A by κ2(A)=σmax(A)/σmin(A) (the ratio of singular values), one has, for X of full rank,
κ2(XTX)=κ2(X)2.
The reason is that with the singular value decomposition X=UΣVT we get XTX=VΣTΣVT, so the eigenvalues of XTX are the squares of the singular values of X (for the diagonalisation of symmetric matrices see orthogonal diagonalisation of real symmetric matrices(Corollary 4.3)[スペクトル定理] in The Spectral Theorem). The condition number indicates by what factor a relative error in the input is amplified in the solution, so the moment one forms XTX the amplification factor is squared.
Example 7.1(Centring alone improves the condition number)
For the data of Example 6.1 we had XTX=(5151555). Being a symmetric 2×2 matrix, its eigenvalues come from the characteristic equation λ2−60λ+50=0 (trace 60, determinant 50), giving
λ=30±900−50=30±850,
that is, λmax≈59.155 and λmin≈0.845. Hence κ2(XTX)≈70.0 and κ2(X)≈70≈8.4.
Now centre x, replacing the second column by xi−xˉ=−2,−1,0,1,2. Its inner product with the first column becomes ∑i(xi−xˉ)=0, so
XcTXc=(50010)
is diagonal and κ2(XcTXc)=10/5=2. The data are the same; only the choice of coordinates changed. This is one of the reasons why centring and scaling the features is recommended as preprocessing. (Centring does not change the fitted line itself; see exercise Exercise 8.2.)
When rankX=p, one can factor X=QR with Q∈Rn×p satisfying QTQ=Ip and R∈Rp×p upper triangular with positive diagonal entries. This is precisely Gram–Schmidt orthogonalisation(Theorem 6.1)[内積空間とグラム・シュミット直交化]. Substituting into the normal equations gives
XTX=RTQTQR=RTR,XTy=RTQTy,
so the normal equations become RTRw=RTQTy. Since R is invertible (positive diagonal), so is RT, and multiplying both sides by (RT)−1 turns the system into the upper triangular system
Rw^=QTy,
which is solved by back substitution. Because XTX is never formed, the condition number stays at κ2(X). The hat matrix also simplifies to P=QQT. When rank deficiency is possible, the still more robust approach via the singular value decomposition (the Appendix at the end of this article) is used.
From the statistical side, one can show that under the assumption that the errors εi have mean 0, variance σ2 and are uncorrelated, the least squares estimator has the smallest variance among unbiased linear estimators (the Gauss–Markov theorem). We do not treat it here, since no probabilistic assumptions have been made in this article, but the proof needs nothing beyond the hat matrix and the orthogonality established above.
Show that if the columns of the design matrix X include 1=(1,…,1)T, then the residual of a least squares solution satisfies ∑ir^i=0. Then verify with explicit data that this fails for the model without intercept y^=wx (whose design matrix is the single column x).
Solution
First part. By Theorem 3.3, a least squares solution satisfies XT(y−Xw^)=XTr^=0. The j-th component of XTr^ is the inner product of the j-th column of X with r^. If the j-th column is 1, that component is ⟨1,r^⟩=∑ir^i, which therefore vanishes.
Second part. Take the data (x1,y1)=(1,1) and (x2,y2)=(2,0). The design matrix is X=(1,2)T with n=2, p=1, and XTX=12+22=5, XTy=1⋅1+2⋅0=1, so w^=1/5=0.2. The fitted values are y^=(0.2,0.4)T and the residuals r^=(0.8,−0.4)T, whence ∑ir^i=0.4=0. Of course ⟨x,r^⟩=1⋅0.8+2⋅(−0.4)=0 still holds. Orthogonality is to the columns of X, and 1, not being in the model, need not be orthogonal to the residual.
Split X=(1X~) with X~∈Rn×d, and split the parameters correspondingly as w=(b,u) with u∈Rd. Write the column means as xˉ=n1X~T1∈Rd and the centred matrix and vector as Xc=X~−1xˉT and yc=y−yˉ1. Show that the normal equations are equivalent to
b^=yˉ−xˉTu^,XcTXcu^=XcTyc.Solution
Write the normal equations XTXw=XTy in block form. Since 1T1=n, 1TX~=nxˉT and 1Ty=nyˉ,
(nnxˉnxˉTX~TX~)(bu)=(nyˉX~Ty).
The first block row reads nb+nxˉTu=nyˉ, that is, b=yˉ−xˉTu. Substituting this into the second block row nxˉb+X~TX~u=X~Ty gives
(X~TX~−nxˉxˉT)u=X~Ty−nxˉyˉ.
It remains to check that the coefficients on the left and right are the centred quantities. From 1T1=n and 1TX~=nxˉT,
This gives the two asserted equations, and conversely the original block system can be recovered from them, so they are equivalent. In other words, one may first centre the data, solve a system in d unknowns, and finally recover the intercept as b^=yˉ−xˉTu^. For d=1 this is exactly the formula of Example 6.1.
Let λ>0 and consider the ridge regression objective
Lλ(w)=∥y−Xw∥2+λ∥w∥2.
(1) Show that XTX+λIp is invertible regardless of the rank of X. (2) Show that Lλ has exactly one minimiser, given by w^λ=(XTX+λIp)−1XTy.
Solution
(1). For v=0,
vT(XTX+λIp)v=∥Xv∥2+λ∥v∥2≥λ∥v∥2>0.
If there were a v=0 with (XTX+λIp)v=0, the left-hand side would be 0, a contradiction. Hence the kernel is {0} and the matrix is invertible.
(2). Consider the augmented design matrix and observation vector
Xλ=(XλIp)∈R(n+p)×p,yλ=(y0)∈Rn+p.
Computing the norm block by block,
∥yλ−Xλw∥2=∥y−Xw∥2+∥λw∥2=Lλ(w),
so ridge regression is an ordinary least squares problem for the augmented data. Since XλTXλ=XTX+λIp and XλTyλ=XTy, by Theorem 3.3 its normal equations are (XTX+λIp)w=XTy. By (1) and Corollary 5.2 there is exactly one solution, given by the stated formula. As long as λ>0, the answer is uniquely determined even for rank-deficient data such as that of Example 5.3; this is the benefit of regularisation.
Let P∈Rn×n be symmetric and idempotent (PT=P, P2=P). (1) Show that the eigenvalues of P are 0 and 1 only. (2) Show that trP=rankP. (3) Verify that this is consistent with trP=p for the hat matrix of Proposition 4.3.
Solution
(1). Suppose Pv=μv with v=0. Multiplying both sides by P gives P2v=μPv=μ2v, while P2=P makes the left-hand side Pv=μv. Hence (μ2−μ)v=0, and since v=0 we get μ2=μ, that is, μ∈{0,1}.
(2). As P is real symmetric, the spectral theorem gives an orthogonal matrix U with P=UΛUT and Λ=diag(μ1,…,μn). By (1) each μi is 0 or 1. By the cyclic property of the trace, trP=tr(ΛUTU)=trΛ=#{i:μi=1}. On the other hand U is invertible, so rankP=rankΛ, which is also the number of ones. The two are therefore equal.
(3). The matrix P=X(XTX)−1XT of Proposition 4.3 is symmetric idempotent by part 1 of that proposition, and its image is ImX by part 2, so rankP=dimImX=rankX=p. Combined with (2) this gives trP=p, agreeing with the result obtained directly from cyclicity in part 4 of the proposition. In Example 4.5 we had n=3, p=2, eigenvalues 1,1,0 and trace 2.
Textbooks (linear algebra and geometry). G. Strang, Introduction to Linear Algebra, 5th ed., Wellesley–Cambridge Press, 2016 — Chapter 4 (orthogonality, projections, least squares). The standard geometric account of projection matrices and the normal equations. Kenichi Kanatani, Kore nara Wakaru Saitekika Sugaku: Kiso Genri kara Keisan Shuho made, Kyoritsu Shuppan, 2005 (in Japanese) — the chapters on least squares and the singular value decomposition; a well-organised introduction for Japanese readers.
Numerical computation. G. H. Golub and C. F. Van Loan, Matrix Computations, 4th ed., Johns Hopkins University Press, 2013 — Chapter 5 (orthogonalisation and least squares problems). The standard source for QR-based solutions and the discussion of condition numbers. Å. Björck, Numerical Methods for Least Squares Problems, SIAM, 1996 — a monograph covering numerical methods for least squares problems comprehensively.
Connections to statistics and machine learning. T. Hastie, R. Tibshirani, and J. Friedman, The Elements of Statistical Learning, 2nd ed., Springer, 2009 — Chapter 3 (linear methods for regression). Ridge regression, multicollinearity and variable selection are explained as extensions of the framework of this article. A PDF is made available by the authors. C. M. Bishop, Pattern Recognition and Machine Learning, Springer, 2006 — Chapter 3 (linear models for regression); a careful treatment of least squares reread as maximum likelihood.
History. S. M. Stigler, The History of Statistics: The Measurement of Uncertainty before 1900, Harvard University Press, 1986 — Part I. The Legendre–Gauss priority dispute and the process by which least squares came to be accepted are traced carefully from the sources.
Appendix: The pseudoinverse and the minimum-norm solution
Pinning down one answer even when the rank drops. As we saw in Example 5.3, when rankX<p there are infinitely many least squares solutions. A numerical library must return one of them. The standard choice is the one of smallest norm.
Let X∈Rn×p and y∈Rn, and let S be the set of least squares solutions. Then S∩Im(XT) consists of a single point, and that element w^+ is the unique element of S of smallest norm.
Proof(Proposition 8.5)
By Theorem 4.2 we have S=∅, and by Theorem 3.3S=w0+KerX for any chosen w0∈S. Applying Lemma 4.1 to XT gives (ImXT)⊥=KerX, so we have the orthogonal decomposition
Rp=Im(XT)⊕KerX.
Decomposing w0=u+z accordingly, with u∈ImXT and z∈KerX, we get u=w0−z∈S and u∈ImXT, so S∩Im(XT)=∅. If two elements u,u′ belong to this intersection, then u−u′∈KerX (from the form of S) and u−u′∈ImXT; the two summands of an orthogonal decomposition intersect in {0}, so u=u′ and the intersection is a single point, which we denote w^+.
For minimality, every w∈S can be written w=w^++v with v∈KerX, and w^+⊥v, so the Pythagorean theorem gives
∥w∥2=∥w^+∥2+∥v∥2≥∥w^+∥2,
with equality only when v=0, that is, w=w^+.
∎
The pseudoinverse. This w^+ can be written using the Moore–Penrose pseudoinverse built from the singular value decomposition X=UΣVT.
Let X=UΣVT be a singular value decomposition of X∈Rn×p, where U and V are orthogonal and the diagonal entries of Σ are the singular values σ1≥⋯≥σr>0 with all other entries 0. Let Σ+ be the matrix obtained by replacing the non-zero diagonal entries of Σ by their reciprocals and transposing. Then
X+=VΣ+UT∈Rp×n
is called the pseudoinverse of X. When rankX=p it agrees with X+=(XTX)−1XT.
One has w^+=X+y; this is checked by writing out, in terms of U, Σ and V, that X+y satisfies the normal equations and lies in ImXT (see Chapter 5 of Golub–Van Loan for details). This is the solution returned by NumPy’s np.linalg.lstsq and np.linalg.pinv. For the solution set (0.5,1.5−2t,t) of Example 5.3, the squared norm
0.25+(1.5−2t)2+t2=5t2−6t+2.5
is minimised at t=3/5=0.6, giving w^+=(0.5,0.3,0.6)T. Indeed this solution is orthogonal to the generator (0,2,−1)T of the kernel (2⋅0.3−0.6=0). Its squared norm is 0.7, smaller than the 2.5 of the solution (0.5,1.5,0) at t=0.