Sub topic 12
Early stopping and pruning: successive halving and Hyperband
This chapter assumes you know how grid and random search work, how cross-validation scores a setting, and what a scikit-learn estimator and pipeline are. Search methods so far spend the same effort on every trial. Most trials are poor, so much of that effort is wasted. Early stopping and pruning cut it.
The idea: spend little on bad settings
A budget here means any resource that makes a trial more accurate when you give it more: training samples, boosting rounds, epochs, or trees. A poor setting usually looks poor after a small budget. You can drop it early and give the saved compute to better settings.
Pruning means stopping a trial before it finishes because its intermediate scores are worse than other trials at the same point.
Successive halving
Successive halving works in rounds:
- Start many candidate settings with a small budget.
- Score them and keep the best fraction, usually the top 1/3 or 1/2.
- Give the survivors a larger budget.
- Repeat until one setting remains at the full budget.
The cost of each round stays similar, because fewer candidates get more budget each. scikit-learn provides HalvingGridSearchCV and HalvingRandomSearchCV. Both are still experimental, so you must enable them with an explicit import.
from sklearn.experimental import enable_halving_search_cv # noqa: F401
from sklearn.model_selection import HalvingRandomSearchCV, train_test_split
from scipy.stats import loguniform
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
param_distributions = {
"max_depth": [2, 4, 8, 16, None],
"min_samples_leaf": [1, 2, 5, 10],
"max_features": loguniform(0.05, 1.0),
}
search = HalvingRandomSearchCV(
RandomForestClassifier(random_state=0),
param_distributions,
factor=3,
resource="n_estimators",
max_resources=300,
min_resources=20,
cv=5,
random_state=0,
n_jobs=-1,
)
search.fit(X_train, y_train)
print(search.best_params_, search.best_score_)
print("Test accuracy:", search.score(X_test, y_test))Here factor=3 keeps one third of the candidates each round, and the budget is the number of trees. The default resource is the number of training samples. Only the training set is used for tuning, and the test set is scored once.
Hyperband
Successive halving needs you to choose how many candidates to start with. Starting many with tiny budgets is risky when a good setting learns slowly. Starting few with large budgets explores too little. Hyperband removes the choice by running several successive-halving runs, called brackets. Each bracket trades off the number of candidates against the starting budget. One bracket is aggressive, with many candidates and a very small budget. Another is conservative, with few candidates and a large budget. Hyperband then reports the best result from any bracket.
Pruning in Optuna
Optuna prunes inside a trial by reporting intermediate scores. A pruner compares them with those of earlier trials. This example prunes a model that trains in steps.
import optuna
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
import numpy as np
X, y = load_breast_cancer(return_X_y=True)
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
classes = np.unique(y)
def objective(trial):
alpha = trial.suggest_float("alpha", 1e-6, 1e-1, log=True)
model = SGDClassifier(alpha=alpha, random_state=0)
for step in range(20):
model.partial_fit(X_train, y_train, classes=classes)
score = model.score(X_val, y_val)
trial.report(score, step)
if trial.should_prune():
raise optuna.TrialPruned()
return score
study = optuna.create_study(
direction="maximize",
sampler=optuna.samplers.TPESampler(seed=0),
pruner=optuna.pruners.HyperbandPruner(min_resource=2, max_resource=20),
)
study.optimize(objective, n_trials=40)
print(study.best_params, study.best_value)Common errors
- Pruning on a misleading early score. Some settings, such as a low learning rate, start slowly and finish well. Aggressive pruning discards them. Use a larger minimum budget when you see this.
- Treating budgets as comparable when they are not. Scores at 100 samples are noisy and sit on a different scale from scores at 900. Compare candidates only within the same round.
- Using the test set for pruning decisions. Pruning scores must come from validation data or cross-validation.
Exercise
You start successive halving with 27 candidates and factor=3. How many candidates remain after each round, and how many rounds are needed to reach one candidate?
Show answer
The counts are 27, 9, 3, 1. That is three halving steps after the first round, so four rounds in total, with the last round at the full budget.