Sub topic 10
The native API: DMatrix and xgb.train
This chapter assumes you have trained an XGBClassifier with the scikit-learn API and know what early stopping does. The native API is the interface the scikit-learn wrapper is built on. It gives you direct control over data containers, parameters, and the training loop.
Why use the native API
The wrapper hides three things that the native API exposes:
- The
DMatrix, XGBoost's internal data container. - A plain
paramsdictionary, using the library's own parameter names. - The
Booster, the trained model object that holds the trees.
You need the native API for xgb.cv, for custom objectives and metrics, and for reusing one DMatrix across many training runs.
DMatrix
A DMatrix stores features, labels, and optional extras such as sample weights, base margins, and feature names. It also pre-processes the data into a format that makes split finding fast. Missing values are handled here: NaN is treated as missing by default, or you can pass missing= to name another sentinel.
Training with xgb.train
Parameters go in a dictionary. The number of trees is not a parameter. It is the num_boost_round argument. Validation sets go in evals as (DMatrix, name) pairs.
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
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
)
dtrain = xgb.DMatrix(X_train, label=y_train)
dval = xgb.DMatrix(X_val, label=y_val)
params = {
"objective": "binary:logistic",
"eval_metric": "logloss",
"eta": 0.05,
"max_depth": 3,
"subsample": 0.8,
"colsample_bytree": 0.8,
}
booster = xgb.train(
params,
dtrain,
num_boost_round=1000,
evals=[(dtrain, "train"), (dval, "val")],
early_stopping_rounds=30,
verbose_eval=False,
)
best = booster.best_iteration
probs = booster.predict(dval, iteration_range=(0, best + 1))
print(best, probs[:5])Early stopping watches the last entry in evals, and the last metric if you list several. Training continues for 1000 rounds at most, but the booster keeps every tree it built, including the 30 after the best round. The iteration_range argument restricts prediction to the trees up to and including the best one.
Naming differences
The native API uses the library's own names. The wrapper translates some of them.
| scikit-learn wrapper | Native API |
|---|---|
| `learning_rate` | `eta` |
| `n_estimators` | `num_boost_round` |
| `reg_lambda` | `lambda` |
| `reg_alpha` | `alpha` |
| `min_split_loss` | `gamma` |
Common errors
- Passing a raw NumPy array to
predict. ABoosterrequires aDMatrix. - Putting
num_boost_roundorn_estimatorsinsideparams. Training does not use them as the round count. - Mismatched feature names between training and prediction
DMatrixobjects when you setfeature_names. - Putting the validation set before the training set in
evals, which makes early stopping watch the wrong one.
Exercise
In the example above, early stopping ends training at round 140 and best_iteration is 109. How many trees does the booster hold, and which iteration_range predicts with the best model?
Show answer
Rounds are numbered from 0, so training ran 141 rounds and the booster holds 141 trees. The best model uses trees 0 to 109, so pass iteration_range=(0, 110). The range end is exclusive, which is why you add 1 to best_iteration.