Linear models · lesson 8 of 12
Parts in this lesson
ARidge(alpha=0.1)squared-error loss plus λ‖w‖²
BLasso(alpha=0.01)squared-error loss plus λ‖w‖₁
CRidgeCV(alphas=...)λ chosen by cross-validation

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, y=sin⁡(2πx), plus noise. Lesson 3.7's trick, taken too far: give a linear model x,x2,…,x15 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.

regularise.ipynb

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:

ℒridge(w,b)=1n∑i=1n(yˆi−yi)2+λ‖w‖22,‖w‖22=∑j=1dwj2

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 b isn't penalised; it only sets the overall level. The normal equations change only a little, to (X⊤X+nλI)w=X⊤y (with the data centred, so b can be left out), which also fixes lesson 3.5's problem: for any λ>0, X⊤X+nλI can be inverted.

scikit-learn calls λ alpha (and scales the data term slightly differently, so its numbers aren't exactly comparable):

regularise.ipynb

Each line is λ, training error, test error, and the largest weight. Even λ=10−6 brings the largest weight from 1.4 billion down to 23 and the test error from 16 to 0.25. At λ=10 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:

ℒlasso(w,b)=1n∑i=1n(yˆi−yi)2+λ‖w‖1,‖w‖1=∑j=1d|wj|
regularise.ipynb

11 of the 15 weights are exactly 0. Lasso has chosen four features (x, x2, x8 and x9) 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 |w| 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 (w12+w22 is fixed on a circle) and diamonds for lasso (|w1|+|w2| 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.

Penalty shapeswhere the loss meets the penalty
×−10123−1012w₁w₂

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 w1 axis and then slides along it, with w2 exactly 0.

Choosing λ by cross-validation

λ is a hyperparameter like Stage 2's k, 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:

regularise.ipynb

It chose λ=0.001, 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 10−6 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:

regularise.ipynb

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:

regularise.ipynb

With alpha=10, lasso sets all 15 weights to 0. The model predicts the same number, the training mean, for every x: 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

An unregularised model has weights in the millions and a test error far above its training error. What’s happening, and what helps?
Predict, then check with the penalty shapes: with lasso, as λ rises, what happens to w₂?
How should λ be chosen?

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.

All sources for Simple Machine Learning