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 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 , with the conditions for a unique solution.
- Interpret the fit as the orthogonal projection of onto the column space of , and handle rank deficiency with the pseudoinverse.
- Judge a fit with 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 training inputs as the rows of the design matrix , with a first column of ones to carry the intercept, and the targets into . From here on counts the columns of , intercept included (statistics texts often call it ). The model is
where the noise is everything about that the features do not explain. Least squares picks
which is empirical risk minimization with the squared loss over linear predictors.
The normal equations
Expand the objective, using (a scalar equals its transpose):
Differentiate with and for symmetric . The gradient is the residual vector fed back through :
Setting it to zero gives the normal equations, linear equations in unknowns:
The Hessian is positive semidefinite, since , so RSS is a convex function and every solution of the normal equations is a global minimizer. If has full column rank (, which needs ), then for every , the Hessian is positive definite, and the minimizer is unique:
With a single feature the normal equations solve by hand. Writing and ,
where is the sample correlation and the standard deviations. The second equation says the line passes through . The slope is the correlation rescaled into the units of per unit of , which is why a slope can be large while the correlation is weak, and vice versa.
Fit a least-squares line to the four points , , , . What is the slope?
Show the answer
2.2
, , and , so and . The residuals are : they sum to zero, and so does , exactly as the normal equations demand.
Geometry: least squares is a projection
Every candidate prediction is a combination of the columns of , so it lives in the column space , a subspace of of dimension . Least squares asks for the point of that subspace closest to . The closest point is the orthogonal projection: the residual must be perpendicular to every column, . That is the normal equations, and "normal" here means perpendicular.
Three consequences follow at once:
- With an intercept column, : the residuals sum to zero, and the fitted values have the same mean as .
- The residuals are uncorrelated (in the sample) with every feature and with , because they are orthogonal to the whole column space.
- Pythagoras splits the variation of around its mean into an explained and an unexplained part: , with , , .
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 (): each makes singular. The projection is still unique, because the closest point of a subspace is unique, but infinitely many produce it: add any vector of the null space of . The conventional choice is the minimum-norm solution , built from the SVD :
Nearly dependent columns are worse in practice than exactly dependent ones. 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 fits almost as well as . Ridge regression, in the Descent lesson Regularization: Ridge & Lasso, is the standard cure.
By mistake, the same feature appears twice in (two identical columns). What happens to least squares?
- No least-squares solution exists
- The coefficients are unique, and the two copies receive equal weights
- The fitted values are unique, but the coefficients are not: only the sum of the two copies' weights is determined
- 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 is unchanged and unique. Any split with the same sum gives the same predictions, so is singular and the minimizers form a line.
How good is the fit?
With an intercept in the model, the coefficient of determination
is the fraction of the variation of around its mean that the fit explains; it lies between 0 and 1 and equals the squared correlation between and . For the four points above, and , so . But never decreases when you add a column, because a larger column space contains the old projection. Pure noise features raise it too. The adjusted charges for each column, and error on held-out data is the more honest judge.
| Residual plot shows | Likely cause | What helps |
|---|---|---|
| A curved band | a nonlinearity the features miss | transformed or extra features (polynomials, splines), in the Descent lesson Basis Functions & Generalized Linear Models |
| A funnel: spread grows with | noise variance that changes with | transform (often a log), weighted least squares, or robust standard errors (Convergence lesson Inference for Linear Models) |
| A few points far from zero | outliers in | check the data; robust losses (Convergence lesson Robust Regression) |
| An isolated point far out in | high leverage | influence diagnostics such as Cook's distance (Convergence lesson The Geometry of Least Squares) |
| Runs of same-sign residuals in time order | correlated noise | time-series models, or standard errors that allow for correlation |
Scaling and centering. Measuring a feature in different units, , divides its weight by and leaves every prediction unchanged: least squares is equivariant to scaling. Centering the features makes the intercept equal to , 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
| Method | Cost | Behavior |
|---|---|---|
| Normal equations (Cholesky of ) | about flops | fastest when ; forming squares the condition number, |
| Householder QR of | about flops | backward stable; the usual default (R's lm uses a QR factorization) |
| SVD of | a few times QR | most robust; handles rank deficiency and gives (NumPy's lstsq is SVD-based) |
| Gradient descent | per step | about steps; works with streaming data and mini-batches |
| Conjugate gradients (LSQR) | per step | about steps; good for large sparse |
Gradient descent on repeats : residuals times inputs, the same "error × input" shape that every gradient in this course will have. The Hessian is with eigenvalues (the squared singular values of ). With step the error contracts by a factor per step:
assuming full column rank. A long, thin valley in the loss (large ) means slow progress, and standardizing the features is the cheapest way to round it out. The Optimization topic proves the general rates.
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) / nThree routes to the same when is well conditioned. They part ways when it is not.
Key takeaways
- Least squares minimizes . Setting the gradient to zero gives the normal equations , with unique solution when has full column rank.
- The fit is the orthogonal projection of onto the column space of , 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.
- 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 flops but square the condition number; QR and the SVD are stabler. Gradient descent costs per step and needs about 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.
A regression has more features than examples (), and has rank . Which statement is true?
- Least squares has no solution
- There is a unique solution, but it overfits
- Infinitely many weight vectors fit the training targets exactly; the pseudoinverse picks the one of minimum norm
- The normal equations still give
Show the answer
C. Infinitely many weight vectors fit the training targets exactly; the pseudoinverse picks the one of minimum norm
With rank the column space is all of , so and the residuals are zero. The null space of has dimension , so adding any null vector gives another exact fit. is the shortest of them.
For a least-squares fit that includes an intercept, which statement about the residuals always holds?
- They sum to zero and are orthogonal to every feature column
- They are normally distributed
- They are all smaller than the noise standard deviation
- Half of them are positive
Show the answer
A. They sum to zero and are orthogonal to every feature column
The normal equations say : the residual vector is orthogonal to every column, including the column of ones, so . This is algebra and holds for any data.
You add a column of pure random noise to and refit. What happens to the training ?
- It drops, because noise hurts the fit
- It stays exactly the same
- It becomes negative
- 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 : RSS cannot increase and cannot decrease. A random column usually picks up a little noise by chance, so creeps up. That is why adjusted or held-out error is used to compare models of different sizes.
You solve a regression with examples and features by the normal equations. Which step dominates the running time?
- Solving the system
- Forming , about operations
- Computing
- Inverting
Show the answer
B. Forming , about operations
Forming costs about flops; the Cholesky solve costs about . For tall data the cost is dominated by passing over the data, which is why sketching and stochastic methods target that term.
Gradient descent on a least-squares loss zigzags and then crawls along a long, narrow valley. Which change helps most directly?
- A much larger learning rate
- More training examples drawn the same way
- Standardizing the features (centering and scaling each one)
- 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 , and the number of steps grows with its condition number. Centering and scaling the features makes much closer to a multiple of the identity, which rounds the valley out.
Go deeper
- The Geometry of Least Squares · Projections, the hat matrix, leverage and numerically stable solvers.
- Inference for Linear Models · Gauss–Markov, standard errors, confidence intervals and their assumptions.
- Robust Regression · Outliers, Huber loss, quantile regression and breakdown points.
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.