GyaanStack. Blog

Articles / machine-learningexplainabilitypython

Explain ML model predictions with SHAP: global and single-row views

Explain a tabular model's predictions with SHAP, cross-check with scikit-learn permutation importance, and avoid three traps that make explanations wrong.

By Raghunath · · 15 min read

A model that predicts disease progression for a patient as 298 will get one question from a doctor, a product manager or an auditor: why 298 and not 150? Accuracy numbers do not answer it. You need two things. A per-row breakdown that says which inputs pushed this prediction up or down and by how much, and a global ranking that says which inputs the model leans on across all rows.

SHAP gives you both from the same numbers. This post trains a gradient-boosted regressor on a dataset that ships inside scikit-learn, explains it with SHAP, checks the result against scikit-learn's permutation importance, and then breaks the explanation on purpose with a duplicated feature and a column of random noise. Every table below is real output from the scripts in the post.

Versions used: Python 3.15, scikit-learn 1.9.1, shap 0.54.1 (shap needs Python 3.12 or newer, per PyPI), pandas 3.1.1, numpy 2.5.5.

python3 -m venv venv
./venv/bin/pip install scikit-learn shap pandas matplotlib

What a SHAP value is#

SHAP (Lundberg and Lee, 2017) borrows the Shapley value from cooperative game theory. Treat the features of one row as players and the model's output as the payout. A feature's Shapley value is its average marginal contribution to the output, averaged over every order in which features could be added. The property that makes it useful in practice is additivity (the paper calls it local accuracy):

prediction(row) = base value + SHAP(feature 1) + SHAP(feature 2) + ... + SHAP(feature n)

base value   = what the model predicts when it knows nothing about this row
SHAP(f) > 0  = feature f pushed this prediction above the base value
SHAP(f) < 0  = feature f pulled it below

Computing exact Shapley values is exponential in the number of features for a general model. For tree ensembles, the TreeSHAP algorithm (Lundberg et al., 2020) computes them exactly in polynomial time, which is why shap.TreeExplainer is fast enough to run on every row of a test set.

LIME (Ribeiro et al., 2016) is the other common choice for per-row explanations. It perturbs one row, queries the model, and fits a small weighted linear model around that point. It works with any model, including text and image classifiers, but the surrogate's weights do not add up to the prediction and can shift between runs because of the random sampling. For a tree model on tabular data, TreeSHAP is exact and deterministic, so it is the better default.

The dataset and the model#

The diabetes dataset in scikit-learn has 442 patients and ten baseline measurements: age, sex, body mass index (bmi), average blood pressure (bp), and six blood serum values s1 to s6 (total cholesterol, LDL, HDL, cholesterol/HDL ratio, a log triglycerides measure, and blood sugar). The target is a quantitative measure of disease progression one year after baseline (dataset docs). It is bundled with the library, so nothing is downloaded.

By default load_diabetes returns mean-centred, scaled features. Passing scaled=False gives the original units, which matters for explanations: "bmi = 36.1" is something a person can read, "bmi = 0.0703" is not.

The first script trains the model, computes SHAP values for the 111 test rows, checks additivity, and builds the global and local tables. It is printed in three parts with the output after each.

import numpy as np
import pandas as pd
import shap
from sklearn.datasets import load_diabetes
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split

pd.set_option("display.width", 120)
SEED = 42

# 1. Data: ships inside scikit-learn, no download.
X, y = load_diabetes(return_X_y=True, as_frame=True, scaled=False)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=SEED)

model = GradientBoostingRegressor(n_estimators=150, max_depth=2, learning_rate=0.05,
                                  subsample=0.8, random_state=SEED)
model.fit(X_train, y_train)
print(f"rows train/test: {len(X_train)}/{len(X_test)}")
print(f"test R^2: {model.score(X_test, y_test):.3f}")

# 2. SHAP values for every test row.
explainer = shap.TreeExplainer(model)
sv = explainer(X_test)                      # shap.Explanation
base = float(np.ravel(sv.base_values)[0])
print(f"\nbase value (mean training prediction): {base:.1f}")

# 3. Additivity check: base + sum(SHAP) must equal the model output.
recon = sv.base_values + sv.values.sum(axis=1)
gap = np.abs(recon - model.predict(X_test)).max()
print(f"max |base + sum(SHAP) - prediction| over test set: {gap:.2e}")
rows train/test: 331/111
test R^2: 0.472

base value (mean training prediction): 153.9
max |base + sum(SHAP) - prediction| over test set: 2.27e-13

Two notes before reading any explanation.

First, the model is mediocre. A test R² of 0.472 means it explains under half the variance, and a plain LinearRegression on the same split scores 0.485. Run that comparison before you explain anything. SHAP will produce a confident-looking breakdown for a bad model just as readily as for a good one, and an explanation of a model you should not ship is wasted work.

Second, the additivity gap is 2.27e-13, which is floating-point noise. Keep this check in your code as an assertion. If you ever pass the explainer a different model than the one you predict with (a retrained version, a different pipeline step, a calibrated wrapper), this number jumps and tells you before a stakeholder does.

The print label says "mean training prediction", which is close but not exact. With no background dataset, TreeExplainer uses the tree_path_dependent mode (docs) and takes the base value from how many training samples fell into each leaf. Here that gives 153.9, while the model's average prediction on the training rows is 154.5. Pass a background sample if you need the base to mean something specific; more on that below.

Global view: mean absolute SHAP#

Average the absolute SHAP value of each feature across rows and you get a ranking of how much each feature moves predictions, in the target's own units. The same script also runs permutation importance on the held-out set: shuffle one column, re-score the model, and record how much R² drops. Thirty shuffles per feature give a mean and a standard deviation.

# 4. Global view: mean |SHAP| per feature.
global_shap = pd.Series(np.abs(sv.values).mean(axis=0), index=X.columns)

# 5. Cross-check: permutation importance on held-out data.
perm = permutation_importance(model, X_test, y_test, n_repeats=30,
                              random_state=SEED, scoring="r2")
table = pd.DataFrame({
    "mean_abs_shap": global_shap,
    "perm_drop_r2": perm.importances_mean,
    "perm_std": perm.importances_std,
}).sort_values("mean_abs_shap", ascending=False)
table["shap_rank"] = range(1, len(table) + 1)
table["perm_rank"] = table["perm_drop_r2"].rank(ascending=False).astype(int)
print("\nGlobal importance (test set)")
print(table.round(3).to_string())
Global importance (test set)
     mean_abs_shap  perm_drop_r2  perm_std  shap_rank  perm_rank
s5          23.829         0.307     0.054          1          1
bmi         23.014         0.207     0.051          2          2
bp          13.731         0.047     0.029          3          3
s3           9.675         0.023     0.025          4          5
s1           5.667        -0.016     0.017          5         10
age          5.060         0.012     0.011          6          7
sex          4.899         0.038     0.012          7          4
s6           3.811         0.019     0.013          8          6
s2           1.903        -0.001     0.005          9          8
s4           1.720        -0.003     0.007         10          9

The top three agree: s5 (triglycerides), bmi and bp. On average, s5 and bmi each move a prediction by about 23 points of disease progression. Shuffling s5 costs 0.307 of R², which is most of the 0.472 the model has.

Below the top three the methods disagree, because the two numbers answer different questions:

mean |SHAP|            -> how much does the model's output move because of this feature?
                          (computed from predictions only; labels are never used)
permutation importance -> how much worse does the model score on held-out labels
                          when this feature's information is destroyed?

Take s1 (total cholesterol). SHAP ranks it fifth: the model does use it, by about 5.7 points per row. Permutation ranks it last with a slightly negative drop, meaning the test score does not get worse when s1 is shuffled. s1 and s2 have a correlation of 0.897 in this data, so the model can recover most of the s1 signal elsewhere, and what it learned from s1 specifically does not generalise. Look at the standard deviations too: for s1 the drop is -0.016 with a spread of 0.017, so zero is inside one standard deviation. Treat any feature whose permutation mean is within about two standard deviations of zero as "no measurable effect on held-out accuracy", whatever its SHAP rank.

sex goes the other way: rank 7 by SHAP, rank 4 by permutation, with a tight spread (0.038 ± 0.012). Its effect is small per row but reliable.

If you only report one, report mean |SHAP| for "what does the model use" and permutation on held-out data for "what does accuracy depend on", and say which one you are showing.

Single-prediction view#

The global table cannot answer the doctor's question about one patient. Pick a row and sort its SHAP values by size. The script uses the row with the highest prediction in the test set.

# 6. Local view: one patient.
i = int(np.argmax(model.predict(X_test)))
row = X_test.iloc[i]
local = pd.DataFrame({"value": row, "shap": sv.values[i]})
local = local.reindex(local["shap"].abs().sort_values(ascending=False).index)
pred = model.predict(X_test.iloc[[i]])[0]
print(f"\nSingle prediction: test row {i} (index {X_test.index[i]})")
print(f"actual={y_test.iloc[i]:.0f}  predicted={pred:.1f}  base={base:.1f}")
print(local.round(2).to_string())
print(f"base + sum(shap) = {base + sv.values[i].sum():.1f}")
Single prediction: test row 102 (index 332)
actual=270  predicted=297.8  base=153.9
      value   shap
bmi   36.10  69.54
s5     5.27  30.92
bp   117.00  24.31
s3    34.00  15.70
sex    1.00   5.37
s1   181.00  -4.76
s6   100.00  -3.82
age   57.00   3.45
s2   108.20   2.59
s4     5.00   0.57
base + sum(shap) = 297.8

Read it as a sum, top to bottom:

base value                     153.9
+ bmi = 36.1                   +69.5   -> 223.4
+ s5  = 5.27                   +30.9   -> 254.4
+ bp  = 117                    +24.3   -> 278.7
+ s3  = 34                     +15.7   -> 294.4
+ six smaller terms             +3.4   -> 297.8   (model output; actual was 270)

In words: this patient's prediction is 144 points above average, and almost half of that gap comes from a bmi of 36.1 (the dataset's bmi range is 18 to 42.2). High triglycerides and blood pressure of 117 (dataset mean 94.6) add most of the rest. An HDL value (s3) of 34, below the dataset mean of 49.8, adds 15.7. Cholesterol and blood sugar pull the prediction down slightly.

That paragraph is the deliverable for a non-technical reader. The table is the evidence behind it.

The same views as charts#

shap draws both views directly. The beeswarm plot shows every row's SHAP value per feature, coloured by feature value, so you can see direction as well as size (high bmi pushes up, low bmi pushes down). The waterfall plot draws the single-row sum above as bars from the base value to the prediction.

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

shap.plots.beeswarm(sv, show=False)          # global view
plt.savefig("beeswarm.png", bbox_inches="tight"); plt.close()
shap.plots.waterfall(sv[102], show=False)     # one prediction
plt.savefig("waterfall.png", bbox_inches="tight"); plt.close()

The waterfall for row 102 shows E[f(X)] = 153.941 at the bottom, f(x) = 297.81 at the top, and the same bars as the table. The plots are good for a slide. For a report or a ticket, the printed table is easier to check and to diff between model versions.

Pitfall 1: correlated features split the credit#

SHAP splits credit among features that carry the same information, and permutation importance underrates both of them. Both effects are easy to show. The second script adds a near-copy of bmi (bmi plus a little noise, correlation 0.985) and a column of pure random noise, then retrains the same model.

rng = np.random.default_rng(SEED)
X, y = load_diabetes(return_X_y=True, as_frame=True, scaled=False)

# Add a near-duplicate of bmi (corr ~0.98) and a column of pure noise.
X = X.copy()
X["bmi_copy"] = X["bmi"] + rng.normal(0, 0.8, len(X))
X["noise"] = rng.normal(0, 1, len(X))
print(f"corr(bmi, bmi_copy) = {X['bmi'].corr(X['bmi_copy']):.3f}")

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=SEED)
model = GradientBoostingRegressor(n_estimators=150, max_depth=2, learning_rate=0.05,
                                  subsample=0.8, random_state=SEED).fit(X_train, y_train)
print(f"test R^2 with extra columns: {model.score(X_test, y_test):.3f}")

ex = shap.TreeExplainer(model)
shap_test = np.abs(ex(X_test).values).mean(axis=0)
shap_train = np.abs(ex(X_train).values).mean(axis=0)
perm_test = permutation_importance(model, X_test, y_test, n_repeats=30, random_state=SEED)
perm_train = permutation_importance(model, X_train, y_train, n_repeats=30, random_state=SEED)

cols = ["bmi", "bmi_copy", "s5", "noise"]
idx = [list(X.columns).index(c) for c in cols]
out = pd.DataFrame({
    "shap_train": shap_train[idx], "shap_test": shap_test[idx],
    "perm_train": perm_train.importances_mean[idx], "perm_test": perm_test.importances_mean[idx],
    "perm_test_std": perm_test.importances_std[idx],
}, index=cols)
print(out.round(3).to_string())
corr(bmi, bmi_copy) = 0.985
test R^2 with extra columns: 0.492
          shap_train  shap_test  perm_train  perm_test  perm_test_std
bmi           14.585     13.847       0.140      0.075          0.031
bmi_copy       9.500      9.996       0.056      0.038          0.020
s5            21.101     22.329       0.206      0.268          0.048
noise          2.816      1.881       0.035      0.008          0.007

Compare with the first run. bmi alone had a mean |SHAP| of 23.0. With a copy in the data, bmi gets 13.8 and bmi_copy gets 10.0. The sum, 23.8, is about where it was, but a reader of the global table now sees bmi in third place behind s5, and could conclude body mass matters less than it did. The model did not change its view of the patient; the credit was split across two columns.

Permutation importance does worse. bmi on its own cost 0.207 of R² when shuffled. Now bmi costs 0.075 and bmi_copy costs 0.038, a combined 0.113, because when one copy is shuffled the model still reads the other. The scikit-learn docs describe this exact failure and show a fix in an example: cluster features by correlation, keep one per cluster, and compute importance on the reduced set.

Before you explain a model, print the correlation matrix and list every pair above about 0.8. Either drop to one feature per group, or sum SHAP values across the group and report the group ("body size") rather than the individual columns. Additivity makes summing SHAP values within a group valid for a single row.

Pitfall 2: noise gets credit in-sample#

The noise column has no relationship with the target by construction. SHAP still gives it a mean |SHAP| of 2.8 on training rows and 1.9 on test rows, because the trees found splits on it that happened to reduce training error. SHAP reports what the model does, and this model uses noise.

Permutation importance tells the two cases apart. On the training set, shuffling noise costs 0.035 of R², which looks real. On the test set it costs 0.008 with a spread of 0.007, close to zero. A feature that matters on training data and stops mattering on held-out data is memorised noise. This is why the permutation runs in this post use X_test, and why the scikit-learn docs warn that importance computed on a model with a poor held-out score says little.

Add a random column to your own feature set once, as a test. Any real feature whose mean |SHAP| falls below the random column's is not one you should talk about.

Pitfall 3: the explanation is about the model, not the world#

The bmi SHAP value of +69.5 for row 102 says: this model's output for this patient is 69.5 higher because of the bmi value it was given. It does not say that lowering this patient's bmi to the average would lower their disease progression by 69.5. That is a causal claim, and SHAP values on observational data cannot support it. Lowering bmi in real life would also change blood pressure, triglycerides and blood sugar, which the model sees as separate inputs. The SHAP docs have a full notebook on this, Be careful when interpreting predictive models in search of causal insights.

The base value adds a quieter version of the same trap. "Above average" depends on what average you chose. With the default tree_path_dependent mode, the base is the training-set average as the trees saw it. If you pass a background dataset (for example shap.TreeExplainer(model, X_train.sample(100, random_state=0))), the explainer switches to interventional mode and every SHAP value is measured against that sample instead. Explaining a loan rejection relative to "all applicants" and relative to "approved applicants" gives different numbers, and both are correct for their question. Write down which background you used.

A checklist before you show an explanation to anyone#

[ ] model beats a simple baseline on held-out data   (here: 0.472 vs 0.485, it does not)
[ ] additivity gap ~ 0 for every explained row       (assert, do not eyeball)
[ ] correlated pairs > 0.8 listed; grouped or dropped
[ ] permutation importance on held-out data, with std
[ ] random-noise column as a floor for "matters"
[ ] background / base value stated in the write-up
[ ] wording says "the model's prediction moved by", never "causes"

The first box failed on this run. That is a real outcome: the honest report here is that a linear model does as well, and its coefficients are an explanation already.

If you are turning a project like this into an interview story, this five-part script shows how to present the model, the numbers and the limits. For an agent that runs this kind of analysis and is checked against the data it reports on, see an EDA agent that cannot make up numbers. Where explainability fits in the production lifecycle is covered in MLOps vs LLMOps.

Sources#

Found this useful? You can buy me a coffee or support with any amount. It pays for hosting and keeps new articles coming.