Skip to content

XGBoost

XGBoost is one of the most successful algorithms for tabular data. It builds an ensemble of decision trees sequentially, each correcting the errors of the previous ones. This page walks a complete classification workflow from training to interpretation.

Every code block runs in a container in the companion repository, so the numbers and figures are real.

from pathlib import Path
import matplotlib.pyplot as plt
import pandas as pd
import xgboost as xgb
from sklearn.datasets import make_classification
from sklearn.metrics import classification_report, roc_auc_score
from sklearn.model_selection import (
StratifiedKFold,
cross_val_score,
train_test_split,
)
out = Path("outputs")
out.mkdir(exist_ok=True)
features, y = make_classification(n_samples=2000,
n_features=20,
n_informative=10,
n_redundant=3,
weights=[0.7, 0.3],
flip_y=0.05,
random_state=42)
feature_names = [f"feature_{i}" for i in range(features.shape[1])]
x_train, x_test, y_train, y_test = train_test_split(features,
y,
test_size=0.2,
random_state=42,
stratify=y)
model = xgb.XGBClassifier(n_estimators=100,
max_depth=4,
learning_rate=0.1,
random_state=42,
eval_metric="logloss")
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, x_train, y_train, cv=cv, scoring="roc_auc")
print(f"Cross-validated ROC-AUC: {scores.mean():.4f} (+/- {scores.std():.4f})")
model.fit(x_train, y_train)
y_prob = model.predict_proba(x_test)[:, 1]
print(f"Test ROC-AUC: {roc_auc_score(y_test, y_prob):.4f}")
print(classification_report(y_test,
model.predict(x_test),
target_names=["Negative", "Positive"]))
Cross-validated ROC-AUC: 0.9286 (+/- 0.0245)
Test ROC-AUC: 0.9477
precision recall f1-score support
Negative 0.89 0.93 0.91 276
Positive 0.84 0.75 0.79 124
accuracy 0.88 400
macro avg 0.87 0.84 0.85 400
weighted avg 0.88 0.88 0.88 400
Parameter Default Effect
n_estimators 100 Number of trees; more capacity, slower
max_depth 6 Tree depth; deeper is more complex
learning_rate 0.3 Step shrinkage; lower needs more trees, generalizes better
subsample 1.0 Fraction of rows per tree
colsample_bytree 1.0 Fraction of columns per tree
min_child_weight 1 Minimum leaf weight; higher is more conservative
reg_alpha / reg_lambda 0 / 1 L1 / L2 regularization

The most impactful to tune are learning_rate, max_depth, n_estimators, and subsample.

RandomizedSearchCV searches the space efficiently.

from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint, uniform
search = RandomizedSearchCV(xgb.XGBClassifier(random_state=42,
eval_metric="logloss"),
{
"n_estimators": randint(100, 500),
"max_depth": randint(3, 8),
"learning_rate": uniform(0.01, 0.3),
"subsample": uniform(0.6, 0.4),
"colsample_bytree": uniform(0.6, 0.4),
"min_child_weight": randint(1, 10),
"reg_alpha": uniform(0, 1),
"reg_lambda": uniform(0.5, 2)
},
n_iter=50,
cv=cv,
scoring="roc_auc",
random_state=42,
n_jobs=-1)
search.fit(x_train, y_train)
print(f"Best ROC-AUC: {search.best_score_:.4f}")
for param, value in sorted(search.best_params_.items()):
if isinstance(value, float):
print(f" {param}: {value:.4f}")
else:
print(f" {param}: {value}")
best_model = search.best_estimator_
tuned_prob = best_model.predict_proba(x_test)[:, 1]
print(f"Tuned Test ROC-AUC: {roc_auc_score(y_test, tuned_prob):.4f}")
Best ROC-AUC: 0.9341
colsample_bytree: 0.9906
learning_rate: 0.1333
max_depth: 7
min_child_weight: 1
n_estimators: 484
reg_alpha: 0.2396
reg_lambda: 0.7898
subsample: 0.7958
Tuned Test ROC-AUC: 0.9428

Tuning lifted the cross-validated ROC-AUC from 0.9286 to 0.9341. On this test split the tuned model scored 0.9428, a little below the default model’s 0.9477, because tuning improves the expected score and not the score on every single split.

Instead of guessing n_estimators, train many and stop when validation stops improving.

x_train_es, x_validation, y_train_es, y_val = train_test_split(
x_train, y_train, test_size=0.2, random_state=42, stratify=y_train
)
model_es = xgb.XGBClassifier(n_estimators=1000,
max_depth=4,
learning_rate=0.05,
random_state=42,
eval_metric="logloss",
early_stopping_rounds=20)
model_es.fit(x_train_es,
y_train_es,
eval_set=[(x_validation, y_val)],
verbose=False)
print(f"Best iteration: {model_es.best_iteration}")
print(f"Best validation logloss: {model_es.best_score:.4f}")
Best iteration: 370
Best validation logloss: 0.2321

Set n_estimators high and let early_stopping_rounds=20 find the right number.

importance = pd.DataFrame({
"feature": feature_names,
"importance": best_model.feature_importances_,
}).sort_values("importance", ascending=False)
print(importance.head(6).to_string(index=False))
feature importance
feature_14 0.138053
feature_17 0.090913
feature_18 0.083418
feature_16 0.078228
feature_9 0.068921
feature_2 0.065309
top15 = importance.head(15)
fig, ax = plt.subplots(figsize=(6, 5))
ax.barh(top15["feature"][::-1], top15["importance"][::-1], color="#4c72b0")
ax.set_xlabel("Importance")
ax.set_title("XGBoost feature importance (top 15)")
fig.tight_layout()
fig.savefig(out / "xgboost-feature-importance.png", dpi=150)
plt.close(fig)

XGBoost feature importance, top 15

Feature importance says which features matter, not how they affect predictions. SHAP (SHapley Additive exPlanations) explains individual predictions.

import numpy as np
import shap
explainer = shap.TreeExplainer(best_model)
shap_values = explainer.shap_values(x_test)
# Rank every feature by mean absolute SHAP value, 1 for the largest.
mean_abs_shap = pd.Series(np.abs(shap_values).mean(axis=0),
index=feature_names)
shap_rank = mean_abs_shap.rank(ascending=False).astype(int)
top_gain = importance.head(6).copy()
top_gain["shap_rank"] = top_gain["feature"].map(shap_rank).to_numpy()
print(top_gain.to_string(index=False))
# rng fixes the random draw order of the dots, so the plot repeats.
shap.summary_plot(shap_values,
x_test,
feature_names=feature_names,
show=False,
rng=42)
plt.tight_layout()
plt.savefig(out / "xgboost-shap-summary.png", dpi=150, bbox_inches="tight")
plt.close()
feature importance shap_rank
feature_14 0.138053 1
feature_17 0.090913 12
feature_18 0.083418 3
feature_16 0.078228 2
feature_9 0.068921 7
feature_2 0.065309 10

SHAP summary plot: each dot is a sample, color is the feature value

Each dot is one sample. The x-axis is the SHAP value (impact on the prediction); the color is the feature value (red high, blue low). For feature_14, high values push the prediction toward the negative class and low values push it toward positive. For feature_16 and feature_18 the direction is reversed. Features are sorted by mean absolute SHAP value, so the order differs from the gain ranking above. The shap_rank column printed above shows the gap: feature_17 is second by gain but twelfth by SHAP, and feature_2 is sixth by gain but tenth by SHAP.

shap.summary_plot(shap_values,
x_test,
feature_names=feature_names,
plot_type="bar",
show=False)
plt.tight_layout()
plt.savefig(out / "xgboost-shap-bar.png", dpi=150, bbox_inches="tight")
plt.close()

SHAP bar plot: mean absolute SHAP value per feature

Step What to do
Baseline XGBClassifier(n_estimators=100, max_depth=4, learning_rate=0.1)
Tuning RandomizedSearchCV with 50+ iterations
Early stopping n_estimators=1000, early_stopping_rounds=20
Importance model.feature_importances_ for a quick ranking
Interpretation SHAP for per-sample explanations

The next page covers LightGBM, which finds splits on binned feature histograms to train fast and grows trees leaf-wise.

Chen and Guestrin, 2016 describe XGBoost, a scalable system for gradient tree boosting.

Lundberg and Lee, 2017 describe SHAP, a unified approach to interpreting model predictions.

  • SHAP TreeExplainer

    The reference defines the explanation output scale and assumptions about feature dependence. Check those settings before interpreting a SHAP value as a change in probability.

  • scikit-learn cross-validation guide

    The guide separates hyperparameter selection from evaluation on unseen rows. It provides context for the random search and separate early-stopping split used here.