Lesson 5 of 227 min
Overfitting and regularization
A model that bends too much learns its own examples and misses new ones, a model too simple misses both, and a penalty on big weights keeps it smooth, with its strength chosen on the validation set.
After this lesson you can spot overfitting and underfitting from the training and validation error, and hold a model back with a penalty on its weights.
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.
What the penalty adds to the loss
Ridge makes one number small: the squared misses on the training set, plus alpha times the squared weights. The starting value, intercept_, is not penalized. Here are both parts at a strength of 1, then the size of the weights, with no penalty and with one: the video's 88,752 and 733.
model = make_pipeline(PolynomialFeatures(9), StandardScaler(), Ridge(alpha=1)).fit(X_train, y_train)
ridge = model[-1]
Z = model[:-1].transform(X_train)
misses = np.sum((ridge.predict(Z) - y_train) ** 2)
size = np.sum(ridge.coef_ ** 2)
print(round(misses), round(size), round(misses + 1 * size))
for reg in [LinearRegression(), Ridge(alpha=1)]:
m = make_pipeline(PolynomialFeatures(9), StandardScaler(), reg).fit(X_train, y_train)
print(round(np.sqrt(np.sum(m[-1].coef_ ** 2))))1372559 536852 1909411 88752 733
The columns the curve is made of
PolynomialFeatures(9) makes ten columns: the flipper to the powers 0 to 9. The first is all 1s, which the scaler turns into 0s, so it changes nothing. The flipper is measured from 20 cm because in millimeters its ninth power reaches about 2 × 10²¹, and numbers that far apart lose digits.
P = PolynomialFeatures(9).fit_transform(X_train)
print(P.shape, P[:3, 0], StandardScaler().fit_transform(P)[:3, 0])
print(f"{df['flipper_length_mm'].max() ** 9:.1e}", round(X['flipper_length_mm'].abs().max() ** 9))(20, 10) [1. 1. 1.] [0. 0. 0.] 1.9e+21 26440
Two other penalties: the lasso and elastic net
The lasso (Lasso) penalizes the weights' sizes without squaring them, and sets some to exactly 0: four of the nine here. Elastic net (ElasticNet) mixes the two, by l1_ratio. On these penguins, at the same strength, Ridge misses new penguins the least.
for name, reg in [("ridge", Ridge(alpha=1)),
("lasso", Lasso(alpha=1, max_iter=100_000)),
("elastic net", ElasticNet(alpha=1, l1_ratio=0.5, max_iter=100_000))]:
m = make_pipeline(PolynomialFeatures(9), StandardScaler(), reg).fit(X_train, y_train)
print(name, np.round(m[-1].coef_[1:]).astype(int), round(root_mean_squared_error(y_val, m.predict(X_val))))ridge [ 680 44 203 101 10 42 -65 -36 -117] 394 lasso [ 845 -262 136 0 0 1108 0 0 -957] 471 elastic net [397 59 190 28 75 2 20 -15 -8] 449
No penalty in logistic regression
LogisticRegression has a penalty on by default, at C=1.0; a smaller C is stronger. For none, today's scikit-learn wants C=np.inf: the older penalty=None still works, with a warning that it will go. On the Adelies and Chinstraps by bill length, a strong penalty halves the weight.
two = pd.read_csv(url).dropna(subset=["bill_length_mm"])
two = two[two["species"].isin(["Adelie", "Chinstrap"])]
for C in [1.0, 0.01, np.inf]:
lr = LogisticRegression(C=C).fit(two[["bill_length_mm"]], two["species"])
print(C, lr.coef_.round(3))1.0 [[1.018]] 0.01 [[0.505]] inf [[1.049]]
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: Training, validation and test data
Your loop printed each setting's score on the validation set, and two questions won with 0.9375. Then the winner, scored once on the test set, printed 0.965. Which number tells you how it will do on new penguins?
2 of 3
A model misses its training set by 150 grams, and its validation set by 900 grams. What is wrong with it, and what do you change?
3 of 3
With the penalty at a strength of 1, degree nine misses its own 20 penguins by 262 grams and new ones by 394. At a strength of 1,000, by 842 and 768. What is wrong at 1,000?
The ideas in this lesson
- Overfitting and underfitting
- Too bendy, a model learns its own examples and misses new ones; too simple, it misses both.
- Training and validation error
- Draw both as a model bends more: training error keeps falling, validation error falls then climbs; keep its lowest point.
- Regularization
- A penalty on big weights keeps a model smooth; its strength is a setting, chosen on the validation set.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Overfitting and regularization
Here's a bet. Two models guess how heavy a penguin is. One is a straight line. The other bends through almost every penguin it learned from. Which one guesses new penguins better?
Keep your guess
Hold on to your guess. Here are the penguins again: flipper length across, and mass up. This time, a model learns from only twenty of them: its training set. With so few, you can see what goes wrong. Two hundred and thirty-six new penguins are kept aside for choosing: the validation set. And eighty-six are sealed as the test set.
A curve that bends
A line guesses a penguin's mass from its flipper, and it learns from twenty penguins. It misses them by two hundred and seventy grams. That's the RMSE: a typical miss, where the big ones count more.
Now let the line bend. Give it a weight for the flipper, another for the flipper's square, and so on, up to its ninth power. How far up it goes is a setting called its degree. Degree one is a straight line. Degree two can bend once. Degree nine can bend up to eight times. Degree nine bends through nearly all of the twenty. It misses them by only two hundred and three grams.
Overfitting
Now the two hundred and thirty-six new penguins. Which one misses them by less: the line, or the curve?
The line misses them by four hundred and six grams. The curve misses them by over thirteen hundred. That's over three times as much. Between its twenty penguins, the curve goes up and down. And for flippers shorter than one hundred and seventy-eight millimeters, the shortest it learned from, it dives below zero kilos. It learned those twenty penguins, but not penguins in general. That's called overfitting.
Underfitting
And the other way? Degree zero is a flat line, at the average of the twenty. It misses its own twenty by nine hundred and nine grams, and new penguins by eight hundred and eleven. It's too simple to learn even its own examples. That's called underfitting.
Two errors
A model learns from a training set, and you check it on a validation set. So how do you tell which way it fails?
Draw both errors, for every degree. As the curve bends more, what does the validation error do?
The training error falls all the way down, from nine hundred and nine grams. At degree nine, it's two hundred and three. The validation error falls only as far as three hundred and ninety-three, at degree three. Then it climbs, and jumps around.
If both errors are high, the curve is too simple: let it bend more.
Now say the training error is low, and the validation error is far above it. Then the curve learned its own penguins: let it bend less. Keep the degree where the validation error is lowest.
A penalty
A curve that bends a lot fits its own examples and misses new ones. Can it stop going up and down, without you guessing the degree?
Draw a line through these dots by hand. You'd draw a smooth one. The ups and downs are only where a few dots happened to fall. A model can't tell that.
And to go up and down like this, degree nine adds and takes away very large amounts: its weights are huge. So add a penalty. Training makes its loss small: the squared misses.
Now add one more number to that loss: how big the weights are. A big weight costs something, so the curve only bends where many penguins ask for it. That's called regularization.
The penalty has a strength, a number you set. With a strength of one, its weights shrink a lot. Degree nine now misses new penguins by three hundred and ninety-four grams.
Every degree
Now turn the penalty on... and look at the chart of both errors again. What happens to it?
It goes flat. Every degree from one to nine now misses new penguins by about four hundred grams. So you don't have to guess the degree anymore. For penguins, the penalty leaves almost a straight line, because that's what they ask for.
Its strength
How strong should the penalty be? Its strength is a setting too, from a ten-thousandth, very weak, to a thousand, very strong. Too weak, and the curve still goes up and down: about seven hundred and fifty grams. Now spot what goes wrong at a thousand.
The curve flattens toward the average. It misses both sets, by about eight hundred grams. That's underfitting again. The validation error is lowest at a strength of one. So keep one, and open the test set once: four hundred and twenty-nine grams. The line gets four hundred and thirty there. Both are a little higher than on the validation set, because the test set is different penguins.
In code
In real code, the flipper is in centimeters, measured from twenty, which keeps its powers small. The masses are in grams. A pipeline makes the curve. First the powers of the flipper, up to nine. Then a step that puts them all on one scale, which is a later lesson. Then Ridge, with the penalty's strength, alpha.
A loop tries four strengths, and scores each one on the validation set. Which strength will win?
One: three hundred and ninety-four grams, the same as in the picture. You'll see the same penalty under other names. In logistic regression, its setting is called C, and a smaller C means a stronger penalty. When neural networks train, it's called weight decay, and AdamW, from the Calculus course, uses it.
The recap
So: a curve that bends too much learns its own examples. One that's too simple misses both. The two errors, side by side, show you which. And a penalty keeps a model smooth, with its strength chosen on the validation set.
Judge it by new examples
Judge a model on new examples, not its own. Now try it on this lesson's page, and take the quiz. Bend the curve all the way, and still beat the line.
You use this lesson in Lab 2: Tune a penguin model on folds, after Cross-validation and tuning.
Facts last checked on .
