🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Model Interpretability — SHAP, LIME and Explainable AI

Advanced TopicsInterpretability🟢 Free Lesson

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

Interpretability vs Accuracy SpectrumModel Complexity / AccuracyLowHighLinearRegressionFully explainableDecisionTreeRule-basedRandomForestFeature importanceXGBoost/ GBMSHAP for explanationDeepNeural NetBlack box (needs XAI)Inherently interpretable modelsPost-hoc explanation methodsTrade-off: More complex models are harder to interpret but often more accurate

SHAP Implementation

python
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

SHAP Waterfall Plot: Individual Prediction ExplanationBase Value: 0.45 (average model output)0+0.25 (income)+0.15 (age)-0.10 (edu)+0.08 (exp)-0.05-0.02= 0.76Feature Contributions• Income > $75K → +0.25• Age > 40 → +0.15• Education = PhD → -0.10• Experience > 10yr → +0.08• Has mortgage → -0.05• Married → -0.02Red = increases predictionGreen = decreases predictionE[f(x)] = 0.45 → f(x) = 0.76

LIME Implementation

python
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

LIME: Local Interpretable Model-Agnostic ExplanationsComplex Model Decision BoundaryLocalRegionx₀Local Surrogate Modelg(x) = 0.3·income + 0.2·age - 0.1·education + 0.15·experienceLinear model fitted locallyLIME perturbs input, fits interpretable model to local neighborhood of predictions

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 personSHAP valueReading
Income above $75K+0.25Largest single push upward
Age above 40+0.15Second strongest push upward
Education at PhD level−0.10Pulls the score down
Experience above ten years+0.08Moderate push upward
Holds a mortgage−0.05Slight downward pull
Marital status−0.02Nearly 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.
MethodScopeCost at realistic scaleCharacteristic failure
TreeSHAPGlobal and localOne pass per tree, linear in trees and depthMisreads the model if the background sample contradicts training data
KernelSHAPLocalUp to two raised to the power of M calls; twenty features already approaches a millionImpractical past roughly fifteen features
LIMELocalA few hundred perturbed samples per explanationUnstable across reruns and neighbourhood widths
Permutation importanceGlobalThirty shuffles per feature, no retrainingCorrelated features hide or split each other's effect
Partial dependenceGlobalOne grid sweep, often a hundred points per featureAssumes 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.

python
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.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-17

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Machine Learning Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement