Your model is 95% accurate. Now someone asks why it made a particular decision. Here’s how to answer.
Most machine learning tutorials end with an accuracy score. In real projects, that’s where the hard questions start. A doctor won’t trust a model that flags a tumour as malignant without a reason. A bank can’t reject a loan application and say “the algorithm decided”.
I ran into this while working on research into explainable machine learning for water quality assessment. A good score wasn’t enough. We needed to show which measurements drove each prediction, so people could check the model’s reasoning against what they already knew.
The tool that made this possible was SHAP. In this tutorial, we’ll train a model on a real medical dataset and use SHAP to explain it two ways: which features matter most overall, and why the model made one specific prediction. The full code is on GitHub.
What SHAP actually does
SHAP stands for SHapley Additive exPlanations. The idea comes from game theory: if a team wins a prize, how do you split it fairly based on how much each player contributed?
SHAP treats each feature as a player and the prediction as the prize. For every single prediction, it calculates how much each feature pushed the result up or down compared to the model’s average prediction.
The key property is that these contributions add up exactly:
\text{prediction} = \text{average prediction} + \sum_i \text{SHAP value}_i
So if the model’s average prediction is 0.62 and it predicts 0.10 for one patient, the SHAP values for that patient add up to -0.52. Each one tells you how much that feature was responsible for.
This makes SHAP more useful than the built-in feature importance in tree models. That gives you one number per feature for the whole dataset. SHAP tells you the direction of the effect, and works for each individual prediction too.
Setup
pip install scikit-learn shap matplotlib pandas
We’ll use the breast cancer dataset that comes with scikit-learn, so there’s nothing to download. It has 569 tumour samples, each described by 30 measurements taken from a scan, such as radius, area, and the number of concave points on the tumour’s edge. Each sample is labelled malignant (212 cases) or benign (357 cases).
from pathlib import Path
import matplotlib
matplotlib.use("Agg") # save plots to files without opening windows
import matplotlib.pyplot as plt
import pandas as pd
import shap
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
from sklearn.model_selection import train_test_split
OUT_DIR = Path("plots")
OUT_DIR.mkdir(exist_ok=True)
Step 1: Load the data
def load_data():
data = load_breast_cancer(as_frame=True)
X, y = data.data, data.target # target: 0 = malignant, 1 = benign
return train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
as_frame=True gives us a pandas DataFrame with proper column names. That matters later: SHAP plots use these names, so they're readable without extra work.
stratify=y keeps the same ratio of malignant to benign cases in both the training and test sets. With an imbalanced dataset like this one, a random split could leave the test set with too few malignant cases to judge the model properly.
Step 2: Train the model
def train_model(X_train, y_train, X_test, y_test):
model = RandomForestClassifier(n_estimators=200, max_depth=6, random_state=42)
model.fit(X_train, y_train)
preds = model.predict(X_test)
print(f"Test accuracy: {accuracy_score(y_test, preds):.3f}")
print(classification_report(y_test, preds, target_names=["malignant", "benign"]))
return model
A Random Forest is a good choice here. It works well on tabular data without much tuning, and SHAP has a fast, exact method for tree models.
On the 114 test samples, the model reaches 94.7% accuracy:
That’s a solid model. But these numbers can’t tell us what it learned. That’s where SHAP comes in.
Step 3: Compute SHAP values
def compute_shap(model, X_test):
explainer = shap.TreeExplainer(model)
shap_values = explainer(X_test)
# For a binary classifier, SHAP returns one set of values per class.
# We keep class 1 ("benign"): positive values push towards benign.
return shap_values[:, :, 1]
TreeExplainer is SHAP's method for tree-based models like Random Forest and XGBoost. It's fast and gives exact values instead of approximations.
The last line trips up a lot of beginners. For a classifier, SHAP returns values for every class, so the result has three dimensions: samples, features, and classes. We pick class 1 (benign). From here on, a positive SHAP value pushes a prediction towards benign, and a negative one pushes it towards malignant.
Step 4: See what the model learned overall
The first question to ask is: which features does the model rely on most?
shap.plots.bar(sv, max_display=10, show=False)
plt.tight_layout()
plt.savefig(OUT_DIR / "shap_bar.png", dpi=150)
plt.close()
The bar plot ranks features by their average impact. The top five are worst perimeter, worst area, worst concave points, worst radius and mean concave points. (“Worst” in this dataset means the largest value measured across the tumour’s cells.) In other words, the model mostly looks at tumour size and the shape of its edges.
The bar plot tells you how much each feature matters, but not in which direction. For that, we use the beeswarm plot:
shap.plots.beeswarm(sv, max_display=10, show=False)
plt.tight_layout()
plt.savefig(OUT_DIR / "shap_beeswarm.png", dpi=150)
plt.close()
This is the most information-dense plot in SHAP, so it’s worth learning to read:
- Each dot is one patient in the test set.
- Its position left or right is the SHAP value: left pushes towards malignant, right towards benign.
- Its colour is the feature’s actual value: red is high, blue is low.
Look at worst perimeter: the red dots (large tumours) sit on the left, and the blue dots (small ones) on the right. So the model has learned that larger, more irregular tumours are more likely to be malignant.
That matches medical knowledge, and this is the real value of SHAP. If the plot had shown the opposite, or if the top feature had been something meaningless like a sample ID, we’d know the model had learned something wrong, even with a 95% accuracy score.
Step 5: Explain one prediction
Global plots describe the model as a whole. But a doctor looking at one patient wants to know why the model flagged this case. Let’s explain the first malignant tumour in the test set.
def explain_one(model, sv, X_test, y_test, idx=0):
proba = model.predict_proba(X_test.iloc[[idx]])[0, 1]
actual = "benign" if y_test.iloc[idx] == 1 else "malignant"
print(f"Sample {idx}: predicted P(benign) = {proba:.3f}, actual = {actual}")
print(f"Base value (average prediction): {sv.base_values[idx]:.3f}")
shap.plots.waterfall(sv[idx], max_display=10, show=False)
plt.tight_layout()
plt.savefig(OUT_DIR / f"shap_waterfall_sample{idx}.png", dpi=150)
plt.close()
The output:
Sample 0: predicted P(benign) = 0.000, actual = malignant
Base value (average prediction): 0.625
The model is certain this tumour is malignant, and it’s right. Here’s why:
Read the waterfall plot from the bottom up:
- It starts at the base value, 0.625. This is the model’s average prediction: before looking at this patient, it leans towards benign, because benign cases are more common.
- Each bar is one feature’s contribution. Every bar here points left, towards malignant.
- The biggest pushes come from worst concave points (0.194), worst perimeter (178.6) and worst area (1,926), each lowering the prediction by about 0.07 to 0.08.
- Together, all the contributions bring the prediction down from 0.625 to 0.
This is the kind of explanation a person can actually check. A doctor could look at this and say: “Yes, a tumour this large with this many irregular points is worrying.” The model’s decision is no longer a black box.
Common mistakes to avoid
- Treating SHAP as cause and effect. SHAP explains what the model relies on, not what causes cancer in the real world. If two features are strongly related, like radius and area here, the model may split credit between them in ways that don’t reflect biology.
- Forgetting which class you’re explaining. If you pick class 0 instead of class 1, every sign flips and your interpretation is backwards. Always write down which class positive values point towards.
- Explaining only the global picture. The bar plot alone can hide a lot. Look at individual predictions too, especially the ones the model got wrong. Those usually teach you the most.
- Using the slow explainer by accident. shap.KernelExplainer works with any model but can be very slow. For tree models, always use TreeExplainer.
Conclusion
In just over 100 lines of Python, we trained a model with 94.7% test accuracy and then answered the questions accuracy can’t: which features drive its decisions, in which direction, and why it made one specific prediction.
The main lesson is simple. Before you trust a model, check that it learned something sensible. Here, SHAP confirmed the model relies on tumour size and edge shape, which matches medical knowledge. In other projects, it might reveal that your model learned a shortcut you never intended.
The complete code is on GitHub. Try it on your own dataset, and let me know in the comments what SHAP reveals about your model.
If you found this useful, follow me for more practical machine learning tutorials.




Top comments (0)