Sub topic 2
Training your first model with the scikit-learn API
Assume you know Python, NumPy, train/validation splits, decision trees, and basic evaluation metrics. XGBoost builds an ensemble by adding trees sequentially. Each new tree corrects errors made by the current ensemble.
Training with the scikit-learn API
XGBClassifier follows the familiar scikit-learn pattern: create a model, call fit, then predict. Keep validation data separate from the final test set.
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_temp, y_train, y_temp = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=0
)
X_val, X_test, y_val, y_test = train_test_split(
X_temp, y_temp, test_size=0.5, stratify=y_temp, random_state=0
)
model = XGBClassifier(
n_estimators=300,
learning_rate=0.05,
max_depth=3,
subsample=0.8,
colsample_bytree=0.8,
eval_metric="logloss",
early_stopping_rounds=20,
)
model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=False)
print("validation accuracy:", model.score(X_val, y_val))
print("test accuracy:", model.score(X_test, y_test))The hyperparameters that matter
n_estimatorsis the maximum number of trees.learning_rateshrinks each tree's contribution. Smaller values usually need more trees.max_depthcontrols tree complexity. Deeper trees can learn more interactions but overfit more easily.subsamplesamples training rows for each boosting round.colsample_bytreesamples features for each tree.
Controlling overfitting
Use shallow trees, a lower learning rate, row or feature sampling, and regularization. min_child_weight, gamma, reg_lambda, and reg_alpha restrict splits or leaf weights. Compare changes using validation data, then report performance once on untouched test data.
Choosing the number of rounds with early stopping
Early stopping stops training when the validation metric fails to improve for a chosen number of rounds. The model can use a large n_estimators cap while validation determines the useful number of trees.
The native API: `DMatrix` and `xgb.train`
The native API exposes XGBoost's DMatrix data structure and xgb.train function. It uses parameter names such as eta instead of learning_rate.
import xgboost as xgb
train = xgb.DMatrix(X_train, label=y_train)
valid = xgb.DMatrix(X_val, label=y_val)
params = {
"objective": "binary:logistic",
"eval_metric": "logloss",
"eta": 0.05,
"max_depth": 3,
}
booster = xgb.train(
params, train, num_boost_round=300,
evals=[(valid, "validation")],
early_stopping_rounds=20,
verbose_eval=False,
)
print(booster.best_iteration)Exercise
Why can a smaller learning rate require more boosting rounds?
Show answer
Each tree makes a smaller update, so more sequential updates are needed to reach a similar fit.