Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 25 min · revision 1

Lab: Explaining Predictions Globally and Locally

Deconstruct black-box machine learning models using global permutation feature importance, analyze local attribution with SHAP and LIME surrogates, and diagnose explainability failure modes arising from feature correlations and sampling instability.

Contentsand lesson path

On this page

  1. Model Interpretability: Global Dependencies and Local Attribution
  2. Practice check
  3. Apply it
  4. Review prompt

Lessons of Responsible ML

  1. Where Bias Enters an ML System Concept · 20 min
  2. Lab: Measuring Fairness Across Groups and Counterfactual Prompts Lab · 30 min
  3. Worked Example: Closing a Gap and Paying the Price Worked example · 20 min
  4. Lab: Explaining Predictions Globally and Locally Lab · 25 min
  5. Model Cards and Risk Documentation Concept · 15 min
  6. Check: Release Review Knowledge check · 10 questions

What you will learn

  • Explain model behaviour globally (permutation importance, partial dependence) and locally (SHAP values or LIME), and state the limits of these explanations.

01. Model Interpretability: Global Dependencies and Local Attribution

As machine learning models are entrusted with high-stakes decisions in credit underwriting, medical diagnosis, and hiring screening, interpretability ceases to be an academic luxury: it becomes a legal, operational, and ethical necessity. Regulators mandate that adverse credit actions provide explicit adverse action notices explaining why an applicant was rejected. Furthermore, debugging silent failures, detecting data leakage, and verifying algorithmic safety require understanding how models map input features to output predictions. Model explainability is categorized into two complementary tiers: global interpretability (understanding overall model mechanics across the entire population) and local interpretability (explaining a single individual prediction).

  • Global Explainability: Permutation Feature Importance:

    • Methodology: Permutation feature importance measures the increase in model prediction error after shuffling the values of a single feature across the test dataset. By randomly permuting feature $j$, the statistical relationship between feature $j$ and the target $Y$ is completely severed while preserving the marginal distribution of all other features. If model validation loss spikes significantly, the model relies heavily on feature $j$.
    • Critical Pitfall: Correlated Features: Permutation importance assumes features are independent. When two features are strongly collinear (e.g., annual_salary and monthly_income), shuffling one feature creates unrealistic synthetic data points (e.g., an applicant with $150,000 annual salary but $800 monthly income). Furthermore, because the model can read the collinear information from the unshuffled twin feature, the permutation importance of both features can appear misleadingly low. Practitioners must cluster correlated features or evaluate partial dependence curves before drawing definitive conclusions.
  • Global Explanations: Partial Dependence Plots (PDP) and ICE:

    • Partial Dependence Plots: Show the marginal effect of one or two features on the predicted outcome of a machine learning model, averaging out the effects of all other features. PDP reveals whether the learned relationship is linear, monotonic, or complexly non-linear (e.g., risk decreasing with credit score up to 720, then plateauing).
    • Individual Conditional Expectation (ICE): While PDP plots the average marginal curve across all instances, ICE plots one individual curve per sample. Plotting ICE curves exposes hidden heterogeneous interaction effects that disappear in global PDP averages (such as a feature having a positive effect for men but a negative effect for women).
  • Local Explainability: SHAP (Shapley Additive Explanations):

    • Cooperative Game Theory Foundations: Rooted in Shapley values from cooperative game theory, SHAP treats features as players in a coalition collaborating to produce the prediction payoff. SHAP is mathematically unique: it is the only feature attribution method that provably satisfies four fundamental axioms: (1) Efficiency (attributions sum up exactly to the difference between the prediction and the baseline expected value); (2) Symmetry (identical contributors receive identical attribution); (3) Dummy / Null Player (features that do not alter predictions receive zero attribution); and (4) Additivity (attributions across ensemble models sum linearly).
    • TreeSHAP vs KernelSHAP: While KernelSHAP approximates Shapley values through weighted linear regression on perturbed samples, TreeSHAP computes exact attributions for tree ensembles (Random Forests, XGBoost, LightGBM) in polynomial time $O(T L D^2)$, making it computationally feasible for production scoring pipelines.
  • Local Surrogates: LIME and Sampling Instability:

    • Local Interpretable Model-agnostic Explanations (LIME): Approximates complex black-box decision boundaries in the immediate local neighborhood of a single query instance by generating random perturbations, weighting them by distance to the query instance, and fitting an interpretable surrogate model (e.g., a sparse linear regression).
    • The Instability Limitation: Because LIME relies on stochastic perturbation sampling and heuristic exponential kernel width settings, running LIME multiple times on the exact same prediction can yield noticeably different top explanatory features. Engineers must verify LIME explanation stability across random seeds before exposing explanations to end users.
  • Counterfactual Explanations and Recourse: Beyond attributing credit to historical features, end users and consumers require actionable recourse: "What specific changes would alter this rejection into an approval?" Counterfactual explanations (Wachter et al. 2017) solve an optimization problem to find the nearest input vector $x^$ that changes the model decision $\hat{y}^ \neq \hat{y}$ while minimizing a distance metric $d(x, x^*)$ and satisfying real-world plausibility constraints (e.g., age cannot decrease, educational degrees cannot vanish). Providing actionable counterfactuals empowers consumers with transparent paths to qualify for services.

  • Adverse Action Notices in Regulated Lending: In United States credit markets, the Equal Credit Opportunity Act (ECOA) and Fair Credit Reporting Act (FCRA) legally mandate that automated credit rejections provide applicants with key principal reasons. Generating legally compliant adverse action notices requires mapping local SHAP attributions or negative feature contributions directly to standardized, human-readable reason codes (e.g., "debt-to-income ratio too high" or "length of credit history insufficient").

  • Local Fidelity vs Interpretability in Surrogate Modeling: A surrogate explanation model—whether fitted via LIME or a shallow rule list approximating a deep network—is fundamentally a local approximation. High human interpretability often comes at the price of reduced local fidelity: the surrogate may fail to capture high-order non-linear feature interactions that drove the actual decision. Responsible ML pipelines compute and log the local fidelity metric (such as the local $R^2$ fit of the linear surrogate within the perturbation neighborhood) alongside every emitted explanation, ensuring that low-fidelity explanations are flagged rather than served blindly to decision-makers.

Python · explain_model_predictions.py Global permutation importance and local attribution
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance

np.random.seed(42)
n = 1500
credit = np.random.normal(650, 50, n)
income = np.random.normal(55000, 15000, n)
debt = np.random.normal(12000, 4000, n)
prob = 1 / (1 + np.exp(-((credit - 620)/35 + (income - 40000)/25000 - debt/8000)))
y = (np.random.rand(n) < prob).astype(int)

X = pd.DataFrame({"credit": credit, "income": income, "debt": debt})
clf = RandomForestClassifier(n_estimators=40, max_depth=4, random_state=42)
clf.fit(X, y)

# Global Permutation Importance
perm = permutation_importance(clf, X, y, n_repeats=5, random_state=42)

print("=== MODEL EXPLAINABILITY AUDIT ===")
print("Global Permutation Importance (drop in accuracy):")
for feat, mean, std in zip(X.columns, perm.importances_mean, perm.importances_std):
    print(f"  {feat:<8}: {mean:.4f} +/- {std:.4f}")

# Local single prediction instance audit
sample = X.iloc[[0]]
pred_prob = clf.predict_proba(sample)[0][1]
print(f"Local Query Predicted Probability: {pred_prob:.4f}")
Expected output · explain_model_predictions.py
=== MODEL EXPLAINABILITY AUDIT ===
Global Permutation Importance (drop in accuracy):
  credit  : 0.1743 +/- 0.0076
  income  : 0.0760 +/- 0.0044
  debt    : 0.0381 +/- 0.0039
Local Query Predicted Probability: 0.9458

02. Practice check

Practice check · 2 questions

Check Your Understanding

Review key concepts and verify your understanding with these practice questions.

Q1. In a credit risk model, the features `annual_income` and `monthly_salary` are 99% correlated. When evaluating permutation importance, both features score near zero. What is the root cause?
Q2. An on-call engineer runs LIME twice on the same high-risk loan rejection record and receives two different sets of top explanatory features. What does this observation demonstrate?
Practice only: not graded, not saved, not evidence.

03. Apply it

When integrating explainability into production machine learning workflows:

  • Group Correlated Features During Permutation Auditing: Cluster collinear features (correlation $|r| > 0.8$) and permute them as a unified block to avoid underestimating collective feature reliance.
  • Adopt TreeSHAP for Production Tree Models: Leverage exact polynomial-time TreeSHAP algorithms for tree ensembles rather than stochastic sampling approximations to guarantee stable, axiomatic attributions.
  • Verify Local Surrogate Stability: When employing LIME for unstructured data (images or text), evaluate explanation stability across multiple random seeds before exposing explanations to compliance officers or end users.
  • Differentiate Reliance from Causation: Explicitly instruct stakeholders that feature attributions measure statistical model reliance on historical patterns, not real-world causal mechanisms.

04. Review prompt

Compare permutation feature importance with SHAP values across computational complexity and axiomatic guarantees. Why do correlated features distort permutation importance scores? How do local surrogate methods like LIME differ from Shapley-based attributions in stability and fidelity?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check