Sub topic 9
Choosing the number of rounds with early stopping
This chapter assumes you can train an XGBClassifier or XGBRegressor, know what learning_rate and max_depth do, and understand a train/validation split. You should also know that a boosted model adds one tree per round, and that too many rounds make it overfit.
Why the number of rounds is a special hyperparameter
In gradient boosting, every round adds a tree that reduces the training loss. Training loss therefore falls with each round and never turns back up. Validation loss behaves differently. It falls at first, flattens, and then rises once the new trees start fitting noise in the training set.
The number of rounds (n_estimators in the scikit-learn API, num_boost_round in the native API) controls where you stop on that curve. It also interacts with the learning rate. A smaller learning_rate needs more rounds to reach the same fit. Tuning the two together by grid search is slow, because every grid point needs a full training run.
Early stopping avoids that cost. You set the round limit high, watch a metric on held-out data after every round, and stop when the metric has not improved for a fixed number of rounds.
How the stopping rule works
After each round, XGBoost computes the evaluation metric on the evaluation set. It remembers the best score and the round that produced it. If the score fails to improve for early_stopping_rounds consecutive rounds, training stops.
Three consequences follow:
- Training always runs
best_iteration + early_stopping_roundsrounds, unless it reaches the cap first. With a patience of 30 and a best round of 212, you train 242 trees. - The model object contains all trees that were trained, including the 30 that did not help. Whether predictions use only the best ones depends on the API and version, covered below.
- The patience value trades off noise against compute. A small value (5 to 10) can stop on a random bump in a noisy validation curve. A large value (50 to 100) wastes time but is safer with a low learning rate.
Early stopping with the scikit-learn API
In current XGBoost releases (2.x), early_stopping_rounds is a constructor argument. In older releases it was an argument to fit, and that form is deprecated and removed in recent versions. If you copy older code and see a TypeError about fit, this is the reason.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
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.2, stratify=y, random_state=0
)
model = XGBClassifier(
n_estimators=1000,
learning_rate=0.05,
max_depth=3,
subsample=0.8,
colsample_bytree=0.8,
eval_metric="logloss",
early_stopping_rounds=30,
)
model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=False)
print(model.best_iteration, model.score(X_val, y_val))Here n_estimators=1000 is a ceiling, not a target. best_iteration is the zero-based index of the best round, so the best model has best_iteration + 1 trees. When early stopping is active, predict and predict_proba use trees up to the best iteration by default in recent versions, so you do not need to slice the model yourself.
Inspecting the learning curve
eval_set can hold several datasets, and evals_result() returns the metric history for each. This lets you plot the curve and see the overfitting point.
results = model.evals_result()
curve = results["validation_0"]["logloss"]
print(len(curve), min(curve), curve.index(min(curve)))The length of curve equals best_iteration + 30 + 1 when training stopped early. The index of the minimum should equal best_iteration.
Which dataset and metric decide when to stop
Two details cause most early stopping mistakes.
First, if eval_set has more than one dataset, XGBoost uses the last one for the stopping decision. Put the dataset you want to monitor last, and put the training set first if you also want to log it.
Second, if you pass several metrics in eval_metric, the last metric is used for stopping. The others are only reported.
| Situation | Which one is used for stopping |
|---|---|
| `eval_set=[(X_train, y_train), (X_val, y_val)]` | The validation set (the last entry) |
| `eval_metric=["auc", "logloss"]` | `logloss` (the last metric) |
| No `eval_metric` given | The default for the objective, such as `logloss` for binary classification |
Choose the metric that matches what you care about. Log loss rewards calibrated probabilities. AUC only measures ranking. A model can have a falling log loss and a flat AUC, so the two metrics can pick different stopping points.
The validation set is no longer a clean test set
Early stopping uses the validation set to choose the number of trees. That makes the validation score slightly optimistic, because the stopping point was selected to look good on exactly that data. The model.score(X_val, y_val) line in the example is therefore not an unbiased estimate of performance on new data.
For a trustworthy final number, split the data three ways: train, validation (for early stopping and tuning), and test (used once at the end).
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
X, y = load_breast_cancer(return_X_y=True)
X_rest, X_test, y_rest, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
X_train, X_val, y_train, y_val = train_test_split(
X_rest, y_rest, test_size=0.25, stratify=y_rest, random_state=0
)
model = XGBClassifier(
n_estimators=1000, learning_rate=0.05, max_depth=3,
eval_metric="logloss", early_stopping_rounds=30,
)
model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=False)
print("best iteration:", model.best_iteration)
print("test accuracy:", model.score(X_test, y_test))Early stopping in the native API
With xgb.train, pass evals and early_stopping_rounds. The returned Booster has best_iteration and best_score.
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
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.2, stratify=y, random_state=0
)
dtrain = xgb.DMatrix(X_train, label=y_train)
dval = xgb.DMatrix(X_val, label=y_val)
params = {
"objective": "binary:logistic",
"eval_metric": "logloss",
"eta": 0.05,
"max_depth": 3,
}
booster = xgb.train(
params,
dtrain,
num_boost_round=1000,
evals=[(dtrain, "train"), (dval, "val")],
early_stopping_rounds=30,
verbose_eval=False,
)
print(booster.best_iteration, booster.best_score)
preds = booster.predict(dval, iteration_range=(0, booster.best_iteration + 1))The iteration_range argument makes the intent explicit: predict with trees from round 0 up to and including the best one. The range end is exclusive, hence the + 1. Being explicit is a good habit, because the default behavior has differed between versions.
Common errors and edge cases
- Stopping too early with a high learning rate. With
learning_rate=0.3the curve is steep and noisy, so a short patience can end training prematurely. Lower the rate before raising the patience. - Reaching the cap. If
best_iterationequalsn_estimators - 1, the validation metric was still improving. Increasen_estimatorsand train again. - Training on the full data afterward. If you refit on train plus validation, you have no validation set left to stop on. Set
n_estimatorsto roughlybest_iteration + 1, often scaled up by 10 to 20 percent because there is more data. - Leaking through the validation set. Do not tune many hyperparameters against one validation set and then report that score as your final result.
- A tiny validation set. The metric is noisy, so the chosen round varies from run to run. Cross-validation, covered in a later chapter, gives a steadier estimate.
- Not stratifying a classification split. A validation set with few positives produces a jumpy metric and unstable stopping.
Exercise
A model is trained with nestimators=500, earlystoppingrounds=20, and training stops with bestiteration=140. How many trees were trained in total, how many trees are in the best model, and what does it suggest if best_iteration were 499 instead?
Show answer
Training ran 140 + 20 + 1 = 161 rounds, because bestiteration is zero-based (round 140 is the 141st tree) and 20 further rounds failed to improve on it. The best model uses bestiteration + 1 = 141 trees. If bestiteration were 499, the validation metric was still improving when the cap was hit, so nestimators is too low. Raise it (or raise the learning rate) and train again.
Exercise
You call fit with evalset=[(Xval, yval), (Xtrain, ytrain)] and evalmetric=["auc", "logloss"]. Which dataset and metric control stopping, and how would you change the call to stop on validation AUC?
Show answer
The last dataset (the training set) and the last metric (logloss) control stopping, which is almost never what you want, because training loss keeps falling and stopping rarely triggers. Reorder to evalset=[(Xtrain, ytrain), (Xval, yval)] and evalmetric=["logloss", "auc"], or pass only eval_metric="auc". Validation AUC then decides when to stop.