Sub topic 10
The native API: DMatrix and xgb.train
This chapter assumes you can train an XGBClassifier with the scikit-learn API and that you know what a train/validation split and early stopping are. It covers the lower-level interface that the scikit-learn wrapper is built on: xgb.DMatrix, a parameter dictionary, and xgb.train.
Why a second API exists
The scikit-learn classes (XGBClassifier, XGBRegressor) are convenient. They fit into pipelines, grid searches and cross_val_score. Under the hood they build a DMatrix, translate their keyword arguments into a parameter dictionary, and call the native trainer.
The native API gives you direct access to things the wrapper hides or only partly exposes:
- Several named evaluation sets, with per-round metric history.
- Custom objectives and custom metrics.
xgb.cv, which runs cross-validation inside XGBoost.- Per-row weights, base margins and feature metadata attached to the data object.
- Prediction options such as
pred_contribsandpred_leaf.
Use the wrapper when you need scikit-learn compatibility. Use the native API when you need control or want to see exactly what is being trained.
The DMatrix
A DMatrix is XGBoost's internal data container. It holds the feature matrix and, optionally, the labels, weights, feature names and feature types. It stores the data in a form that the tree learner can scan efficiently, so training avoids repeated conversion.
import numpy as np
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X_train, X_val, y_train, y_val = train_test_split(
data.data, data.target, test_size=0.2, stratify=data.target, random_state=0
)
dtrain = xgb.DMatrix(
X_train,
label=y_train,
feature_names=list(data.feature_names),
)
dval = xgb.DMatrix(
X_val,
label=y_val,
feature_names=list(data.feature_names),
)
print(dtrain.num_row(), dtrain.num_col())
print(dtrain.feature_names[:3])A DMatrix accepts several input types: NumPy arrays, SciPy sparse matrices, pandas DataFrames, and file paths. With a DataFrame, column names become feature names automatically.
Useful constructor arguments
| Argument | Purpose |
|---|---|
| `label` | Target values. Omit it for prediction-only data. |
| `weight` | One weight per row. Rows with larger weights contribute more to the gradients. |
| `missing` | Value to treat as missing. The default is `NaN`. |
| `feature_names` | Names used in importance reports and model dumps. |
| `feature_types` | Types such as `"float"`, `"int"`, `"i"` (indicator) or `"c"` (categorical). |
| `base_margin` | Initial raw prediction per row, before any tree is added. |
| `enable_categorical` | Allows pandas categorical columns when set to `True`. |
Two points cause most confusion:
- Feature names must match between training and prediction. If you train with names and predict with a
DMatrixthat has different or missing names, XGBoost raises an error. Build everyDMatrixfor one model the same way. missingis about the encoding of the input. If your data uses-999for missing, passmissing=-999. Otherwise XGBoost treats-999as a real number.
Setting data after construction
You can also set fields afterward. This is useful when labels and weights arrive separately.
dtrain.set_weight(np.ones(dtrain.num_row()))
dtrain.set_info(base_margin=np.zeros(dtrain.num_row()))The parameter dictionary
The native API takes parameters as a plain dictionary. The names are the native ones, which differ in places from the scikit-learn names.
| scikit-learn name | Native name |
|---|---|
| `learning_rate` | `eta` |
| `n_estimators` | `num_boost_round` (argument of `xgb.train`, not a parameter) |
| `reg_lambda` | `lambda` |
| `reg_alpha` | `alpha` |
| `min_split_loss` | `gamma` |
| `random_state` | `seed` |
XGBoost's recent versions accept most scikit-learn names in the dictionary as well, but sticking to native names avoids surprises when you read the documentation.
The objective key decides the loss and the output scale. For example, binary:logistic makes predict return probabilities, while binary:logitraw returns raw margins. The eval_metric key chooses what is reported on the evaluation sets.
Training with xgb.train
xgb.train takes the parameter dictionary, the training DMatrix and the maximum number of rounds. It returns a Booster, the trained model object.
params = {
"objective": "binary:logistic",
"eval_metric": ["logloss", "auc"],
"eta": 0.05,
"max_depth": 3,
"subsample": 0.8,
"colsample_bytree": 0.8,
"seed": 0,
}
evals_result = {}
booster = xgb.train(
params,
dtrain,
num_boost_round=1000,
evals=[(dtrain, "train"), (dval, "val")],
early_stopping_rounds=30,
evals_result=evals_result,
verbose_eval=50,
)
print(booster.best_iteration, booster.best_score)Points to note:
evalsis a list of(DMatrix, name)pairs. The name appears in the log and as a key inevals_result.- With several metrics, early stopping watches the last metric on the last evaluation set. Here that is
auconval. Order your lists on purpose. evals_resultis filled in place with the metric history per round, for exampleevals_result["val"]["auc"]. Use it to plot learning curves.verbose_eval=50prints every 50th round.Falsesilences the log.num_boost_round=1000is only a cap. Early stopping ends training when the watched metric has not improved for 30 rounds.
Which model do you get after early stopping?
The returned Booster contains all trees that were built, including the extra ones after the best round. The attributes best_iteration and best_score record where the best round was. By default, predict on a Booster uses the best iteration when early stopping was used, in current XGBoost versions. To be explicit and version-proof, pass the range yourself:
preds = booster.predict(dval, iteration_range=(0, booster.best_iteration + 1))
print(preds[:5])iteration_range is half-open, so the + 1 is needed to include the best round.
If you want the saved model itself to contain only the best trees, pass xgb.callback.EarlyStopping(rounds=30, save_best=True) through the callbacks argument. Do not combine this with the early_stopping_rounds argument.
booster = xgb.train(
params,
dtrain,
num_boost_round=1000,
evals=[(dval, "val")],
callbacks=[xgb.callback.EarlyStopping(rounds=30, save_best=True)],
verbose_eval=False,
)
print(booster.num_boosted_rounds())Predicting and reading the raw output
booster.predict(dmatrix) returns a NumPy array. What it contains depends on the objective:
binary:logistic: probabilities between 0 and 1. Apply your own threshold for class labels.multi:softprob: an array of shape(n_rows, n_classes).multi:softmax: the predicted class index only.reg:squarederror: the predicted value.
The scikit-learn wrapper adds predict (labels) and predict_proba on top. With the native API, you do that step yourself.
proba = booster.predict(dval)
labels = (proba >= 0.5).astype(int)
print("accuracy:", (labels == y_val).mean())You can request the raw margin before the sigmoid with output_margin=True. This is the sum of the base score and all tree outputs, which is the quantity that boosting actually builds.
Inspecting the Booster
A Booster has several methods for looking inside the model:
booster.num_boosted_rounds()returns the number of boosting rounds.booster.get_score(importance_type="gain")returns importance per feature.booster.trees_to_dataframe()lists every node of every tree as a pandas DataFrame, with split feature, threshold, gain and cover.booster.get_dump()returns text dumps of the trees.
df = booster.trees_to_dataframe()
print(df.head())Moving between the two APIs
The two interfaces are interchangeable at the model level. A fitted XGBClassifier exposes its Booster through get_booster(). You can save a model with one API and load it with the other, because both use the same file formats.
from xgboost import XGBClassifier
clf = XGBClassifier(n_estimators=50, learning_rate=0.1, max_depth=3)
clf.fit(X_train, y_train)
native = clf.get_booster()
print(native.predict(xgb.DMatrix(X_val))[:3])Note that the Booster here has no feature names, because NumPy arrays carry none. A DMatrix built from a DataFrame would need to match the names the model was trained with.
Common errors
- Feature name mismatch. Training used a DataFrame with names and prediction used a bare array. Wrap the array in a
DMatrixwith the samefeature_names. - Passing the sklearn-only argument
n_estimatorsin the dictionary. The native trainer ignores it or warns. Usenum_boost_round. - Evaluating early stopping on the training set. The metric keeps improving and training never stops early. Put a held-out set last in
evals. - Reporting the validation score as the final score. Early stopping selects the round using the validation set, so that score is optimistic. Keep a separate test set.
- Expecting class labels from
predict. Withbinary:logisticyou get probabilities.
Exercise
You call xgb.train with params containing "evalmetric": ["auc", "logloss"], and evals=[(dtrain, "train"), (dval, "val")], earlystopping_rounds=20. Which metric on which dataset decides when training stops, and how would you change it so that AUC on the validation set decides?
Show answer
Early stopping watches the last metric on the last evaluation set, so here it is logloss on val. To make AUC on val decide, reorder the metrics to ["logloss", "auc"] so auc comes last. Keeping the validation set last in evals is also required, so the training set is never the one being watched.
Exercise
After training with earlystoppingrounds=30, booster.best_iteration is 212. Write the call that predicts on dval using only the trees up to and including the best round.
Show answer
booster.predict(dval, iterationrange=(0, booster.bestiteration + 1)). The range is half-open, so the end value is 213, which includes the tree at index 212.