Sub topic 16
Choosing alpha with RidgeCV and GridSearchCV
This chapter assumes you can fit a Ridge model, build a Pipeline, and run cross_val_score. Ridge has one setting you choose yourself, alpha. Settings like this are called hyperparameters. Here you will pick alpha from the training data only.
Why alpha needs tuning
alpha sets how strongly Ridge shrinks coefficients. A very small alpha behaves like plain least squares and can overfit. A very large alpha pushes coefficients toward zero and underfits. The best value depends on the data, so you search for it.
Do not choose alpha by checking the test set. If you do, the test score is no longer an honest estimate. Choose alpha with cross-validation on the training data. Touch the test set once, at the end.
RidgeCV: the fast path
RidgeCV takes a list of candidate values and picks the best one. By default it uses an efficient form of leave-one-out cross-validation, which is cheaper than refitting for every fold. Candidates are usually spaced on a log scale, because alpha matters in orders of magnitude.
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 chosen value is stored in alpha_, with a trailing underscore, because it is learned during fit.
GridSearchCV: the general tool
GridSearchCV works with any estimator and any metric. It runs k-fold cross-validation for every combination in a parameter grid. It then refits the best model on the whole training set.
In a pipeline, address a parameter as step__parameter. make_pipeline names each step after its lowercase class name, so Ridge is ridge.
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 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(), Ridge())
grid = GridSearchCV(
pipe,
param_grid={"ridge__alpha": np.logspace(-3, 3, 13)},
cv=5,
scoring="neg_root_mean_squared_error",
)
grid.fit(X_train, y_train)
print("best params:", grid.best_params_)
print("best CV RMSE:", -grid.best_score_)
print("test RMSE:", -grid.score(X_test, y_test))Scorers follow a "higher is better" rule. Error metrics are therefore negated, which is why the code prints -grid.best_score_.
Common errors
- Tuning on the test set. Fit the search on
X_trainonly. - Scaling outside the pipeline. Scaling the full data first leaks fold information into validation. Keep the scaler inside the pipeline so it is refit per fold.
- A linear grid. Values like 1, 2, 3 miss the useful range. Use
np.logspace. - A best value at the grid edge. If the winner is the smallest or largest candidate, widen the grid.
- A wrong parameter name.
alphaalone raises an error in a pipeline. Useridge__alpha.
Exercise
Your GridSearchCV reports bestparams of {"ridge__alpha": 1000.0}, and 1000.0 is the largest value in your grid. What should you do, and why?
Show answer
Extend the grid upward, for example to np.logspace(-3, 5, 17), and rerun the search. A winner at the edge suggests the true optimum may lie beyond the grid, so the search has not found it yet.