Sub topic 6
Training your first model with the scikit-learn API
This chapter assumes you know Python and NumPy, the idea of a train/validation split, and the basic idea of a decision tree. It also assumes you have read the earlier chapters on boosting and on XGBoost's gradient and hessian objective. Here you train a real model, read its output, and learn the errors people hit most often.
Why start with the scikit-learn API
XGBoost has two interfaces. The native API uses DMatrix and xgb.train. The scikit-learn API wraps the same engine in classes named XGBClassifier and XGBRegressor. These classes follow the usual fit, predict and predict_proba conventions. They work with Pipeline, GridSearchCV, cross_val_score and other scikit-learn tools.
Use the scikit-learn API when you want a model that behaves like any other estimator. The native API gives you more control, and a later chapter covers it.
The first model
The example below trains a classifier on the breast cancer dataset. It sets a large n_estimators cap and lets early stopping on a validation set choose how many trees are used.
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. Each round adds one tree (for binary problems).learning_rateshrinks every tree's contribution. Smaller values need more trees but usually generalize better.max_depthlimits how deep each tree grows. Shallow trees act as weak learners.subsampleis the fraction of rows sampled for each tree.colsample_bytreeis the fraction of columns sampled for each tree.eval_metricis the metric computed on the evaluation set after every round.early_stopping_roundsstops training when the last evaluation-set metric has not improved for that many rounds.
The eval_set argument is a list of (X, y) pairs. XGBoost evaluates all of them each round. Early stopping uses the last pair in the list.
What happens during fit
Training follows the loop you saw in the gradient boosting chapter.
- The model starts from a constant prediction. For binary classification this is a base score on the log-odds scale.
- For each training row, XGBoost computes the gradient and hessian of the loss at the current prediction.
- It grows one tree using those statistics to score splits.
- It scales the new tree's leaf values by
learning_rateand adds them to the running prediction. - It evaluates the metric on each
eval_setand checks the stopping rule.
Reading the results
After training with early stopping, two attributes matter:
model.best_iterationis the zero-based index of the best round. The best model usesbest_iteration + 1trees.model.best_scoreis the metric value at that round.
Early stopping continues for early_stopping_rounds extra rounds after the best one. The fitted model contains all trees trained, but predict uses only the trees up to the best iteration. This is the default behavior in recent XGBoost versions. Check your installed version's documentation if you are on an older release.
Use predict_proba to get class probabilities and predict to get class labels. For a binary model, predict_proba returns an array with two columns, and predict thresholds the positive probability at 0.5.
proba = model.predict_proba(X_val)[:, 1]
labels = model.predict(X_val)
print(proba[:3], labels[:3])Classifier or regressor
Choose the class by the target type. Each class picks a default objective.
| Class | Task | Default objective | Typical metric |
|---|---|---|---|
| `XGBClassifier` | Binary classification | `binary:logistic` | `logloss`, `auc` |
| `XGBClassifier` | Multiclass classification | `multi:softprob` | `mlogloss` |
| `XGBRegressor` | Regression | `reg:squarederror` | `rmse`, `mae` |
A regressor follows the same pattern:
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor
X, y = fetch_california_housing(return_X_y=True)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=0)
reg = XGBRegressor(
n_estimators=1000,
learning_rate=0.05,
max_depth=4,
eval_metric="rmse",
early_stopping_rounds=30,
)
reg.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=False)
print(reg.best_iteration, reg.best_score)Change the objective with the objective argument when the default does not fit, for example reg:absoluteerror for median-style regression.
Common errors
Reporting the early-stopping score as the final score
Early stopping picks the round using the validation set, so the validation score is slightly optimistic. For an honest estimate, hold out a separate test set that is never used during training or stopping.
Labels in the wrong form
XGBClassifier expects class labels as integers starting at 0, such as 0 and 1 or 0 to 4. Labels such as 1 and 2, or strings, can raise an error. Encode them first, for example with LabelEncoder.
Using the wrong API version style
Older tutorials pass early_stopping_rounds and eval_metric to fit. Current XGBoost versions expect them in the constructor, as shown above. If you see a TypeError about an unexpected keyword argument, check which version you have with xgboost.__version__.
Forgetting that `n_estimators` is a cap
With early stopping on, n_estimators=1000 does not mean 1000 trees are used. If best_iteration is close to the cap, the cap was too low. Raise it or increase learning_rate.
Evaluating on the training set only
If eval_set holds only the training data, the metric keeps improving and early stopping never helps. Always pass a separate validation set.
Checking for overfitting with the learning curve
evals_result() returns a dictionary keyed by evaluation set name. By default the names are validation_0, validation_1, and so on, in the order you passed them. Passing both the training and validation sets shows the gap between them.
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=300,
learning_rate=0.1,
max_depth=3,
eval_metric="logloss",
)
model.fit(
X_train, y_train,
eval_set=[(X_train, y_train), (X_val, y_val)],
verbose=False,
)
history = model.evals_result()
train_loss = history["validation_0"]["logloss"]
val_loss = history["validation_1"]["logloss"]
best = min(range(len(val_loss)), key=val_loss.__getitem__)
print("best round:", best, "val loss:", round(val_loss[best], 4))
print("final train loss:", round(train_loss[-1], 4))
print("final val loss:", round(val_loss[-1], 4))Training loss usually keeps falling. Validation loss falls, flattens, and may rise. The round where validation loss is lowest is where early stopping would stop. A wide gap between the two curves signals overfitting, which the overfitting chapter addresses.
Practical defaults
A reasonable first configuration for tabular data is a learning_rate of 0.05 to 0.1, max_depth of 3 to 6, subsample and colsample_bytree of 0.7 to 1.0, a large n_estimators, and early stopping. Get this baseline working before you tune anything else. It gives you a number to beat.
Exercise
You train an XGBClassifier with nestimators=500 and earlystopping_rounds=20. The validation log loss is lowest at zero-based round 120. How many trees does predict use, how many trees were trained in total, and why is the validation accuracy a poor final estimate?
Show answer
predict uses 121 trees (best_iteration + 1). Training runs 20 more rounds after the best one without improvement, so 141 trees were trained in total, assuming no other stop. The validation set was used to choose the stopping round, so its score is optimistically biased. Report the score on a separate test set that was never used in training or stopping.
Exercise
Your learning curve shows training log loss falling steadily to near zero while validation log loss reaches its minimum at round 40 and then rises. Name two constructor arguments you could change to reduce this gap.
Show answer
Any two of: lower maxdepth (simpler trees), lower learningrate with a higher nestimators cap, lower subsample or colsamplebytree (more randomness), or set earlystoppingrounds so training halts near round 40. Regularization arguments such as reg_lambda also help, and later chapters cover them.