Linear regression is where supervised learning’s whole conceptual toolkit appears for the first time: a model class, a loss, an estimator, and three different lenses that each make something visible the others hide. Most treatments pick one lens. A practitioner needs all three, because debugging a regression means knowing which lens the symptom belongs to.
The model and the loss
Data: pairs with . Model: predictions linear in the parameters,
(‘s first column is all-ones for the intercept). “Linear” constrains the parameters, not the inputs — replace the columns of with polynomials, splines or interactions and everything in this lesson survives untouched; that flexibility is exactly what the widget below exploits. The estimator is ordinary least squares (OLS):
Lens 1 — optimization: the normal equations
The objective is a convex quadratic (its Hessian is — the convexity lesson of the Optimization module), so setting the gradient to zero is sufficient:
— the normal equations. If has full column rank, exists and is unique. Two computational regimes follow:
| Regime | Method | Cost |
|---|---|---|
| small–moderate (≲ 10⁴) | solve the normal equations (Cholesky) or, better, QR on | |
| huge or streaming | gradient descent / SGD on the same objective | per pass |
The Optimization module is not a separate subject here: the GD route’s iteration count scales with , and — conditioning is squared by forming the normal equations, which is why numerical libraries prefer QR and why unstandardized features (one in , one in ) can make gradient-based fitting absurdly slow. If you did exercise 5 of the gradient-descent lesson, this is the payoff.
Lens 2 — geometry: prediction is projection
ranges over the column space of — a -dimensional plane inside . Minimizing means finding the point of that plane closest to : orthogonal projection. The fitted values are
with the hat matrix (it puts the hat on ): symmetric, idempotent (), a projection. The residual is the perpendicular component, which forces
residuals are exactly orthogonal to every column of X — mean-zero (the intercept column), and uncorrelated with every feature, by construction. This is why “I see structure in my residuals” is such a powerful diagnostic: any pattern the residuals show against a variable is structure the model could not represent, since anything representable was projected out. And counts the model’s degrees of freedom — a number that returns, fractionally, when ridge regression bends this projection in the next lesson.
The dashed green curve is the true function that generated the data; the blue curve is the least-squares fit. At degree 1–2 the model underfits (residual sticks stay long and patterned — the projection lens says the pattern is unrepresentable structure). Around degree 3–5 it tracks the truth. Push the degree toward 10–12 and watch train MSE fall while test MSE explodes — the fit contorts through the training points. You are watching the capacity axis of the bias–variance trade-off; the next lesson measures it properly. (Leave the penalty on “none” here — ridge and lasso get their own lesson.)
Lens 3 — statistics: when is OLS the right estimator?
Assume the data really are with , . Then:
- Unbiasedness: — substitute and use .
- Covariance: . Read this matrix: nearly-collinear columns make nearly singular, so coefficient variances blow up along the associated directions — the statistical face of the same ill-conditioning that slowed gradient descent. One pathology, three lenses.
- Gauss–Markov: among all linear unbiased estimators, OLS has minimal variance — it is BLUE. Note what is not assumed: normality. Gaussian errors add only the exact finite-sample distributions (-tests on coefficients) and make OLS equal to maximum likelihood, since minimizing squared error is maximizing a Gaussian log-likelihood.
The fine print is where real datasets live: heteroscedastic errors break the covariance formula (weighted least squares or robust/sandwich errors), correlated errors break it worse (time series — its own track), and squared loss’s sensitivity to outliers is a choice, inherited from the Gaussian assumption, swappable for Huber or absolute loss at the price of closed forms. And Gauss–Markov’s “best” is conditional on unbiased — the next lesson exists precisely because a little bias, bought wisely, can be a bargain.
import numpy as np
# The three computational routes to the same estimator
beta_ne, *_ = np.linalg.lstsq(X, y, rcond=None) # QR/SVD route — use this
beta_ch = np.linalg.solve(X.T @ X, X.T @ y) # normal equations (κ²!)
beta_gd = np.zeros(X.shape[1]) # the optimization route
for _ in range(2000):
beta_gd -= 1e-2 * X.T @ (X @ beta_gd - y) / len(y)
Exercises
Work these before the next lesson
- Derive the normal equations by expanding and differentiating. Where exactly does convexity enter to make the stationary point a global minimum?
Solution
Worked solutions are part of Premium — unlock all of them for £5/month →
- 4 more exercises — each with a worked solution — are part of Premium. Unlock everything for £5/month →
References
- T. Hastie, R. Tibshirani, J. Friedman, The Elements of Statistical Learning, 2nd ed., ch. 3 — the canonical treatment of all three lenses (free PDF from the authors).
- G. James et al., An Introduction to Statistical Learning, ch. 3 — the gentler companion, with labs.
- G. Strang, Linear Algebra and Learning from Data, 2019 — the projection picture, done properly.