Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 119/ 160
06. Feature Engineering & Model Evaluation

Model Explainability with SHAP & LIME

Explain predictions globally/locally with SHAP and LIME for trust and debugging.

AdvancedSHAP · LIME3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

SHAP and LIME show which inputs pushed a particular prediction up or down and by how much, like itemising the reasons behind a score.

Think of it like…

Splitting a restaurant bill among friends fairly: each person's share reflects what they added on average across every possible order in which the group could have arrived; the shares always add up to the total, and the base value is the cost of the empty table.

Where you’ve seen it

A two-feature model has f(∅) = 10 (the base value), f({A}) = 14, f({B}) = 12 and f({A, B}) = 18. Shapley values average each feature's marginal contribution over both orderings: φ_A = ½[(14 − 10) + (18 − 12)] = ½(4 + 6) = 5 and φ_B = ½[(12 − 10) + (18 − 14)] = ½(2 + 4) = 3. They sum to 8 = 18 − 10, as local accuracy requires. For a churn model on the log-odds scale, the base value is −2.2 (p = 0.10) and a customer's contributions are +1.10 (5 support tickets), +0.45 (short tenure) and −0.15 (autopay), giving −0.80 and a probability of σ(−0.80) = 0.31. Mean |SHAP| across 10,000 customers ranks tickets first, tenure second; a dependence plot shows risk rising sharply after 3 tickets. Debugging reveals that days_since_cancel_request is the top feature, a leak, and the team removes it. A LIME explanation for the same customer gives similar signs but different magnitudes on a second run (random perturbations), which is why the team uses SHAP for tabular models and checks stability before showing explanations to customers.

Words you’ll hear

Shapley value
A feature's average marginal contribution over all feature orderings.
Base value
The model's expected output without feature information (average prediction).
Local vs global explanation
Why one prediction happened versus how the model behaves overall.
Surrogate model
A simple model (LIME's local linear fit) approximating the complex one near a point.

Visual diagram

Loading interactive diagram

Theory & deep dive

SHAP: values, algorithms and plots

The Shapley value of feature i is φ_i = Σ_{S ⊆ F∖{i}} [|S|!(M − |S| − 1)!/M!] (f(S ∪ {i}) − f(S)), the weighted average of its marginal contribution over all subsets S of the other M − 1 features. With features A and B and f(∅) = 10, f(A) = 14, f(B) = 12, f(AB) = 18: φ_A = ½(4 + 6) = 5 and φ_B = ½(2 + 4) = 3. SHAP satisfies local accuracy (the base value plus Σφ_i equals the prediction: 10 + 5 + 3 = 18), missingness (absent features get zero) and consistency (a feature that contributes more in a changed model never gets less credit). Computing exact values needs 2^M model evaluations (over a million for M = 20), so practical algorithms matter: TreeSHAP exploits tree structure for exact values in polynomial time (shap.TreeExplainer(model).shap_values(X)), DeepSHAP approximates for neural networks, and KernelSHAP samples feature coalitions for any model using a background dataset to represent "missing" features.

Reading outputs: a waterfall or force plot shows how each feature moves the prediction from the base value (−2.2 to −0.80 in the churn example); a beeswarm plot shows the distribution of SHAP values per feature across the dataset; mean |SHAP| gives a global importance ranking that, unlike impurity importance, reflects effect on predictions and is consistent; dependence plots reveal non-linear and interaction effects (risk rising after 3 tickets). For classification, SHAP is usually computed on the log-odds scale, where contributions are additive, and then mapped to probabilities through the sigmoid, which is non-linear (equal log-odds contributions don't add equally in probability).

Additivity in log-odds

Base value −2.2. Contributions: +1.10 (tickets), +0.45 (tenure), −0.15 (autopay). Output = −2.2 + 1.10 + 0.45 − 0.15 = −0.80. Probability = 1/(1 + e^0.80) = 0.31, versus a base probability of 1/(1 + e^2.2) = 0.10.

Key takeaway: SHAP distributes a prediction among features additively from a base value; TreeSHAP is exact for trees and KernelSHAP approximates others.

LIME, caveats and responsible use

LIME explains one prediction by sampling perturbed versions of the instance (turning words on and off in text, masking image segments, adding noise to tabular features), querying the model, weighting samples by proximity to the original (for example exp(−d²/σ²)) and fitting a sparse linear model whose coefficients explain the local behaviour. It's model-agnostic, intuitive and good for text and images, but unstable (different runs or kernel widths yield different explanations), depends on how neighbourhoods are defined and has no additivity guarantee. SHAP has stronger theory and consistency, but is slower for non-tree models and relies on assumptions about how absent features are replaced.

Caveats: correlated features share credit arbitrarily (interventional SHAP breaks correlations by sampling from a background, which may create unrealistic inputs; conditional variants respect the data distribution but change the interpretation); explanations describe the model's behaviour, not causal effects (a high SHAP for tickets doesn't mean reducing tickets will reduce churn); results depend on the background data and the model's output scale; and explanations can be gamed or misread by users. Use them for debugging (finding leakage such as days_since_cancel_request, spurious features and data errors), auditing and fairness checks (do protected attributes or proxies drive decisions?), reason codes for adverse decisions (top contributing features with stable wording) and monitoring (drift in SHAP distributions). Validate explanations: check additivity, stability across seeds and samples, agreement with domain knowledge and with simpler baselines, and combine with partial dependence and permutation importance. Communicate limits clearly.

A debugging win

The mean |SHAP| ranking shows days_since_cancel_request as the strongest feature of a churn model. That value only exists after a customer asks to cancel, so it leaks the outcome. Removing it drops cross-validated AUC from 0.93 to 0.81, the honest figure.

Key takeaway: Use SHAP and LIME to debug and audit, check stability and background choices, and never read them as causal effects.

How it works, step by step

Step 1 of 4
Analyst

1. Choose the explainer

Use TreeSHAP for tree ensembles, KernelSHAP or DeepSHAP for others, and LIME for quick local text or image explanations.

TreeExplainer for XGBoost
Key numbers at this step
Background
representative sample

When to use it & trade-offs

What it is

Model explainability methods show why a model produced a prediction. SHAP (SHapley Additive exPlanations) assigns each feature a Shapley value, its average marginal contribution to the prediction across all orderings of features, so that the contributions plus a base value sum exactly to the model output (local accuracy). TreeSHAP computes them exactly and quickly for tree ensembles; KernelSHAP approximates them for any model. LIME (Local Interpretable Model-agnostic Explanations) perturbs an instance, queries the model and fits a simple weighted sparse linear model around it to explain that single prediction. Aggregating SHAP values (mean |φ|) gives global importance; dependence and beeswarm plots show how features drive predictions across the dataset.

Why it matters: Stakeholders, regulators and engineers need to know why a model decided something: a lender must give reasons for a declined loan, a doctor must judge whether a risk score is plausible, and a data scientist debugging a model needs to see that it relies on a leaked or spurious feature. Explanations build trust, support audits and fairness reviews and expose bugs, but they explain the model, not the world, and they can mislead when features are correlated or when used as proof of causation.

When to reach for it

  • Debugging models and finding leakage
  • Adverse-action reason codes and audits
  • Explaining predictions to domain experts

When to avoid or be careful

  • Reading explanations as causal effects
  • Showing LIME results without stability checks
  • Ignoring correlated features when interpreting credit

Explainability methods

SHAP (TreeSHAP, KernelSHAP)
Best for: Consistent local and global explanations

Strengths: Additive; strong theory; exact for trees.

Watch out: Costly for non-tree models; depends on background data.

LIME
Best for: Quick local explanations, text and images

Strengths: Model-agnostic and intuitive.

Watch out: Unstable; no additivity guarantee.

Permutation importance and partial dependence
Best for: Global behaviour and sanity checks

Strengths: Simple; performance-based.

Watch out: Misleading with correlated features.

Interview signals & numbers to know

When this topic comes up

  • “Why did the model decline this customer?”
  • Shapley values
  • TreeSHAP
  • Local vs global explanations
  • LIME surrogate

Benchmarks & rules of thumb

φ_A = 5 · φ_B = 3 -
Shapley values in the two-feature example (sum 8)
−2.2 → −0.80 -
log-odds from base value to prediction
2^M -
model evaluations for exact Shapley values

Common mistakes & follow-ups

Common interview mistakes

  • Interpreting a high SHAP value as a lever to change the outcome.
  • Using a non-representative background dataset.
  • Reporting impurity importance as if it were SHAP.

Likely interviewer follow-ups

  • How are Shapley values computed and what do they guarantee?
  • How does LIME differ from SHAP?
  • How can explanations help find data leakage?
Interview tip: Work the two-feature Shapley example (φ = 5 and 3). It shows you understand the definition behind the library call.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Model Explainability with SHAP & LIME with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Model Calibration (Platt Scaling & Isotonic)
Next topic
Error Analysis & Residual Diagnostics