Sub topic 14
Tuning hyperparameters
This chapter assumes you can build a scikit-learn Pipeline, you know how cross_val_score works, and you have already split off a test set that you have not touched.
Parameters and hyperparameters
A model learns parameters from data. In logistic regression these are the coefficients. A hyperparameter is a setting you choose before training, such as the regularization strength C. The model cannot learn it from the training data, so you try several values and compare them.
Tune with cross-validation, not the test set
Each candidate value needs a score. Compute that score with cross-validation on the training data. If you scored candidates on the test set, you would pick the value that happens to fit the test set best. The test score would then be too optimistic, which is a form of leakage. The test set is for one final report, covered in the next chapter.
Grid search with a pipeline
GridSearchCV tries every combination in a grid. It runs cross-validation for each one and keeps the best. Inside a pipeline, address a step's hyperparameter as stepname__parameter, with two underscores.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
model = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
grid = {"clf__C": [0.01, 0.1, 1, 10, 100]}
search = GridSearchCV(model, grid, cv=5, scoring="f1")
search.fit(X_train, y_train)
print("best params:", search.best_params_)
print("best CV F1:", search.best_score_)
# Check the test set once, after tuning is finished.
print("test F1:", f1_score(y_test, search.predict(X_test)))Because the scaler is inside the pipeline, it is refitted on each training fold. The validation fold never influences the scaling.
After the search, GridSearchCV refits the best configuration on the whole training set by default (refit=True). So search.predict is ready to use.
Common errors
- Tuning on the test set. Any choice made by looking at test scores uses the test set up. Keep it for the end.
- Trusting
best_score_as final. It is the maximum over several candidates, so it is slightly optimistic. - Scoring with the wrong metric.
scoring="f1"ranks candidates by F1. The default, accuracy, may pick a different winner on imbalanced data. - Grids that are too large. The cost is the number of combinations times the number of folds. For many hyperparameters,
RandomizedSearchCVsamples a fixed number of combinations and is often enough. - Best value on the grid edge. If the best
Cis the largest value you tried, extend the grid in that direction.
Exercise
You run GridSearchCV and get bestscore of 0.97. The test F1 is 0.95. Is something wrong, and why can you not use the test score to choose between two further grids?
Show answer
Nothing is necessarily wrong. bestscore is the best of several cross-validated scores, so it is mildly optimistic, and a small gap to the test score is normal. You should not use the test score to choose between grids, because each choice based on it makes the test set part of model selection. It would then no longer give an unbiased estimate. Compare grids with cross-validation on the training data instead.