Sub topic 15
Interpreting a model: importance and contributions
A boosted ensemble of hundreds of trees is hard to read directly. This chapter covers two ways to look inside a trained XGBoost model. Global importance scores say which features the model relies on overall. Per-prediction contributions say why one row got its score.
It assumes you can train a model with xgb.train or XGBClassifier, as in earlier chapters. It also assumes you know that XGBoost sums tree outputs in log-odds space for binary classification.
Global importance: which features matter
XGBoost counts how each feature is used in the splits of all trees. A Booster exposes five importance types through get_score(importance_type=...):
| Type | What it measures |
|---|---|
| `weight` | Number of splits that use the feature |
| `gain` | Average loss reduction per split that uses the feature |
| `total_gain` | Sum of the loss reduction over all those splits |
| `cover` | Average number of training rows (hessian mass) affected per split |
| `total_cover` | Sum of cover over all those splits |
gain is usually the most informative. A feature that is used in many tiny splits has a high weight but may add little accuracy. weight also favors continuous features, which offer many split points.
Two defaults cause confusion:
Booster.get_scoredefaults toweight.- The scikit-learn wrapper's
feature_importances_usesgainfor tree models, normalized to sum to 1.
Features that never appear in a split are missing from the get_score dictionary. Treat a missing key as zero importance.
Per-prediction contributions
Passing pred_contribs=True to predict returns SHAP-style values computed by the TreeSHAP algorithm. For a binary or regression model, the output has shape (n_samples, n_features + 1). The last column is the bias, the model's expected output before any feature is considered.
Contributions are additive. For each row, the feature contributions plus the bias equal the raw margin. For binary:logistic, the margin is the log-odds, not the probability.
import numpy as np
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, as_frame=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", "eta": 0.1, "max_depth": 3}
booster = xgb.train(params, dtrain, num_boost_round=100)
# Global view: compare importance types
for kind in ["weight", "gain"]:
scores = booster.get_score(importance_type=kind)
top = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)[:3]
print(kind, top)
# Contributions on the validation set
contribs = booster.predict(dval, pred_contribs=True)
margin = booster.predict(dval, output_margin=True)
print(np.allclose(contribs.sum(axis=1), margin, atol=1e-4)) # True
# Local view: the five largest contributions for the first row
names = list(X_val.columns) + ["bias"]
row = sorted(zip(names, contribs[0]), key=lambda kv: abs(kv[1]), reverse=True)[:5]
print(row)
# Global view from contributions: mean absolute value per feature
mean_abs = np.abs(contribs[:, :-1]).mean(axis=0)
order = np.argsort(mean_abs)[::-1][:5]
print([(X_val.columns[i], round(float(mean_abs[i]), 3)) for i in order])The allclose check confirms the additivity property. A positive contribution pushes the log-odds up, toward class 1. A negative one pushes it down.
Mean absolute contribution is a global importance measure built from local explanations. It is measured in the units of the model output, so it is easier to interpret than gain.
Checking importance on held-out data
Gain is computed from the splits made on the training data. A feature can look important only because the model used it to fit noise. Permutation importance asks a different question: how much does the validation score drop when one feature's values are shuffled?
from sklearn.datasets import load_breast_cancer
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
model = XGBClassifier(n_estimators=100, learning_rate=0.1, max_depth=3)
model.fit(X_train, y_train)
gain_rank = sorted(
zip(X.columns, model.feature_importances_), key=lambda kv: kv[1], reverse=True
)[:5]
print("gain:", gain_rank)
result = permutation_importance(
model, X_val, y_val, scoring="roc_auc", n_repeats=10, random_state=0
)
perm_rank = sorted(
zip(X.columns, result.importances_mean), key=lambda kv: kv[1], reverse=True
)[:5]
print("permutation:", perm_rank)If the two rankings disagree, investigate before trusting either. Common causes are noisy features, correlated features, or a small validation set.
Common errors and limits
- Correlated features split the credit. If two features carry the same signal, the trees may use one or the other, or both. Each gets part of the importance, and either can look weaker than the underlying signal. Group correlated features, or drop one and compare the score.
- Importance is not causation. A high-importance feature predicts well. It does not mean that changing it would change the outcome.
- Probability is not margin. Contributions explain the log-odds. A contribution of +1.0 does not mean +1.0 probability points. The effect on probability depends on where the row sits on the sigmoid curve.
- Multi-class output has more dimensions. Recent versions of XGBoost return one set of contributions per class, so the array gains a class axis. Check
contribs.shapebefore indexing. - Missing values get contributions too. A missing entry follows the learned default direction in each tree. Its contribution can be large, so a missing value is not neutral.
- Contributions depend on the model, not the data alone. They explain this model's behavior, including its mistakes. Two models with the same accuracy can give different explanations.
pred_interactions=True goes one step further. It returns pairwise feature interaction values with shape (n_samples, n_features + 1, n_features + 1). It can be slow and memory-heavy with many features.
Exercise
A binary:logistic model returns pred_contribs values for one row. The feature contributions sum to 1.2 and the bias is -0.4. What is the predicted probability, and which prediction mode would you compare against to confirm the sum?
Show answer
The raw margin is 1.2 + (-0.4) = 0.8 log-odds, so the probability is 1 / (1 + exp(-0.8)), about 0.69. You confirm it by comparing the sum of the whole contribution row, including the bias column, with predict(..., output_margin=True). That prediction mode returns the log-odds before the sigmoid.
Exercise
A feature ranks first by weight but near the bottom by gain and by permutation importance. What is the most likely explanation, and what would you do next?
Show answer
The feature is used in many splits but each split reduces the loss very little. This is common for continuous features that offer many split points, and it can mean the model is fitting noise. Trust gain and permutation importance over weight. Next, check whether removing the feature changes the validation score, and consider stronger regularization.