Sub topic 3
Cross-validation and production practices in XGBoost
Assume you know Python, NumPy, train/validation splits, decision trees, overfitting, and basic evaluation metrics. This chapter focuses on choosing, inspecting, and deploying XGBoost models.
Cross-validation with `xgb.cv`
xgb.cv runs cross-validation directly on a DMatrix, XGBoost's optimized data structure. It reports the mean and standard deviation of each metric across folds. Early stopping ends training when the validation metric stops improving.
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
X, y = load_breast_cancer(return_X_y=True)
data = xgb.DMatrix(X, label=y)
params = {
"objective": "binary:logistic",
"eval_metric": "auc",
"eta": 0.05,
"max_depth": 3,
}
results = xgb.cv(
params,
data,
num_boost_round=1000,
nfold=5,
stratified=True,
early_stopping_rounds=30,
seed=0,
)
best_rounds = len(results)
model = xgb.train(params, data, num_boost_round=best_rounds)
model.save_model("breast_cancer.json")
loaded = xgb.Booster()
loaded.load_model("breast_cancer.json")Split finding: exact and histogram methods
Exact methods examine every possible feature threshold. They can be accurate but require more memory and computation. The histogram method groups feature values into bins, then evaluates bin boundaries. It is usually faster and is selected with tree_method="hist".
Missing values and categorical features
XGBoost can learn a default branch for missing numeric values. You can leave missing values as NaN; do not silently replace them with a misleading value.
Categorical features require explicit handling. With supported versions, use enable_categorical=True and categorical data types. Otherwise, encode categories before training, using one-hot encoding for small unordered sets.
> callout note > Keep preprocessing identical during training and prediction. A changed category mapping can make a valid model produce incorrect results.
Handling imbalanced classes
For binary classification, scale_pos_weight increases the influence of positive examples. A common starting value is the number of negative examples divided by the number of positive examples. Evaluate with metrics such as PR AUC, recall, or calibrated probabilities rather than accuracy alone.
Importance and contributions
get_score(importance_type="gain") measures the average loss reduction from splits using each feature. Per-row contributions from pred_contribs=True explain how features move a prediction from the bias value. These explanations are associations, not proof of causation.
A practical tuning workflow
Start with a shallow tree, moderate learning rate, and a large round limit. Use cross-validation or a validation set to choose rounds. Then tune max_depth, min_child_weight, row and column subsampling, and regularization. Keep a final test set untouched.
Saving and scaling
Save models with save_model, preferably in JSON when portability and readable metadata matter. Reload the artifact in a fresh process before deployment.
For larger data, use tree_method="hist". If supported by your installation and hardware, device="cuda" enables GPU training. Compare speed and validation metrics, because GPU use does not automatically improve accuracy.
Exercise
Why should the final test set remain untouched while xgb.cv chooses the number of rounds?
Show answer
Reusing the test set for decisions makes its score optimistic. It should measure the completed workflow only once.