ML fundamentals6 / 22

Lesson 6 · Will it work on new data?

Regularisation and cross-validation

The problem

In the last lesson, a degree-9 polynomial overfitted the ten deliveries. It went through every training dot and swung wildly between them. Its validation error was about 630,000.

One fix was to lower the degree. Another was more data. This lesson adds a third: keep the flexible model, but make wild curves expensive.

Look at the degree-9 fit's weights. To bend through all ten dots, it uses weights like 2,817, −8,413 and 7,210, which nearly cancel each other out. A gentle curve doesn't need weights like that. So charge the model for large weights.

A penalty on big weights

Add a second term to the loss, which grows with the size of the weights:

L(w,b)=MSE+λ2∑jwj2.L(\mathbf{w}, b) = \text{MSE} + \frac{\lambda}{2} \sum_{j} w_j^2 .

Now training has to balance two things. A smaller MSE fits the data better. Smaller weights pay less penalty. The number λ\lambda (lambda) sets the exchange rate between them. It's a hyperparameter, chosen before training.

Anything that holds a model back from fitting noise is called regularisation. This penalty, on the sum of squared weights, is L2 regularisation. With a linear model it's also called ridge regression. "L2" is the name of the usual length of a vector, ∥w∥=∑jwj2\lVert \mathbf{w} \rVert = \sqrt{\sum_j w_j^2} (the vector length). The penalty is λ2∥w∥2\tfrac{\lambda}{2}\lVert \mathbf{w} \rVert^2.

Two details matter:

  • The intercept isn't penalised. Shrinking bb would pull every prediction towards 0 minutes, which isn't simpler, only wrong.
  • The features must be on the same scale. The penalty treats every weight alike. A feature measured in metres needs a weight 1,000 times smaller than the same feature in km, so it would get off lightly. Standardise the features first (feature scaling).

Worked example

Ridge on one weight, by hand

  1. Take the two deliveries from the Gradient descent lesson: 1 km in 4 minutes and 2 km in 8 minutes. The model is minutes=w×km\text{minutes} = w \times \text{km}. Its MSE is 2.5 (w−4)22.5\,(w - 4)^2, with its lowest point at w=4w = 4.

The penalty's slope, λw\lambda w, always points back towards 0, and it's strongest for big weights. That's the whole effect: every weight is pulled towards 0, big ones hardest.

Predict first

Back on the degree-9 fit, you raise λ from 0. What happens to the training error, and to the validation error?

012345601020304050distance (km)minutes

● 10 training · ○ 100 validation · ━ degree-9 fit with ridge

λ = 0.1: training error 2.12 · validation error 9.23

Lowest validation error: λ = 0.1, error 9.23.

123456789−20−1001020weight on the power z¹ … z⁹weight00.00020.010.50.11101001,00010,000λ (log steps)error- - validation— training
Ridge on the degree-9 polynomial. Slide λ from 0 to 10. Below: the nine weights, then training and validation error for every λ.

Things to notice:

  • At λ = 0, it's the last lesson's degree-9 fit. The weights run into the thousands, and the validation error is about 630,000.
  • A tiny penalty does a lot. At λ = 0.001 the largest weight drops from 8,413 to 16, and the validation error from 630,000 to 83.
  • At λ = 0.1 the validation error is lowest, 9.23. The curve is nearly a straight line, with a slight bend. It's almost as good as degree 1 (8.38), from a model with nine powers.
  • Past that, the curve flattens. At λ = 10 every weight is below 1, the curve barely rises with distance, and the validation error climbs to 33.6.
  • Training error only goes up, from 0 to 18.1.

So λ\lambda works like the degree did in the last lesson: it sets the capacity. Small λ\lambda is a flexible model with high variance. Large λ\lambda is a stiff one with high bias. It's the same bias–variance trade-off, but now with a dial that turns smoothly.

Lasso: a penalty that removes features

Change the penalty from squares to sizes:

L(w,b)=MSE+λ∑j∣wj∣.L(\mathbf{w}, b) = \text{MSE} + \lambda \sum_j \lvert w_j \rvert .

This is L1 regularisation, or the lasso. ("L1" is the name for the sum of sizes, ∥w∥1=∑j∣wj∣\lVert \mathbf{w} \rVert_1 = \sum_j \lvert w_j \rvert.) It looks like a small change. It behaves quite differently.

Worked example

Lasso on the same weight

  1. Same two deliveries: L(w)=2.5 (w−4)2+λ∣w∣L(w) = 2.5\,(w - 4)^2 + \lambda \lvert w \rvert.

Ridge divides the weight: 20/(5+λ)20 / (5 + \lambda). Lasso subtracts from it: 4−λ/54 - \lambda / 5, until it hits 0. The figure shows both.

05101520253001234penalty strength λbest weight w— ridge: 20 / (5 + λ)- - lasso: 4 − λ/5

Ridge: w = 20 / (5 + 5) = 2.00

Lasso: w = 4 − 5/5 = 3.00

The best weight for the two deliveries, as λ grows. Ridge (solid) shrinks it but never reaches 0. Lasso (dashed) shrinks it at a steady rate and stops at 0.

Ridge's pull is λw\lambda w: it fades as the weight gets small, so the weight never quite arrives. Lasso's pull is λ\lambda whatever the weight's size, so a small weight gets pushed all the way to 0.

All six features

Now use all six delivery features from the linear regression lesson: distance, traffic, rain, hour, items and driver. The deliveries were made with no effect from items or the driver. Standardise the features, then trace each weight as λ\lambda grows. These traces are called coefficient paths.

Ridge (L2)
0.010.111010002468λ (log scale)weight (minutes per std)
Lasso (L1)
0.010.111010002468λ (log scale)weight (minutes per std)all 0 here
FeatureRidgeLasso
distance4.456.14
traffic4.826.68
rain1.421.57
hour−0.58−0.22
items0.040 exactly
driver−0.230 exactly
Weights for the six delivery features (standardised) as λ grows, for ridge and for lasso. The table lists the values at the slider's λ.

Things to notice:

  • Ridge shrinks every weight smoothly. None of them reaches 0, even at λ = 100.
  • Lasso drops features one by one. At λ = 1, the driver and items weights are exactly 0. By λ = 4, hour is 0 too, and rain is nearly 0.
  • The features lasso drops first are the useless ones. The driver and items have no effect on time. Lasso has picked the features for you.
  • The weights it keeps shrink less. At λ = 1, lasso keeps distance at 6.14, while ridge has pulled it to 4.45.

A model with many weights at exactly 0 is called sparse. It's cheaper to run and easier to read: "time depends on distance, traffic and rain". When you suspect many features don't matter, try lasso. When you think all of them matter a little, ridge is usually the better choice.

Why lasso lands on zero: the circle and the diamond

There's a picture behind the difference. Adding a penalty is like setting a budget for the weights' size, then finding the lowest loss within the budget. For L2, the weights with w12+w22w_1^2 + w_2^2 within budget fill a circle. For L1, the weights with ∣w1∣+∣w2∣\lvert w_1 \rvert + \lvert w_2 \rvert within budget fill a diamond.

The loss is a bowl, drawn as a contour plot: ovals of equal loss around its lowest point. The answer is where the smallest oval touches the shape.

L2 (ridge): a circle
−101234−1012w₁w₂×no penalty

best: (1.55, 0.74)

L1 (lasso): a diamond
−101234−1012w₁w₂×no penalty

best: (2.40, 0.00) · w₂ is exactly 0

thin ovals: equal loss · × lowest loss · shaded: every pair of weights no bigger than the answer · dashed: the oval through the answer · ● the answer

A made-up loss over two weights, lowest at (3, 1). Left: the L2 circle. Right: the L1 diamond. The dot is the penalised answer, where an oval of the loss touches the shape.

Things to notice:

  • The circle is round, so the oval touches it at an ordinary point. Both weights shrink, and both stay nonzero.
  • The diamond has corners on the axes. The ovals tend to touch it at a corner first. At a corner, one weight is exactly 0. Here, from about λ = 1.5 on, w2=0w_2 = 0.
  • At λ = 0 both answers sit on the ×. As λ grows, both shapes shrink and pull the answer towards (0, 0).

With six features, the diamond becomes a shape with corners and edges where some weights are 0. The more corners, the more likely the touching point lands on one.

DeeperA penalty is a priorRidge and lasso are what you get if you believe, before seeing data, that weights are probably small. · 2 min

Later in the course, you'll fit models by asking which weights make the data most probable (maximum likelihood). The mean squared error falls out of that, if the noise is bell-shaped.

You can also say what you believed about the weights before seeing any data: a prior. Believing "each weight is probably near 0, with a bell-shaped spread" adds exactly an L2 penalty to the loss. A narrower bell means a bigger λ\lambda. Believing in a sharper peak at 0 with longer tails (the Laplace distribution) adds an L1 penalty.

So the penalised fit is the most probable set of weights, given the data and the prior. That's the MAP estimate, and the lesson on maximum likelihood and MAP works it through.

Choosing λ: cross-validation

How should you pick λ\lambda? With a validation set, as you picked the degree. But that needs data to spare.

Suppose the shop has only 30 light-traffic deliveries in all. Hold out 6 for validation and the score rests on 6 deliveries, which is a noisy number. Hold out a different 6 and you may pick a different λ\lambda. On these 30 deliveries, each of five different 6-delivery splits picks its own winner: λ = 3, 0.1, 0.03, 0.001 and 0.01.

The fix is to take turns:

  1. Cut the data into 5 equal parts, called folds: here, 5 folds of 6.
  2. Hold out fold 1. Train on the other 24, and score on fold 1.
  3. Do the same with fold 2, then 3, 4 and 5.
  4. Average the five scores.

Every delivery is used for validation exactly once, and for training four times. This is cross-validation, or k-fold cross-validation with kk folds. Five and ten are the usual choices.

Worked example

The 5-fold average for λ = 0.01

  1. The five fold scores are 4.4, 9.3, 3.2, 9.6 and 11.1.

Step through the folds, then change λ\lambda.

VVVVVVTTTTTTTTTTTTTTTTTTTTTTTT

T = trains this fit · V = validates it · gaps separate the 5 folds of 6 deliveries

012345601020304050distance (km)minutesfold 1: error 4.39
Fold 0 of 5

Fold errors so far: 4.39 · ? · ? · ? · ?

Running average at λ = 0.01: 4.39

0.00010.0010.010.030.10.31310051015202530λvalidation errorlowest

●━ average of 5 folds · • single folds (capped at 30)

5-fold cross-validation on 30 deliveries, with a degree-9 ridge fit. Each step holds out one fold (rings), fits on the rest, and scores the fold. Below: the average for every λ.

Things to notice:

  • The curve changes from fold to fold. Each fit sees a different 24 deliveries.
  • Fold scores vary a lot. At λ = 0.01 they run from 3.2 to 11.1. The single-fold dots in the lower plot scatter widely at every λ.
  • The average is steadier. It traces a gentle U: 8.7 at λ = 0.0001, lowest at λ = 0.01 (7.53), and 17.2 at λ = 10.

Trying many hyperparameter settings and keeping the one with the best validation score is hyperparameter search. Trying every value from a list, as here, is a grid search. Once you've chosen, retrain on all the training data with that setting.

Cross-validation costs kk fits per setting: 9 values of λ\lambda and 5 folds make 45 fits. For small data and fast models, that's nothing. For a large neural network, one training run can take days, so people use a single validation set instead.

Cross-validation replaces the validation set, not the test set. The search can still overfit the folds a little. So keep a test set aside for the final score (train, validation and test sets).

DigressionNested cross-validation: when the search itself overfitsCross-validation inside cross-validation, for an honest score with no test set to spare. · 2 min

The winning λ\lambda's cross-validation score is the best of 9 tries. Some of its advantage is luck, so the score is a little too hopeful, as the validation score was in the last lesson.

With plenty of data, a separate test set fixes that. With little data, you can't spare one. Then wrap the whole search in a second, outer cross-validation:

  1. Split the data into outer folds, say 5.
  2. For each outer fold, run the complete search (inner cross-validation, choose λ\lambda, refit) on the other four. Score the result on the held-out outer fold.
  3. Average the five outer scores.

Each outer score comes from data the search never saw. The cost is large: 5 outer × 9 settings × 5 inner folds is 225 fits. Use it to report how good the whole method is, not to choose λ\lambda.

In scikit-learn

scikit-learn's Ridge and Lasso take the penalty strength as a parameter called alpha. It isn't the learning rate α\alpha from gradient descent, and it isn't quite this lesson's λ\lambda either. Each class scales the loss its own way:

This lesson minimisesscikit-learn minimisesSo set
RidgeMSE+λ2∑w2\text{MSE} + \tfrac{\lambda}{2} \sum w^2∑(y−y^)2+α∑w2\sum (y - \hat y)^2 + \alpha \sum w^2alpha =nλ/2= n\lambda / 2
LassoMSE+λ∑∣w∣\text{MSE} + \lambda \sum \lvert w \rvert12n∑(y−y^)2+α∑∣w∣\tfrac{1}{2n} \sum (y - \hat y)^2 + \alpha \sum \lvert w \rvertalpha =λ/2= \lambda / 2

Here nn is the number of training rows. Ridge's loss uses the total squared error rather than the mean, so its alpha grows with the data. In practice nobody converts: you search over alpha directly. The table matters when you compare numbers across libraries. LogisticRegression from the logistic regression lesson uses yet another convention, C, where a smaller C means a stronger penalty.

Ridge on the degree-9 polynomial, as in the figure:

Ridge on the degree-9 polynomial
def ridge_polynomial(lam: float, n_train: int) -> Pipeline:
    """Degree-9 polynomial in the distance, with an L2 penalty of strength λ (the lesson's units)."""
    return make_pipeline(
        StandardScaler(),  # scale the distance
        PolynomialFeatures(9, include_bias=False),  # z, z², …, z⁹
        StandardScaler(),  # put every power on the same scale, so the penalty treats them alike
        Ridge(alpha=n_train * lam / 2) if lam > 0 else LinearRegression(),  # scikit-learn's alpha = nλ/2
    )


for lam in [0, 0.001, 0.01, 0.1, 1, 10]:
    model = ridge_polynomial(lam, len(X_train)).fit(X_train, minutes_train)
    train_mse = mean_squared_error(minutes_train, model.predict(X_train))
    val_mse = mean_squared_error(minutes_val, model.predict(X_val))
    weights = model[-1].coef_  # the 9 weights, one per power
    print(f"λ = {lam:<6} train {train_mse:6.2f}  validation {val_mse:10.2f}  largest |w| {np.abs(weights).max():8.2f}")
# λ = 0: train 0.00, validation about 630,000 · λ = 0.1: 2.12 / 9.23 · λ = 10: 18.12 / 33.62
λ = 0      train   0.00  validation  628789.92  largest |w|  8413.26
λ = 0.001  train   0.32  validation      83.12  largest |w|    16.16
λ = 0.01   train   0.81  validation      23.10  largest |w|     8.99
λ = 0.1    train   2.12  validation       9.23  largest |w|     3.83
λ = 1      train   5.84  validation      16.06  largest |w|     2.64
λ = 10     train  18.12  validation      33.62  largest |w|     0.71

The pipeline has a second StandardScaler after PolynomialFeatures. It puts every power on the same scale, so the penalty treats them alike. model[-1] is the pipeline's last step, the Ridge model, and its .coef_ holds the nine weights.

Lasso and ridge on the six features:

Lasso and ridge on six features
df = deliveries()
X6 = StandardScaler().fit_transform(df[FEATURES].to_numpy())  # all six features, each mean 0, std 1
y = df["minutes"].to_numpy()

for lam in [0.1, 1, 4]:
    lasso = Lasso(alpha=lam / 2).fit(X6, y)  # scikit-learn's alpha = λ/2
    ridge = Ridge(alpha=len(y) * lam / 2).fit(X6, y)  # alpha = nλ/2
    print(f"λ = {lam}")
    print("  lasso", np.round(lasso.coef_, 2))  # items and driver hit exactly 0 first
    print("  ridge", np.round(ridge.coef_, 2))  # everything shrinks; nothing is exactly 0
λ = 0.1
  lasso [ 6.58  7.09  2.02 -0.64 -0.23 -0.06]
  ridge [ 6.31  6.81  1.99 -0.68 -0.23 -0.13]
λ = 1
  lasso [ 6.14  6.68  1.57 -0.22 -0.   -0.  ]
  ridge [ 4.45  4.82  1.42 -0.58  0.04 -0.23]
λ = 4
  lasso [ 4.66  5.35  0.09 -0.    0.   -0.  ]
  ridge [ 2.26  2.46  0.73 -0.35  0.14 -0.19]

A -0. is a zero that came from the negative side. The order is distance, traffic, rain, hour, items, driver.

Cross-validation

scikit-learn's cross_val_score and GridSearchCV do the fold loop for you. cross_val_score returns one score per fold:

5-fold cross-validation
km_30, minutes_30 = light_traffic_deliveries(30, seed=606)  # a shop with only 30 deliveries in all
X_30 = km_30.reshape(-1, 1)
folds = KFold(n_splits=5)  # 5 folds of 6, in order; use shuffle=True, random_state=… if rows are sorted

# Each fold trains on 24 rows, so the pipeline's alpha is 24·λ/2.
scores = cross_val_score(ridge_polynomial(0.01, 24), X_30, minutes_30, cv=folds, scoring="neg_mean_squared_error")
fold_mse = -scores  # scikit-learn maximises scores, so errors come back negated
print(np.round(fold_mse, 2), round(fold_mse.mean(), 2))  # five validation MSEs and their average
[ 4.39  9.26  3.25  9.63 11.15] 7.53
  • KFold(n_splits=5) cuts the rows into 5 folds in order. If the rows are sorted (by date, or by distance), pass shuffle=True and a random_state, or each fold will be unlike the others.
  • scikit-learn treats higher scores as better, so error scores come back negated: "neg_mean_squared_error". Flip the sign to read them.
  • The whole pipeline is refitted inside each fold, scalers included. So the scalers never see the held-out fold. Scaling all 30 rows first would leak a little information from the validation rows into training.

GridSearchCV runs cross-validation for every setting in a grid and keeps the best:

Grid search over λ
LAMBDAS = [0.0001, 0.001, 0.01, 0.03, 0.1, 0.3, 1, 3, 10]
search = GridSearchCV(
    ridge_polynomial(1, 24),  # the Ridge step's alpha is replaced by each value below
    param_grid={"ridge__alpha": [24 * lam / 2 for lam in LAMBDAS]},
    cv=folds,
    scoring="neg_mean_squared_error",
)
search.fit(X_30, minutes_30)  # 9 settings × 5 folds = 45 fits, then one refit on all 30 rows
best_lam = search.best_params_["ridge__alpha"] * 2 / 24
print(best_lam, round(-search.best_score_, 2))  # 0.01, the λ with the lowest average fold error
0.01 7.53
  • param_grid names a pipeline step's parameter as <step>__<parameter>. make_pipeline names each step after its class in lower case, so the ridge step's alpha is ridge__alpha.
  • Each fold trains on 24 rows, so the grid lists alpha =24λ/2= 24\lambda/2 for each λ\lambda, to match the figure.
  • After the search, search.best_params_ holds the winner and search.best_score_ its (negated) score. With refit=True, the default, search is then refitted on all 30 rows and can .predict like any model.

In PyTorch: weight decay

In PyTorch, the L2 penalty is a setting on the optimiser. torch.optim.SGD(..., weight_decay=λ) adds λw\lambda \mathbf{w} to every gradient. That's the slope of λ2∥w∥2\tfrac{\lambda}{2}\lVert \mathbf{w} \rVert^2, so it trains with exactly this lesson's ridge loss. The Neural-net foundations course calls this weight decay, because each step shrinks every weight by a small fraction.

Ridge as SGD with weight_decay
torch.manual_seed(0)
X = torch.tensor(X6, dtype=torch.float32)  # (300, 6), standardised
target = torch.tensor(y, dtype=torch.float32)  # (300,)
lam = 1.0

model = nn.Linear(6, 1)
optimizer = torch.optim.SGD(
    [
        {"params": [model.weight], "weight_decay": lam},  # adds λ·w to the gradient: the L2 penalty
        {"params": [model.bias], "weight_decay": 0.0},  # don't penalise the intercept
    ],
    lr=0.1,
)
model.train()
for step in range(500):  # full batch: all 300 rows each step
    optimizer.zero_grad()
    loss = F.mse_loss(model(X).squeeze(1), target)  # (300, 1) → (300,)
    loss.backward()
    optimizer.step()

print(model.weight.detach().numpy().round(2))  # the same weights as Ridge(alpha=150)
print(Ridge(alpha=len(y) * lam / 2).fit(X6, y).coef_.round(2))
[[ 4.45  4.82  1.42 -0.58  0.04 -0.23]]
[ 4.45  4.82  1.42 -0.58  0.04 -0.23]

The weights match Ridge(alpha=150) to two decimals: nλ/2=300×1/2=150n\lambda/2 = 300 \times 1 / 2 = 150. Two things to copy:

  • Parameter groups give the weights and the bias different settings. weight_decay would otherwise shrink the bias too, which ridge doesn't do.
  • F.mse_loss averages over the batch, so weight_decay=λ matches the lesson's λ\lambda directly. With Adam, use torch.optim.AdamW instead; the Neural-net foundations course explains why.

Putting it together

The recipe for a model with a penalty:

  1. Set aside a test set. Standardise the features, fitting the scaler on training rows only (a pipeline does this for you).
  2. Pick a grid of λ\lambda values that spans several factors of 10. The figure's grid is 0.0001, 0.001, 0.01, 0.03, 0.1, 0.3, 1, 3 and 10.
  3. Score each with 5-fold cross-validation, and keep the lowest average error.
  4. Refit on all the training data with that λ\lambda. Report the test score once.

On the 30 deliveries, cross-validation picks λ = 0.01, with an average error of 7.53. Ridge keeps the degree-9 model from going wild; lasso, on the six features, drops the two that don't matter. The same idea, a penalty that holds the weights back, is how large neural networks are kept in check too.

Common misconceptions

"Regularisation makes the model fit better." It makes training error worse on purpose: on the degree-9 fit, from 0 to 2.12 at λ = 0.1. What gets better is validation error, from about 630,000 to 9.23.

"Bigger λ is always safer." Too big a λ\lambda underfits. At λ = 10 every weight is below 1 and the validation error is 33.6, worse than at λ = 0.1.

"Ridge removes useless features." Ridge shrinks every weight but sets none to exactly 0. Lasso sets weights to 0. On the six features, lasso drops items and the driver by λ = 1; ridge still gives them small nonzero weights.

"scikit-learn's alpha is the learning rate." It's the penalty strength, and it's scaled differently in Ridge and Lasso. The learning rate α from gradient descent is unrelated.

"Cross-validation replaces the test set." It replaces the validation set. Choosing λ\lambda by cross-validation still uses those scores to make a choice, so you need untouched test data for the final number.

Recap

  • Regularisation holds a model back from fitting noise. The usual way is a penalty on large weights, added to the loss. Don't penalise the intercept, and standardise the features first.
  • L2 (ridge) adds λ2∑w2\tfrac{\lambda}{2}\sum w^2. It shrinks every weight, big ones hardest, but never to 0.
  • L1 (lasso) adds λ∑∣w∣\lambda \sum \lvert w \rvert. It pushes some weights to exactly 0, which removes features. The diamond's corners on the axes are why.
  • λ\lambda sets the capacity: raising it raises training error, while validation error falls, then rises.
  • k-fold cross-validation scores a setting on every row once, by rotating the validation fold, and averages the k scores. Hyperparameter search keeps the setting with the best average.
  • Code names: scikit-learn's Ridge and Lasso (alpha), KFold, cross_val_score and GridSearchCV (param_grid, best_params_, best_score_); PyTorch's torch.optim.SGD with weight_decay and parameter groups, and F.mse_loss.