Sub topic 14
Tuning Hyperparameters
This chapter assumes you can build a scikit-learn Pipeline, that you know how k-fold cross-validation works, and that you have a held-out test set you have not touched. Tuning is the step that uses all three.
Parameters and hyperparameters
A model has two kinds of settings:
- Parameters are learned from data during
fit. Examples are the coefficients of a logistic regression and the split thresholds of a tree. - Hyperparameters are chosen by you before
fitruns. Examples are the regularization strengthC, the tree depthmax_depth, and the number of treesn_estimators.
Tuning means trying several hyperparameter settings and keeping the one that generalizes best. "Generalizes best" must be measured on data the model was not fitted on, and it must not be the test set. If you pick settings by looking at test scores, the test set becomes a second validation set and the final score is optimistic.
Where tuning fits
Tuning runs entirely inside the training data. Cross-validation supplies the validation folds, so you do not need a separate validation split.
The search objects GridSearchCV and RandomizedSearchCV carry out the first five boxes. The last box is yours to run, once.
Grid search on a pipeline
GridSearchCV tries every combination in a grid. When the estimator is a pipeline, you address a step's hyperparameter as stepname__param, with two underscores. Because the whole pipeline is cloned and refit for each fold, the scaler is fitted on the training part of each fold only. That prevents leakage during tuning.
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
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)),
])
param_grid = {"clf__C": [0.001, 0.01, 0.1, 1, 10, 100]}
search = GridSearchCV(model, param_grid, cv=5, scoring="f1", n_jobs=-1)
search.fit(X_train, y_train)
print(search.best_params_, round(search.best_score_, 3))
results = pd.DataFrame(search.cv_results_)[
["param_clf__C", "mean_test_score", "std_test_score", "rank_test_score"]
]
print(results.sort_values("rank_test_score").to_string(index=False))After the search, three attributes matter:
best_params_holds the winning combination.best_score_is the mean cross-validated score of that combination.best_estimator_is the pipeline refit on the whole training set with those settings. This happens becauserefit=Trueis the default, sosearch.predict(...)already uses it.
Look at cv_results_, not only the winner. If the top three candidates differ by less than one std_test_score, the data cannot tell them apart. In that case prefer the simplest one, which for C means the smallest value, because it regularizes most.
Random search for larger spaces
A grid grows multiplicatively. Three hyperparameters with ten values each means 1,000 candidates, and with 5-fold cross-validation that is 5,000 fits. RandomizedSearchCV instead draws n_iter candidates from distributions, so cost is fixed by you. It often finds a comparable score because usually only one or two hyperparameters matter much, and random draws test more distinct values of those than a grid does.
from scipy.stats import randint
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import RandomizedSearchCV, train_test_split
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
)
distributions = {
"n_estimators": randint(100, 400),
"max_depth": randint(2, 12),
"min_samples_leaf": randint(1, 10),
}
search = RandomizedSearchCV(
RandomForestClassifier(random_state=0),
distributions,
n_iter=20,
cv=5,
scoring="f1",
random_state=0,
n_jobs=-1,
)
search.fit(X_train, y_train)
print(search.best_params_, round(search.best_score_, 3))Set random_state on both the estimator and the search, or your results will change between runs.
For scale-type hyperparameters such as C or a learning rate, sample on a log scale (scipy.stats.loguniform(1e-3, 1e2)). A uniform draw from 0 to 100 would almost never try small values.
| Method | Cost | Best when |
|---|---|---|
| `GridSearchCV` | Product of all value counts | One or two hyperparameters, a few values each |
| `RandomizedSearchCV` | `n_iter` candidates | Three or more hyperparameters, or continuous ranges |
Common errors
- Tuning on the test set. Call
fiton the search withX_trainonly. ScoreX_testafter the search finishes, and only once. - Scaling before the search. If you scale the full training set and then pass it to the search, each validation fold has influenced the scaler. Put the scaler in the pipeline.
- Winner at the edge of the grid. If the best
Cis the largest value you tried, the true optimum may lie outside. Extend the range and rerun. - Wrong metric.
scoringdefaults to accuracy for classifiers. On imbalanced data, pass the metric you chose earlier, such as"f1"or"roc_auc". - Treating
best_score_as the final estimate. It is the maximum over many noisy scores, so it is biased upward. This is called selection bias. The more candidates you try, the larger the bias. - Leaving the pipeline's
n_jobsand fit time unchecked. Candidates times folds is the number of fits. Estimate this before you start a long run.
Estimating the selection bias with nested cross-validation
If you want an honest estimate without spending the test set, wrap the whole search in an outer cross-validation. Each outer fold runs a complete inner search on its own training part and scores the result on its own held-out part.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
model = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
inner = GridSearchCV(
model, {"clf__C": [0.01, 0.1, 1, 10]},
cv=StratifiedKFold(5, shuffle=True, random_state=1), scoring="f1",
)
outer = StratifiedKFold(5, shuffle=True, random_state=2)
scores = cross_val_score(inner, X, y, cv=outer, scoring="f1")
print(scores.mean().round(3), scores.std().round(3))This costs the number of outer folds times the cost of one search, so use it to compare modeling approaches, not for every run. Once you have decided on the approach, run a normal search on the training set and evaluate once on the test set.
Practical limits
Tuning usually gives smaller gains than better features or more data. Expect a few points at most for well-regularized linear models. If a search moves the score by less than the fold-to-fold standard deviation, the improvement is probably noise. Stop tuning at that point, keep the simpler model, and move on to the final evaluation.
Exercise
You run a grid search and best_score_ is 0.97 F1. You then score the refit model on the test set and get 0.93. Is something wrong, and what should you report?
Show answer
Nothing is necessarily wrong. best_score_ is the maximum over many candidates, so it is optimistically biased, and a drop of a few points on unseen data is expected. Report the test-set score (0.93) as the performance estimate. If the gap were large, check for leakage outside the pipeline or a search space that is too large for the amount of data.
Exercise
A random search for a learning rate samples from uniform(0, 1). Why is this a poor choice, and what would you use instead?
Show answer
Useful learning rates often span several orders of magnitude, such as 0.001 to 0.1. A uniform draw puts about 90 percent of samples above 0.1 and rarely tries small values. Use a log-uniform distribution such as loguniform(1e-4, 1).