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:
Now training has to balance two things. A smaller MSE fits the data better. Smaller weights pay less penalty. The number (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, (the vector length). The penalty is .
Two details matter:
- The intercept isn't penalised. Shrinking 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
Take the two deliveries from the Gradient descent lesson: 1 km in 4 minutes and 2 km in 8 minutes. The model is . Its MSE is , with its lowest point at .
The penalty's slope, , 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?
● 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.
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 works like the degree did in the last lesson: it sets the capacity. Small is a flexible model with high variance. Large 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:
This is L1 regularisation, or the lasso. ("L1" is the name for the sum of sizes, .) It looks like a small change. It behaves quite differently.
Worked example
Lasso on the same weight
Same two deliveries: .
Ridge divides the weight: . Lasso subtracts from it: , until it hits 0. The figure shows both.
Ridge: w = 20 / (5 + 5) = 2.00
Lasso: w = 4 − 5/5 = 3.00
Ridge's pull is : it fades as the weight gets small, so the weight never quite arrives. Lasso's pull is 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 grows. These traces are called coefficient paths.
| Feature | Ridge | Lasso |
|---|---|---|
| distance | 4.45 | 6.14 |
| traffic | 4.82 | 6.68 |
| rain | 1.42 | 1.57 |
| hour | −0.58 | −0.22 |
| items | 0.04 | 0 exactly |
| driver | −0.23 | 0 exactly |
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 within budget fill a circle. For L1, the weights with 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.
best: (1.55, 0.74)
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
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, .
- 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 . 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 ? 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 . 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:
- Cut the data into 5 equal parts, called folds: here, 5 folds of 6.
- Hold out fold 1. Train on the other 24, and score on fold 1.
- Do the same with fold 2, then 3, 4 and 5.
- 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 folds. Five and ten are the usual choices.
Worked example
The 5-fold average for λ = 0.01
The five fold scores are 4.4, 9.3, 3.2, 9.6 and 11.1.
Step through the folds, then change .
T = trains this fit · V = validates it · gaps separate the 5 folds of 6 deliveries
Fold errors so far: 4.39 · ? · ? · ? · ?
Running average at λ = 0.01: 4.39
●━ average of 5 folds · • single folds (capped at 30)
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 fits per setting: 9 values of 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 '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:
- Split the data into outer folds, say 5.
- For each outer fold, run the complete search (inner cross-validation, choose , refit) on the other four. Score the result on the held-out outer fold.
- 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 .
In scikit-learn
scikit-learn's Ridge and Lasso take the penalty strength as a parameter called alpha. It isn't the learning rate from gradient descent, and it isn't quite this lesson's either. Each class scales the loss its own way:
| This lesson minimises | scikit-learn minimises | So set | |
|---|---|---|---|
Ridge | alpha | ||
Lasso | alpha |
Here 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:
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.71The 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:
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:
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.53KFold(n_splits=5)cuts the rows into 5 folds in order. If the rows are sorted (by date, or by distance), passshuffle=Trueand arandom_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:
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 error0.01 7.53param_gridnames a pipeline step's parameter as<step>__<parameter>.make_pipelinenames each step after its class in lower case, so the ridge step'salphaisridge__alpha.- Each fold trains on 24 rows, so the grid lists
alphafor each , to match the figure. - After the search,
search.best_params_holds the winner andsearch.best_score_its (negated) score. Withrefit=True, the default,searchis then refitted on all 30 rows and can.predictlike any model.
In PyTorch: weight decay
In PyTorch, the L2 penalty is a setting on the optimiser. torch.optim.SGD(..., weight_decay=λ) adds to every gradient. That's the slope of , 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.
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: . Two things to copy:
- Parameter groups give the weights and the bias different settings.
weight_decaywould otherwise shrink the bias too, which ridge doesn't do. F.mse_lossaverages over the batch, soweight_decay=λmatches the lesson's directly. With Adam, usetorch.optim.AdamWinstead; the Neural-net foundations course explains why.
Putting it together
The recipe for a model with a penalty:
- Set aside a test set. Standardise the features, fitting the scaler on training rows only (a pipeline does this for you).
- Pick a grid of 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.
- Score each with 5-fold cross-validation, and keep the lowest average error.
- Refit on all the training data with that . 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 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 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 . It shrinks every weight, big ones hardest, but never to 0.
- L1 (lasso) adds . It pushes some weights to exactly 0, which removes features. The diamond's corners on the axes are why.
- 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
RidgeandLasso(alpha),KFold,cross_val_scoreandGridSearchCV(param_grid,best_params_,best_score_); PyTorch'storch.optim.SGDwithweight_decayand parameter groups, andF.mse_loss.