Linear Regression
The first real algorithm — and the one every later model is benchmarked against. Fit a line in closed form, buy curves with basis functions, read the geometry as a projection, and meet regularisation and the Bayesian view.
01 · Motivation
Why does this matter?
Pick a number you wish you could predict. House price next month. Tomorrow’s temperature. A patient’s blood-pressure response to a new dose. These are all regression problems: the target is a real number on a continuous scale, and you want to estimate it from a handful of measured inputs.
Out of the whole zoo of regression models, the linear one — a weighted sum of the inputs plus an offset — is the first thing a working data scientist tries and the model every later technique is benchmarked against. Three reasons earn it that status:
It's solvable on paper
Linear regression has a one-formula, closed-form answer — no iterative optimisation, no random seeds, just . That clarity makes it the perfect lab specimen.
It teaches the whole toolbox
Loss functions, gradient descent, the bias–variance trade-off, regularisation, MAP and MLE, the geometry of projection — every one of these shows up here in its cleanest form. Master it and you’ve touched 70% of supervised learning.
It's a real workhorse
Many physical, biological and economic relationships are locally linear. And when they aren’t, one small twist — basis functions — extends the model to arbitrary curves while keeping solvability.
The reason linear models keep winning
Across decades of empirical studies, linear models with thoughtful features beat fancier alternatives roughly half the time. They train in milliseconds, extrapolate predictably, every coefficient has a meaning, and they fail loudly when their assumptions break. Reach for the simple thing first; reach for the deep network only when you can show the simple thing is not enough.
This chapter is the gateway to every supervised model that follows. Logistic regression (Ch. 3) is linear regression with a sigmoid. SVMs (Ch. 7) swap the loss. Kernel methods (Ch. 6) do it in an infinite feature space. Neural networks stack linear-plus-non-linearity. The line you fit here is the first vertebra of a long spine.
02 · Intuition
The idea in plain language
Imagine a cloud of points on a 2-D plot. The horizontal axis is something you can measure cheaply — say, the size of a flat in square metres. The vertical axis is something you’d like to predict — its sale price. You squint, notice the cloud slopes up to the right, and reach for a ruler. Linear regression is the maths of choosing where to put the ruler.
Two knobs control any straight line:
- The intercept — where the line crosses the vertical axis. Lift it, the whole line shifts up.
- The slope — how steeply it climbs as you move right. Steepen it, the line rotates.
Two unknowns, infinitely many candidate lines. The job is to pick the one line that “agrees with the cloud” the most — so we must be precise about what disagreement means.
Why we measure error vertically
For each training point, look straight up or down to the line. The length of that vertical segment is the residual — what the model got wrong, in the units of the output. We square each residual before summing, for three reasons that compound:
Sign cancellation
A point 5 above the line shouldn’t cancel one 5 below. Squaring forces every miss to count as positive.
Big mistakes matter more
Squaring hurts four times as much for a residual of 2 as for one of 1 — the model is forced to pay attention to large errors.
Differentiability
Squared error is smooth everywhere. Set the gradient to zero, solve a linear system, done. (Absolute error has a kink at zero — Ch. 7.)
A useful image: the shortest vertical ropes
Imagine an elastic rope from every training point straight down (or up) to your candidate line. The shorter the ropes on average, the better the fit. Least squares says: pick the line so the sum of squared rope lengths is as small as possible. That phrase is the whole pedagogy of this chapter.
”Linear” — but linear in what?
Here is the subtlety that catches every student once. A model can be linear in the inputs, in the parameters, or both. In machine learning, “linear regression” means linear in the parameters. Linear in the inputs is a bonus, not a requirement.
Linear in w → counts as linear regression
The output is a weighted sum of known functions of ; the weights enter linearly and we solve with a single matrix formula.
Non-linear in w → NOT linear regression
Weights appear inside non-linear functions or multiplied together. No closed form; you must optimise iteratively (and may find only local minima).
- (this is Ch. 3)
Once you accept this distinction, the world of “linear” regression becomes surprisingly large. Polynomials, splines, radial-basis networks, Fourier expansions — all of them are linear regression with cleverer features. We formalise this with basis functions next.
03 · Formalism
Definitions and equations
Now we anchor the intuition in notation. Every symbol below re-appears in chapters 3, 6, and 7 — invest the minute to make them stick.
- x
- an input, a column vector in . For an intercept we tack a constant 1 on top: the augmented input .
- t
- the target, a real number. The training set stacks of them in .
- w
- the parameter vector — one weight per feature. is the offset, the rest are slopes.
- y
- the prediction the model emits for input .
- ε
- the residual on example : .
- L
- the loss — one number scoring how bad is on the training set.
The linear model
Plain linear regression writes the prediction as a weighted sum of the input coordinates plus an offset:
With the augmented input the offset folds into the dot product — neat for the maths, easy to forget when you write code.
Buying non-linearity with basis functions
Replace the raw coordinates with hand-chosen transformations — features that may be wildly non-linear in but are still fed into a linear combination:
Convention: so is still the offset. is the number of basis functions (including the constant); it controls the size of the hypothesis space.
Three families show up over and over again:
| Family | Character | |
|---|---|---|
| Polynomial | Each basis adds a degree. Cheap and powerful but global — a wiggle near changes the fit near . Numerically fragile at high degree. | |
| Gaussian | Bumps centred at . Local — each weight affects only its neighbourhood. Width sets smoothness; needs feature scaling. | |
| Sigmoidal | Smooth steps. Useful for threshold/saturation behaviour; the building block of logistic regression and neural nets. |
The basis-function move, in one sentence
Choose features wisely and a linear model can fit almost anything. The heavy lifting moves from “what kind of curve?” to “what kind of ?”. The closed-form solution below treats every basis identically — once is built, the maths is the same.
The design matrix
Stack one row per training example, one column per basis function. This is the design matrix, the object you’ll see in every derivation from now on:
All predictions in one shot: . The first column is all ones (because ), encoding the offset.
The squared-error loss
Pack the residuals into a vector ; the loss is the squared -norm of that vector:
The is cosmetic — it cancels when you differentiate. is also the residual sum of squares (RSS); dividing by gives the mean squared error (MSE).
Setting the gradient to zero gives the normal equations and the closed-form OLS estimator:
The Hessian is positive semi-definite, so this critical point is a global minimum — unique when has full column rank.
Why squared error? The probabilistic answer
Beyond the three intuitive reasons in §2, the squared loss has a deep justification. Suppose the target is a deterministic function plus Gaussian noise of fixed variance:
Then is itself Gaussian, and with i.i.d. examples the log-likelihood is
MLE = least squares, exactly
The first term has no in it; the second is times the RSS. So maximising the log-likelihood over is identical to minimising the RSS. Squared error is the negative log-likelihood of a Gaussian noise model, up to constants. When you fit a line by minimising vertical squared distances, you are assuming the noise is symmetric, Gaussian, and the same size everywhere.
Optional depth The unbiased noise-variance estimate, and the Minkowski loss family
Differentiating the log-likelihood with respect to gives the MLE of the noise variance as the mean squared residual. The bias-corrected version divides by instead of , because degrees of freedom were “used up” fitting the weights:
If the model fits perfectly and is undefined — a structural warning, not a bug.
Squared error is one member of a family . Different encode different noise models:
| Loss | Optimal predictor at | Implicit noise | |
|---|---|---|---|
| 2 | squared error | conditional mean | Gaussian |
| 1 | absolute error | conditional median | Laplace |
| 0/1 hit | conditional mode | — |
Use when outliers are real and you don’t want a few extreme points dragging the fit. The rest of this chapter sticks with .
When the closed form is too expensive: gradient descent
The OLS formula inverts an matrix at cost . For thousands of features, or streaming data that never fits in memory, the fallback is iterative gradient descent:
is the learning rate. Too small and convergence crawls; too large and the iterates overshoot and diverge. Hands-on lab #2 lets you feel both failure modes.
Batch gradient descent uses the full sum over samples each step (). Stochastic GD (SGD) uses one sample (or a mini-batch) per step (, works online) at the price of a jittery path. SGD converges if the learning-rate schedule satisfies the Robbins–Monro conditions and — large enough to travel anywhere, shrinking fast enough that the noise settles. For the convex quadratic loss of linear regression, gradient descent reaches the same the closed form gives: a different route to the same answer, and the route every later model is forced to take.
04 · Worked example
Closed-form OLS on four points, by hand
Time to make every symbol concrete. We fit a straight line to four points with the closed-form formula, doing the matrix arithmetic step-by-step. This is the derivation the exam asks you to reproduce.
1 · The dataset
Four flat sizes (tens of m²) and their measured rents (hundreds of €):
| 1 | 1 | 2 |
| 2 | 2 | 3 |
| 3 | 3 | 5 |
| 4 | 4 | 6 |
We model rent as a line , with the simplest basis .
2 · Build the design matrix and target vector
First column is the ones for the offset; second column is the values themselves.
3 · Run the normal-equation pipeline
Compute — a of column dot-products — and :
Invert the — determinant :
Multiply through:
So , , and the best-fit line is .
4 · Sanity-check the residuals
Plug the four inputs back in and read the residuals:
| 1 | 2 | 1.9 | |
| 2 | 3 | 3.3 | |
| 3 | 5 | 4.7 | |
| 4 | 6 | 6.1 |
Two checks pop out for free, both worth memorising:
- The residuals sum to zero: . Whenever the model has an intercept, this is automatic.
- The residuals are uncorrelated with each feature: . This is exactly the optimality condition .
The total loss is .
Map the example back onto the formalism
- training samples; basis functions ( and ).
- , , .
- Closed form: .
- Residual identities and are the optimality conditions, written out.
05 · Generalization
Underfitting, overfitting, and why training fit isn’t enough
We have a closed form that minimises RSS on the training data. The temptation is to declare victory and pick whatever hits the training points hardest. That temptation is the single biggest trap in supervised learning, and it shows up first and clearest in linear regression.
Fit polynomials of growing degree to data from a smooth curve plus noise:
- (a line). Too rigid to capture the curve — both training and unseen error are large. Underfitting: high bias.
- (a cubic). Flexible enough to bend, simple enough not to chase noise. Both errors drop.
- on 10 points. Passes through every training point, training RSS — but it wiggles wildly between points and predicts garbage off-training. Overfitting: it memorised the noise.
Training error tells you only how well the model learned what it has already seen. To estimate performance on the next input, measure error on a held-out test set. Test error follows a characteristic U-shape: high bias on the left, high variance on the right, the sweet spot in the middle.
A tell-tale fingerprint of overfitting
When linear regression with too many basis functions overfits, the fitted weights become enormous and opposite-signed, so big positive and negative contributions cancel at the training points and explode between them. Bishop’s classic degree-9 fit to 10 sinusoidal points produces coefficients of order . If you ever see weights orders of magnitude larger than your data, you have an overfitting problem — and ridge regression is the first thing to try.
The natural response — penalise large weights so the optimiser prefers smoother solutions — is exactly regularisation, and it produces the next two estimators we study (ridge and lasso). You can watch all of this happen in the hands-on labs below.
06 · Visual explanation
The geometry of least squares
The formulas hide a story that becomes obvious once you draw it.
The prediction as a projection
Lift your eyes from the scatter plot. The target values stack into a single vector in — one dimension per data point. Each column of is also an -dimensional vector; together the columns span an -dimensional subspace . Every prediction the model can produce lives in , no matter how you choose .
With hovering off the plane, the closest reachable point is the orthogonal projection . The residual sticks out perpendicular to — exactly the condition we got by setting the gradient to zero. The matrix that performs the projection is the hat matrix , with — symmetric, idempotent, and its trace equals the effective number of fitted parameters.
Two pictures, same maths
The scatter-plot view (“vertical residuals, sum of squares”) and the subspace view (“orthogonal projection in ”) are literally the same calculation. The first lives in input space and is friendly; the second lives in sample space and is profound — it generalises immediately to ridge, kernel methods, and the Gauss–Markov theorem.
Ridge vs lasso — the constraint geometry
Regularised least squares is “minimise while the weight vector stays inside a small region of parameter space.” For ridge that region is a ball; for lasso, a diamond. The shape decides the answer.
The elliptical contours are the loss — each ellipse is “all with the same training error”. The regularised optimum is where the smallest ellipse first touches the constraint region. Ridge’s smooth ball is usually touched at a point with all components non-zero, simply shrunk. The lasso diamond has corners; the ellipse usually touches at a corner, sending some components to exactly zero — which is why lasso performs variable selection and ridge does not. In formulas the two regularisers differ by one exponent:
As the constraint shrinks (higher ), predictions become more biased but less sensitive to the particular training sample (lower variance) — the bias–variance trade-off, seen here in its cleanest setting and the central story of Ch. 4.
07 · The Bayesian view
Treating the weights as a probability distribution
Everything so far produced a single best vector . The Bayesian view refuses to commit to one answer: it carries an entire distribution over the weights — narrow when the data are informative, wide when they are not — and uses it for both prediction and honest uncertainty.
Before seeing data we encode beliefs about plausible weights as a prior . After observing , Bayes’ rule gives the posterior:
For Gaussian noise the likelihood is Gaussian in ; choose a Gaussian prior and the posterior is again Gaussian (the prior is conjugate):
Read as “total information = prior information + data information”. The posterior mean is a precision-weighted blend of prior mean and data estimate — and the posterior can serve as the prior for the next batch, so Bayesian updating is naturally online.
Connection to ridge regression
The mode of a Gaussian is its mean, so the MAP estimate is . Set a zero-mean isotropic prior , and it simplifies to
Compare with ridge: identical, with . Ridge regression is MAP estimation under a Gaussian prior on the weights. A tight prior means strong regularisation; a vague prior () recovers OLS.
Predictive distribution: prediction with error bars
For a new input , instead of plugging in one we integrate over the whole posterior. The result is again Gaussian:
Two sources of uncertainty, cleanly separated. The first never disappears — even a perfect model cannot predict pure noise. The second shrinks toward zero as data accumulate. Predictions far from the training inputs get wider error bars, exactly the behaviour you want.
Why care about the Bayesian view?
Three reasons. It gives a principled, automatic way to regularise (the prior is the regulariser); it returns honest uncertainty alongside every prediction; and it unifies the chapter — OLS is MLE, ridge is MAP, and full Bayesian prediction generalises both. The price is more integration — but for linear-Gaussian models, every integral is closed form.
08 · Hands-on
Try it yourself
Four labs, each tuned to drill in one concept that students usually need to see move before it sticks. Push the controls, watch the numbers, then read the takeaway.
Watch the line settle on noisy data
The true relationship is t = −0.3 + 0.9 x. Each Resampledraws fresh training points (orange) from that line plus Gaussian noise, and the least-squares line (gold) is fit on the spot. Raise the noise to see the fit wobble; raise the sample size to see it lock back in.
Step gradient descent across the loss surface
The closed form is instant, but real problems descend iteratively: w⁽ᵏ⁺¹⁾ = w⁽ᵏ⁾ − α ∇L(w⁽ᵏ⁾). The left panel is the loss L(w₀,w₁) (bright = low); the right shows the current line on the data. Tune α to feel under-shoot, the sweet spot, and over-shoot.
Linear → polynomial → Gaussian basis
The data come from a smooth non-linear curve (blue). Switch the basis family and the number of basis functions M. The fit stays linear in w— the closed-form formula never changes — but the shapes it can take do.
Ridge regression — tame an overfit polynomial
We fit a degree-15 polynomial to 12 noisy points — far more parameters than data. Slide log₁₀ λ and watch ŵ = (λI + ΦᵀΦ)⁻¹Φᵀt reshape the fit, collapse the weight norm ‖w‖², and trade train error for test error.
09 · Exam intel
What the exam actually tests
Linear regression carries a heavy exam load — derivations are short, definite, and easy to grade. Five question shapes appear essentially every year.
Derive the closed-form OLS estimator
Start from . Take the gradient , set it to zero for the normal equations , and conclude . For full marks, note the Hessian is positive semi-definite, so the critical point is a global minimum.
Show that MLE = LS under Gaussian noise
Assume with i.i.d. Write the log-likelihood; the term in is , so maximising it over minimises the RSS. One-sentence summary: “squared error is the negative log-likelihood of a Gaussian noise model, up to constants.”
Derive the ridge estimator
The penalised loss has gradient ; setting it to zero gives . Mention: (i) is positive definite for any , so it’s always invertible — even with collinear features; (ii) ridge is MAP under a Gaussian prior with ; (iii) lasso uses , has no closed form, and yields sparse solutions.
State and use the Gauss–Markov theorem
Among linear unbiased estimators of , ordinary least squares has the smallest variance, component by component: . The catch: “unbiased” is doing real work — a biased estimator like ridge can have smaller mean-squared error. Gauss–Markov is what motivates regularisation as a deliberate bias-for-variance trade.
Place linear regression on the four ML dichotomies
| Dichotomy | Where linear regression sits |
|---|---|
| Parametric vs Nonparametric | Parametric — fixed parameters |
| Frequentist vs Bayesian | Frequentist by default; Bayesian under a prior |
| Generative vs Discriminative | Discriminative (direct or just ) |
| ERM vs SRM | OLS is empirical-risk minimisation; ridge/lasso are structural-risk minimisation |
Memorise four formulas and you have the chapter
- Linear model: .
- OLS: .
- Ridge: .
- Predictive variance: .
10 · Common mistakes
Where students get this wrong
” is non-linear regression” It looks bent, but it is linear regression — linear in the parameter vector . The non-linearity lives in the fixed, known basis . The closed-form OLS formula applies untouched. The distinction is “linear in ”, not “linear in ”.
Forgetting to scale features before Gaussian or polynomial bases
A Gaussian basis has its bandwidth baked into the units of ; a single cannot fit metres and kilograms at once. Always standardise (zero mean, unit variance) before fitting — same goes for high-degree polynomials, where explodes unless .
Multicollinearity → 'the OLS formula doesn't work'
When two features are nearly dependent, becomes near-singular, and inverting it gives wild, opposite-signed coefficients that cancel on training data but blow up on test inputs. Three honest responses: drop one offender, combine them (PCA), or regularise with ridge — is always invertible for .
Maximising R² as the goal
measures explained training variance and is monotone in the number of features — adding a useless predictor never lowers it. A model with on training and catastrophic test error is overfitting, not winning. Use held-out error (Ch. 4), not .
'Ridge eliminates parameters'
It doesn’t. Ridge shrinks coefficients toward zero but rarely makes them exactly zero. For sparse, interpretable models with a built-in feature selector you want lasso ( penalty) — the diamond geometry in §6 is the visual reason.
'More basis functions always improve the fit'
Training error never rises as grows; test error follows the U-shape — low underfits, high overfits. Bishop’s coefficients reach and predict garbage off-training: a textbook case of why a bigger without regularisation is a trap.
Confusing 'noise in t' with 'noise in x'
Ordinary linear regression assumes the inputs are known exactly and the target is the noisy thing — that asymmetry is why we measure error vertically, not perpendicular to the line. If the inputs are themselves noisy, OLS is biased; you want errors-in-variables or total least squares (out of scope).
11 · Self-check
Can you answer these?
Six short questions that mirror how the chapter gets tested. Click an option for instant feedback.
Which of the following models is linear regression?
You have N = 200 samples and M = 5 basis functions. What shape is the matrix ΦᵀΦ?
Under what assumption is the least-squares solution identical to the maximum-likelihood estimator?
You fit a degree-15 polynomial: training MSE is near zero but test MSE is much higher. Which intervention is most likely to help?
You place a zero-mean isotropic Gaussian prior N(0, τ²I) on the weights and compute the MAP estimate under Gaussian noise with variance σ². What do you get?
Training MSE is 0.02 and test MSE is 0.18 on a model with M = 12 basis functions and N = 15 samples. What is most likely happening?
12 · Recap
One-screen summary
Chapter 02 — load-bearing ideas
- Least squares fits the line that minimises vertical squared residuals. Sign-cancellation, outlier sensitivity, and differentiability are the three reasons we square.
- “Linear” means linear in , not in . Basis functions let the same algorithm fit curves: polynomial (global), Gaussian (local bumps), sigmoidal (smooth steps).
- The OLS closed form is , derived in three lines from , at cost .
- Geometric story. is the orthogonal projection of onto the column space of ; the hat matrix does the projecting.
- Probabilistic story. Under i.i.d. Gaussian noise, MLE coincides exactly with OLS; squared error is the negative log-likelihood of a Gaussian. Unbiased noise estimate .
- Generalisation. Training error always falls with complexity ; test error is U-shaped. Low underfits (bias), high overfits (variance); the right is picked by held-out validation (Ch. 4).
- Regularisation. Ridge shrinks weights and fixes collinearity; lasso () gives sparse solutions with no closed form.
- Gradient descent for big data. . Batch is stable but ; SGD is and converges under Robbins–Monro.
- Bayesian linear regression. Gaussian prior + Gaussian likelihood ⇒ Gaussian posterior. MAP equals ridge with ; predictive variance separates noise from parameter uncertainty.
- Four formulas to memorise: the linear model, the OLS solution, the ridge solution, and the predictive variance.