Least Squares
The simplest guess at f is a straight line. Where that line comes from, how good it is, and why the number you report depends on which data you computed it on.
Dr. Asaf Madar · lecturer
The linear model
The simplest guess at f is a straight line: we assume y changes by a constant amount for every unit of x.
Two numbers, both readable in plain language:
- β0, the intercept: the predicted y when x = 0. Here, the recall score of an average-sized hippocampus.
- β1, the slope: how much y moves per one-unit increase in x. This is the number we interpret.
The slope turns the line about x = 0, marked on the plot. That is the one point it leaves alone, which is why we often measure a predictor from its own mean: it puts the pivot inside the data instead of far outside it.
Fitting the model means nothing more than choosing these two numbers. Try it by hand, you are the optimiser:
Hippocampal volume against a delayed-recall score, 14 simulated subjects. Volume is measured as the difference from the group mean, so x = 0 is an average-sized hippocampus. Drag a point to move it, click empty space to add one, shift-click a point to delete it.
Least squares
We just moved a line until it looked right. To do that automatically, we need to say precisely what “right” means.
For each subject the model predicts yi = β0 + β1xi, and reality delivered yi.
The gap between them is the residual, ei = yi − yi: the vertical distance from the point to the line.
We cannot simply add the residuals up, because the positive and negative ones cancel and a terrible line can score zero. We square each one first, then add. That is the residual sum of squares:
Squaring does two jobs: every error counts as positive, and large misses are punished out of proportion. Being off by 4 is sixteen times worse than being off by 1, not four times worse.
Ordinary least squares (OLS) is the choice of β0 and β1 that makes RSS as small as it can be.
Below, each residual is a red stick running from the observation to the line. A better line means shorter sticks, all of them at once:
Each stick is one residual. RSS squares every length and adds them up, so the long sticks dominate the total. Least squares is the line that leaves the smallest total.
The same 14 subjects and the same line as the first tab. Move either one and both follow.
The error surface
Every pair (β0, β1) is one possible line, and each one has its own RSS. Treat that number as a height and the whole space of lines becomes a landscape.
It is a bowl, a paraboloid. One bottom, no local minima to get trapped in, no flat plateaus. That is a rare luxury, and it is why linear regression has an exact formula while most models in this course have to be searched for numerically.
The bowl also sits upright rather than leaning, because x is measured from its own mean. That is the same fact as the pivot in the previous tab: with a centred predictor, the best slope does not depend on the intercept.
On the left is the surface itself. On the right is the same surface seen from directly above, drawn as a contour map. The dot is our current line and the cross is the least-squares solution, on both.
From the side. Height is RSS, with a scale up the nearest upright. Drag to turn it, and look for the single low point.
From above. The same bowl as a contour map, the way a hill is drawn on an Ordnance Survey sheet. Click anywhere to move the line there, and watch the sliders and the scatter above follow.
Colour bands are evenly spaced in the square root of RSS. Even spacing in RSS itself would put the whole floor of the bowl inside one band, because a paraboloid climbs so steeply.
Solving it with calculus
Hunting for the best line by hand is fine for two parameters, but we can do better.
Think of RSS as a function of β. It is a parabola: steep where the line is badly wrong, flattening out as it improves, and perfectly flat at its lowest point.
Flat means the derivative is zero, and that is the whole trick: write RSS as a function of β, differentiate, set it to zero, and solve.
To keep the algebra visible we drop the intercept for now and fit a line through the origin, y = βx, leaving one unknown. Reveal one step at a time:
Six points, one parameter. Drag any of them vertically and watch the two sums, and β, recompute.
Putting the intercept back
Doing the same with two unknowns (take the partial derivative with respect to β0 and to β1, set both to zero, solve the pair) gives the formulas we actually use:
Same structure as step 05, with every variable measured from its own mean instead of from zero. Two things fall straight out, both worth remembering.
First, β0 = − β1 rearranges to say the fitted line always passes exactly through the point (, ).
Second, the numerator is the covariance of x and y and the denominator is the variance of x, which means:
The regression slope is the correlation, rescaled by the spread of the two variables. Correlation and simple regression are the same fact in different units, which is exactly why a strong p-value on a slope tells us nothing about whether the model can predict.
How good is the fit?
RSS on its own is unreadable. Is 4,300 good? It depends on the units of y and on how many subjects we have. Two fixes:
MSE divides RSS by n, so it no longer grows just because we collected more data.
Its square root, RMSE, is back in the original units: “on average we miss by 3.4 points” is a sentence a clinician can use.
R2 compares our model to the laziest one available. With no x at all, the best guess for everybody is the mean .
The error of that null model is the total sum of squares, TSS. R2 asks what fraction of it our line removed.
R2 = 0 means the line did no better than guessing the mean every time. R2 = 1 means the residuals vanished.
Toggle between the two models below and watch the sticks shorten: the fraction of the total we removed is R2.
The same 14 subjects. Go back to the first tab, drag one point far away, and return here to see what a single subject does to R2.
Noisy data, small samples
Everything so far works beautifully with 500 clean observations. Neuroscience rarely offers those.
We get 25 subjects, an effect explaining a few percent of the variance, and a hundred candidate predictors.
The demo below is the one to sit with: fit the same linear model on a small training sample, then score it honestly on fresh subjects from the same population.
Test R2 can be negative. That is not a bug: it means the model predicts new subjects worse than simply guessing the mean would have.
Two things to notice as you click through cohorts.
At n = 20 the estimated slope swings wildly around the true one. Each cohort tells a different story, and any single published one might be ours.
Train R2 is systematically optimistic: it is computed on the very points used to place the line, so it gets to peek at the answer.
Drag n up to 200 and both problems fade. That gap between the two numbers is why this course insists on a test set.
A metric computed on the data we fitted is a description. The same metric on data the model has never seen is a prediction. Only the second one generalises, and it is the only one worth believing.
What this looks like in Python
Everything in this class is four lines of scikit-learn. That is exactly the danger: the library will happily let us skip the split.
More than one predictor
Nothing so far needed x to be a single measurement. With p features the model just grows a term each:
The recipe does not change: write RSS, take the partial derivative with respect to every β, set them all to zero, and solve the system. With one predictor that was one equation. With p predictors it is p + 1 equations, which a computer solves in microseconds.
What does change is the picture.
One predictor gives a line in a plane. Two predictors give a plane in a cube: for every pair (x1, x2) the model returns a height. The residuals are still vertical distances from each point to that surface, and least squares still picks the surface leaving the smallest total.
Below, recall is predicted from hippocampal volume and age, both measured from the group mean.
Three numbers now, so three sliders: one height and two tilts. Drag the figure itself to turn it.
Each β is read the same way as before: the change in y for a one-unit change in that feature, with the other features held fixed. That last clause is the whole difference between a simple and a multiple regression.
Two features give a plane, three give a volume, and beyond that the picture runs out. The algebra does not: it is the same normal equations at every p. Losing the ability to see the model is exactly why the checks from the previous tabs start to matter.
Glossary
Everything introduced today, in the notation the course will keep using.
Next time
What happens when features correlate with each other, why adding them always helps in-sample and often hurts out-of-sample, and the first tool for dealing with it, regularisation.
Interactions with a group and between two continuous predictors, KNN regression, and the bias-variance tradeoff.
Fitting vs. predicting, supervised vs. unsupervised, regression vs. classification, and EDA.