Sub topic 14
Choosing the regularisation strength
This chapter assumes you know how ridge and lasso penalties work, how k-fold cross-validation works, and how to build a scikit-learn pipeline. It covers how to pick the penalty strength without using the test set.
Strength is a hyperparameter
Every penalty has a knob that sets how much complexity costs. In scikit-learn's Ridge and Lasso it is alpha. A larger alpha shrinks coefficients more.
- With
alphanear zero, the model is almost unregularised and can overfit (high variance). - With a very large
alpha, coefficients are pushed toward zero and the model underfits (high bias). - A good value sits between those extremes, where validation error is lowest.
The training loss cannot choose this value. Training error only increases as alpha grows, so it always favours the weakest penalty. You need error measured on data the model did not fit.
Naming differs between libraries
The direction of the knob changes between libraries, which causes many mistakes.
| Library or class | Parameter | Larger value means |
|---|---|---|
| `Ridge`, `Lasso`, `ElasticNet` | `alpha` | Stronger penalty |
| `LogisticRegression`, `SVC` | `C` | Weaker penalty (C is an inverse strength) |
| Keras `regularizers.l2(x)` | `x` | Stronger penalty |
| `ElasticNet` | `l1_ratio` | More L1, less L2 |
Search on a log scale
Useful values of alpha span many orders of magnitude, so a grid like 0.1, 0.2, 0.3 wastes most of its points. Use a geometric grid such as np.logspace(-4, 2, 13), which gives values from 0.0001 to 100.
Each candidate is scored with k-fold cross-validation on the training portion only. The following code reuses the degree-15 polynomial from earlier and compares candidates. Scaling sits inside the pipeline, so each fold fits its scaler on that fold's training rows.
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 "higher is better", so error metrics appear negated. The code negates the mean to print a normal mean squared error.
The full procedure
The test set must stay untouched until the very end. The tuning loop is only allowed to see the training portion.
GridSearchCV automates the loop and refits the best model on the full training portion by default. The parameter name uses the pipeline step name, a double underscore, then the parameter. make_pipeline names the ridge step ridge.
import numpy as np
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(60, 1))
y = np.sin(X).ravel() + rng.normal(0, 0.2, size=60)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
grid = np.logspace(-4, 2, 13)
pipe = make_pipeline(PolynomialFeatures(15), StandardScaler(), Ridge())
search = GridSearchCV(pipe, {"ridge__alpha": grid}, cv=5,
scoring="neg_mean_squared_error")
search.fit(X_train, y_train)
print("best alpha:", search.best_params_["ridge__alpha"])
print("CV MSE:", round(-search.best_score_, 3))
print("test MSE:", round(mean_squared_error(y_test, search.predict(X_test)), 3))The test error is computed once, after the choice is final. If you look at it and then adjust alpha again, the test set has become a second validation set and no longer gives an honest estimate.
Reading the CV results
The best score is not the only useful output. Look at the whole curve in search.cv_results_.
- Best value on the edge of the grid. The true optimum may lie outside. Extend the grid in that direction and search again.
- Flat curve. Many strengths perform about the same. Prefer the simpler, more strongly regularised one.
- Noisy curve. With small datasets, differences between neighbouring values are often smaller than the fold-to-fold spread. Repeated k-fold (
RepeatedKFold) gives steadier estimates.
The one-standard-error rule
A common way to handle a flat or noisy curve is to find the best mean CV error, then choose the strongest penalty whose mean error is within one standard error of it. This favours a simpler model when the data cannot tell the options apart.
mean_mse = -search.cv_results_["mean_test_score"]
std = search.cv_results_["std_test_score"]
best = mean_mse.argmin()
threshold = mean_mse[best] + std[best] / np.sqrt(5) # 5 folds
chosen = grid[mean_mse <= threshold].max()
print("1-SE alpha:", chosen)This works because grid is sorted and cv_results_ follows the grid order for a single parameter. Treat the rule as a convention rather than a theorem. It trades a little validation error for a model that is less likely to be overfitted to the CV folds.
Specialised helpers
For linear models, scikit-learn includes estimators that tune the penalty internally and often faster, because they reuse work across the alpha path.
RidgeCV(alphas=...)uses an efficient leave-one-out scheme by default.LassoCV(cv=5)builds its own alpha path and exposesalpha_after fitting.ElasticNetCV(l1_ratio=[...], cv=5)searches bothalphaandl1_ratio.
Put these inside the same pipeline as the scaler. They remove the need for a manual grid, but the test-set rule still applies.
Pitfalls
- Scaling outside the pipeline. Fitting a scaler on all data before cross-validation leaks validation statistics into training. Keep it in the pipeline.
- Tuned score is optimistic. The best CV score was selected as the best of many, so it is biased low in error. The untouched test set gives the honest number. For small data, nested cross-validation (an outer loop for evaluation, an inner loop for tuning) gives a fairer estimate.
- Unscaled features. Without scaling, one penalty strength acts very differently on features with different units, so the "best"
alphais misleading. - Sparsity depends on strength. For lasso, a larger
alphazeroes more coefficients. The CV-optimalalphaselects the best predictive model, and that may keep more features than you want for interpretation. - Neural networks. For weight decay, dropout rate, and early stopping patience, each trial is costly. Use a fixed validation split, search on a log scale for the weight decay, and tune one setting at a time.
Exercise
A grid search over alpha = 1e-4 ... 1e2 reports the best CV error at alpha = 100, the largest value. What should you do, and why?
Show answer
Extend the grid upward (for example to 1e4) and search again. The best value on the edge suggests the true optimum may be larger than any value tried. Do not use the test set to check; keep tuning with cross-validation on the training portion.
Exercise
Why does the training error cannot be used to select alpha, and which data should be used instead?
Show answer
Training error rises as alpha grows, because the penalty restricts the fit, so it always prefers the weakest penalty and rewards overfitting. Use cross-validation error computed on the training portion, and keep the test set for one final evaluation.