Unit 4, lesson 21

Multiple Linear Regression and Least Squares

How multiple linear regression fits several features by least squares, why the normal equations make the fitted values a projection, when full column rank makes the coefficients unique, and how QR solves the fit stably.

  • Video 21
  • Fitting Linear Regression Models

A delivery takes longer when the route is longer and also when there are more packages to drop off. Long routes often carry more packages, so a line in distance alone mixes the two influences. Multiple linear regression puts both features into one prediction rule with a coefficient for each. This lesson fits such a rule by least squares, shows that its fitted values are a projection in the space of observations, and explains when the coefficients are unique and how software computes them reliably.

Key terms

Multiple linear regression

Definition Multiple linear regression predicts a numerical target from pp features x1,…,xpx_1, \dots, x_p with

y^=b+w1x1+⋯+wpxp.\hat{y} = b + w_1 x_1 + \dots + w_p x_p .

For nn training cases, collect the parameters in θ=(b,w1,…,wp)\boldsymbol{\theta} = (b, w_1, \dots, w_p) and build the design matrix XX from a leading column of ones, which carries the intercept, followed by one column per feature. Then XX is n×(p+1)n \times (p + 1), θ\boldsymbol{\theta} has p+1p + 1 entries, and the vector of predictions y^=Xθ\hat{\mathbf{y}} = X\boldsymbol{\theta} has nn entries. Because the ones column already supplies the intercept, no separate intercept is added. Least squares chooses θ\boldsymbol{\theta} to minimize ∥Xθ−y∥22\lVert X\boldsymbol{\theta} - \mathbf{y} \rVert_2^2, the sum of the squared residuals ri=y^i−yir_i = \hat{y}_i - y_i, which on this page are prediction minus observed as in Simple Linear Regression.

In plain words Each feature gets its own coefficient, and the prediction adds the contributions of all features to a baseline. The design matrix holds one case per row, so a single matrix product makes every prediction at once.

Example Four constructed deliveries have distance x1x_1 in kilometers, package count x2x_2 and duration yy in minutes, given by the rows (1,1,10)(1, 1, 10), (1,3,14)(1, 3, 14), (3,1,12)(3, 1, 12) and (3,3,20)(3, 3, 20). With p=2p = 2 features the design matrix is 4×34 \times 3,

X=[111113131133],y=[10141220].X = \begin{bmatrix} 1 & 1 & 1 \\ 1 & 1 & 3 \\ 1 & 3 & 1 \\ 1 & 3 & 3 \end{bmatrix}, \quad \mathbf{y} = \begin{bmatrix} 10 \\ 14 \\ 12 \\ 20 \end{bmatrix}.

The least-squares coefficients found below are θ=(4,2,3)\boldsymbol{\theta} = (4, 2, 3). For the first delivery the prediction is 4+2⋅1+3⋅1=94 + 2 \cdot 1 + 3 \cdot 1 = 9 minutes, a baseline of 4 minutes, plus 2 for its one kilometer, plus 3 for its one package.

Normal equations

Definition For a real n×kn \times k matrix XX and a target vector y\mathbf{y} in Rn\mathbb{R}^n, the normal equations are

X⊤Xθ=X⊤y.X^{\top}X\boldsymbol{\theta} = X^{\top}\mathbf{y}.

They come from the objective J(θ)=12∥Xθ−y∥22J(\boldsymbol{\theta}) = \tfrac12 \lVert X\boldsymbol{\theta} - \mathbf{y} \rVert_2^2, whose gradient is

∇J(θ)=X⊤(Xθ−y).\nabla J(\boldsymbol{\theta}) = X^{\top}(X\boldsymbol{\theta} - \mathbf{y}).

The function JJ is convex, because its Hessian X⊤XX^{\top}X is positive semidefinite, so θ\boldsymbol{\theta} minimizes JJ exactly when the gradient is zero. The least-squares solutions are therefore exactly the solutions of the normal equations, and at least one always exists. Entry jj of X⊤(Xθ−y)X^{\top}(X\boldsymbol{\theta} - \mathbf{y}) is the dot product of column jj with the residual vector, so the equations say that the residual is orthogonal to every column of XX. With an intercept column, the first equation says that the residuals add to zero.

In plain words At the best coefficients the residual has zero dot product with every column. If it had a nonzero dot product with some column, moving that column’s coefficient a little in the right direction would lower the squared error.

Example For the deliveries,

X⊤X=[4888201681620],X^{\top}X = \begin{bmatrix} 4 & 8 & 8 \\ 8 & 20 & 16 \\ 8 & 16 & 20 \end{bmatrix},X⊤y=[56120124].X^{\top}\mathbf{y} = \begin{bmatrix} 56 \\ 120 \\ 124 \end{bmatrix}.

The vector θ=(4,2,3)\boldsymbol{\theta} = (4, 2, 3) solves the equations, since 16+16+24=5616 + 16 + 24 = 56, 32+40+48=12032 + 40 + 48 = 120 and 32+32+60=12432 + 32 + 60 = 124. The predictions are 9, 15, 13 and 19 minutes, so the residuals are −1-1, 11, 11 and −1-1. They add to zero, their sum weighted by distance is −1+1+3−3=0-1 + 1 + 3 - 3 = 0, and their sum weighted by package count is −1+3+1−3=0-1 + 3 + 1 - 3 = 0. The sum of squared residuals is 4 squared minutes.

Least-squares projection

Definition The column space Col⁡X\operatorname{Col} X is the set of all vectors XθX\boldsymbol{\theta}, the prediction vectors the model can produce for the nn training cases. The least-squares fitted vector y^=Xθ^\hat{\mathbf{y}} = X\hat{\boldsymbol{\theta}} is the orthogonal projection p\mathbf{p} of y\mathbf{y} onto Col⁡X\operatorname{Col} X. For every θ\boldsymbol{\theta}, the vector Xθ−pX\boldsymbol{\theta} - \mathbf{p} lies in Col⁡X\operatorname{Col} X and p−y\mathbf{p} - \mathbf{y} is orthogonal to it, so

∥Xθ−y∥22=∥Xθ−p∥22+∥p−y∥22.\begin{aligned} \lVert X\boldsymbol{\theta} - \mathbf{y} \rVert_2^2 &= \lVert X\boldsymbol{\theta} - \mathbf{p} \rVert_2^2 \\[0.4em] &\quad + \lVert \mathbf{p} - \mathbf{y} \rVert_2^2 . \end{aligned}

Hence θ\boldsymbol{\theta} is a least-squares solution exactly when Xθ=pX\boldsymbol{\theta} = \mathbf{p}, and the smallest sum of squared residuals is ∥p−y∥22\lVert \mathbf{p} - \mathbf{y} \rVert_2^2. The fitted vector is unique even when several coefficient vectors produce it. This picture lives in observation space Rn\mathbb{R}^n, with one axis per training case, not in feature space, where the fitted model is a plane over the features.

In plain words Treat the whole column of targets as one point in a space with one axis per case. The model can reach only a flat subspace of that space, and least squares picks the point of the subspace closest to the target. The leftover arrow, the residual, meets the subspace at a right angle, and any other choice adds a second, perpendicular piece of error.

Example For the deliveries, p=(9,15,13,19)\mathbf{p} = (9, 15, 13, 19) and p−y=(−1,1,1,−1)\mathbf{p} - \mathbf{y} = (-1, 1, 1, -1). The alternative coefficients (5,2,2.5)(5, 2, 2.5) predict 9.5, 14.5, 13.5 and 18.5 minutes. Their squared error is 0.25+0.25+2.25+2.25=50.25 + 0.25 + 2.25 + 2.25 = 5, which splits as 11, the squared distance from p\mathbf{p}, plus the unavoidable 44. Since p\mathbf{p} is orthogonal to p−y\mathbf{p} - \mathbf{y}, also ∥y∥22=840\lVert \mathbf{y} \rVert_2^2 = 840 splits as ∥p∥22=836\lVert \mathbf{p} \rVert_2^2 = 836 plus 44. In feature space the same fit is the plane y^=4+2x1+3x2\hat{y} = 4 + 2x_1 + 3x_2 above the distance and count axes.

Full column rank

Definition An n×kn \times k matrix XX has full column rank when rank⁡X=k\operatorname{rank} X = k, that is, when its columns are linearly independent, so that Xv=0X\mathbf{v} = \mathbf{0} only for v=0\mathbf{v} = \mathbf{0}. This requires n≥kn \ge k, so a design with an intercept and pp features needs at least p+1p + 1 cases. The matrix X⊤XX^{\top}X is invertible if and only if XX has full column rank, because X⊤Xv=0X^{\top}X\mathbf{v} = \mathbf{0} gives ∥Xv∥22=v⊤X⊤Xv=0\lVert X\mathbf{v} \rVert_2^2 = \mathbf{v}^{\top}X^{\top}X\mathbf{v} = 0 and hence Xv=0X\mathbf{v} = \mathbf{0}. With full column rank the least-squares coefficients are unique,

θ^=(X⊤X)−1X⊤y.\hat{\boldsymbol{\theta}} = (X^{\top}X)^{-1}X^{\top}\mathbf{y}.

Without it, if θ^\hat{\boldsymbol{\theta}} is one least-squares solution, the solutions are exactly the vectors θ^+h\hat{\boldsymbol{\theta}} + \mathbf{h} with Xh=0X\mathbf{h} = \mathbf{0}. They all give the same fitted vector, so the predictions for the training cases stay unique while the coefficients do not. A feature that is constant across the cases, for example, repeats the ones column up to a factor and breaks full column rank.

In plain words Full column rank means no column can be built from the others, so each coefficient has its own direction to account for. When one column is a combination of others, the data cannot say how to split the credit between them, although the best predictions are still well defined.

Example The delivery design has rank 3 and det⁡(X⊤X)=64\det(X^{\top}X) = 64, so (4,2,3)(4, 2, 3) is the only solution. Now append a fourth column equal to twice the package count, with coefficient w3w_3. The predictions depend on the two count coefficients only through w2+2w3w_2 + 2w_3, which must equal 3. The vectors (4,2,3,0)(4, 2, 3, 0) and (4,2,1,1)(4, 2, 1, 1) both give the fitted values 9, 15, 13 and 19, the new 4×44 \times 4 matrix X⊤XX^{\top}X is singular, and the rank is still 3. NumPy’s least-squares routine returns (4,2,0.6,1.2)(4, 2, 0.6, 1.2), the solution with the smallest Euclidean norm. That choice is a convention of the solver, not a finding about deliveries. For a new delivery whose fourth feature is again twice its count, all these solutions predict the same value.

Partial effect

Definition In a fitted multiple regression, the coefficient wjw_j is the partial effect of xjx_j in the model, the change in the predicted value when xjx_j increases by one unit while every other feature in the model stays fixed. It is measured in target units per unit of xjx_j. It describes the fitted model, and it reflects a comparison the data support only when they contain cases in which xjx_j varies while the other features stay roughly the same. It is not a causal effect unless the study design or a separate causal argument justifies that reading. If another feature is computed from xjx_j, such as xj2x_j^2, the other features cannot stay fixed and wjw_j alone has no such reading.

In plain words Each coefficient says what the model adds for one more unit of its feature, with the other features in the model unchanged. When features move together in the data, that question concerns combinations the data rarely show, and the individual coefficients can become unstable even while the predictions stay sensible.

Example For θ=(4,2,3)\boldsymbol{\theta} = (4, 2, 3), one more kilometer at a fixed package count adds 2 minutes to the prediction, and one more package at a fixed distance adds 3 minutes. Deliveries 1 and 4 differ by 2 kilometers and 2 packages, and their predictions 9 and 19 differ by 2⋅2+3⋅2=102 \cdot 2 + 3 \cdot 2 = 10 minutes, a mix of both effects. In these four rows distance and package count are uncorrelated, so the slope of duration on distance alone is also 2 minutes per kilometer. When the features are correlated, the slope on one feature alone and its partial coefficient generally differ.

QR decomposition

Definition Let XX be a real n×kn \times k matrix with full column rank. Its reduced QR decomposition is

X=QR,X = QR,

where QQ is n×kn \times k with orthonormal columns, so that Q⊤Q=IkQ^{\top}Q = I_k, and RR is k×kk \times k, upper triangular and invertible. Requiring positive diagonal entries in RR makes the decomposition unique. Substituting it into the normal equations gives R⊤Rθ=R⊤Q⊤yR^{\top}R\boldsymbol{\theta} = R^{\top}Q^{\top}\mathbf{y}, and since R⊤R^{\top} is invertible the least-squares coefficients solve

Rθ^=Q⊤y,R\hat{\boldsymbol{\theta}} = Q^{\top}\mathbf{y},

a triangular system solved by back substitution, while the fitted vector is QQ⊤yQQ^{\top}\mathbf{y}. This route never forms X⊤XX^{\top}X. For full column rank the condition number κ2(X)\kappa_2(X), the ratio of the largest to the smallest singular value, satisfies κ2(X⊤X)=κ2(X)2\kappa_2(X^{\top}X) = \kappa_2(X)^2, so working through X⊤XX^{\top}X can lose up to about twice as many correct digits to rounding as working with XX directly. The singular value decomposition is another stable route. It also handles rank deficiency by treating singular values below a stated tolerance as zero, and it is the method behind NumPy’s lstsq. Neither method can create information that the columns do not contain.

In plain words QR rewrites the columns of XX as orthonormal directions together with a triangular recipe for rebuilding the original columns from them. Projecting onto orthonormal directions is easy and numerically gentle, and the triangular system is solved one coefficient at a time from the bottom up. The formula with an inverse is correct on paper, but it is not how careful software computes a fit.

Example For the delivery design, the Gram-Schmidt process applied to the three columns gives

Q=12[1−1−11−1111−1111],Q = \frac12\begin{bmatrix} 1 & -1 & -1 \\ 1 & -1 & 1 \\ 1 & 1 & -1 \\ 1 & 1 & 1 \end{bmatrix},R=[244020002],R = \begin{bmatrix} 2 & 4 & 4 \\ 0 & 2 & 0 \\ 0 & 0 & 2 \end{bmatrix},

and Q⊤y=(28,4,6)Q^{\top}\mathbf{y} = (28, 4, 6). The last row of Rθ=Q⊤yR\boldsymbol{\theta} = Q^{\top}\mathbf{y} gives 2w2=62w_2 = 6, so w2=3w_2 = 3. The middle row gives 2w1=42w_1 = 4, so w1=2w_1 = 2. The first row gives 2b+4⋅2+4⋅3=282b + 4 \cdot 2 + 4 \cdot 3 = 28, so b=4b = 4. Here κ2(X)≈9.9\kappa_2(X) \approx 9.9 and κ2(X⊤X)≈98\kappa_2(X^{\top}X) \approx 98. In NumPy both routes return the same coefficients. Its QR routine may flip the signs of some columns of QQ and rows of RR, which does not change the solution.

import numpy as np

X = np.array([[1, 1, 1], [1, 1, 3], [1, 3, 1], [1, 3, 3]], dtype=float)
y = np.array([10, 14, 12, 20], dtype=float)

Q, R = np.linalg.qr(X)                   # reduced QR, R is 3 by 3
theta_qr = np.linalg.solve(R, Q.T @ y)   # R is upper triangular
theta, _, rank, sv = np.linalg.lstsq(X, y, rcond=None)
print(theta_qr, theta, rank)             # [4. 2. 3.] [4. 2. 3.] 3

Check yourself

  1. A fitted model for delivery time in minutes is y^=5+2.5x1+3x2\hat{y} = 5 + 2.5x_1 + 3x_2, with distance x1x_1 in kilometers and package count x2x_2. Write the design-matrix row of a delivery of 6 kilometers with 4 packages and find its prediction. Then find how the prediction changes when the distance becomes 8 kilometers and the count stays at 4.
Show the answer

The row is (1,6,4)(1, 6, 4), where the leading 1 multiplies the intercept. The prediction is 5+2.5⋅6+3⋅4=5+15+12=325 + 2.5 \cdot 6 + 3 \cdot 4 = 5 + 15 + 12 = 32 minutes.

At 8 kilometers it is 5+20+12=375 + 20 + 12 = 37 minutes, an increase of 5 minutes. That is the distance coefficient times the 2-kilometer change, 2.5⋅2=52.5 \cdot 2 = 5, with the package count held fixed. It describes the model, not what would happen if a particular route were made longer.

  1. For the four deliveries on this page, a design matrix has a column of ones, the distance in kilometers, the package count and the distance in meters. Is X⊤XX^{\top}X invertible? Give two different coefficient vectors with the same fitted values. Are the fitted values unique?
Show the answer

The meters column is 1000 times the kilometers column, so the four columns are linearly dependent. The rank is 3, less than the 4 columns, and X⊤XX^{\top}X is singular.

The predictions depend on the two distance coefficients only through wkm+1000 wmw_{\text{km}} + 1000\,w_{\text{m}}, which must equal the original distance coefficient 2. So (4,2,3,0)(4, 2, 3, 0) and (4,0,3,0.002)(4, 0, 3, 0.002) both give the fitted values 9, 15, 13 and 19 minutes, and so does every vector (4,2−1000t,3,t)(4, 2 - 1000t, 3, t).

The fitted values are unique, because they are the projection of y\mathbf{y} onto the column space, which the extra column does not change. Only the split of the distance effect between the two columns is undetermined. Dropping one of the two distance columns restores full column rank.

  1. Four constructed deliveries have planned distance x1x_1 and driven distance x2x_2, in kilometers, of (1,1.1)(1, 1.1), (2,1.9)(2, 1.9), (3,2.9)(3, 2.9) and (4,4.1)(4, 4.1). In one sample the durations are 3.0, 4.8, 7.4 and 8.8 minutes, and least squares gives (b,w1,w2)=(1,3,−1)(b, w_1, w_2) = (1, 3, -1). In a second sample with the same features the durations are 3.4, 4.4, 7.0 and 9.2 minutes, each 0.4 minute away from the first, and least squares gives (1,−1,3)(1, -1, 3). Compare the two fits’ predictions for a delivery with x1=x2=3x_1 = x_2 = 3 and for one with x1=3x_1 = 3 and x2=2x_2 = 2. Why do the coefficients change so much?
Show the answer

At x1=x2=3x_1 = x_2 = 3 the fits predict 1+9−3=71 + 9 - 3 = 7 and 1−3+9=71 - 3 + 9 = 7 minutes, the same value. At x1=3x_1 = 3 and x2=2x_2 = 2 they predict 1+9−2=81 + 9 - 2 = 8 and 1−3+6=41 - 3 + 6 = 4 minutes, which differ by 4 minutes.

In these data the driven distance is always within 0.1 kilometer of the planned one, so the two columns are nearly dependent, with correlation about 0.996. Writing

w1x1+w2x2=(w1+w2) x1+w2 (x2−x1)\begin{aligned} w_1 x_1 + w_2 x_2 &= (w_1 + w_2)\,x_1 \\[0.4em] &\quad + w_2\,(x_2 - x_1) \end{aligned}

shows that the data pin down w1+w2w_1 + w_2, which is 2 in both fits, but barely constrain how it is split. Raising w2w_2 by 4 and lowering w1w_1 by 4 changes each training prediction by only 4⋅0.1=0.44 \cdot 0.1 = 0.4 minute, so a change of 0.4 minute in the durations is enough to swing each coefficient by 4.

The matrix still has full column rank, so each fit has unique coefficients, yet they are poorly determined. The partial effect of planned distance at a fixed driven distance concerns deliveries like x1=3x_1 = 3, x2=2x_2 = 2, which the data never show, so neither fit should be trusted there. A fit on planned distance alone gives the same line y^=1+2x1\hat{y} = 1 + 2x_1 for both samples.

How this lesson connects