Week 5 · Regression: least squares and its Bayesian view
Read the words of the video
- Imagine you're trying to guess the price of a house. You look at its size, how many rooms it has, and compare it to other houses you know. This is like 'supervised learning' where you learn from examples with correct answers. We want to find a simple rule, like a line, to make good guesses.
- We find this 'best line' by making the total 'mistake' as small as possible. Imagine the line is like a target, and each data point is an arrow. We measure how far each arrow misses the target. We then square these misses and add them up. The line that gives the smallest total squared miss is our best guess!
- Let's try! If we have points like (zero, one), (one, two), and (two, two), our best line might be 'y equals seven-sixths plus one-half x'. To predict for a new input, say 'x equals three', we just plug it into our line's rule. The line helps us make educated guesses for new data!
- Remember, we use a 'line' to predict numbers, finding it by making total squared errors smallest. This is linked to 'Gaussian noise' for exams! Always test your line on new, unseen data to see how well it truly performs, not just on the data it learned from. Keep practicing, you've got this!
The one-minute story
Supervised learning means learning with a teacher: every example comes with the right answer. This week the answer is a number (a house price, a temperature, tomorrow's sales). That is regression.
You have met the idea before: draw the best straight line through a cloud of dots. We now look at it three ways:
- as geometry (a shadow, from MLF week 3),
- as calculus (make the total squared mistake as small as possible),
- as probability (assume the data is the line plus random noise, and find the most likely line).
All three give the same line. The probability view is new, and it opens a door: once you can say what kind of noise you expect, you can also say what kind of line you believe in beforehand, which is the Bayesian view and leads straight to next week's ridge regression.
By the end of this week you can:
- write linear regression with a design matrix and solve the normal equations;
- explain least squares as projection, as gradient descent, and as MLE under Gaussian noise;
- use basis functions (polynomial regression) to fit curves with a linear model;
- measure quality with MSE and validate with a held-out set or leave-one-out cross-validation.
Words you need
- Regression - predicting a real number.
- Feature vector and target - the inputs and the right answer for example .
- Weights - the numbers the model learns. Prediction: .
- Design matrix - one row per example here (), so is the vector of all predictions.
- Residual - , the mistake on one example.
- Training / validation error - error on the data used for fitting / on held-back data.
- Basis function - a fixed transformation of the input (like ) that we feed to a linear model.
Idea 1: Linear regression
Model: (add a constant 1 to to get an intercept). For all examples at once, with the design matrix whose rows are the :
Loss. The sum of squared errors:
Solving it (calculus). The gradient is . Setting it to zero:
These are the normal equations. Geometrically: is the projection of onto the column space of , and the residual is perpendicular to every column of (MLF week 3). By iteration: you can also reach by gradient descent, (MLF week 7). With millions of examples that is how it is done.
If the columns of are linearly dependent, is not invertible and the best is not unique. That is exactly the situation ridge regression fixes next week.
Question. The data are . We found in MLF week 3 that the best line is . Predict at and compute the training MSE.
Solution. . Fitted values at : . Residuals: . Sum of squares , so MSE .
Idea 2: The probabilistic view
Suppose the world works like this:
i.e. a true line plus bell-shaped noise. Then , and the log-likelihood of the data is
Maximising means minimising the sum of squared errors. So:
Least squares maximum likelihood estimation under Gaussian noise.
This is why squared error is the "natural" loss for regression: it is what you get when the noise is bell-shaped.
The Bayesian view (a preview of ridge)
Now put a prior on the weights too: , "I expect the weights to be small". Then (week 4's recipe: posterior likelihood prior) the MAP estimate minimises
That is ridge regression, which we study next week. Least squares is the special case with an infinitely wide (uninformative) prior.
Idea 3: Curves from lines, using basis functions
"Linear" means linear in the weights, not in . To fit a curve, replace with features such as . The model is still linear in , so all the machinery above applies with the new design matrix.
- Underfitting: too small, the curve is too stiff to follow the pattern (high bias).
- Overfitting: too large, the curve wiggles through every noisy dot and fails on new data (high variance). With the polynomial passes through all points exactly and training error is , yet predictions can be wild.
Fitting a curve through every dot is like a student who memorises the answers to last year's paper, including its printing mistakes. The score on that paper is perfect; on the new paper it is a disaster. We want the student who understood the pattern.
Idea 4: Checking quality honestly
MSE . : the fraction of the variation explained (1 is perfect, 0 is as good as predicting the mean).
Training error always shrinks as the model gets more flexible. So judge on data the model has not seen:
- Hold-out / validation set: keep a slice aside.
- Leave-one-out cross-validation (LOOCV): for each example , train on the other , predict example , record the squared error; average over all . Accurate but costly (it needs fits).
- -fold CV: split into parts, each used once as validation.
Question. A very simple model predicts the mean of the training targets. The targets are . Compute the LOOCV error.
Solution. Leave out each in turn:
| left out | train on | prediction (mean) | squared error |
|---|---|---|---|
| 1 | 2, 6 | 4 | |
| 2 | 1, 6 | 3.5 | |
| 6 | 1, 2 | 1.5 |
LOOCV error .
Idea 5: Kernel regression, briefly
Just as in kernel PCA, a linear regression only needs dot products between inputs, so we can swap them for a kernel and fit curvy functions without ever building the features. The prediction takes the form , a weighted sum of "similarity to training point ".
Your turn
Fit a no-intercept line to .
Need a hint?
is the column .
Show the full solution
, . .
Using from the previous problem, give the three fitted values and the sum of squared errors.
Need a hint?
.
Show the full solution
. Errors: . Squares: . Sum . (Check the normal equation: ✓.)
Targets and the "predict the mean of the others" model. Find the LOOCV error.
Need a hint?
Leave each out; use the mean of the other two.
Show the full solution
Predictions . Errors: . Mean .
(a) Training error never increases when you add polynomial features. (b) A degree-9 polynomial through 10 noisy points has zero training error. (c) Least squares is MLE under uniform noise. (d) The residual vector is perpendicular to the columns of .
Need a hint?
Think about flexibility and the normal equations.
Show the full solution
(a) True (the old model is a special case). (b) True, 10 points determine a degree-9 polynomial. (c) False, Gaussian noise. (d) True.
Under which noise assumption does minimising (absolute error) become MLE?
Need a hint?
The Gaussian gave squared error.
Show the full solution
Laplace noise (): its log-likelihood is . So absolute error corresponds to Laplace noise (and gives a median-like fit).
Exam radar
In MLT Quiz 2 (which covers weeks 5 to 8) the summaries mention linear regression in 10 papers, kernel regression in 8, ridge in 7, gradient descent in 6, update rule in 6, LOOCV in 4, model evaluation in 6, projection in linear regression and linear regression and MSE in a few. In the End Term, linear regression appears in 19 papers and ridge regression in 20.
Typical: "which of the following is the solution of the normal equation?", MSE for a small data set, gradient-descent update for regression, "LOOCV error for this tiny data set", and "least squares equals MLE under what noise?".
- Normal equations: (not ). The shape of matters ( rows are examples).
- Training error is not a good measure of quality; validation error is.
- Squared-error corresponds to Gaussian noise.
- A lower training MSE does not mean a better model if it overfits.
- Don't forget the intercept column of ones.
Quick quiz
The least-squares weights w satisfy...
- X w = 0
- X transpose X w = X transpose y
- w = y
- X transpose w = X y
Least squares is the maximum likelihood estimate when the noise is...
- uniform
- Gaussian
- exponential
- Poisson
A polynomial of degree n-1 fitted to n distinct points has training error...
- always large
- zero
- equal to the variance
- negative
Select all TRUE statements. (select all that apply)
- The residual is perpendicular to the columns of X at the optimum.
- Polynomial regression is still linear in the weights.
- LOOCV needs only one fit.
- The best w is always unique.
Recap
- Loss ; normal equations ; geometric meaning: projection.
- Gaussian noise MLE least squares; Gaussian prior on MAP ridge.
- Basis functions give curves; too flexible overfit. Judge with validation / LOOCV / -fold.
- Kernel regression replaces dot products by kernels.
- ; ;
- ; gradient step
- MSE ;
- LOOCV
- MLF week 3 - Vectors, matrices and the best-fit line: Least-squares regression is the same problem as MLF week 3's best-fit line.
- MLF week 12 - Estimating parameters, and EM: MLE and MAP give the probabilistic view of least squares and ridge.
- MLP week 3 - Linear regression and gradient descent in sklearn: Linear regression: the theory, then the code.
Practise with real exam questions
These come straight from past papers (with the real figures and the official answer key). Open 50 real questions on this week All Quiz 2 papers