Regularisation: ridge and lasso
Last updated
Give a linear model enough features and it can fit anything, noise included. Lesson 2.6 controlled that by choosing a simpler model. Regularisation keeps the model and adds a cost for big weights instead, so the model only uses a large weight when the data really pays for it. Ridge shrinks every weight; lasso sets some to exactly zero. One setting, λ, says how strong the cost is, and cross-validation chooses it.
By the end of this lesson you can
- Show a degree-15 polynomial overfitting, and read its weights
- Write the ridge and lasso losses, and fit both with scikit-learn
- Explain with the circle and diamond picture why lasso gives exact zeros
- Choose λ by cross-validation
A degree-15 polynomial overfits
Twenty points from a wave, , plus noise. Lesson 3.7's trick, taken too far: give a linear model as features. Each notebook here starts with the same setup: the data, 200 new points for testing, a rmse helper, and poly, which builds a pipeline of polynomial features, scaling and a model.
On the training points the error is 0.073; on new points, 16.08, more than 20 times worse than predicting the average every time (about 0.73). Lesson 2.6's overfitting, at its worst: with 15 weights and 20 points, the curve bends through nearly every point, noise and all, and swings wildly between them.
The weights give it away: the largest is 1.4 billion. To bend that sharply, the model adds and subtracts enormous multiples of the features, which cancel almost exactly at the training points and not at all anywhere else.
Ridge (L2)
So add a cost for big weights to the loss. Ridge regression adds times the sum of the squared weights:
In words: fit the data, but pay for every unit of squared weight. (lambda) is a hyperparameter: 0 is plain linear regression; bigger values push harder for small weights. The bias isn't penalised; it only sets the overall level. The normal equations change only a little, to (with the data centred, so can be left out), which also fixes lesson 3.5's problem: for any , can be inverted.
scikit-learn calls alpha (and scales the data term slightly differently, so its numbers aren't exactly comparable):
Each line is , training error, test error, and the largest weight. Even brings the largest weight from 1.4 billion down to 23 and the test error from 16 to 0.25. At the model is too constrained to follow the wave, and both errors rise to over 0.4: underfitting.
Lasso (L1) and zero weights
Lasso penalises the sum of the weights' sizes instead of their squares:
11 of the 15 weights are exactly 0. Lasso has chosen four features (, , and ) and switched the rest off. That's feature selection for free, and it makes a model easier to read: with thousands of features, lasso can tell you which few matter. Ridge never does this; its weights get small but not zero. (scikit-learn finds lasso's answer by a method called coordinate descent, since has no derivative at 0; max_iter gives it enough rounds to finish.)
The geometry: circle and diamond
Why exact zeros? Picture two weights. The data's loss is a bowl with elliptical contours (lesson 3.2), lowest at the unpenalised answer. The penalty is smallest at the origin, and its contours are circles for ridge ( is fixed on a circle) and diamonds for lasso ( is fixed on a diamond).
The best compromise is where a loss contour just touches a penalty contour. A circle is smooth, so it's touched anywhere, almost never exactly on an axis. A diamond has corners sticking out along the axes, and a contour coming in from the side usually hits a corner first. At a corner, one weight is 0.
The answer is (1.04, 0.68), where a loss contour just touches the circle. Ridge shrinks both weights, but neither ever reaches exactly 0.
The dotted line is the answer for every from 0 to 12. Ridge's curves smoothly into the origin. Lasso's runs into the axis and then slides along it, with exactly 0.
Choosing λ by cross-validation
is a hyperparameter like Stage 2's , so choose it the same way: cross-validation on the training data (lesson 2.9). RidgeCV tries a list of values, by default with an efficient form of leave-one-out cross-validation:
It chose , with a test error of 0.271. That's not the best of step 2's four values on the test set (0.1 and scored 0.254), and it shouldn't be expected to be: with 20 training points, cross-validation's estimate is noisy, and picking by the test set would be lesson 2.9's mistake. All three are close, and far from the unregularised 16.
A coefficient path shows every weight as grows:
On the left, with tiny , the weights are spread widely; as grows they all shrink towards 0 together.
Wrong way: λ so large every weight is zero
More regularisation isn't always safer:
With alpha=10, lasso sets all 15 weights to 0. The model predicts the same number, the training mean, for every : its test error, 0.727, is about the spread of the test labels themselves, 0.711. It has learned nothing about the wave. That's the far end of the dial, underfitting as complete as the degree-15 fit was overfitting.
If a regularised model's weights are all zero, or its predictions are all the same, is too big. Cross-validating over a wide range of values, ten times apart, avoids both ends.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- Hoerl and Kennard, Ridge regression: biased estimation for nonorthogonal problems, Technometrics 12(1), 1970: where ridge regression comes from
- Tibshirani, Regression shrinkage and selection via the lasso, Journal of the Royal Statistical Society B 58(1), 1996: the lasso, and the diamond picture
- scikit-learn: Linear models: Ridge, Lasso and RidgeCV, and how their alpha is defined
- Goodfellow, Bengio and Courville, Deep Learning, chapter 7: Regularization for Deep Learning: L2 and L1 penalties on the weights (7.1)