Model Interpretability (SHAP, LIME)
Model Interpretability: SHAP and LIME
Learn how to investigate Machine Learning predictions using global and local explanations, SHAP values, LIME explanations, feature importance, reliability checks, and responsible interpretation practices.
Introduction
A Machine Learning model can achieve strong evaluation results while remaining difficult to understand. A performance metric may show how accurately the model predicts, but it does not explain which inputs influenced the predictions or whether the model learned reasonable patterns.
Model interpretability helps people investigate how a model behaves. It can support debugging, feature review, stakeholder communication, risk analysis, fairness assessment, and human oversight.
SHAP and LIME are widely used post-hoc explanation methods. SHAP attributes a model output to input features using ideas from Shapley values. LIME creates an interpretable local surrogate model around one selected prediction.
Learning Objectives
By the End of This Lesson
- Explain why model interpretability is important
- Distinguish interpretability from predictive performance
- Compare intrinsic and post-hoc explanations
- Distinguish global and local interpretability
- Understand model-specific and model-agnostic methods
- Interpret coefficients and tree-based feature importance cautiously
- Calculate permutation importance
- Explain the general idea behind Shapley values
- Use SHAP for global and local explanations
- Interpret SHAP bar, beeswarm, waterfall, and dependence plots
- Explain how LIME creates a local surrogate model
- Generate a LIME explanation for one prediction
- Compare SHAP and LIME
- Recognize instability caused by correlated features
- Understand how preprocessing affects feature explanations
- Distinguish predictive attribution from causal evidence
- Test explanation stability and fidelity
- Communicate explanations responsibly
Prerequisites
Recommended Knowledge
- Supervised Machine Learning
- Classification and regression
- Training, validation, and test datasets
- Feature preprocessing and pipelines
- Linear models and tree-based models
- Model evaluation metrics
- Basic probability and statistics
- Python, NumPy, pandas, and scikit-learn
Required Packages
- NumPy
- pandas
- scikit-learn
- SHAP
- LIME
- Matplotlib
python -m pip install numpy pandas scikit-learn shap lime matplotlib
Why Interpretability Matters
| Purpose | Question Interpretability Can Help Investigate |
|---|---|
| Debugging | Is the model relying on an incorrect or leaking feature? |
| Validation | Are the learned relationships consistent with the available evidence? |
| Feature Review | Which inputs influence predictions most strongly? |
| Individual Review | Which feature values contributed to one prediction? |
| Communication | How can model behavior be explained to stakeholders? |
| Fairness Review | Does the model rely on sensitive attributes or possible proxy features? |
| Monitoring | Has the model's attribution behavior changed in production? |
| Human Oversight | What evidence should a reviewer examine before taking action? |
Interpretability vs Explainability
The terms interpretability and explainability are often used interchangeably. A useful practical distinction is to treat interpretability as direct understanding of model mechanics and explainability as a human-understandable description of behavior, sometimes generated after the model has been trained.
| Concept | General Meaning | Example |
|---|---|---|
| Interpretability | Understanding the model's internal structure or parameters | Reviewing coefficients in a linear model |
| Explainability | Producing understandable information about model behavior or predictions | Using SHAP to explain a gradient-boosted model |
Intrinsic and Post-Hoc Interpretability
Intrinsic Interpretability
- The model is understandable by design
- Examples include small trees and sparse linear models
- The internal logic can often be inspected directly
- Interpretability depends on model size and feature design
Post-Hoc Explainability
- The explanation is generated after model training
- Useful for complex or black-box models
- Examples include SHAP, LIME, and permutation importance
- The explanation may approximate model behavior
Global vs Local Explanations
| Explanation Scope | Main Question | Possible Method |
|---|---|---|
| Global | How does the model generally behave across many observations? | Mean absolute SHAP values or permutation importance |
| Local | Why did the model produce this prediction? | SHAP waterfall plot or LIME explanation |
| Cohort | How does the model behave for a defined subgroup? | Grouped SHAP summaries and subgroup analysis |
Model-Specific vs Model-Agnostic Methods
| Method Type | Meaning | Example |
|---|---|---|
| Model-Specific | Uses knowledge of a particular model structure | Tree-aware SHAP explanations |
| Model-Agnostic | Treats the model as a prediction function | LIME or permutation importance |
Built-In Feature Importance
Some estimators expose built-in feature-importance values. Tree models may report split-based importance, while linear models expose coefficients.
| Importance Type | What It Represents | Important Limitation |
|---|---|---|
| Linear Coefficient | Direction and magnitude in the fitted linear equation | Depends on feature scale, encoding, and correlation |
| Tree Split Importance | Contribution to split-quality improvement | May favor features with many possible split points |
| Permutation Importance | Performance reduction after disrupting a feature | Correlated features may mask one another |
| Mean Absolute SHAP | Average magnitude of local feature attributions | Depends on model, background data, and explanation settings |
Permutation Importance
Permutation importance measures how much model performance changes when one feature is randomly shuffled. Shuffling breaks the relationship between that feature and the target while leaving the other columns unchanged.
In this expression, \(S_{\text{baseline}}\) is the original evaluation score and \(S_{\text{permuted }j}\) is the score after shuffling feature \(j\).
import pandas as pd
from sklearn.inspection import permutation_importance
permutation_result = permutation_importance(
estimator=trained_pipeline,
X=X_test,
y=y_test,
scoring="roc_auc",
n_repeats=20,
random_state=42,
n_jobs=-1
)
importance_table = pd.DataFrame({
"feature": X_test.columns,
"mean_importance": permutation_result.importances_mean,
"importance_std": permutation_result.importances_std
}).sort_values(
by="mean_importance",
ascending=False
)
print(
importance_table.head(15)
)
What Is SHAP?
SHAP stands for SHapley Additive exPlanations. It uses ideas from cooperative game theory to assign feature contributions to a model output.
The prediction is represented as a baseline value plus feature-level contributions.
| Symbol | Meaning |
|---|---|
| \(f(x)\) | Model output for the selected observation |
| \(\phi_0\) | Baseline or expected model output |
| \(\phi_j\) | Contribution assigned to feature \(j\) |
| \(p\) | Number of represented features |
Shapley Value Intuition
Imagine that the input features are participants cooperating to produce a prediction. A feature's Shapley value is based on its average marginal contribution across possible feature coalitions.
The formula considers how much feature \(j\) changes the model output when added to different subsets of other features.
Prepare a Classification Model
The following example trains a Random Forest classifier on a built-in scikit-learn dataset. The dataset is used only to demonstrate the interpretation workflow.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
dataset = load_breast_cancer(
as_frame=True
)
X = dataset.data
y = dataset.target
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.20,
random_state=42,
stratify=y
)
model = RandomForestClassifier(
n_estimators=300,
random_state=42,
n_jobs=-1
)
model.fit(
X_train,
y_train
)
print(
"Test accuracy:",
model.score(
X_test,
y_test
)
)
Generate SHAP Values
import shap
background_data = X_train.sample(
n=min(200, len(X_train)),
random_state=42
)
explainer = shap.Explainer(
model,
background_data
)
X_explain = X_test.iloc[:100].copy()
shap_values = explainer(
X_explain
)
print(
"SHAP value shape:",
shap_values.values.shape
)
The explainer choice may depend on the estimator. Modern SHAP APIs can select an appropriate explainer automatically in many standard cases, but the resulting output dimensions must still be inspected.
SHAP Global Importance
Mean absolute SHAP values summarize the average magnitude of each feature's contributions across the explained observations.
import numpy as np
import pandas as pd
values = shap_values.values
if values.ndim == 3:
positive_class_values = values[:, :, 1]
else:
positive_class_values = values
global_shap_importance = pd.DataFrame({
"feature": X_explain.columns,
"mean_absolute_shap": np.abs(
positive_class_values
).mean(axis=0)
}).sort_values(
by="mean_absolute_shap",
ascending=False
)
print(
global_shap_importance.head(15)
)
SHAP Beeswarm Plot
A beeswarm plot combines global importance, contribution direction, feature value, and observation-level variation.
classification_values = shap_values
if shap_values.values.ndim == 3:
classification_values = shap_values[:, :, 1]
shap.plots.beeswarm(
classification_values,
max_display=15
)
| Plot Element | Meaning |
|---|---|
| Feature Row | One input feature |
| Point | One explained observation |
| Horizontal Position | Direction and magnitude of the SHAP contribution |
| Color | Relative feature value when available |
| Feature Order | Commonly ordered by mean absolute SHAP magnitude |
SHAP Waterfall Plot
A waterfall plot explains one prediction by starting from the baseline and showing how individual feature contributions move the output toward the final prediction.
observation_index = 0
local_explanation = classification_values[
observation_index
]
shap.plots.waterfall(
local_explanation,
max_display=15
)
SHAP Dependence and Scatter Plots
A SHAP scatter or dependence plot shows how one feature's value relates to its attributed contribution across observations.
feature_name = "mean radius"
shap.plots.scatter(
classification_values[
:,
feature_name
]
)
Patterns to Review
- Approximately linear relationships
- Threshold-like changes
- Saturation at high or low values
- Different contributions for similar feature values
- Possible interactions with other variables
- Sparse regions with limited data support
- Unreasonable extrapolation behavior
SHAP Additivity
A useful property of additive explanations is that the feature contributions combine with the baseline to reproduce the explained model output, subject to the explainer's output scale and numerical precision.
import numpy as np
local_values = local_explanation.values
base_value = local_explanation.base_values
reconstructed_output = (
base_value
+ np.sum(local_values)
)
print(
"Reconstructed explained output:",
reconstructed_output
)
What Is LIME?
LIME stands for Local Interpretable Model-agnostic Explanations. It explains one prediction by generating perturbed examples near that observation, obtaining predictions from the original model, and fitting a simpler local surrogate model.
| Symbol | Meaning |
|---|---|
| \(f\) | Original model being explained |
| \(g\) | Interpretable local surrogate model |
| \(\pi_x\) | Weights emphasizing samples near observation \(x\) |
| \(\mathcal{L}\) | Local fidelity loss |
| \(\Omega(g)\) | Complexity penalty encouraging a simple explanation |
LIME Classification Example
import numpy as np
from lime.lime_tabular import LimeTabularExplainer
lime_explainer = LimeTabularExplainer(
training_data=X_train.to_numpy(),
feature_names=X_train.columns.tolist(),
class_names=dataset.target_names.tolist(),
mode="classification",
discretize_continuous=True,
random_state=42
)
observation_index = 0
observation = X_test.iloc[
observation_index
].to_numpy()
lime_explanation = lime_explainer.explain_instance(
data_row=observation,
predict_fn=model.predict_proba,
num_features=10
)
for feature_rule, contribution in lime_explanation.as_list():
print(
feature_rule,
contribution
)
The returned rules describe the locally fitted surrogate rather than the complete internal logic of the original model.
Export a LIME Explanation
lime_explanation.save_to_file(
"lime_local_explanation.html"
)
LIME can produce an HTML explanation for review. Before sharing it, verify that it does not expose confidential feature values, personal information, hidden business rules, or sensitive model details.
SHAP vs LIME
| Area | SHAP | LIME |
|---|---|---|
| Foundation | Shapley-value feature attribution | Local interpretable surrogate modeling |
| Primary Use | Local attribution and aggregated global analysis | Local explanation of selected predictions |
| Model Support | Model-specific and model-agnostic explainers | Primarily model-agnostic |
| Output | Feature contributions related to a baseline output | Locally fitted feature weights or rules |
| Global View | Can aggregate local attributions across observations | Requires aggregation of many local explanations |
| Consistency | Depends on explainer, background data, and assumptions | Can vary with perturbations, neighborhood, and random seed |
| Computational Cost | Varies substantially by model and explainer | Requires repeated model predictions around each observation |
| Main Caution | Attribution is not causation | The surrogate may not faithfully represent the original model beyond the local region |
Correlated Features
Correlated features create attribution challenges because several variables may contain overlapping information. An explanation method must allocate credit among features that can substitute for one another.
Review Practices
- Inspect feature correlations and known relationships
- Group related features where appropriate
- Compare explanations after removing redundant variables
- Review explanation stability across data samples
- Compare SHAP, permutation importance, and domain evidence
- Avoid interpreting one feature in isolation when variables are dependent
Explain the Complete Pipeline
Production models often include imputation, scaling, category encoding, feature generation, selection, and the estimator. Explanations must account for the representation actually received by the model.
category__region_East without mapping them back to
understandable business concepts.
Explain a Mixed-Feature Pipeline
The following pattern shows how transformed feature names can be retrieved from a fitted scikit-learn preprocessing pipeline.
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import StandardScaler
numeric_pipeline = Pipeline(
steps=[
(
"imputer",
SimpleImputer(
strategy="median"
)
),
(
"scaler",
StandardScaler()
)
]
)
categorical_pipeline = Pipeline(
steps=[
(
"imputer",
SimpleImputer(
strategy="most_frequent"
)
),
(
"encoder",
OneHotEncoder(
handle_unknown="ignore"
)
)
]
)
preprocessor = ColumnTransformer(
transformers=[
(
"numeric",
numeric_pipeline,
numeric_columns
),
(
"categorical",
categorical_pipeline,
categorical_columns
)
]
)
model_pipeline = Pipeline(
steps=[
(
"preprocessor",
preprocessor
),
(
"model",
model
)
]
)
model_pipeline.fit(
X_train,
y_train
)
transformed_feature_names = (
model_pipeline
.named_steps["preprocessor"]
.get_feature_names_out()
)
print(
transformed_feature_names
)
Classification Output Scales
For classification, an explanation may describe probability, raw decision score, log odds, or another estimator-specific output. These values are not interchangeable.
| Output Scale | Interpretation |
|---|---|
| Probability | Estimated class probability when supported and appropriately calibrated |
| Log Odds | Logarithm of the odds associated with a binary probability |
| Raw Score | Internal decision value before conversion into a probability or class |
| Class Output | Selected category after applying model decision logic |
Regression Explanations
For a regression model, SHAP values commonly describe how features move the numerical prediction relative to a baseline prediction.
Explanations Are Not Causal Effects
SHAP and LIME describe the behavior of a fitted predictive model. They do not establish what would happen if a person or organization deliberately changed a feature.
Why Causal Interpretation Is Risky
- Features may be correlated
- Some variables may be proxies for hidden factors
- The model learns associations from historical data
- Changing one feature may also change other variables
- The dataset may contain selection bias
- The explanation describes the model rather than the real data-generating process
Explanation Stability
A reliable explanation should not change unpredictably when the random seed, background sample, perturbation sample, or a tiny input change is modified without a meaningful reason.
Stability Checks
- Repeat LIME explanations using several seeds
- Compare SHAP results using justified background samples
- Explain nearby observations with similar predictions
- Compare explanations across cross-validation models
- Review whether top features remain reasonably consistent
- Investigate large changes caused by tiny input differences
- Document materially unstable explanations
Explanation Fidelity
Fidelity describes how accurately an explanation represents the behavior of the original model in the relevant region.
| Evaluation Question | Why It Matters |
|---|---|
| Does the additive explanation reconstruct the expected output? | Checks arithmetic alignment with the model output |
| Does the LIME surrogate fit the local predictions well? | Checks whether the simple surrogate represents the local model behavior |
| Do repeated runs produce similar explanations? | Checks stability |
| Do explanations remain sensible across representative cases? | Detects isolated or misleading examples |
| Do known irrelevant features receive large importance? | May reveal leakage, artifacts, or explanation problems |
| Does removing an important feature materially affect validated performance? | Provides an additional behavioral check |
Interpretability and Fairness
Explanations can help identify sensitive attributes, proxy features, and unusual subgroup patterns. However, feature attributions alone do not prove that a model is fair.
Responsible Review
- Evaluate performance across relevant groups
- Review false-positive and false-negative behavior
- Inspect sensitive features and possible proxies
- Compare attribution distributions across groups
- Review historical-label quality
- Use domain, legal, compliance, and policy review where required
- Provide appropriate human oversight for consequential decisions
Privacy and Security
Explanation artifacts can reveal input values, feature names, business logic, model behavior, or sensitive information. They should be protected according to the same security and privacy requirements that apply to model inputs and predictions.
Protection Checklist
- Restrict explanation access according to business need
- Remove unnecessary identifiers
- Redact sensitive values before sharing
- Protect stored explanation files
- Avoid exposing confidential model features publicly
- Define retention periods
- Log explanation access where required
- Review whether explanations could support model probing or gaming
Explain Results for the Audience
| Audience | Useful Explanation |
|---|---|
| Data Scientist | Attributions, interactions, output scale, fidelity, and stability |
| Developer | Feature lineage, preprocessing, version, and serving behavior |
| Domain Expert | Recognizable feature effects, unusual cases, and actionable review points |
| Business Stakeholder | Main behavior, expected impact, uncertainty, and limitations |
| Risk Reviewer | Validation evidence, fairness analysis, controls, and audit trail |
| Affected User | Clear, relevant, non-misleading factors and available review process |
Common Interpretation Mistakes
Recommended Interpretability Workflow
Define the Explanation Question
Decide whether the goal is debugging, global understanding, individual review, fairness analysis, communication, or monitoring.
Validate the Model
Confirm representative evaluation, data quality, calibration, subgroup behavior, and operational suitability.
Identify the Audience
Determine the required language, detail, privacy controls, and decision context.
Select the Method
Choose intrinsic interpretation, permutation importance, SHAP, LIME, or another justified technique.
Preserve Feature Lineage
Map transformed model features to original business concepts, units, categories, and time windows.
Generate Global and Local Evidence
Review overall behavior, representative cohorts, typical cases, boundary cases, and important errors.
Test Reliability
Evaluate fidelity, stability, correlated-feature behavior, output reconstruction, and sensitivity to configuration.
Review Risks
Assess leakage, proxies, bias, privacy, security, potential gaming, and unsupported causal claims.
Communicate with Limitations
State what the explanation shows, what it does not show, and what action or human review is appropriate.
Monitor Explanations
Track important-feature distributions, local attribution patterns, model versions, and changes in production behavior.
Explanation Record
| Record | What to Document |
|---|---|
| Model | Model name, version, task, target, and evaluation status |
| Explanation Purpose | Debugging, review, communication, monitoring, or another purpose |
| Audience | Intended users and required level of detail |
| Method | SHAP, LIME, permutation importance, coefficients, or another method |
| Configuration | Explainer, background data, seed, perturbation settings, and output scale |
| Data | Dataset version, explained sample, cohort, and feature lineage |
| Results | Global patterns, local findings, interactions, and unusual cases |
| Reliability | Fidelity, stability, sensitivity, and correlated-feature observations |
| Limitations | Approximation, uncertainty, non-causality, and unsupported conclusions |
| Review | Domain, technical, risk, compliance, and human-oversight findings |
Hands-On Practice
Train and Validate a Model
Train a classifier or regressor using a leakage-safe pipeline and validate its performance before generating explanations.
Calculate Permutation Importance
Rank features using validation data and compare the result with the estimator's built-in importance.
Generate Global SHAP Results
Create a mean absolute SHAP ranking and beeswarm plot using a representative explanation sample.
Explain Individual Predictions
Generate waterfall plots for one correct prediction, one false positive, and one false negative.
Generate LIME Explanations
Explain the same observations using LIME and compare feature direction, ranking, and stability.
Test Explanation Stability
Repeat explanations using several seeds or background samples and document material differences.
Investigate Correlated Features
Identify a correlated feature pair and examine how their importance changes when one feature is removed.
Create a Stakeholder Explanation
Translate one technical explanation into clear language that states the main factors, output scale, uncertainty, and limitations.
Knowledge Check
What is the difference between global and local interpretability?
Explain overall model behavior versus one selected prediction.
What is a post-hoc explanation?
Explain how it differs from a model that is interpretable by design.
What does permutation importance measure?
Explain how shuffling a feature affects validated model performance.
What does a SHAP value represent?
Explain the feature's attributed contribution relative to a baseline model output.
How does LIME explain one prediction?
Explain perturbation, model scoring, proximity weighting, and local surrogate fitting.
Why do correlated features create interpretation problems?
Explain how overlapping information can be distributed among related features.
Why are feature attributions not causal effects?
Explain the difference between predictive association and the result of an intervention.
What is explanation fidelity?
Explain how accurately an explanation represents the original model's behavior in the relevant region.
Why should explanations be tested for stability?
Explain how sampling, seeds, backgrounds, and nearby observations may affect the result.
Why is interpretability not a complete fairness assessment?
Explain why performance, outcomes, proxies, labels, groups, and governance must also be reviewed.
Lesson Summary
| Concept | Main Point |
|---|---|
| Interpretability | Supports understanding of model behavior and predictions |
| Intrinsic Method | Uses a model that is understandable by design |
| Post-Hoc Method | Creates an explanation after training |
| Global Explanation | Describes behavior across many observations |
| Local Explanation | Describes one selected prediction |
| Permutation Importance | Measures performance loss after feature disruption |
| SHAP | Attributes model output to features using Shapley-value concepts |
| SHAP Baseline | Reference output from which feature contributions are measured |
| LIME | Fits an interpretable surrogate around one prediction |
| Fidelity | Measures how well the explanation represents model behavior |
| Stability | Measures consistency under reasonable explanation changes |
| Correlation | Can make individual feature attributions ambiguous |
| Feature Lineage | Connects transformed features to understandable source concepts |
| Causality | Cannot be established by ordinary predictive attribution alone |
| Responsible Use | Requires privacy, fairness, security, validation, and human oversight |
Key Takeaway
SHAP and LIME can make complex model behavior easier to investigate, but their outputs must be interpreted carefully. SHAP attributes an explained model output to features relative to a baseline, while LIME fits a simple surrogate around one prediction. Neither method proves causation, correctness, fairness, or safety. Reliable interpretability requires a validated model, preserved feature lineage, representative explanation data, known output scales, stability and fidelity checks, careful treatment of correlated features, and communication that clearly states limitations.
Get Machine Learning updates by email
Short, practical lessons and course updates from Rumman Ansari. No spam.