Lesson 3 of 227 min
Linear regression
Linear regression sets one weight for each input so the squared misses are as small as they can be, and you judge it on new data by its misses, next to always guessing the average.
After this lesson you can fit a line by making the squared error small, and score it with MAE, RMSE and R².
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
The three scores, by hand
A miss is the guess minus the real mass. The MAE averages the misses with their sign dropped. The RMSE averages the squared misses, then takes the root, so it is back in grams. R² is one minus the line's squared misses over the average's. By hand, they are the video's three numbers.
miss = guess - y_test
print(np.mean(np.abs(miss)))
print(np.sqrt(np.mean(miss ** 2)))
print(1 - np.sum(miss ** 2) / np.sum((y_test - y_test.mean()) ** 2))234.0184585027885 281.70793684700584 0.8824514920483932
R² can fall below zero
Zero means as good as always guessing the average. A model that does worse than that gets a score below zero. Here, a guess of 3,500 g for every penguin misses more than the average does.
print(r2_score(y_test, np.full(len(y_test), 3500)))-0.5237588423576682
Read the weights
Each input has one weight: how many grams the guess changes when that input goes up by one, the others held still. A male is guessed about 440 g heavier than a female with the same measurements, and a Gentoo about 1 kg heavier than an Adelie. Drop an input, and the other weights change.
print(pd.Series(model.coef_, index=X.columns).round(1).tail(3))sex_MALE 436.9 species_Chinstrap -209.2 species_Gentoo 1019.5 dtype: float64
The RMSE in older code
Older tutorials get the RMSE with mean_squared_error(..., squared=False). Today's scikit-learn no longer takes squared, and the call fails. Use root_mean_squared_error instead. scikit-learn documentation
from sklearn.metrics import mean_squared_error
try:
mean_squared_error(y_test, guess, squared=False)
except TypeError as error:
print(error)
print(root_mean_squared_error(y_test, guess))got an unexpected keyword argument 'squared' 281.70793684700584
Why the Calculus line was a little different
The video's line, from the flipper alone, is about 0.505 kg for each centimeter and 4.17 kg at 20 cm. The Calculus course found 0.497 and 4.156, fitted on all 342 penguins with a flipper and a mass. This one is fitted on the 249 of the training set. Other penguins, a slightly different line.
flipper = df[["flipper_length_mm"]] / 10 - 20
X_a, X_b, y_a, y_b = train_test_split(flipper, y / 1000, test_size=0.25, random_state=0)
line = LinearRegression().fit(X_a, y_a)
print(len(X_a), line.coef_.round(3), round(line.intercept_, 3))249 [0.505] 4.166
Run on Python 3.13.3, scikit-learn 1.9.1, pandas 3.1.1 and NumPy 2.5.5. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: What machine learning is
On the 86 penguins kept aside, the rule by hand got 83 right and the computer's rule 82. So why learn a rule from examples at all?
2 of 3
On new penguins, a line that guesses the mass is off by 317 grams on average. What do you need beside it, to say whether it's a good model?
3 of 3
Two models guess the penguins' mass. On the test set, model A prints MAE 234 and RMSE 282. Model B prints MAE 230 and RMSE 400. What does B's gap between the two say?
The ideas in this lesson
- Linear regression
- One weight for each input, set so the squared misses on the training set are as small as they can be.
- MAE and RMSE
- Two sizes of a typical miss, in the label's own units; RMSE squares the misses first, so big ones count more.
- R² as a score
- How much of always guessing the average's squared miss a model takes away: 1 is no miss, 0 no better.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Linear regression
Here's a puzzle. A line guesses how heavy a penguin is, from its flipper. On new penguins, it's off by a few hundred grams. Is that a good model?
Keep your guess
Hold on to your guess. Here are three hundred and thirty-three penguins: flipper length across, and mass up. Two hundred and forty-nine are the training set. Eighty-four are kept aside as the test set.
A number as the label
Here the label is each penguin's mass, a number. So this is regression. A line can turn a flipper length into a guess, as in Calculus. Two numbers set the line: its weights.
One is how much each centimeter of flipper adds. The other is the guess for a flipper of twenty centimeters. So which line?
Linear regression
Each penguin's miss is how far the line's guess is from its real mass.
So which line is best?
The one whose squared misses on the training set are as small as they can be.
You saw that score in the Calculus course: the mean squared error.
There, gradient descent walked down to that line, step by step. For a line, there's a shortcut. scikit-learn works it out in one step.
The first weight comes out at about half a kilo for each centimeter. The second, at about four point two kilos.
Finding the weights this way... is called linear regression.
MAE
A line guesses each penguin's mass from its flipper. How far off is it, on penguins it never learned from? We'll measure the misses in grams. Open the test set: eighty-four penguins, each with its miss, the guess minus the real mass.
Drop the sign, so a miss above the line counts the same as one below it. Then average them: three hundred and seventeen grams. That's the mean absolute error, the MAE.
RMSE
Does one big miss count the same as many small ones? Here's another score. Square each miss, average the squares, and take the square root. Will it come out above three hundred and seventeen grams, or below?
Above: three hundred and eighty-three grams. That's the root mean squared error, the RMSE.
If every miss were the same size, the two would be equal. The RMSE sits above the MAE, because squaring makes the big misses count more. The biggest here is eight hundred and sixty-seven grams. Use the MAE when every gram costs the same.
Use the RMSE when a big miss costs more.
Compared with what?
A line guesses each penguin's mass, and on new penguins it's off by three hundred and seventeen grams. So is that good? Compared with what?
The laziest guess is to always say the average mass of these penguins. That misses by seven hundred and eight grams.
R squared
One more score compares the two. It's called R squared. Take the average's squared misses.
R squared is the share of them that the line takes away. Here... zero point seven eight: close to four fifths of them. You saw r squared in the Probability course, as the share of the spread a line explains. It's the same number.
Zero means no better than the average. One means no miss at all. So yes, it's a good line. But you only know that because you compared it with the average.
More inputs
Would more measurements help?
Linear regression can take many inputs, with a weight for each.
With more than one input, one flat line can't show the model anymore. So each penguin's guess goes up, and its real mass goes across. A dot on the diagonal is an exact guess.
Add the bill's length and depth.
No better: still zero point seven eight.
Now add the penguin's sex and its species, each turned into columns of zeros and ones. The misses shrink: two hundred and thirty-four grams, and R squared zero point eight eight.
The training score fools you
So should you add every column you have?
Add twenty columns of made-up random numbers. On the training set, R squared goes up, from zero point eight seven to zero point eight eight.
Spot the problem.
On the test set, it falls, from zero point eight eight to zero point eight six.
It falls almost every time you try this.
Linear regression gives every column a small weight, even a column of nonsense, if it makes the training misses a little smaller.
On new penguins, those small weights only get in the way.
Only the test set tells you whether a column helped.
In code
In real code, the masses are in grams, the file's own units. Take the five inputs, with sex and species turned into columns of zeros and ones. That part is a later lesson. Then split off the test set. Make a linear regression, fit it on the training set, and predict the test set. Three lines print its scores. What will the MAE be?
Two hundred and thirty-four grams.
The RMSE, two hundred and eighty-two.
R squared, zero point eight eight.
The same few lines guess any number in a table, like a price, or a delivery time.
Four ideas
So: linear regression finds the weights with the smallest squared misses. The MAE is the typical miss. The RMSE counts big misses more. And R squared says how much better than the average it does.
Judge all of them on the test set.
The lab
That's the end of this unit. In its lab, you use these three lessons to make a first model, and judge it on new penguins.
Judge it next to the average
Judge a guess by its misses, next to the average. Now try it on this lesson's page, and take the quiz. Move the line until it does worse than the average.
You use this lesson in Lab 1: A first model, judged on new penguins, which comes next.
Facts last checked on .
