Sub topic 12
Early stopping and pruning: successive halving and Hyperband
This chapter assumes you can run GridSearchCV and RandomizedSearchCV, know what cross-validation does, and understand that a model's training cost grows with resources such as epochs, trees, or training samples. The chapter covers how to stop weak trials early so the same compute budget tests more settings.
Why stop trials early
Grid search and random search treat every trial equally. Each setting trains to completion, even when its first few iterations show it will finish near the bottom. If 100 settings each take 10 minutes, that is about 17 hours, and most of it goes to settings that were clearly poor after the first minute.
Early stopping methods spend a small amount of compute on many settings and a large amount on only a few. The idea depends on one assumption: performance after a small budget predicts performance after a large budget, at least well enough to rank settings.
Two terms are used throughout this chapter:
- A resource is the quantity you can increase to spend more compute on one trial. Examples are the number of boosting rounds, training epochs, or the number of training samples.
- Pruning means abandoning a running trial before it reaches the full resource because its intermediate score is unpromising.
Early stopping inside a single model
Some models already include early stopping. It watches a validation score during training and stops once the score no longer improves. This is different from pruning, which compares trials with each other. Early stopping looks at one trial's own history.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import train_test_split
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
)
model = HistGradientBoostingClassifier(
max_iter=1000,
early_stopping=True,
validation_fraction=0.15,
n_iter_no_change=10,
random_state=0,
)
model.fit(X_train, y_train)
print("Rounds actually used:", model.n_iter_)
print("Test accuracy:", model.score(X_test, y_test))Here max_iter=1000 is an upper limit, not a setting you must tune carefully. The model holds out 15% of the training data internally and stops after 10 rounds without improvement. Treat max_iter as a budget and let early stopping choose the real number of rounds.
Early stopping has a cost. The internal validation split is carved out of the training data, so the model trains on less data. The stopping point is also chosen using that split, so its score is slightly optimistic. Keep your test set out of this process entirely.
Successive halving
Successive halving runs a tournament. It starts many candidates on a small resource, keeps the best fraction, gives the survivors more resource, and repeats.
The procedure has three parameters:
- The number of starting candidates,
n. - The minimum resource each candidate receives in the first round,
r_min. - The reduction factor,
eta(often 3). Each round keeps the top1/etaof candidates and multiplies the resource byeta.
With n = 27, r_min = 1, and eta = 3, the rounds look like this:
| Round | Candidates | Resource each | Total resource |
|---|---|---|---|
| 0 | 27 | 1 | 27 |
| 1 | 9 | 3 | 27 |
| 2 | 3 | 9 | 27 |
| 3 | 1 | 27 | 27 |
Every round costs the same, 27 units, so the whole tournament costs 108 units. Training 27 candidates to the full resource of 27 would cost 729 units. That is a saving of roughly 85%.
Successive halving in scikit-learn
scikit-learn provides HalvingGridSearchCV and HalvingRandomSearchCV. They are still marked experimental, so you must enable them with an extra import.
from scipy.stats import loguniform
from sklearn.datasets import load_breast_cancer
from sklearn.experimental import enable_halving_search_cv # noqa: F401
from sklearn.model_selection import HalvingRandomSearchCV, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
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
)
pipe = make_pipeline(StandardScaler(), SVC())
param_distributions = {
"svc__C": loguniform(1e-2, 1e2),
"svc__gamma": loguniform(1e-4, 1e0),
}
search = HalvingRandomSearchCV(
pipe,
param_distributions,
n_candidates=60,
factor=3,
resource="n_samples",
min_resources=40,
cv=5,
random_state=0,
n_jobs=-1,
)
search.fit(X_train, y_train)
print(search.best_params_, search.best_score_)
print("Resource per round:", search.n_resources_)
print("Candidates per round:", search.n_candidates_)
print("Test accuracy:", search.score(X_test, y_test))Here the resource is the number of training samples. Early rounds fit each candidate on a small subset, and later rounds use more rows. The attributes n_resources_ and n_candidates_ show how the tournament shrank.
To halve on a model setting instead of on sample count, name that setting in resource, for example resource="n_estimators" with max_resources=300. Then include that setting in the estimator but not in the search space.
Weaknesses of successive halving
Successive halving makes a bet that early rankings hold up. That bet fails in predictable ways:
- Slow starters. A model with a small learning rate and strong regularization may look poor at 1 epoch and be the best at 100. Halving can discard it in round 0.
- Small samples are noisy. With 40 rows, cross-validation scores vary a lot, so the ranking in early rounds is partly luck.
- Rankings change with size. A flexible model, such as a deep tree or a high-
gammaSVM, can overfit a small subset and look worse than a simple model. With more data the order may reverse. - Class imbalance. A small subset may contain few or no minority-class rows. Use stratified splits and a
min_resourcesvalue large enough to cover every class.
The best score reported by a halving search comes from the final round, where fewer candidates were evaluated on more data. Scores from different rounds are not comparable, so do not compare a round-0 score with a final-round score.
Hyperband
Successive halving forces a choice you cannot easily make: how many candidates to start with, given a fixed budget. Many candidates with a tiny starting resource gives broad coverage but noisy early ranking. Few candidates with a larger starting resource gives reliable ranking but less coverage.
Hyperband removes the choice by running several successive halving tournaments, called brackets, that make different trade-offs. The most aggressive bracket starts with many candidates at the smallest resource. The least aggressive bracket is plain training: few candidates, each at the full resource. The brackets in between fall on a spectrum. The final answer is the best result across all brackets.
| Bracket | Starting candidates | Starting resource | Behavior |
|---|---|---|---|
| Aggressive | Many | Small | Broad, but trusts early scores |
| Middle | Some | Medium | Balanced |
| Conservative | Few | Full | No early pruning |
If slow starters exist in your problem, the conservative brackets still give them a fair run. If early scores are reliable, the aggressive bracket finds good settings cheaply.
Hyperband samples its candidates at random, so it does not learn from earlier trials. Later methods such as BOHB combine Hyperband's brackets with a Bayesian sampler that proposes candidates. Optuna offers HyperbandPruner for this purpose.
Pruning in Optuna
Optuna implements pruning by letting a trial report intermediate scores. The pruner compares the report with those of earlier trials at the same step and raises an exception to stop a trial that lags.
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
)
mean, std = X_train.mean(axis=0), X_train.std(axis=0)
X_train = (X_train - mean) / std
X_val = (X_val - mean) / std
classes = np.unique(y_train)
def objective(trial):
alpha = trial.suggest_float("alpha", 1e-6, 1e-1, log=True)
model = SGDClassifier(alpha=alpha, random_state=0)
for epoch in range(30):
model.partial_fit(X_train, y_train, classes=classes)
score = model.score(X_val, y_val)
trial.report(score, step=epoch)
if trial.should_prune():
raise optuna.TrialPruned()
return score
study = optuna.create_study(
direction="maximize",
sampler=optuna.samplers.TPESampler(seed=0),
pruner=optuna.pruners.SuccessiveHalvingPruner(),
)
study.optimize(objective, n_trials=40)
states = [t.state.name for t in study.trials]
print("Pruned trials:", states.count("PRUNED"))
print("Completed trials:", states.count("COMPLETE"))
print(study.best_params, study.best_value)The model must be trainable in steps for this to work. partial_fit gives one epoch per call. Models that fit in a single call, such as an SVM, can only be pruned by varying the sample count, as in the scikit-learn halving search above.
The standardization statistics come from the training portion only, which follows the leakage rules from the earlier chapter. In a real project, put the scaler in a pipeline.
Choosing a method
| Situation | Reasonable choice |
|---|---|
| Model trains in one call and is fast | Plain random search |
| Many candidates, one cost-driving resource such as sample count | `HalvingRandomSearchCV` |
| Iterative model such as boosting or a neural network | Optuna pruner with `report` |
| Learning curves cross, or slow starters are likely | Hyperband, or a larger minimum resource |
| Very noisy scores | Larger minimum resource, or no pruning |
A sensible default is to set the minimum resource so that the cheapest round still gives a stable score. If two runs of the same setting with different seeds differ more than the gaps between settings, pruning at that resource will mostly remove candidates by chance.
Exercise
A halving search starts with 81 candidates, a minimum resource of 2 units, and a reduction factor of 3. How many candidates and how many units per candidate does the third round (round 2, counting from round 0) use, and what is the total resource spent in that round?
Show answer
Round 0 has 81 candidates at 2 units. Round 1 has 27 candidates at 6 units. Round 2 has 9 candidates at 18 units, so the round spends 9 × 18 = 162 units, the same as every other round (81 × 2 = 162).
Exercise
A team prunes a boosting study at 5 rounds and finds the best final models all used a very low learning rate. Why might pruning have hurt them, and what two changes could help?
Show answer
Low learning rates improve slowly, so after 5 rounds they trail higher-rate models and get pruned as slow starters. Raise the minimum resource so pruning starts later, or use Hyperband, whose conservative brackets run some candidates to full resource without pruning.