Sub topic 14
Choosing the regularisation strength
This chapter assumes you know ridge and lasso penalties, k-fold cross-validation, and scikit-learn pipelines.
Strength is a hyperparameter
A regularised model has a penalty weight, called alpha in scikit-learn's Ridge and Lasso. Training cannot choose it. If it could, it would set alpha to zero, because that minimises training error. You must pick alpha using data the model was not fitted on.
- A very small
alphaleaves the model free to overfit. - A very large
alphapushes coefficients towards zero and causes underfitting. - The best value is usually somewhere between these extremes.
Search on a logarithmic grid
The effect of alpha depends on its order of magnitude. Going from 1 to 2 changes little, but going from 1 to 100 changes a lot. Try values spaced by powers of ten, such as 1e-4, 1e-2, 1, 100. Once you find a promising region, add a finer grid around it.
Compare strengths with cross-validation
Score each candidate alpha with k-fold cross-validation and keep the value with the lowest average error. The code below does this for a degree-15 polynomial.
import numpy as np
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import Ridge
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(40, 1))
y = np.sin(X).ravel() + rng.normal(0, 0.2, size=40)
for alpha in (1e-4, 1e-2, 1, 100):
model = make_pipeline(PolynomialFeatures(15), StandardScaler(), Ridge(alpha=alpha))
scores = cross_val_score(model, X, y, cv=5, scoring="neg_mean_squared_error")
print(alpha, round(-scores.mean(), 3))Scikit-learn scorers follow the rule that higher is better, so the error is reported as a negative number. That is why the code prints -scores.mean().
The scaler sits inside the pipeline. In each fold, it learns its mean and standard deviation from that fold's training part only. This prevents data leakage.
Expect the error to be high at the smallest alpha and again at the largest. The lowest error should fall between them. The exact numbers depend on the data.
Keep the test set out of the search
Tune only on the training pool. After choosing alpha, refit on the whole pool and evaluate on the test set once. If you keep adjusting alpha after seeing test results, the test score becomes an optimistic estimate.
Common errors
- Picking the edge of the grid. If the best value is the smallest or largest you tried, extend the grid.
- Reading small differences as meaningful. Cross-validation scores vary between folds. Two
alphavalues with nearly equal averages are effectively tied, so prefer the stronger penalty, which gives the simpler model. - Scaling outside the pipeline. Fitting a scaler on all the data before cross-validation leaks information from the validation folds.
- Using the validation score as the final estimate. The chosen
alphawas selected because it scored well there, so that score is biased upwards.
Exercise
You search alpha over 1e-4, 1e-2, 1, and 100, and the lowest cross-validated error is at 100. What should you do next, and why?
Show answer
Extend the grid to larger values, for example 1e3 and 1e4. The best value sits at the edge of the grid, so the true optimum may lie beyond it. Keep the test set untouched during this search.