Sub topic 6
Training your first model with the scikit-learn API
This chapter assumes you know Python and NumPy, can split data into train and validation sets, and understand log loss and accuracy. It also assumes you have read the earlier chapters on gradient boosting and the XGBoost objective.
Why start with the scikit-learn API
XGBoost ships a scikit-learn style interface. XGBClassifier and XGBRegressor follow the usual fit, predict and score conventions. They also work inside pipelines and with tools such as GridSearchCV. The native API (DMatrix and xgb.train) comes in a later chapter.
A first classifier
The example below trains on the breast cancer dataset. It sets a large n_estimators cap and lets early stopping on a validation set decide how many trees are kept.
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))Each argument has a job:
n_estimatorsis the maximum number of boosting rounds, one tree per round.learning_rateshrinks each tree's contribution. Smaller values need more trees.max_depthlimits tree depth. Shallow trees keep each learner weak.subsampleandcolsample_bytreetrain each tree on a random fraction of rows and columns.eval_metricis the metric computed on the evaluation set after each round.early_stopping_roundsstops training when the last metric ineval_metrichas not improved for that many rounds.
What happens during fit
The diagram shows the loop that fit runs.
Reading the results
best_iteration is the zero-based index of the best round. The fitted model uses trees up to that round when you call predict.
The validation set picked the stopping point, so its score is slightly optimistic. For an honest final number, hold out a separate test set.
For regression, use XGBRegressor the same way. Its default objective is squared error. For classification, predict returns class labels and predict_proba returns probabilities.
Common errors
- Evaluating early stopping on the training data. The metric keeps improving, so training never stops early.
- Reporting the validation score as the final score after using it for early stopping.
- Setting
n_estimatorssmall andlearning_ratesmall together. The model underfits because it runs out of rounds. - Passing
early_stopping_roundswithout aneval_set, which raises an error.
Exercise
You train with nestimators=1000, earlystoppingrounds=30, and model.bestiteration is 212. Roughly how many trees were actually built, and which are used by predict?
Show answer
About 243 trees were built (rounds 0 to 212, then 30 more without improvement). Predict uses the trees up to the best iteration, 212, not the full set that was built.