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.
| Model | Largest weight | Error on fitted students | Error on new students |
|---|---|---|---|
| Degree 2 | 7.4 | 11.9 | 28.8 |
| Degree 9 | 442 | 5.2 | 192 |
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
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:
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
- With there is no penalty, and we are back to plain least squares.
- With a huge 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
Taming the degree-9 curve
- Fitted students
- New students (hollow)
- No penalty
- Penalty λ
- none
- Largest weight
- 442
- Error on fitted students
- 5.2
- Error on new students
- 191.7
With no penalty the largest weight is 442 and the error on new students is 192. A penalty of only brings that error down to about 36, close to what the degree-2 model achieved, and the curve stops lurching. Push too far and the curve flattens toward a horizontal line: the model is now underfitting.
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:
This is called the
Squaring a small number makes it much smaller: . 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 costs . 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.
Shrinking against switching off
- Penalty λ
- 0.100
- Weights at exactly zero
- 0 of 9
- Total size of weights
- 14.3
- Error on new students
- 48.3
An orange ring marks a weight that is exactly zero.
A model in which most weights are zero is called
| Ridge | Lasso | |
|---|---|---|
| Penalty on each weight | its square | its absolute value |
| Effect | shrinks all weights | sets some weights to exactly zero |
| Good when | most features matter a little | only a few features matter |
| Result | every feature still used | a shorter, more readable model |
Choosing the strength
The penalty strength is a hyperparameter, like the degree in
Finding λ without the test set
- Cross-validation
- New students
- Fitted students
- Penalty λ
- 1.0
- Cross-validation
- 25.2
- New students
- 64.7
- Fitted students
- 18.0
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-validation | Error on new students there | Best possible on new students |
|---|---|---|---|
| Lasso | 0.063 | 37.4 | 36.1 |
| Ridge | 0.25 | 55.5 | 35.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.
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 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.
- 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.
Two models have the same mean squared error, 10. Model A has weights and model B has weights . With , 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: , a loss of 18. B: , a loss of 19. Ridge prefers A.
Lasso adds the sizes of the weights. A: , a loss of 14. B: , 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.
A model has a single weight. Without a penalty the best value is 4, and the loss is . Add a ridge penalty, giving . Find the best for , 1 and 3. Does it ever reach zero?
Hint
Set the derivative to zero: , and solve for .
Solution
Set the derivative to zero: , which gives .
- :
- :
- :
The weight shrinks towards zero as λ grows, and it never gets there. However large λ is, is still positive. Ridge shrinks weights and does not remove them.
Now use a lasso penalty on the same model: , for at or above zero. Find the best for , 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: , which gives .
- :
- :
- : the formula gives , which is outside the allowed range. The lowest point within the range is .
The weight falls in a straight line and hits zero at . From there on it stays at exactly zero. This is why lasso can switch features off and ridge cannot.
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 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 .
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 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 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
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
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.