Explaining a tree model with SHAP values

MediumInterpretability & Explainable AIModel interpretability

Goal: Finding the most influential features globally and for a single sample.

Python — example.py
import numpy as np, shap, xgboost as xgb
from sklearn.datasets import load_diabetes

data = load_diabetes()
model = xgb.XGBRegressor(n_estimators=100, max_depth=3, random_state=0).fit(data.data, data.target)
explainer = shap.TreeExplainer(model)
sv = explainer.shap_values(data.data)
imp = np.abs(sv).mean(0)
print("Top features:", [data.feature_names[i] for i in imp.argsort()[::-1][:3]])
i = 0
print(f"Sample 0: base {explainer.expected_value:.2f} + sum of SHAP {sv[i].sum():.2f} = {explainer.expected_value + sv[i].sum():.2f}")
print(f"Model prediction: {model.predict(data.data[:1])[0]:.2f}")

Code explanation

TreeExplainer computes Shapley values exactly and quickly for tree models. The mean absolute value of each feature gives global importance, and the sum of a sample's values plus the base value equals the model's output for it (the additivity property).

Requirements

Shell
pip install shap xgboost scikit-learn

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

Top features: ['s5', 'bmi', 'bp']
Sample 0: base 152.14 + sum of SHAP 42.02 = 194.15
Model prediction: 194.15

This example was actually run and tested on 21 November 2026 on a CPU — shap 0.54.1, xgboost 3.4.1, scikit-learn 1.9.1, python 3.13.18

Libraries used

Related examples

AdvancedCaptumRun and tested

Integrated Gradients for a PyTorch network

Attributing the network's prediction to input features and checking the completeness axiom.

Interpretability & Explainable AI · Explaining networks