Class 1 · Part 2 of 2

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

RSS shrinking onto the fit
01

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.

yβ0 + β1x

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:

Move the line yourself
the points are draggable too

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.

RSS, total squared error
best possible RSS
02

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 = yiyi: 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:

RSS = nΣi=1 (yiyi)2

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:

Every residual, and their total
make the sticks as short as you can

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.

RSS, the total to beat
minimum achievable

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.

RSS over every possible line
turn the bowl, or click the map to move the line

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.

03

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:

01
RSS = f(β) = nΣi=1 (yiβxi)2
The data xi and yi are fixed numbers we already measured. The only thing free to vary is β, so RSS is an ordinary function of one variable, and we want its minimum.
02
f′(β) = −2 nΣi=1 (yiβxi) xi
Differentiate with respect to β. Each term is something squared, so the chain rule gives 2·(inside)·(derivative of inside), and the derivative of (yiβxi) is just −xi.
03
−2 nΣi=1 (yixiβxi2) = 0
Set the derivative to zero, which is the definition of the minimum, and multiply out the bracket. The −2 in front now does nothing, since zero divided by −2 is still zero.
04
nΣi=1 yixi  =  β nΣi=1 xi2
Split the sum in two and move one side across. β is a single number, not indexed by i, so it comes out in front of the sum.
05
β = nΣi=1 yixi nΣi=1 xi2
Divide. That is it: a closed-form answer. No search, no iteration, no learning rate. Two sums over our data give the optimal slope exactly.
The formula, on actual numbers
drag a point, every column updates

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:

β1 = nΣi=1(xix)(yiy) nΣi=1(xix)2 β0 = yβ1x

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 = yβ1x rearranges to say the fitted line always passes exactly through the point (x, y).
Second, the numerator is the covariance of x and y and the denominator is the variance of x, which means:

β1 = r · sysx
Key idea

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.

04

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 y.
The error of that null model is the total sum of squares, TSS. R2 asks what fraction of it our line removed.

R2 = 1 − RSSTSS TSS = Σ(yiy)2

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.

R2 is the error you removed
switch between the null model and the fit
TSS, null model error
RSS, our model’s error
R2
RMSE (recall-score units)

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.

R2 never goes down when we add a predictor. Add pure random noise as a variable and R2 creeps up, because the extra freedom lets the model chase that noise. A high in-sample R2 is not evidence of anything until we have checked it out of sample.
05

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.

In-sample vs. out-of-sample, small n
press “new cohort” repeatedly and watch the line jump
train R2
test R2 (200 fresh subjects)
estimated slope β1
true slope

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.

Key idea

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.

from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score, mean_squared_error X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0) model = LinearRegression().fit(X_tr, y_tr) model.intercept_ # beta_0 model.coef_ # beta_1 ... beta_p r2_score(y_tr, model.predict(X_tr)) # the flattering number r2_score(y_te, model.predict(X_te)) # the honest one
06

More than one predictor

Nothing so far needed x to be a single measurement. With p features the model just grows a term each:

yβ0 + β1x1 + β2x2 + … + βpxp

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.

Two predictors, one plane
drag the figure to turn it

RSS, total squared error
best possible RSS
R2

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.

Key idea

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.

Adding a feature can only lower RSS. Even a column of random noise gives the model somewhere to put a little error, so R2 creeps up every single time. In neuroscience, where p is often larger than n, this stops being a nuisance and becomes the central problem. Next class: what to do about it.
07

Glossary

Everything introduced today, in the notation the course will keep using.

x
Feature, or predictor. What we measured and are willing to use as input.
y
Outcome, or target. What we want the model to produce.
f
The true relationship between them. Unknown, and stays unknown.
f
Our estimate of it: the fitted model. The hat means “estimated from data”.
ε
Irreducible noise. The part of y no model can ever recover.
yi
The model’s prediction for subject i.
n / p
Number of observations / number of features. In neuroscience p > n is normal, and it breaks things.
residual
ei = yiyi. The vertical miss for one observation.
RSS
Sum of squared residuals. What least squares minimises.
TSS
Sum of squared deviations from y. The error of the null model.
MSE
RSS divided by n. The standard regression loss.
RMSE
Square root of MSE, back in the units of y.
R2
1 − RSS/TSS. Fraction of variance in y the model accounts for.
β0, β1
Intercept and slope. The weights the model learns.
OLS
Ordinary least squares. The recipe for finding those weights.
training set
The data used to choose the weights.
test set
Data held back and touched exactly once, to estimate real performance.
overfitting
Fitting the noise. Train error falls, test error rises.
supervised
Learning with labelled y. Regression or classification.
unsupervised
Structure-finding with no y. Clustering, dimensionality reduction.
accuracy
Proportion of correct classifications. Misleading when classes are imbalanced.
recall
Of the true positives, the fraction the model found.

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.

Machine Learning for Neuroscience · 1501.1027 · Semester A, 5787
Course text: James, Witten, Hastie & Tibshirani, An Introduction to Statistical Learning with Applications in Python (2023). Chapter 3 covers today.
All data on this page is simulated.