ML Engineering
Interpretability — Understanding Why Your Model Predicts What It Does
Dive into model interpretability techniques that help you understand, explain, and trust your machine learning models. Learn SHAP, LIME, and other explainability methods.
- SHAP Values — Game theory-based feature importance
- LIME — Local interpretable model-agnostic explanations
- Partial Dependence Plots — Visualizing feature effects
"If you can't explain it, you don't understand it well enough."
Model Interpretability — Complete Guide
Interpretability explains why a model makes specific predictions. Essential for trust, debugging, and regulatory compliance.
Interpretability Methods
Global (model-level):
- Feature importance (tree-based)
- Permutation importance
- Partial dependence plots
- SHAP summary plots
Local (prediction-level):
- LIME
- SHAP waterfall plots
- Counterfactual explanations
- Anchors
Interpretability Spectrum
SHAP Implementation
import shap
# TreeExplainer for tree models
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_test)
# Summary plot
shap.summary_plot(shap_values, X_test)
# Force plot (single prediction)
shap.force_plot(explainer.expected_value, shap_values[0], X_test.iloc[0])
# Dependence plot
shap.dependence_plot("feature_name", shap_values, X_test)
SHAP Waterfall Plot Visualization
LIME Implementation
from lime.lime_tabular import LimeTabularExplainer
explainer = LimeTabularExplainer(
X_train.values,
feature_names=feature_names,
class_names=['Not Fraud', 'Fraud']
)
# Explain single prediction
explanation = explainer.explain_instance(
X_test.iloc[0].values,
model.predict_proba,
num_features=10
)
explanation.show_in_notebook()
LIME Local Approximation
Reading a SHAP Waterfall — Worked Numbers
A SHAP explanation has three parts and each one carries a number you can check. The base value is the model's average output over the training background set. For the classifier drawn above the base value is 0.45, meaning that before seeing any attribute of this person the model would answer 0.45. Feature contributions then move that number, and the final output is 0.76.
Check the arithmetic yourself: 0.45 + 0.25 (income above $75K) + 0.15 (age above 40) − 0.10 (PhD) + 0.08 (experience above ten years) − 0.05 (mortgage) − 0.02 (married) = 0.76. Nothing is lost and nothing is left unexplained. That identity is the efficiency property of Shapley values: contributions always sum to the difference between this prediction and the expected prediction. If your own explainer output does not add up, you either fed it a background sample that does not match the training distribution or you read the wrong output index in a multi-class model.
| Feature of this person | SHAP value | Reading |
|---|---|---|
| Income above $75K | +0.25 | Largest single push upward |
| Age above 40 | +0.15 | Second strongest push upward |
| Education at PhD level | −0.10 | Pulls the score down |
| Experience above ten years | +0.08 | Moderate push upward |
| Holds a mortgage | −0.05 | Slight downward pull |
| Marital status | −0.02 | Nearly irrelevant here |
Sort the entries by absolute contribution rather than by the order the plot prints them, then translate each label back to the real feature value instead of the abstract column name. A score of 0.76 against a decision threshold of 0.50 means this person is approved, and the two features capable of flipping that outcome are income and age — the explanation already tells an analyst where to hunt for the rule the model has effectively learned.
Choosing an Explainer
Match the method to the question you are asking, because the wrong explainer is worse than none: it hands back a confident story about a model that behaves differently.
- Which features matter across the whole model? Use permutation importance for a fast check, then a TreeSHAP summary plot for detail.
- Why did this one prediction land where it did? Use a SHAP waterfall, or LIME when the model type has no dedicated explainer.
- What would have to change for the answer to flip? Use counterfactual explanations, the only family phrased as an action a person can take.
- Can I publish a rule a human can follow? Use an intrinsically interpretable model, or an anchor that lists conditions holding with at least 90% precision.
| Method | Scope | Cost at realistic scale | Characteristic failure |
|---|---|---|---|
| TreeSHAP | Global and local | One pass per tree, linear in trees and depth | Misreads the model if the background sample contradicts training data |
| KernelSHAP | Local | Up to two raised to the power of M calls; twenty features already approaches a million | Impractical past roughly fifteen features |
| LIME | Local | A few hundred perturbed samples per explanation | Unstable across reruns and neighbourhood widths |
| Permutation importance | Global | Thirty shuffles per feature, no retraining | Correlated features hide or split each other's effect |
| Partial dependence | Global | One grid sweep, often a hundred points per feature | Assumes independence and invents impossible feature combinations |
Permutation importance rewards a quick test because it measures behaviour instead of structure: shuffle one column, rescore, and watch the metric fall.
import numpy as np
from sklearn.inspection import permutation_importance
result = permutation_importance(
model, X_test, y_test,
n_repeats=30, random_state=0, scoring="roc_auc",
)
baseline_auc = 0.871
for i in np.argsort(result.importances_mean)[::-1][:8]:
drop = result.importances_mean[i]
noise = result.importances_std[i]
verdict = "keep" if drop > 2 * noise else "drop"
print(f"{X_test.columns[i]:<22} AUC -{drop:.3f} +/- {noise:.3f} {verdict}")
Reading that output needs a threshold rule. Shuffling session_count costs 0.028 AUC with a standard deviation of 0.004 across the thirty shuffles, which is seven times the noise band — a real signal. Shuffling signup_weekday moves AUC by 0.001 with a standard deviation of 0.005, so the effect is indistinguishable from zero and the column is a candidate for removal.
Where Explanations Mislead
Three failure modes dominate production reviews. Correlated features divide or swap credit: when two columns both encode income, SHAP splits the contribution between them, and removing either column alone barely moves the score. An analyst reading the waterfall then concludes income hardly matters. Group correlated columns before explaining, or compute conditional SHAP against a background sample that preserves the correlation structure.
LIME is stochastic by design. It samples a neighbourhood around the instance, fits a weighted linear model, and returns the coefficients; rerun it with another seed and the ranked features can change order or drop out entirely, which is why a single LIME screenshot in a notebook is not evidence. Run it ten to twenty times, report the features that appear in most runs, and state the width of the neighbourhood you used.
Explanations also do not repair a bad model. A classifier that under-approves one group will still produce a fluent, plausible waterfall for each rejected applicant, and that fluency accelerates a wrong decision if aggregate metrics were never checked. Keep the order of work fixed: validate accuracy, calibration and fairness slices first, then explain individual predictions. Under the EU AI Act, high-risk systems additionally require logging, documentation and human oversight, which is why writing model cards and running explainability analysis turn out to be the same discipline.
Common Mistakes
Reading a SHAP value as a causal claim about the world
Fix: Treat it as attribution for one model's output — a positive value for income says the model reacted to that column, not that raising income causes approval.
Running LIME once and pasting the first result
Fix: Run it ten to twenty times with different seeds, keep the features that recur, and record the neighbourhood width used.
Explaining individual predictions before checking aggregate metrics
Fix: Verify accuracy, calibration and fairness slices first, then explain cases — a local explanation of a broken model only rationalizes the error.
Key Takeaways
What to Learn Next
-> ML Ethics — Fairness, Bias, Interpretability and Responsible AI Learn about ml ethics — fairness, bias, interpretability and responsible ai.
-> Random Forest — Complete Guide for Ensemble Learning Learn about random forest — complete guide for ensemble learning.
-> Decision Trees — Complete Guide with Visualizations Learn about decision trees — complete guide with visualizations.
-> XGBoost and Gradient Boosting — Complete Guide Learn about xgboost and gradient boosting — complete guide.
-> Model Evaluation — Metrics, Cross-Validation and Selection Learn about model evaluation — metrics, cross-validation and selection.
-> ML System Design — Architecture and Production Patterns Learn about ml system design — architecture and production patterns.