XGBoost
XGBoost fits gradient boosted decision trees: each new tree corrects the errors of the trees before it. On a table of expression values and sample annotations it is one of the strongest default models, and a tree can split on one gene and then another, so it can pick up an interaction without a product term in the input. Every block below ran with XGBoost 3.4.
Quick reference
Section titled “Quick reference”| Task | Call |
|---|---|
| Classifier with early stopping | xgb.XGBClassifier(early_stopping_rounds=50, eval_metric="logloss") |
| Fit with a validation set | model.fit(x, y, eval_set=[(x_valid, y_valid)]) |
| Categorical columns | enable_categorical=True on the model or the DMatrix |
| Gain importance | model.get_booster().get_score(importance_type="gain") |
| SHAP values | booster.predict(dmat, pred_contribs=True) |
| Native training | xgb.train(params, dtrain, evals=[...], early_stopping_rounds=50) |
| Cross-validation | xgb.cv(params, dtrain, nfold=5, stratified=True) |
| Imbalanced classes | XGBClassifier(scale_pos_weight=n_neg / n_pos) |
| Regression | xgb.XGBRegressor(eval_metric="rmse") |
| Save | model.save_model("model.json") |
Setup and data
Section titled “Setup and data”The simulated table has a thousand samples with 30 genes and a tissue label. The outcome depends on
Gene_01 and Gene_02, on the product of Gene_03 and Gene_04, and on the tissue. The
other 26 genes are noise. The data splits three ways: training rows fit the trees, validation
rows decide when to stop, and test rows give the final score.
from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport xgboost as xgbfrom sklearn.metrics import ( accuracy_score, r2_score, recall_score, roc_auc_score, root_mean_squared_error,)from sklearn.model_selection import train_test_split
rng = np.random.default_rng(42)Path("outputs").mkdir(exist_ok=True)
n_samples, n_genes = 1000, 30genes = [f"Gene_{i:02d}" for i in range(1, n_genes + 1)]expr = pd.DataFrame(rng.normal(size=(n_samples, n_genes)), columns=genes)tissue = rng.choice(["blood", "liver", "lung"], size=n_samples)tissue_shift = pd.Series(tissue).map({"blood": -1.0, "liver": 0.0, "lung": 1.0})logit = (2.0 * expr["Gene_01"] - 1.5 * expr["Gene_02"] + 1.5 * expr["Gene_03"] * expr["Gene_04"] + tissue_shift)label = rng.binomial(1, 1 / (1 + np.exp(-logit)))expr["tissue"] = pd.Categorical(tissue)
x_rest, x_test, y_rest, y_test = train_test_split( expr, label, test_size=0.2, stratify=label, random_state=42)x_train, x_valid, y_train, y_valid = train_test_split( x_rest, y_rest, test_size=0.25, stratify=y_rest, random_state=42)print(f"train {len(x_train)}, valid {len(x_valid)}, test {len(x_test)}")print(f"positive rate {label.mean():.2f}")train 600, valid 200, test 200positive rate 0.50XGBClassifier with early stopping
Section titled “XGBClassifier with early stopping”Set a generous n_estimators and let early stopping choose the number of trees. Training
stops when the validation log loss has not improved for 50 rounds. enable_categorical=True
lets XGBoost split on the pandas category column directly, with no one-hot encoding.
model = xgb.XGBClassifier( n_estimators=1000, learning_rate=0.05, max_depth=3, subsample=0.8, colsample_bytree=0.8, eval_metric="logloss", early_stopping_rounds=50, enable_categorical=True, tree_method="hist", random_state=42, n_jobs=1,)model.fit( x_train, y_train, eval_set=[(x_train, y_train), (x_valid, y_valid)], verbose=False,)print(f"best iteration = {model.best_iteration}")print(f"best validation log loss = {model.best_score:.4f}")best iteration = 74best validation log loss = 0.4857Early stopping watches the last pair in eval_set, so put the validation set last.
early_stopping_rounds and eval_metric belong in the constructor. Older code passes them
to fit(), which XGBoost 3.4 no longer accepts. n_jobs=1 and a fixed
random_state make the run repeat exactly.
Predict and evaluate
Section titled “Predict and evaluate”After early stopping, predict and predict_proba use the trees up to the best iteration.
test_prob = model.predict_proba(x_test)[:, 1]test_pred = model.predict(x_test)print(f"test accuracy = {accuracy_score(y_test, test_pred):.3f}")print(f"test ROC AUC = {roc_auc_score(y_test, test_prob):.3f}")test accuracy = 0.780test ROC AUC = 0.844Learning curve
Section titled “Learning curve”evals_result() holds the metric for every round and every evaluation set, in the order of
eval_set.
history = model.evals_result()fig, ax = plt.subplots(figsize=(6, 3.8))ax.plot(history["validation_0"]["logloss"], label="train")ax.plot(history["validation_1"]["logloss"], label="validation")ax.axvline(model.best_iteration, color="grey", linestyle="--", label=f"best iteration ({model.best_iteration})")ax.set(xlabel="boosting round", ylabel="log loss", title="XGBoost learning curve")ax.legend(frameon=False)fig.tight_layout()fig.savefig("outputs/xgboost-learning-curve.png", dpi=150)plt.close(fig)
Feature importance
Section titled “Feature importance”get_score reports importance per feature. "gain" is the average loss reduction of the
splits that use a feature, which tracks real signal better than "weight", the raw count of
splits. The other types are "cover", "total_gain", and "total_cover".
gain = pd.Series( model.get_booster().get_score(importance_type="gain")).sort_values(ascending=False)print(gain.head(6).round(2))Gene_02 12.03Gene_01 10.56tissue 7.90Gene_14 4.84Gene_04 4.82Gene_03 4.78dtype: float64Gene_14 carries no signal in this simulation and still ranks fourth, level with the two
interacting genes, so read the gain from a single fit as a rough ranking.
fig, ax = plt.subplots(figsize=(6, 4))xgb.plot_importance(model, importance_type="gain", max_num_features=10, show_values=False, height=0.6, grid=False, ax=ax)ax.set(title="Top 10 features by gain", xlabel="average gain")fig.tight_layout()fig.savefig("outputs/xgboost-importance.png", dpi=150)plt.close(fig)
Native API
Section titled “Native API”DMatrix and xgb.train
Section titled “DMatrix and xgb.train”The native API takes a DMatrix and a parameter dictionary. Here nthread and seed are the
names for n_jobs and random_state, and eta is accepted for learning_rate.
dtrain = xgb.DMatrix(x_train, label=y_train, enable_categorical=True)dvalid = xgb.DMatrix(x_valid, label=y_valid, enable_categorical=True)dtest = xgb.DMatrix(x_test, label=y_test, enable_categorical=True)params = { "objective": "binary:logistic", "eval_metric": "logloss", "learning_rate": 0.05, "max_depth": 3, "subsample": 0.8, "colsample_bytree": 0.8, "tree_method": "hist", "nthread": 1, "seed": 42,}booster = xgb.train( params, dtrain, num_boost_round=1000, evals=[(dtrain, "train"), (dvalid, "valid")], early_stopping_rounds=50, verbose_eval=False,)best_range = (0, booster.best_iteration + 1)native_prob = booster.predict(dtest, iteration_range=best_range)print(f"best iteration = {booster.best_iteration}")print(f"test ROC AUC = {roc_auc_score(y_test, native_prob):.3f}")best iteration = 74test ROC AUC = 0.844Booster.predict uses every tree unless you pass iteration_range. Older code passes
ntree_limit=bst.best_ntree_limit; neither exists in XGBoost 3.4.
SHAP contributions
Section titled “SHAP contributions”pred_contribs=True returns one SHAP value per feature per sample, plus a bias column, with
no extra package. Each row sums to the model’s log-odds for that sample, up to float32
rounding.
contrib = booster.predict(dtest, pred_contribs=True, iteration_range=best_range)margin = booster.predict(dtest, output_margin=True, iteration_range=best_range)print(f"shape {contrib.shape}: {len(x_test)} samples, " f"{x_test.shape[1]} features + bias")sums_match = np.allclose(contrib.sum(axis=1), margin, atol=1e-5)print(f"rows sum to the log-odds: {sums_match}")
mean_abs = pd.Series(np.abs(contrib[:, :-1]).mean(axis=0), index=x_test.columns)print(mean_abs.sort_values(ascending=False).head(5).round(3))shape (200, 32): 200 samples, 31 features + biasrows sum to the log-odds: TrueGene_01 0.770Gene_02 0.638tissue 0.304Gene_07 0.076Gene_21 0.050dtype: float32Cross-validation
Section titled “Cross-validation”xgb.cv runs k-fold training on a DMatrix and returns one row per round, trimmed to the
best round when early stopping is on.
cv_results = xgb.cv( params, dtrain, num_boost_round=1000, nfold=5, stratified=True, early_stopping_rounds=50, seed=42,)print(f"rounds kept = {len(cv_results)}")print(cv_results.tail(3).round(4))rounds kept = 143 train-logloss-mean train-logloss-std test-logloss-mean test-logloss-std140 0.2263 0.0056 0.4913 0.0381141 0.2249 0.0056 0.4915 0.0385142 0.2238 0.0056 0.4909 0.0384Imbalanced outcome
Section titled “Imbalanced outcome”scale_pos_weight
Section titled “scale_pos_weight”scale_pos_weight multiplies the weight of every positive sample, and the usual value is the
number of negatives divided by the number of positives. The block shifts the same simulated
outcome so that positives are rare. Weighting raises recall at the 0.5 cut while the ROC AUC
barely moves, because the ranking of samples hardly changes. It also pushes every predicted
probability up, so do not read weighted outputs as risks. When you need calibrated risks,
leave the weight at 1 and choose the threshold on validation data instead.
rare = rng.binomial(1, 1 / (1 + np.exp(-(logit - 3.0))))xr_train, xr_test, yr_train, yr_test = train_test_split( expr, rare, test_size=0.3, stratify=rare, random_state=42)pos_weight = (yr_train == 0).sum() / (yr_train == 1).sum()print(f"positive rate {rare.mean():.3f}, scale_pos_weight {pos_weight:.1f}")
for weight in [1.0, pos_weight]: rare_model = xgb.XGBClassifier( n_estimators=200, learning_rate=0.05, max_depth=3, scale_pos_weight=weight, enable_categorical=True, tree_method="hist", random_state=42, n_jobs=1, ) rare_model.fit(xr_train, yr_train) rare_prob = rare_model.predict_proba(xr_test)[:, 1] print(f"weight {weight:4.1f}: " f"ROC AUC {roc_auc_score(yr_test, rare_prob):.3f}, " f"recall {recall_score(yr_test, rare_prob >= 0.5):.3f}, " f"mean predicted risk {rare_prob.mean():.3f}")print(f"observed positive rate in test: {yr_test.mean():.3f}")positive rate 0.172, scale_pos_weight 4.8weight 1.0: ROC AUC 0.797, recall 0.346, mean predicted risk 0.156weight 4.8: ROC AUC 0.781, recall 0.442, mean predicted risk 0.252observed positive rate in test: 0.173Regression
Section titled “Regression”XGBRegressor
Section titled “XGBRegressor”The regressor takes the same arguments. The target here is a continuous score built from
Gene_01 and the square of Gene_02, on the same train, validation, and test rows.
score = 2.0 * expr["Gene_01"] + expr["Gene_02"] ** 2score = score + rng.normal(scale=0.5, size=n_samples)
regressor = xgb.XGBRegressor( n_estimators=1000, learning_rate=0.05, max_depth=3, eval_metric="rmse", early_stopping_rounds=50, enable_categorical=True, tree_method="hist", random_state=42, n_jobs=1,)regressor.fit( x_train, score[x_train.index], eval_set=[(x_valid, score[x_valid.index])], verbose=False,)score_pred = regressor.predict(x_test)score_test = score[x_test.index]print(f"best iteration = {regressor.best_iteration}")print(f"test RMSE = {root_mean_squared_error(score_test, score_pred):.3f}")print(f"test R-squared = {r2_score(score_test, score_pred):.3f}")best iteration = 140test RMSE = 0.617test R-squared = 0.937Save and load
Section titled “Save and load”save_model writes JSON or UBJSON, chosen by the file extension. XGBoost keeps this format
loadable by later releases, while a pickle ties the model to the version that wrote it. The best
iteration travels with the model.
model.save_model("outputs/xgboost-model.json")reloaded = xgb.XGBClassifier()reloaded.load_model("outputs/xgboost-model.json")same = np.allclose(reloaded.predict_proba(x_test)[:, 1], test_prob)print(f"reloaded best iteration = {reloaded.best_iteration}")print(f"same test probabilities: {same}")reloaded best iteration = 74same test probabilities: TrueKey parameters
Section titled “Key parameters”| Parameter | What it controls | Default |
|---|---|---|
n_estimators |
maximum number of boosting rounds | 100 |
learning_rate, eta |
shrinkage applied to each tree | 0.3 |
max_depth |
depth of each tree | 6 |
min_child_weight |
minimum hessian sum in a leaf | 1 |
subsample |
fraction of rows sampled per tree | 1 |
colsample_bytree |
fraction of columns sampled per tree | 1 |
gamma |
minimum loss reduction to make a split | 0 |
reg_alpha |
L1 penalty on leaf weights | 0 |
reg_lambda |
L2 penalty on leaf weights | 1 |
early_stopping_rounds |
rounds without improvement before stopping | none |
enable_categorical |
split on pandas category columns |
False |
| Task | objective |
Typical eval_metric |
|---|---|---|
| Binary class | binary:logistic |
logloss, auc |
| Multi-class | multi:softprob |
mlogloss, merror |
| Regression | reg:squarederror |
rmse, mae |
| Counts | count:poisson |
poisson-nloglik |
A lower learning_rate with more rounds usually generalizes better, and early stopping finds
the round count. Tune max_depth and min_child_weight next, then the sampling fractions.
See also
Section titled “See also”Scientific references
Section titled “Scientific references”Chen and Guestrin, 2016 describe XGBoost, a scalable system for gradient tree boosting.
Further reading
Section titled “Further reading”-
The guide explains DMatrix inputs, native training, early stopping, prediction ranges, and model persistence.