Sub topic 7
Early stopping and controlling overfitting
This chapter assumes you know what overfitting is, how a train/validation split works, and what RMSE, log loss and AUC measure. It also assumes you have read the chapter on how gradient boosted trees work, so you know that each new tree is fitted to the gradients of the loss and added to the ensemble.
Why boosting overfits
Boosting adds trees one at a time. Each tree reduces the training loss a little, so training loss falls with every round. Validation loss falls at first, then flattens, then rises once the model starts fitting noise in the training rows.
The number of trees is therefore a complexity setting, not just a cost setting. Too few trees underfit. Too many overfit. Early stopping chooses the number of trees from the data instead of from a guess.
How early stopping works
You give the library a validation set and a patience value, called stopping_rounds in LightGBM and early_stopping_rounds in CatBoost. After every round the library computes the validation metric. If the metric has not improved for patience rounds in a row, training stops. The model then reports the round with the best score as its best iteration.
Two details matter in practice.
- Direction of the metric. RMSE and log loss are better when lower. AUC is better when higher. LightGBM and CatBoost know the direction of their built-in metrics. A custom metric must declare it.
- Patience versus learning rate. A small learning rate makes progress per round small and noisy, so it needs more patience. A patience of 50 is a common default with a learning rate near 0.05 to 0.1. With a learning rate of 0.01, a patience of 200 or more is safer.
Early stopping in LightGBM
The scikit-learn API passes the validation set through eval_set and early stopping through a callback. Set n_estimators high, because early stopping decides the real count.
import lightgbm as lgb
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
X, y = fetch_california_housing(return_X_y=True, as_frame=True)
X_train, X_valid, y_train, y_valid = train_test_split(
X, y, test_size=0.2, random_state=0
)
model = lgb.LGBMRegressor(n_estimators=2000, learning_rate=0.05, num_leaves=31)
model.fit(
X_train,
y_train,
eval_set=[(X_valid, y_valid)],
eval_metric="rmse",
callbacks=[lgb.early_stopping(stopping_rounds=50), lgb.log_evaluation(100)],
)
print(model.best_iteration_)After fit, predict uses the best iteration automatically. The log shows the validation RMSE every 100 rounds, and best_iteration_ holds the winning round.
When you pass several validation sets, or several metrics, LightGBM by default checks all of them and stops when any one of them stops improving. Set first_metric_only=True in the early stopping callback if only the first metric should decide. Training data included in eval_set is ignored for stopping purposes.
Early stopping in CatBoost
CatBoost takes the validation data as a Pool and the patience as a fit argument.
import numpy as np
import pandas as pd
from catboost import CatBoostClassifier, Pool
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
n = 5000
df = pd.DataFrame({
"age": rng.integers(18, 70, n),
"city": rng.choice(["A", "B", "C", "D"], n),
"plan": rng.choice(["free", "basic", "pro"], n),
})
signal = (df["plan"] == "pro") | (df["age"] > 55)
flip = rng.random(n) < 0.1
y = (signal ^ flip).astype(int)
X_train, X_valid, y_train, y_valid = train_test_split(
df, y, test_size=0.2, random_state=0
)
cat_features = ["city", "plan"]
train_pool = Pool(X_train, y_train, cat_features=cat_features)
valid_pool = Pool(X_valid, y_valid, cat_features=cat_features)
model = CatBoostClassifier(
iterations=1000,
learning_rate=0.1,
depth=6,
eval_metric="AUC",
verbose=100,
)
model.fit(train_pool, eval_set=valid_pool, early_stopping_rounds=50)
print(model.get_best_iteration())By default CatBoost keeps the model at the best iteration and discards the later trees, because use_best_model is true whenever an eval_set is given. Set use_best_model=False if you want to keep every tree.
The validation set is no longer a clean test
Early stopping picks the best round using the validation set. That choice is a form of fitting, so the validation score is slightly optimistic. The more you tune against the same validation set, the more optimistic it becomes.
Keep three roles separate.
- Training data fits the trees.
- Validation data chooses the stopping round and the hyperparameters.
- Test data is touched once, at the end, to report the final score.
If you retrain on all of the data after tuning, use the best iteration found earlier as the fixed number of trees, perhaps scaled up by 10 to 20 percent because there is more data. Do not run early stopping against data that the final model also trains on.
For small datasets, run early stopping inside cross-validation. Each fold stops at its own round. Take the mean of the best iterations as the tree count for the final model.
Other controls on overfitting
Early stopping fixes the tree count. These settings limit how much each tree can memorize. The LightGBM names are shown first, and the CatBoost equivalents follow.
| Control | LightGBM | CatBoost | Effect |
|---|---|---|---|
| Learning rate | `learning_rate` | `learning_rate` | Smaller steps need more trees and generalize better |
| Tree size | `num_leaves`, `max_depth` | `depth` | Fewer leaves or shallower trees limit interactions |
| Leaf size | `min_data_in_leaf` | `min_data_in_leaf` (Lossguide or Depthwise grow policies only) | Blocks leaves built from very few rows |
| Row sampling | `bagging_fraction` with `bagging_freq` | `subsample`, `bootstrap_type` | Each tree sees a random subset of rows |
| Feature sampling | `feature_fraction` | `rsm` | Each tree sees a random subset of columns |
| L2 penalty | `lambda_l2` | `l2_leaf_reg` | Shrinks leaf values toward zero |
| Minimum gain | `min_gain_to_split` | not a direct equivalent | Rejects splits that barely help |
A practical order is: lower the learning rate, give early stopping a large tree budget, then reduce tree complexity until the gap between training and validation scores narrows.
Reading the gap
Compare the training and validation metrics at the best iteration.
- A large gap with a validation curve that turns upward early means overfitting. Reduce complexity or add regularization.
- A small gap with both scores poor means underfitting. Allow more leaves, lower
min_data_in_leaf, or raise the learning rate. - A validation curve that is still improving when training stops means the tree budget is too small. Raise
n_estimatorsornum_boost_round.
A validation score that is far better than expected usually points to leakage, such as a feature built from the label, or related rows split across train and validation. More regularization will not fix that.
Common errors
- Stopping on the training set. Without a separate validation set, the training metric never turns upward, so training runs to the limit.
- Random splits on time-ordered or grouped data. Rows from the same customer or time period leak across the split. Use time-based or group-based splits.
- A noisy validation set. With a few hundred rows, the metric jitters and stops training too early or too late. Raise the patience or use cross-validation.
- Mismatched metrics. Training minimizes the objective, such as log loss, while you stop on AUC. This is allowed, but the two can disagree, so stop on the metric you care about.
- Forgetting the best iteration at prediction time. With the native
lgb.trainAPI, callbooster.predict(X, num_iteration=booster.best_iteration)if you are unsure which iteration is used.
Exercise
A LightGBM model trained with learning_rate=0.01, n_estimators=5000 and stopping_rounds=20 stops at round 140. The validation curve was still falling slowly but was noisy. What is the likely problem, and what two changes would you try?
Show answer
The patience of 20 is too short for a small learning rate, where gains per round are tiny and noisy, so a few flat rounds ended training early. Raise stopping_rounds to 200 or more, and either use a larger learning rate such as 0.05 or validate with cross-validation so the stopping point is less sensitive to noise.
Exercise
You tuned hyperparameters and chose the stopping round using one validation set, then report that set's AUC as the final result. Why is the number biased, and how do you fix the setup?
Show answer
The validation set was used to pick the number of trees and the hyperparameters, so the score is optimistic. Hold out a separate test set that is used only once for the final score, or use nested cross-validation.