Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 2

Lab: Tuning a Gradient-Boosted Model with Early Stopping

Train HistGradientBoostingClassifier on a seeded churn table with native categorical columns, let early stopping choose the number of trees, measure the learning-rate versus rounds trade-off with cross-validation, run a randomised search over tree size, leaf size, L2 and feature subsampling, test once, and repeat early stopping in XGBoost and LightGBM.

Contentsand lesson path

What you will learn

  • Train and tune a gradient-boosted model (scikit-learn HistGradientBoosting, XGBoost or LightGBM) with early stopping and a cross-validated search over its key hyperparameters.

01. Goal and setup

In this lab you tune a gradient-boosted model the way it is done in practice. The most important setting is the number of trees (also called rounds), and it interacts with the learning rate, the factor that shrinks each tree before it is added. Rather than search over the number of trees, you let early stopping pick it: training watches the loss on a held-out slice of the training rows and stops when it has not improved for a set number of rounds. A cross-validated search can then concentrate on how complex each tree may be.

The data is a synthetic churn table of 6,000 customers, generated with a fixed seed, with thresholds, interactions and two categorical columns. You use scikit-learn's HistGradientBoostingClassifier for most steps, then XGBoost and LightGBM. The metric is ROC AUC (the probability that a random churner gets a higher score than a random stayer), plus log loss where the size of the probabilities matters.

You need: Python 3.12, scikit-learn 1.9, pandas 3.x, SciPy, XGBoost 3.x and LightGBM 4.x. The outputs below come from scikit-learn 1.9.1, XGBoost 3.4.1 and LightGBM 4.7.0 on Linux; other versions and platforms can differ in the last digits.

Project layout at the end of the lab
boosting-lab/
├── data.py             step 1: the seeded churn table and one train/test split
├── early_stop.py       step 2: early stopping in HistGradientBoosting
├── learning_rate.py    step 3: learning rate against number of trees
├── search.py           step 4: randomised search on cross-validation folds
├── best_params.json    written by search.py
├── final.py            step 5: refit the chosen settings, test once
└── other_libraries.py  step 6: early stopping in XGBoost and LightGBM
Terminal
mkdir boosting-lab && cd boosting-lab
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install "scikit-learn==1.9.*" "pandas==3.1.*" scipy
python -m pip install "xgboost==3.4.*" "lightgbm==4.7.*"

02. Step 1: A seeded table with categories

The churn probability comes from rules that trees handle well: a jump at three support calls, a fee effect only on the basic plan, a usage effect only for new customers, and three regions that churn more. age carries no signal. The text columns become the pandas category dtype, which is how you tell all three libraries that a column is categorical. The 20% test set is split off once and not touched until step 5.

Python · data.py
"""A seeded, synthetic churn table with thresholds, interactions and categories."""
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split


def make_churn(n=6000, seed=0):
    rng = np.random.default_rng(seed)
    df = pd.DataFrame({
        "tenure_months": rng.integers(1, 73, n),
        "monthly_fee": rng.normal(50, 15, n).clip(10, 120).round(2),
        "support_calls": rng.poisson(1.5, n),
        "usage_hours": rng.gamma(2.0, 8.0, n).round(1),
        "age": rng.integers(18, 81, n),
        "plan": rng.choice(["basic", "standard", "premium", "family"], n),
        "region": rng.choice([f"r{i}" for i in range(10)], n),
    })
    logit = (
        -1.0
        + 1.2 * (df.support_calls >= 3)                        # a threshold
        - 0.04 * df.tenure_months
        + 1.0 * ((df.plan == "basic") & (df.monthly_fee > 60))  # an interaction
        + 1.0 * ((df.usage_hours < 5) & (df.tenure_months < 12))
        + 0.8 * df.region.isin(["r2", "r5", "r7"])
    )
    df["churned"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
    for col in ["plan", "region"]:
        df[col] = df[col].astype("category")                  # marks them categorical
    return df


def load():
    df = make_churn()
    X, y = df.drop(columns="churned"), df["churned"]
    return train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)


if __name__ == "__main__":
    X_train, X_test, y_train, y_test = load()
    print("train", X_train.shape, " test", X_test.shape)
    print("churn rate in train:", round(y_train.mean(), 3))
    print(X_train.dtypes.to_string())
Terminal
python data.py
Expected output
train (4800, 7)  test (1200, 7)
churn rate in train: 0.177
tenure_months       int64
monthly_fee       float64
support_calls       int64
usage_hours       float64
age                 int64
plan             category
region           category

About 18% of customers churn. With categorical_features="from_dtype", the default since scikit-learn 1.6, every category column is treated as categorical. A native categorical split sends a set of categories left and the rest right, for example {r2, r5, r7} against the other seven regions, which one-hot encoding could only reach with several splits.

03. Step 2: Let early stopping choose the number of trees

Set max_iter high, as an upper bound, and turn early stopping on explicitly: the default "auto" switches it on only above 10,000 rows, or when you pass your own X_val and y_val to fit. validation_fraction=0.15 carves 15% out of the rows passed to fit, here the training set, and n_iter_no_change=20 stops training after 20 rounds without improvement. For comparison, the script also fits all 1,000 rounds.

Python · early_stop.py
import numpy as np
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score

from data import load

X_train, X_test, y_train, y_test = load()

model = HistGradientBoostingClassifier(
    learning_rate=0.1,
    max_iter=1000,             # an upper bound; early stopping picks the real number
    early_stopping=True,       # the default "auto" only turns it on above 10,000 rows
    validation_fraction=0.15,  # carved out of X_train: the test set is not touched
    n_iter_no_change=20,       # stop after 20 rounds without improvement
    random_state=0,            # fixes the carve-out, so n_iter_ is repeatable
)
model.fit(X_train, y_train)
print("trees built (n_iter_):", model.n_iter_)
val_loss = -model.validation_score_                # stored as negative log loss
print("inner validation log loss: start {:.4f}, best {:.4f} at round {}".format(
    val_loss[0], val_loss.min(), val_loss.argmin()))
print("categorical features seen:", list(X_train.columns[model.is_categorical_]))

no_stop = HistGradientBoostingClassifier(learning_rate=0.1, max_iter=1000,
                                         early_stopping=False, random_state=0)
no_stop.fit(X_train, y_train)
for name, m in [("early stopping", model), ("1000 rounds", no_stop)]:
    train_auc = roc_auc_score(y_train, m.predict_proba(X_train)[:, 1])
    print(f"{name:<15} trees {m.n_iter_:4d}  train AUC {train_auc:.3f}")
Terminal
python early_stop.py
Expected output
trees built (n_iter_): 46
inner validation log loss: start 0.4659, best 0.3995 at round 26
categorical features seen: ['plan', 'region']
early stopping  trees   46  train AUC 0.909
1000 rounds     trees 1000  train AUC 1.000

The inner validation loss was lowest at round 26, and training ran 20 more rounds to confirm the stop, so n_iter_ is 46. scikit-learn keeps all 46 trees; it does not roll back to round 26. The 1,000-round model reaches a training AUC of 1.000: it has memorised the training rows, noise included. Training metrics keep improving long after overfitting starts, so they cannot tell you when to stop.

04. Step 3: Learning rate against number of trees

A smaller learning rate makes each tree count for less, so more trees are needed to reach the same fit. To measure the trade-off honestly, the script runs 5-fold cross-validation on the training set for four learning rates. Inside each fold, early stopping carves its own 15% from that fold's training part, so the fold's validation part plays no role in choosing the number of trees. The same StratifiedKFold object, with a fixed random_state, is reused in step 4 so that all comparisons use the same folds.

Python · learning_rate.py
import numpy as np
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import StratifiedKFold, cross_validate

from data import load

X_train, X_test, y_train, y_test = load()
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)   # reused in step 4

print("learning rate  trees (mean)  CV log loss  CV AUC")
for lr in [0.3, 0.1, 0.03, 0.01]:
    model = HistGradientBoostingClassifier(
        learning_rate=lr, max_iter=3000, early_stopping=True,
        validation_fraction=0.15, n_iter_no_change=20, random_state=0)
    res = cross_validate(model, X_train, y_train, cv=cv, return_estimator=True,
                         scoring=["neg_log_loss", "roc_auc"])
    trees = np.mean([est.n_iter_ for est in res["estimator"]])
    loss, auc = -res["test_neg_log_loss"], res["test_roc_auc"]
    print(f"{lr:13.2f} {trees:13.0f} {loss.mean():12.4f} "
          f"{auc.mean():7.4f} ± {auc.std():.4f}")
Terminal
python learning_rate.py
Expected output
learning rate  trees (mean)  CV log loss  CV AUC
         0.30            26       0.4501  0.7222 ± 0.0113
         0.10            38       0.4139  0.7445 ± 0.0111
         0.03            83       0.4082  0.7468 ± 0.0131
         0.01           203       0.4078  0.7473 ± 0.0159

Lowering the rate from 0.3 to 0.1 improves both log loss and AUC clearly: big steps overshoot, and the model stops after a few useful trees. From 0.1 to 0.03 the gain is small, and from 0.03 to 0.01 it is close to nothing, while the number of trees, and so the cost, more than doubles each time. Taking away the 20 patience rounds, 0.03 needs about 63 useful trees and 0.01 about 183: roughly three times the trees for a third of the step. So fix a moderate rate such as 0.05, let early stopping find the number of trees, and lower the rate at the end only if the gain is worth the cost.

05. Step 4: A randomised search over tree complexity

With the learning rate fixed at 0.05 and the number of trees left to early stopping, search the settings that control how much each tree can fit:

  • max_leaf_nodes and max_depth cap the size of each tree, and so how many features one tree can combine in an interaction;
  • min_samples_leaf forbids leaves with fewer training rows, which stops trees from isolating single noisy rows;
  • l2_regularization shrinks leaf values towards zero, so leaves supported by few rows move the prediction less;
  • max_features lets each split see only a random share of the features, as in a random forest.

RandomizedSearchCV draws 20 combinations, which covers the space better than a grid of the same cost, and scores each on the folds from step 3. loguniform(1e-3, 10) spreads L2 values across orders of magnitude. The 100 fits take about a minute on a laptop.

Python · search.py
import json

import pandas as pd
from scipy.stats import loguniform
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold

from data import load

X_train, X_test, y_train, y_test = load()
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)   # same folds as step 3

base = HistGradientBoostingClassifier(
    learning_rate=0.05, max_iter=3000, early_stopping=True,
    validation_fraction=0.15, n_iter_no_change=20, random_state=0)
space = {
    "max_leaf_nodes": [7, 15, 31, 63],        # tree size
    "max_depth": [3, 5, None],                # another cap on tree size
    "min_samples_leaf": [10, 20, 50, 100, 200],
    "l2_regularization": loguniform(1e-3, 10),
    "max_features": [0.5, 0.8, 1.0],          # share of features tried at each split
}
search = RandomizedSearchCV(base, space, n_iter=20, cv=cv, scoring="roc_auc",
                            random_state=0)
search.fit(X_train, y_train)

res = pd.DataFrame(search.cv_results_).sort_values("rank_test_score")
cols = ["param_max_leaf_nodes", "param_max_depth", "param_min_samples_leaf",
        "param_l2_regularization", "param_max_features",
        "mean_test_score", "std_test_score"]
table = res[cols].head(5).copy()
table.columns = ["leaves", "depth", "min_leaf", "l2", "max_feat", "AUC", "std"]
print(table.round(4).to_string(index=False))
print("worst of 20:", round(res["mean_test_score"].min(), 4))
with open("best_params.json", "w") as f:
    json.dump(search.best_params_, f)
Terminal
python search.py
Expected output
 leaves depth  min_leaf     l2  max_feat    AUC    std
     15     3        10 0.1878       0.5 0.7623 0.0178
      7     3        50 0.0155       0.5 0.7621 0.0185
      7     3       100 0.3100       1.0 0.7613 0.0208
     31     3        50 0.2936       0.8 0.7610 0.0183
      7     3       200 0.0568       1.0 0.7608 0.0187
worst of 20: 0.7486

All five leaders use depth 3, so shallow trees suit this data: the true rules combine at most two features. The leading AUCs differ by 0.0015, while the fold-to-fold standard deviation is about 0.018, so the order among the top five is mostly luck. What the search does show is that the space matters: the worst draw scored 0.7486. Treat the winner as one good configuration, not the unique best.

06. Step 5: Refit the chosen settings and test once

Refit the chosen configuration on all training rows, with early stopping still on, and score it on the test set once, next to a default model, so the report shows what tuning added.

Python · final.py
import json

from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score

from data import load

X_train, X_test, y_train, y_test = load()
with open("best_params.json") as f:
    best = json.load(f)
for key, value in best.items():
    print(f"chosen {key} = {round(value, 4) if isinstance(value, float) else value}")

common = dict(max_iter=3000, early_stopping=True, validation_fraction=0.15,
              n_iter_no_change=20, random_state=0)
models = {
    "defaults, lr 0.1": HistGradientBoostingClassifier(learning_rate=0.1, **common),
    "tuned, lr 0.05": HistGradientBoostingClassifier(learning_rate=0.05, **best,
                                                     **common),
}
for name, model in models.items():
    model.fit(X_train, y_train)               # all training rows; the test set once
    auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
    print(f"{name:<17} trees {model.n_iter_:4d}  test AUC {auc:.4f}")
Terminal
python final.py
Expected output
chosen l2_regularization = 0.1878
chosen max_depth = 3
chosen max_features = 0.5
chosen max_leaf_nodes = 15
chosen min_samples_leaf = 10
defaults, lr 0.1  trees   46  test AUC 0.7778
tuned, lr 0.05    trees  119  test AUC 0.7928

The tuned model scores 0.7928 on test against 0.7778 for the defaults, with 119 trees instead of 46 because of the smaller learning rate. One test set of 1,200 rows is a noisy sample, but the cross-validation in steps 3 and 4 points the same way. Report this test score, not the cross-validated score of the winner, which was selected from 20 and so is slightly optimistic.

07. Step 6: The same idea in XGBoost and LightGBM

XGBoost and LightGBM need you to pass the early-stopping data yourself, so carve it out of the training set with train_test_split. In XGBoost 2 and 3, early_stopping_rounds is a constructor argument and eval_set is passed to fit; enable_categorical=True with tree_method="hist" uses the category columns natively. In LightGBM, early stopping is a callback, lgb.early_stopping(50), and in LightGBM 4.7 the validation data goes in eval_X and eval_y (the older eval_set still works there but raises a deprecation warning). LightGBM reads category columns as categorical by default. Both libraries can subsample rows (subsample) and columns (colsample_bytree) for each tree.

Python · other_libraries.py
import lightgbm as lgb
import xgboost as xgb
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split

from data import load

X_train, X_test, y_train, y_test = load()
# carve the early-stopping set out of the training rows, never out of the test set
X_fit, X_val, y_fit, y_val = train_test_split(
    X_train, y_train, test_size=0.15, stratify=y_train, random_state=0)

xgb_model = xgb.XGBClassifier(
    n_estimators=3000, learning_rate=0.05, max_depth=3, subsample=0.8,
    colsample_bytree=0.8, tree_method="hist", enable_categorical=True,
    early_stopping_rounds=50,            # a constructor argument in XGBoost 2 and 3
    eval_metric="logloss", random_state=0)
xgb_model.fit(X_fit, y_fit, eval_set=[(X_val, y_val)], verbose=False)
auc = roc_auc_score(y_test, xgb_model.predict_proba(X_test)[:, 1])
print(f"XGBoost   best_iteration {xgb_model.best_iteration:4d}  test AUC {auc:.4f}")

lgb_model = lgb.LGBMClassifier(
    n_estimators=3000, learning_rate=0.05, num_leaves=7, min_child_samples=50,
    subsample=0.8, subsample_freq=1, colsample_bytree=0.8,
    random_state=0, verbose=-1)
lgb_model.fit(X_fit, y_fit, eval_X=X_val, eval_y=y_val, eval_metric="binary_logloss",
              callbacks=[lgb.early_stopping(50, verbose=False)])
auc = roc_auc_score(y_test, lgb_model.predict_proba(X_test)[:, 1])
print(f"LightGBM  best_iteration {lgb_model.best_iteration_:4d}  test AUC {auc:.4f}")
Terminal
python other_libraries.py
Expected output
XGBoost   best_iteration  159  test AUC 0.7903
LightGBM  best_iteration  125  test AUC 0.7887

Both land close to the tuned scikit-learn model. Unlike scikit-learn, they track the best round: XGBoost built 210 trees (best round 159, counted from 0, plus 50 rounds of patience), and its predict_proba uses only the first 160 trees. LightGBM's predict_proba uses best_iteration_ in the same way. The settings were set by hand to resemble the winner of step 4; in a project, search for the library you deploy.

08. Check your understanding

Practice check · 3 questions

Reading the tuning run

Answer from the code and outputs of this lab.

Q1. In step 2, the inner validation loss was best at round 26 and `n_iter_` is 46. How many trees does this `HistGradientBoostingClassifier` use when it predicts?
Q2. In `data.py`, suppose you delete the line that converts `plan` and `region` to the `category` dtype, so they stay text columns. What happens in step 2?
Q3. You change `n_iter_no_change=20` to `n_iter_no_change=2` in `early_stop.py`. What is the most likely effect?
Practice only: not graded, not saved, not evidence.

09. Apply it: stretch tasks

  1. Tune for your project. On your project dataset, run the step 4 search on the folds you fixed in the previous lesson, with the learning rate at 0.05 and early stopping on. Report the top five configurations with their fold standard deviations and say which differences you trust.
  2. One-hot against native. Replace the category columns with OneHotEncoder inside a ColumnTransformer and compare the cross-validated AUC and the number of trees with step 3.
  3. Search a second library. Run the same search for LGBMClassifier over num_leaves, min_child_samples, reg_lambda, subsample and colsample_bytree, passing the early-stopping callback through fit parameters, and compare its test score with step 5.

10. Review prompt

Without looking back, explain what early stopping watches and where its data must come from; why training metrics cannot tell you when to stop; how the learning rate and the number of trees trade off and how you would choose them; which four settings you would search and what each one limits; and how scikit-learn, XGBoost and LightGBM differ in passing validation data and in which trees they use to predict.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check