Sub topic 16
Choosing alpha with RidgeCV and GridSearchCV
This chapter assumes you can fit a Ridge model, build a Pipeline with StandardScaler, and run cross_val_score. You should also know why a test set must stay untouched until the end. Here you will learn to pick the regularization strength alpha without leaking test data.
Why alpha needs tuning
alpha is a hyperparameter. It is a setting you choose before fitting, and the fit does not learn it from the data.
- With
alphanear 0, Ridge behaves like ordinary least squares and can overfit. - With a very large
alpha, the coefficients shrink toward zero and the model underfits. - The best value depends on your data, so you estimate it from data that is not the final test set.
A single train/validation split gives a noisy answer. Cross-validation gives a steadier one. Scikit-learn offers two main tools for this: RidgeCV for Ridge only, and GridSearchCV for any estimator.
The search workflow
Both tools follow the same pattern. Split off a test set first. Search for the best setting using only the training portion. Refit on all the training data. Score once on the test set.
RidgeCV: the shortcut for Ridge
RidgeCV takes a list of candidate alphas and picks the best one. By default (cv=None) it uses an efficient form of leave-one-out cross-validation. That form exploits the closed-form Ridge solution, so it costs about as much as one fit, not one fit per sample.
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import RidgeCV
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
pipe = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 3, 13)))
pipe.fit(X_train, y_train)
print("chosen alpha:", pipe[-1].alpha_)
print("test R2:", pipe.score(X_test, y_test))The fitted RidgeCV step stores the winner in alpha_. Index the pipeline with pipe[-1] to reach it.
Two details matter:
- Pass
cv=5to use ordinary k-fold instead of the leave-one-out shortcut. This is slower but lets you choose ascoringmetric such as"neg_mean_absolute_error". - The scaler sits outside
RidgeCV, so it is fitted on all training rows before the internal leave-one-out loop runs. This leaks a little information between those internal folds. It cannot reach the test set, and for standardization the effect is usually tiny. If you need strict isolation, useGridSearchCVaround the whole pipeline, as below.
GridSearchCV: tune anything
GridSearchCV tries every combination in a parameter grid. For each combination it runs k-fold cross-validation, and it keeps the combination with the best mean score. It works with any estimator, including a whole pipeline.
To address a parameter inside a pipeline, write stepname__parametername with two underscores.
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
pipe = Pipeline([
("scale", StandardScaler()),
("model", Ridge()),
])
param_grid = {"model__alpha": np.logspace(-3, 3, 13)}
search = GridSearchCV(
pipe,
param_grid,
cv=5,
scoring="neg_root_mean_squared_error",
)
search.fit(X_train, y_train)
print("best params:", search.best_params_)
print("CV RMSE:", -search.best_score_)
print("test RMSE:", -search.score(X_test, y_test))Because the scaler is inside the pipeline, it is refitted on each training fold. Each validation fold never influences the scaling.
Reading the results
best_params_holds the winning parameter values.best_score_is the mean cross-validated score of the winner.best_estimator_is the pipeline refitted on the full training set. This is on by default (refit=True), andsearch.predictandsearch.scoreuse it.cv_results_holds every combination's mean and standard deviation of score, which you can load into a pandas DataFrame.
import pandas as pd
results = pd.DataFrame(search.cv_results_)
print(
results[["param_model__alpha", "mean_test_score", "std_test_score"]]
.sort_values("mean_test_score", ascending=False)
.head()
)Scores are negated
Scikit-learn assumes that a higher score is better. Error metrics are therefore exposed as negative values, such as neg_mean_squared_error and neg_root_mean_squared_error. Negate them to get the familiar error. Forgetting this leads to reading "-54.2" as a bad score when it is a good one.
Choosing the grid
Alpha effects are multiplicative, so search on a log scale. np.logspace(-3, 3, 13) gives values from 0.001 to 1000, four per decade.
Check whether the best value sits at an edge of the grid. If best_params_ shows the smallest or largest alpha you tried, the true optimum may lie outside the range. Extend the grid in that direction and search again.
A common approach is coarse and then fine. Run a wide grid first. Then run a narrow one around the winner, for example np.logspace(-1, 1, 21).
Tuning more than one parameter
Grids multiply. ElasticNet has two settings: alpha and l1_ratio. The ratio controls the mix of L1 and L2 penalties.
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import ElasticNet
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
pipe = Pipeline([
("scale", StandardScaler()),
("model", ElasticNet(max_iter=10000)),
])
param_grid = {
"model__alpha": np.logspace(-3, 1, 9),
"model__l1_ratio": [0.1, 0.5, 0.9],
}
search = GridSearchCV(pipe, param_grid, cv=5, scoring="r2", n_jobs=-1)
search.fit(X_train, y_train)
print(search.best_params_)
print("test R2:", search.score(X_test, y_test))This grid has 9 × 3 = 27 combinations. With cv=5 that is 135 fits. Cost grows fast as you add parameters, so use n_jobs=-1 to run fits in parallel. For large grids, consider RandomizedSearchCV, which samples a fixed number of combinations.
Which tool to use
| Situation | Tool |
|---|---|
| Ridge only, one alpha | `RidgeCV` |
| Lasso or ElasticNet with one alpha | `LassoCV` or `ElasticNetCV` |
| Several hyperparameters or several model types | `GridSearchCV` |
| Strict isolation of preprocessing in every fold | `GridSearchCV` around a `Pipeline` |
Common errors
- Tuning on the test set. Never pass test data to the search. The test score is only honest if the test set played no part in any choice.
- Reporting
best_score_as final performance. It is the maximum over many noisy estimates, so it is slightly optimistic. Report the test score instead. - Wrong parameter name.
alphaalone raises an error on a pipeline. Usemodel__alpha, and check valid names withpipe.get_params().keys(). - Fitting the scaler outside the search. Scaling the full training set before
GridSearchCVleaks each validation fold's statistics into training. - Ignoring spread. If
std_test_scoreis larger than the gap between neighbouring alphas, the data cannot tell them apart. Prefer the larger alpha, which gives the simpler model.
Exercise
You run GridSearchCV over alphas np.logspace(-3, 3, 13) and bestparams reports the largest value, 1000. What should you do next, and why?
Show answer
Extend the grid upward, for example to np.logspace(-3, 5, 17), and search again. A winner at the edge means the true optimum may lie beyond the range you tried. If the best alpha stays at the edge even after extending, check whether the features carry any signal, because a huge alpha shrinks all coefficients toward zero and the model then predicts close to the mean.
Exercise
Why does the pipeline ("scale", StandardScaler()), ("model", Ridge()) go inside GridSearchCV instead of scaling X_train first and passing the scaled array?
Show answer
Inside the search, the scaler is refitted on each training fold, so the validation fold's mean and standard deviation never influence training. Scaling X_train beforehand uses statistics from all training rows, including those later used for validation, which leaks information and makes the cross-validated scores slightly optimistic.