Chapter 5 // Learning from Data

Regularization.

Can a flexible model be stopped from overfitting without making it less flexible?

Reading time
17 min
Data
Read first
Generalization

ended with a choice: pick a model simple enough not to overfit. That works when “simple” is a dial you can turn, like the degree of a curve. Often it is not. A model with a hundred features has a hundred weights, and you cannot know in advance which ones to remove.

This chapter takes a different route. Keep the flexible model, and change what it is rewarded for.

What overfitting looks like inside

Go back to the degree-9 curve that swung wildly between the students. Here are a few of its weights, next to those of the well-behaved degree-2 curve.

ModelLargest weightError on fitted studentsError on new students
Degree 27.411.928.8
Degree 94425.2192

The overfitted model has enormous weights. That is not a coincidence. To bend sharply enough to pass near every dot, the curve needs huge positive weights and huge negative ones that almost cancel each other. Small changes in the input then cause huge changes in the output.

So large weights are a symptom of overfitting. The idea of is to treat the symptom directly: make large weights cost something.

A price on large weights

Until now training has minimised one thing, the mean squared error. Add a second term that grows with the size of the weights:

loss=MSE+λ∑jwj 2\text{loss} = \text{MSE} + \lambda \sum_{j} w_j^{\,2}

what we minimise = how badly it fits + λ × how large the weights are

The model now has two aims that pull against each other. It still wants to fit the data, but every bit of weight has to earn its place by reducing the error more than it adds to the penalty. The number sets the exchange rate between the two.

  • With λ=0\lambda = 0 there is no penalty, and we are back to plain least squares.
  • With a huge λ\lambda the penalty is all that matters. Every weight is driven to zero and the model predicts the average score for everyone.

Least squares with this squared penalty is called . The bias bb is left out of the sum: it only moves the curve up and down, which is not the kind of flexibility we are trying to limit.

Figure

Taming the degree-9 curve

New student: 2.6 h, score 43New student: 3 h, score 50New student: 3.4 h, score 47New student: 3.8 h, score 60New student: 4.3 h, score 57New student: 4.5 h, score 56New student: 5.1 h, score 65New student: 5.5 h, score 81New student: 6.1 h, score 81New student: 6.2 h, score 83New student: 6.7 h, score 78New student: 7.1 h, score 81New student: 7.5 h, score 80New student: 7.9 h, score 85New student: 8.4 h, score 81New student: 8.9 h, score 75New student: 9.2 h, score 76New student: 9.4 h, score 80New student: 10.2 h, score 69New student: 10.3 h, score 653 h, score 453.1 h, score 503.9 h, score 585 h, score 755.5 h, score 675.9 h, score 756.6 h, score 697.3 h, score 808.5 h, score 788.6 h, score 749.7 h, score 7010.2 h, score 65
  • Fitted students
  • New students (hollow)
  • No penalty
Penalty λ
none
Largest weight
442
Error on fitted students
5.2
Error on new students
191.7
0.010
The same nine-bend model as before, on the same twelve students. Hollow blue dots are the new students. Try it: add the penalty, then drag λ from the far left to the far right. Watch the largest weight, and find where the error on new students is lowest.

With no penalty the largest weight is 442 and the error on new students is 192. A penalty of only λ=0.003\lambda = 0.003 brings that error down to about 36, close to what the degree-2 model achieved, and the curve stops lurching. Push λ\lambda too far and the curve flattens toward a horizontal line: the model is now underfitting.

Checkpoint

You increase λ in ridge regression. What happens to the error on the training data?

A different penalty: lasso

Ridge penalises the squares of the weights. Another choice is to penalise their absolute values:

loss=MSE+λ∑j∣wj∣\text{loss} = \text{MSE} + \lambda \sum_{j} \lvert w_j \rvert

This is called the . The change looks minor and has a striking effect.

Squaring a small number makes it much smaller: 0.12=0.010.1^2 = 0.01. So under ridge, a weight that is already small costs almost nothing, and there is no pressure to remove it entirely. Ridge shrinks every weight and almost never makes one exactly zero.

The absolute value does not have that property. A weight of 0.10.1 costs 0.10.1. Each weight is pushed toward zero with the same force however small it gets, and many of them arrive there. A weight of exactly zero means the model ignores that feature completely.

Figure

Shrinking against switching off

Weight on x to the power 1: 3.88Weight on x to the power 2: -2.50Weight on x to the power 3: 1.69Weight on x to the power 4: -2.36Weight on x to the power 5: 0.77Weight on x to the power 6: -1.59Weight on x to the power 7: 0.34Weight on x to the power 8: -1.03Weight on x to the power 9: 0.17
Penalty λ
0.100
Weights at exactly zero
0 of 9
Total size of weights
14.3
Error on new students
48.3
0.100

An orange ring marks a weight that is exactly zero.

Each bar is one weight of the degree-9 model. Feature 1 is x, feature 2 is x squared, and so on. Try it: with Ridge selected, drag λ upward and watch all the bars shrink together. Switch to Lasso and do the same, counting the orange rings.

A model in which most weights are zero is called . The lasso has in effect chosen which features to keep, a job known as . At λ=1\lambda = 1 it keeps four of the nine features and its error on new students is about 40, far below the 192 it started from.

RidgeLasso
Penalty on each weightits squareits absolute value
Effectshrinks all weightssets some weights to exactly zero
Good whenmost features matter a littleonly a few features matter
Resultevery feature still useda shorter, more readable model

Choosing the strength

The penalty strength λ\lambda is a hyperparameter, like the degree in , and it is chosen the same way. Try a range of values, score each by cross-validation on the training data, and keep the best. Because useful values span several powers of ten, the values tried are spaced by multiplication: 0.001, 0.01, 0.1, 1, 10.

Figure

Finding λ without the test set

chosen by cross-validation0, 25.24
  • Cross-validation
  • New students
  • Fitted students
Penalty λ
1.0
Cross-validation
25.2
New students
64.7
Fitted students
18.0
1.0
The orange curve is the cross-validation error, computed from the twelve fitted students only. The blue curve is the error on the twenty new students, shown for comparison. The λ axis goes up in powers of ten. Try it: drag λ to the lowest point of the orange curve and read the error on new students. Then switch between ridge and lasso.

The orange curve is the same U shape as before. Too little penalty overfits. Too much underfits. The lowest point of the curve is the value to use.

How good is that choice? Switch between the two penalties and compare with the blue curve.

Penaltyλ chosen by cross-validationError on new students thereBest possible on new students
Lasso0.06337.436.1
Ridge0.2555.535.9

For the lasso, cross-validation lands almost exactly on the best value. For ridge it asks for more penalty than the new students would have wanted. Both are far better than the 192 of the unpenalised model, but the ridge result is a reminder that cross-validation is an estimate. With only twelve students each round holds out two or three, and a score built from so few is noisy. With more data the two curves agree much more closely.

Checkpoint

A lasso model trained on 200 features ends up with 12 non-zero weights. What has happened?

In code

In scikit-learn the penalty strength is called alpha. The RidgeCV and LassoCV classes run the cross-validation for you.

import numpy as np
from sklearn.linear_model import LassoCV, RidgeCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler

alphas = np.logspace(-3, 1.5, 30)              # 30 values from 0.001 to about 32

def penalised(final_step):
    # Scaling comes before the penalty, so every feature is charged fairly.
    return make_pipeline(PolynomialFeatures(9, include_bias=False), StandardScaler(), final_step)

ridge = penalised(RidgeCV(alphas=alphas, cv=5)).fit(X_train, y_train)
lasso = penalised(LassoCV(alphas=alphas, cv=5, max_iter=100_000)).fit(X_train, y_train)

print(ridge[-1].alpha_, lasso[-1].alpha_)      # the strengths chosen by cross-validation
print(np.sum(lasso[-1].coef_ == 0))            # how many features the lasso switched off
print(ridge.score(X_test, y_test), lasso.score(X_test, y_test))   # R² on the test set

Libraries scale the penalty slightly differently from one another, so the best alpha here will not equal the best λ\lambda in the figures. The behaviour is the same.

Key Takeaways

  • Overfitted models have very large weights. Regularization makes large weights cost something.
  • The new loss is the error plus λ times the size of the weights. λ sets how much simplicity is worth.
  • Ridge (squared weights) shrinks all weights smoothly. Lasso (absolute weights) sets some to exactly zero.
  • Too little penalty overfits, too much underfits. Choose λ by cross-validation.
  • Put features on a common scale before penalising, or the penalty treats them unfairly.
You can now
  • Explain why large weights are a sign of overfitting.
  • Write down the ridge and lasso losses and say how they differ.
  • Predict what happens to the weights, the training error and the error on new data as λ grows.
  • Choose λ without touching the test set.

Exercises

Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.

Exerciseby hand

Two models have the same mean squared error, 10. Model A has weights [2, 2][2,\ 2] and model B has weights [0, 3][0,\ 3]. With λ=1\lambda = 1, which model does ridge prefer, and which does lasso prefer?

Hint

Ridge adds the sum of squared weights to the error. Lasso adds the sum of their sizes.

Solution

Ridge adds the squared weights. A: 4+4=84 + 4 = 8, a loss of 18. B: 0+9=90 + 9 = 9, a loss of 19. Ridge prefers A.

Lasso adds the sizes of the weights. A: 2+2=42 + 2 = 4, a loss of 14. B: 0+3=30 + 3 = 3, a loss of 13. Lasso prefers B.

Squaring punishes one large weight more than two medium ones, so ridge likes the weight spread out. Lasso counts every unit of weight the same, so it is happy to put everything on one feature and switch the other off.

Exerciseby hand

A model has a single weight. Without a penalty the best value is 4, and the loss is (w−4)2(w - 4)^2. Add a ridge penalty, giving (w−4)2+λw2(w - 4)^2 + \lambda w^2. Find the best ww for λ=0\lambda = 0, 1 and 3. Does it ever reach zero?

Hint

Set the derivative to zero: 2(w−4)+2λw=02(w - 4) + 2\lambda w = 0, and solve for ww.

Solution

Set the derivative to zero: 2(w−4)+2λw=02(w - 4) + 2\lambda w = 0, which gives w=4/(1+λ)w = 4 / (1 + \lambda).

  • λ=0\lambda = 0: w=4w = 4
  • λ=1\lambda = 1: w=2w = 2
  • λ=3\lambda = 3: w=1w = 1

The weight shrinks towards zero as λ grows, and it never gets there. However large λ is, 4/(1+λ)4 / (1 + \lambda) is still positive. Ridge shrinks weights and does not remove them.

Exerciseby hand

Now use a lasso penalty on the same model: (w−4)2+λw(w - 4)^2 + \lambda w, for ww at or above zero. Find the best ww for λ=2\lambda = 2, 8 and 10.

Hint

Set the derivative to zero as before. If the answer is negative, the best allowed value is 0.

Solution

Set the derivative to zero: 2(w−4)+λ=02(w - 4) + \lambda = 0, which gives w=4−λ/2w = 4 - \lambda / 2.

  • λ=2\lambda = 2: w=3w = 3
  • λ=8\lambda = 8: w=0w = 0
  • λ=10\lambda = 10: the formula gives −1-1, which is outside the allowed range. The lowest point within the range is w=0w = 0.

The weight falls in a straight line and hits zero at λ=8\lambda = 8. From there on it stays at exactly zero. This is why lasso can switch features off and ridge cannot.

Exercisethink

You fit a ridge model for a range of λ values, from very small to very large. Sketch, in words, what happens to the training error and to the validation error along the way. Where is the best λ?

Hint

At λ=0\lambda = 0 the model fits the training data as closely as it can. Think about what each increase takes away.

Solution

Training error rises all the way. With no penalty the model fits the training data as closely as it can. Every increase in λ pulls the weights away from that best fit, so the training error can only get worse.

Validation error falls, then rises. At very small λ the model overfits and validation error is high. As λ grows the weights calm down and validation error drops. Past a certain point the model is too restrained to follow the real pattern, and validation error climbs again.

The best λ is at the bottom of the validation curve. The training curve cannot tell you where that is, because it is lowest at λ=0\lambda = 0.

Exercisewith the figure

In the figure “Shrinking against switching off”, raise λ slowly with ridge selected, then again with lasso. How does the way the bars shrink differ? At λ=1\lambda = 1 under lasso, how many features are still in use?

Hint

Look for bars that reach exactly zero, and count the ones that remain.

Solution

Under ridge all the bars shrink together, each in proportion to its size, and none of them ever reaches zero. Under lasso the bars drop one at a time to exactly zero and stay there.

At λ=1\lambda = 1 the lasso keeps four of the nine features. It has chosen a simpler model for you, which ridge never does.

Going further

Why scaling comes first

A weight’s size depends on its feature’s units. Measure sleep in minutes instead of hours and the same model needs a weight sixty times smaller. A penalty on weight size would then punish the two versions differently, though they make identical predictions. To each feature first, giving it an average of 0 and a spread of 1, removes the problem. The scaling must be learned from the training data only.

Both at once

The elastic net uses both penalties together, with a second setting for the mix between them. It keeps the lasso’s ability to switch features off while behaving better when several features carry nearly the same information.

Other ways to regularize

A penalty on weights is one form of regularization among many. Stopping gradient descent early, before it has fully fitted the training data, has a similar effect. Neural networks add their own methods, such as dropout, which have later in the book.

References and further reading

  • G. James, D. Witten, T. Hastie and R. Tibshirani, An Introduction to Statistical Learning, chapter 6. Free at statlearning.com.
  • T. Hastie, R. Tibshirani and J. Friedman, The Elements of Statistical Learning, chapter 3, hastie.su.domains/ElemStatLearn.
  • H. Kinsley and D. Kukieła, Neural Networks from Scratch in Python, chapter 14, nnfs.io.

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 5.1What overfitting looks like inside
  3. 5.2A price on large weights
  4. 5.3A different penalty: lasso
  5. 5.4Choosing the strength
  6. 5.5In code
  7. Exercises
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in