Simple Algorithm
Machine Learning · Descent · 24 min

Linear Regression & Least Squares

Fitting lines, the normal equations and the geometry of projection.

Least squares has a closed-form answer, a geometric meaning and a computational cost, and each of the three explains something the other two hide. This lesson derives the normal equations, shows that every least-squares fit is an orthogonal projection, reads a fit through R2R^2 and its residuals, and weighs exact solvers against gradient descent.

What you’ll learn

  • Write linear regression in matrix form and derive the normal equations X⊤Xw^=X⊤yX^\top X\hat{\mathbf w} = X^\top\mathbf y, with the conditions for a unique solution.
  • Interpret the fit as the orthogonal projection of y\mathbf y onto the column space of XX, and handle rank deficiency with the pseudoinverse.
  • Judge a fit with R2R^2 and residual plots, and explain how centering, scaling and collinearity change the coefficients.
  • Compare the cost and numerical behavior of the normal equations, QR, the SVD and gradient descent.

The model in matrix form

Stack the nn training inputs as the rows of the design matrix XX, with a first column of ones to carry the intercept, and the targets into y∈Rn\mathbf y \in \R^n. From here on dd counts the columns of XX, intercept included (statistics texts often call it pp). The model is

y=Xw+ε,\mathbf y = X\mathbf w + \boldsymbol\varepsilon,

where the noise ε\boldsymbol\varepsilon is everything about y\mathbf y that the features do not explain. Least squares picks

w^∈arg min⁡w∈Rd ∥y−Xw∥2=arg min⁡w∈Rd ∑i=1n(yi−xi⊤w)2,\hat{\mathbf w} \in \argmin_{\mathbf w \in \R^d}\ \norm{\mathbf y - X\mathbf w}^2 = \argmin_{\mathbf w \in \R^d}\ \sum_{i=1}^n \big(y_i - \mathbf x_i^\top \mathbf w\big)^2,

which is empirical risk minimization with the squared loss over linear predictors.

X=(1x11⋯x1,d−11x21⋯x2,d−1⋮⋮⋮1xn1⋯xn,d−1)∈Rn×d,w=(bw1⋮wd−1)X = \begin{pmatrix} 1 & x_{11} & \cdots & x_{1,d-1} \\ 1 & x_{21} & \cdots & x_{2,d-1} \\ \vdots & \vdots & & \vdots \\ 1 & x_{n1} & \cdots & x_{n,d-1} \end{pmatrix}\in\R^{n\times d},\qquad \mathbf w = \begin{pmatrix} b \\ w_1 \\ \vdots \\ w_{d-1}\end{pmatrix}
Row ii is example ii; column jj is one feature across all examples. The column of ones turns the intercept bb into an ordinary weight.

The normal equations

DerivationMinimizing the residual sum of squares
  1. RSS(w)=∥y−Xw∥2=y⊤y−2 w⊤X⊤y+w⊤X⊤X w\mathrm{RSS}(\mathbf w) = \norm{\mathbf y - X\mathbf w}^2 = \mathbf y^\top\mathbf y - 2\,\mathbf w^\top X^\top\mathbf y + \mathbf w^\top X^\top X\,\mathbf w

    Expand the objective, using w⊤X⊤y=y⊤Xw\mathbf w^\top X^\top\mathbf y = \mathbf y^\top X\mathbf w (a scalar equals its transpose):

  2. ∇ RSS(w)=−2X⊤y+2X⊤X w=−2X⊤(y−Xw)\nabla\,\mathrm{RSS}(\mathbf w) = -2X^\top\mathbf y + 2X^\top X\,\mathbf w = -2X^\top(\mathbf y - X\mathbf w)

    Differentiate with ∇w(a⊤w)=a\nabla_{\mathbf w}(\mathbf a^\top\mathbf w) = \mathbf a and ∇w(w⊤Aw)=2Aw\nabla_{\mathbf w}(\mathbf w^\top A\mathbf w) = 2A\mathbf w for symmetric AA. The gradient is the residual vector fed back through X⊤X^\top:

  3. X⊤X w^=X⊤yX^\top X\,\hat{\mathbf w} = X^\top\mathbf y

    Setting it to zero gives the normal equations, dd linear equations in dd unknowns:

  4. w^=(X⊤X)−1X⊤y\hat{\mathbf w} = (X^\top X)^{-1}X^\top\mathbf y

    The Hessian 2X⊤X2X^\top X is positive semidefinite, since v⊤X⊤Xv=∥Xv∥2≥0\mathbf v^\top X^\top X\mathbf v = \norm{X\mathbf v}^2 \ge 0, so RSS is a convex function and every solution of the normal equations is a global minimizer. If XX has full column rank (rank⁡X=d\rank X = d, which needs n≥dn \ge d), then Xv≠0X\mathbf v \ne \mathbf 0 for every v≠0\mathbf v \ne \mathbf 0, the Hessian is positive definite, and the minimizer is unique:

With a single feature the normal equations solve by hand. Writing Sxy=∑i(xi−xˉ)(yi−yˉ)S_{xy} = \sum_i (x_i - \bar x)(y_i - \bar y) and Sxx=∑i(xi−xˉ)2S_{xx} = \sum_i (x_i - \bar x)^2,

w^1=SxySxx=rxy sysx,b^=yˉ−w^1xˉ,\hat w_1 = \frac{S_{xy}}{S_{xx}} = r_{xy}\,\frac{s_y}{s_x}, \qquad \hat b = \bar y - \hat w_1 \bar x,

where rxyr_{xy} is the sample correlation and sx,sys_x, s_y the standard deviations. The second equation says the line passes through (xˉ,yˉ)(\bar x, \bar y). The slope is the correlation rescaled into the units of yy per unit of xx, which is why a slope can be large while the correlation is weak, and vice versa.

Predict before you look

Fit a least-squares line to the four points (0,1)(0, 1), (1,3)(1, 3), (2,4)(2, 4), (3,8)(3, 8). What is the slope?

Show the answer

2.2

xˉ=1.5\bar x = 1.5, yˉ=4\bar y = 4, Sxy=(−1.5)(−3)+(−0.5)(−1)+(0.5)(0)+(1.5)(4)=11S_{xy} = (-1.5)(-3) + (-0.5)(-1) + (0.5)(0) + (1.5)(4) = 11 and Sxx=2.25+0.25+0.25+2.25=5S_{xx} = 2.25 + 0.25 + 0.25 + 2.25 = 5, so w^1=11/5=2.2\hat w_1 = 11/5 = 2.2 and b^=4−2.2×1.5=0.7\hat b = 4 - 2.2 \times 1.5 = 0.7. The residuals are 0.3,0.1,−1.1,0.70.3, 0.1, -1.1, 0.7: they sum to zero, and so does ∑ixiei=0.1−2.2+2.1\sum_i x_i e_i = 0.1 - 2.2 + 2.1, exactly as the normal equations demand.

Geometry: least squares is a projection

Every candidate prediction XwX\mathbf w is a combination of the columns of XX, so it lives in the column space col(X)\mathrm{col}(X), a subspace of Rn\R^n of dimension rank⁡X\rank X. Least squares asks for the point of that subspace closest to y\mathbf y. The closest point is the orthogonal projection: the residual e=y−Xw^\mathbf e = \mathbf y - X\hat{\mathbf w} must be perpendicular to every column, X⊤e=0X^\top\mathbf e = \mathbf 0. That is the normal equations, and "normal" here means perpendicular.

y^=Xw^=X(X⊤X)−1X⊤⏟H y,e=(I−H) y ⊥ col(X)\hat{\mathbf y} = X\hat{\mathbf w} = \underbrace{X(X^\top X)^{-1}X^\top}_{H}\,\mathbf y, \qquad \mathbf e = (I - H)\,\mathbf y \ \perp\ \mathrm{col}(X)
HH is the hat matrix: it puts the hat on y\mathbf y. It is the projection onto col(X)\mathrm{col}(X), so projecting twice changes nothing, H2=HH^2 = H. The Convergence lesson on the geometry of least squares takes it apart.

Three consequences follow at once:

  • With an intercept column, 1⊤e=0\mathbf 1^\top\mathbf e = 0: the residuals sum to zero, and the fitted values have the same mean as y\mathbf y.
  • The residuals are uncorrelated (in the sample) with every feature and with y^\hat{\mathbf y}, because they are orthogonal to the whole column space.
  • Pythagoras splits the variation of y\mathbf y around its mean into an explained and an unexplained part: TSS=ESS+RSS\mathrm{TSS} = \mathrm{ESS} + \mathrm{RSS}, with TSS=∥y−yˉ1∥2\mathrm{TSS} = \norm{\mathbf y - \bar y\mathbf 1}^2, ESS=∥y^−yˉ1∥2\mathrm{ESS} = \norm{\hat{\mathbf y} - \bar y\mathbf 1}^2, RSS=∥e∥2\mathrm{RSS} = \norm{\mathbf e}^2.

When the columns are dependent. A feature recorded twice in different units, one-hot indicators for every category alongside the intercept (the "dummy-variable trap"), or more features than examples (d>nd > n): each makes X⊤XX^\top X singular. The projection y^\hat{\mathbf y} is still unique, because the closest point of a subspace is unique, but infinitely many w\mathbf w produce it: add any vector of the null space of XX. The conventional choice is the minimum-norm solution w^=X+y\hat{\mathbf w} = X^+\mathbf y, built from the SVD X=UΣV⊤X = U\Sigma V^\top:

X+=∑j: σj>01σj vjuj⊤.X^+ = \sum_{j:\ \sigma_j > 0} \frac{1}{\sigma_j}\,\mathbf v_j\mathbf u_j^\top.

Nearly dependent columns are worse in practice than exactly dependent ones. X⊤XX^\top X is then invertible but ill-conditioned (its condition number is huge), and the coefficients become extremely variable: two strongly correlated features can trade weight, so that w1=100, w2=−98w_1 = 100,\ w_2 = -98 fits almost as well as w1=w2=1w_1 = w_2 = 1. Ridge regression, in the Descent lesson Regularization: Ridge & Lasso, is the standard cure.

Check your understanding

By mistake, the same feature appears twice in XX (two identical columns). What happens to least squares?

  1. No least-squares solution exists
  2. The coefficients are unique, and the two copies receive equal weights
  3. The fitted values are unique, but the coefficients are not: only the sum of the two copies' weights is determined
  4. The fit becomes worse than with a single copy of the feature
Show the answer

C. The fitted values are unique, but the coefficients are not: only the sum of the two copies' weights is determined

The column space is the same as with one copy, so the projection y^\hat{\mathbf y} is unchanged and unique. Any split (wa,wb)(w_a, w_b) with the same sum wa+wbw_a + w_b gives the same predictions, so X⊤XX^\top X is singular and the minimizers form a line.

How good is the fit?

With an intercept in the model, the coefficient of determination

R2=1−RSSTSS=ESSTSSR^2 = 1 - \frac{\mathrm{RSS}}{\mathrm{TSS}} = \frac{\mathrm{ESS}}{\mathrm{TSS}}

is the fraction of the variation of yy around its mean that the fit explains; it lies between 0 and 1 and equals the squared correlation between y\mathbf y and y^\hat{\mathbf y}. For the four points above, RSS=1.8\mathrm{RSS} = 1.8 and TSS=26\mathrm{TSS} = 26, so R2≈0.93R^2 \approx 0.93. But R2R^2 never decreases when you add a column, because a larger column space contains the old projection. Pure noise features raise it too. The adjusted R2=1−RSS/(n−d)TSS/(n−1)R^2 = 1 - \frac{\mathrm{RSS}/(n - d)}{\mathrm{TSS}/(n-1)} charges for each column, and error on held-out data is the more honest judge.

Residual plot showsLikely causeWhat helps
A curved banda nonlinearity the features misstransformed or extra features (polynomials, splines), in the Descent lesson Basis Functions & Generalized Linear Models
A funnel: spread grows with y^\hat ynoise variance that changes with x\mathbf xtransform yy (often a log), weighted least squares, or robust standard errors (Convergence lesson Inference for Linear Models)
A few points far from zerooutliers in yycheck the data; robust losses (Convergence lesson Robust Regression)
An isolated point far out in x\mathbf xhigh leverageinfluence diagnostics such as Cook's distance (Convergence lesson The Geometry of Least Squares)
Runs of same-sign residuals in time ordercorrelated noisetime-series models, or standard errors that allow for correlation
Plot the residuals eie_i against the fitted values y^i\hat y_i and against each feature. A good fit leaves a shapeless horizontal band.

Scaling and centering. Measuring a feature in different units, xj→c xjx_j \to c\,x_j, divides its weight by cc and leaves every prediction unchanged: least squares is equivariant to scaling. Centering the features makes the intercept equal to yˉ\bar y, the prediction at the average input. Neither changes the fit. Penalized fits, however, are not scale-equivariant, and the speed of gradient descent depends on the scales, which is why features are usually standardized first.

Categorical features enter through one-hot encoding, with one category dropped as the baseline when the model has an intercept; each remaining weight is then a difference from the baseline.

Computing the solution

MethodCostBehavior
Normal equations (Cholesky of X⊤XX^\top X)about nd2+d3/3nd^2 + d^3/3 flopsfastest when n≫dn \gg d; forming X⊤XX^\top X squares the condition number, κ(X⊤X)=κ(X)2\kappa(X^\top X) = \kappa(X)^2
Householder QR of XXabout 2nd2−23d32nd^2 - \tfrac23 d^3 flopsbackward stable; the usual default (R's lm uses a QR factorization)
SVD of XXa few times QRmost robust; handles rank deficiency and gives X+X^+ (NumPy's lstsq is SVD-based)
Gradient descentO(nd)\order{nd} per stepabout κ(X⊤X)log⁡(1/ϵ)\kappa(X^\top X)\log(1/\epsilon) steps; works with streaming data and mini-batches
Conjugate gradients (LSQR)O(nd)\order{nd} per stepabout κ(X)log⁡(1/ϵ)\kappa(X)\log(1/\epsilon) steps; good for large sparse XX
Flop counts from Golub & Van Loan (2013, §5.3). With n=106n = 10^6 and d=100d = 100, forming X⊤XX^\top X costs about 101010^{10} flops and the Cholesky solve only about 3×1053\times10^5: for tall data the cost is dominated by touching the data.

Gradient descent on f(w)=12∥y−Xw∥2f(\mathbf w) = \tfrac12\norm{\mathbf y - X\mathbf w}^2 repeats w←w+η X⊤(y−Xw)\mathbf w \leftarrow \mathbf w + \eta\, X^\top(\mathbf y - X\mathbf w): residuals times inputs, the same "error × input" shape that every gradient in this course will have. The Hessian is X⊤XX^\top X with eigenvalues σd2≤⋯≤σ12\sigma_d^2 \le \dots \le \sigma_1^2 (the squared singular values of XX). With step η=1/σ12\eta = 1/\sigma_1^2 the error contracts by a factor 1−σd2/σ121 - \sigma_d^2/\sigma_1^2 per step:

∥wt−w^∥≤(1−1κ)t∥w0−w^∥,κ=σ12σd2=κ(X)2,\norm{\mathbf w_t - \hat{\mathbf w}} \le \Big(1 - \frac{1}{\kappa}\Big)^t\norm{\mathbf w_0 - \hat{\mathbf w}}, \qquad \kappa = \frac{\sigma_1^2}{\sigma_d^2} = \kappa(X)^2,

assuming full column rank. A long, thin valley in the loss (large κ\kappa) means slow progress, and standardizing the features is the cheapest way to round it out. The Optimization topic proves the general rates.

python
import numpy as np

X1 = np.column_stack([np.ones(len(X)), X])        # add the intercept column
w_svd, *_ = np.linalg.lstsq(X1, y, rcond=None)    # SVD-based; copes with rank deficiency
w_ne = np.linalg.solve(X1.T @ X1, X1.T @ y)       # normal equations: fast, less stable

# gradient descent on (1/2n)||y - Xw||^2 with step 1/L
n = len(y)
L = np.linalg.norm(X1, 2) ** 2 / n                # largest eigenvalue of X^T X / n
w = np.zeros(X1.shape[1])
for t in range(5000):
    w -= (1 / L) * X1.T @ (X1 @ w - y) / n

Three routes to the same w^\hat{\mathbf w} when XX is well conditioned. They part ways when it is not.

Key takeaways

  • Least squares minimizes ∥y−Xw∥2\norm{\mathbf y - X\mathbf w}^2. Setting the gradient −2X⊤(y−Xw)-2X^\top(\mathbf y - X\mathbf w) to zero gives the normal equations X⊤Xw^=X⊤yX^\top X\hat{\mathbf w} = X^\top\mathbf y, with unique solution (X⊤X)−1X⊤y(X^\top X)^{-1}X^\top\mathbf y when XX has full column rank.
  • The fit y^=Hy\hat{\mathbf y} = H\mathbf y is the orthogonal projection of y\mathbf y onto the column space of XX, and the residual is perpendicular to every column. The projection is always unique; when the coefficients are not, the pseudoinverse picks the minimum-norm ones.
  • R2=1−RSS/TSSR^2 = 1 - \mathrm{RSS}/\mathrm{TSS} measures in-sample fit and never falls as columns are added. Residual plots expose curvature, changing variance, outliers and leverage, and coefficients describe associations, not causes.
  • The normal equations cost about nd2+d3/3nd^2 + d^3/3 flops but square the condition number; QR and the SVD are stabler. Gradient descent costs O(nd)\order{nd} per step and needs about κ(X⊤X)log⁡(1/ϵ)\kappa(X^\top X)\log(1/\epsilon) steps, so scaling the features matters.

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 more features than examples (d>nd > n), and XX has rank nn. Which statement is true?

  1. Least squares has no solution
  2. There is a unique solution, but it overfits
  3. Infinitely many weight vectors fit the training targets exactly; the pseudoinverse picks the one of minimum norm
  4. The normal equations still give w^=(X⊤X)−1X⊤y\hat{\mathbf w} = (X^\top X)^{-1}X^\top\mathbf y
Show the answer

C. Infinitely many weight vectors fit the training targets exactly; the pseudoinverse picks the one of minimum norm

With rank nn the column space is all of Rn\R^n, so y^=y\hat{\mathbf y} = \mathbf y and the residuals are zero. The null space of XX has dimension d−n>0d - n > 0, so adding any null vector gives another exact fit. X+yX^+\mathbf y is the shortest of them.

Question 2

For a least-squares fit that includes an intercept, which statement about the residuals always holds?

  1. They sum to zero and are orthogonal to every feature column
  2. They are normally distributed
  3. They are all smaller than the noise standard deviation
  4. Half of them are positive
Show the answer

A. They sum to zero and are orthogonal to every feature column

The normal equations say X⊤e=0X^\top\mathbf e = \mathbf 0: the residual vector is orthogonal to every column, including the column of ones, so ∑iei=0\sum_i e_i = 0. This is algebra and holds for any data.

Question 3

You add a column of pure random noise to XX and refit. What happens to the training R2R^2?

  1. It drops, because noise hurts the fit
  2. It stays exactly the same
  3. It becomes negative
  4. It rises slightly or stays the same; it can never fall
Show the answer

D. It rises slightly or stays the same; it can never fall

The new column space contains the old one, so the projection can only get closer to y\mathbf y: RSS cannot increase and R2R^2 cannot decrease. A random column usually picks up a little noise by chance, so R2R^2 creeps up. That is why adjusted R2R^2 or held-out error is used to compare models of different sizes.

Question 4

You solve a regression with n=106n = 10^6 examples and d=100d = 100 features by the normal equations. Which step dominates the running time?

  1. Solving the 100×100100 \times 100 system
  2. Forming X⊤XX^\top X, about nd2=1010n d^2 = 10^{10} operations
  3. Computing yˉ\bar y
  4. Inverting XX
Show the answer

B. Forming X⊤XX^\top X, about nd2=1010n d^2 = 10^{10} operations

Forming X⊤XX^\top X costs about nd2=1010nd^2 = 10^{10} flops; the Cholesky solve costs about d3/3≈3×105d^3/3 \approx 3\times10^5. For tall data the cost is dominated by passing over the data, which is why sketching and stochastic methods target that term.

Question 5

Gradient descent on a least-squares loss zigzags and then crawls along a long, narrow valley. Which change helps most directly?

  1. A much larger learning rate
  2. More training examples drawn the same way
  3. Standardizing the features (centering and scaling each one)
  4. Starting from a random point instead of zero
Show the answer

C. Standardizing the features (centering and scaling each one)

The valley's shape is the Hessian X⊤XX^\top X, and the number of steps grows with its condition number. Centering and scaling the features makes X⊤XX^\top X much closer to a multiple of the identity, which rounds the valley out.

Go deeper

Further reading

  • T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (Springer, 2009), chapter 3.
  • G. A. F. Seber & A. J. Lee, Linear Regression Analysis, 2nd ed. (Wiley, 2003).
  • G. H. Golub & C. F. Van Loan, Matrix Computations, 4th ed. (Johns Hopkins University Press, 2013), chapter 5.
  • C. M. Bishop, Pattern Recognition and Machine Learning (Springer, 2006), §3.1.