Machine Learning | Model Interpretability

Master SHAP, LIME, and feature importance techniques

Table of Contents
  1. Interpretability Fundamentals
  2. Feature Importance
  3. SHAP Values
  4. LIME
  5. Partial Dependence Plots
  6. Regulated Industries
  7. Interview Questions

Interpretability Fundamentals

Why Interpretability Matters

Model interpretability helps us understand why a model makes certain predictions. This is crucial for:

  • Trust: Stakeholders need to trust model decisions
  • Debugging: Finding and fixing model errors
  • Compliance: Regulatory requirements (GDPR "right to explanation")
  • Fairness: Detecting and mitigating bias
Intrinsically Interpretable

Models that are inherently explainable:

  • Linear/Logistic Regression
  • Decision Trees (shallow)
  • Rule-based systems
  • GAMs (Generalized Additive Models)

Coefficients/rules directly explain predictions

Post-hoc Explanations

Explain any model after training:

  • SHAP (SHapley Additive exPlanations)
  • LIME (Local Interpretable Explanations)
  • Permutation Importance
  • Partial Dependence Plots

Model-agnostic techniques

Global vs Local Explanations

Global: Overall model behavior

  • Feature importance rankings
  • Partial dependence plots
  • "Which features matter most?"

Local: Individual prediction

  • SHAP values for one instance
  • LIME explanations
  • "Why was this loan denied?"
Interpretability vs Accuracy

Often a trade-off exists:

  • Simple models: High interpretability, lower accuracy
  • Complex models: Lower interpretability, higher accuracy

Modern view: Post-hoc methods can explain complex models without sacrificing performance

Feature Importance

Impurity-Based (Trees)

Sum of impurity decrease weighted by samples:

\[\text{Importance}_j = \sum_{t \in T_j} \frac{n_t}{n} \Delta i(t)\]

  • Fast to compute
  • Built into tree models
  • Bias: Favors high-cardinality features
Permutation Importance

Measure performance drop when feature is shuffled:

\[\text{PI}_j = s - \frac{1}{K}\sum_{k=1}^{K} s_{j,k}\]

  • Model-agnostic
  • Uses held-out data
  • Can be slow (recompute for each feature)
Drop-Column Importance

Retrain without each feature:

\[\text{DCI}_j = s_{\text{all}} - s_{\text{-}j}\]

  • Most accurate
  • Very expensive (retrain n times)
  • Handles feature interactions
from sklearn.inspection import permutation_importance
import numpy as np

# 1. Impurity-based (for tree models)
feature_importance = model.feature_importances_
sorted_idx = np.argsort(feature_importance)[::-1]

for idx in sorted_idx[:10]:
    print(f"{feature_names[idx]}: {feature_importance[idx]:.4f}")

# 2. Permutation Importance (model-agnostic)
perm_importance = permutation_importance(
    model, X_test, y_test,
    n_repeats=10,
    random_state=42,
    n_jobs=-1
)

# Sort by mean importance
sorted_idx = perm_importance.importances_mean.argsort()[::-1]
for idx in sorted_idx[:10]:
    print(f"{feature_names[idx]}: {perm_importance.importances_mean[idx]:.4f} "
          f"± {perm_importance.importances_std[idx]:.4f}")

# 3. Plot feature importance
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10, 8))
top_n = 15
top_idx = sorted_idx[:top_n]

ax.barh(range(top_n), perm_importance.importances_mean[top_idx])
ax.set_yticks(range(top_n))
ax.set_yticklabels([feature_names[i] for i in top_idx])
ax.set_xlabel('Permutation Importance')
ax.set_title('Top Feature Importances')
plt.tight_layout()
plt.show()

SHAP Values

Shapley Values from Game Theory

SHAP (SHapley Additive exPlanations) distributes the prediction among features based on their contribution. For each feature, it answers: "How much did this feature contribute to moving the prediction from the average?"

Shapley Value Formula

\[\phi_i = \sum_{S \subseteq N \setminus \{i\}} \frac{|S|!(|N|-|S|-1)!}{|N|!} [f(S \cup \{i\}) - f(S)]\]

Key properties:

  • Efficiency: \(\sum_i \phi_i = f(x) - E[f(x)]\)
  • Symmetry: Equal features get equal values
  • Null: Non-contributing features get 0
  • Additivity: Values can be combined
SHAP Explainers
  • TreeExplainer: Fast, exact for trees (XGBoost, LightGBM, RF)
  • DeepExplainer: For neural networks (DeepLIFT-based)
  • GradientExplainer: Gradient-based for NNs
  • KernelExplainer: Model-agnostic (slow but universal)
  • LinearExplainer: For linear models

Python Implementation

import shap

# For tree-based models (XGBoost, LightGBM, Random Forest)
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_test)

# For any model (slower)
explainer = shap.KernelExplainer(model.predict, shap.sample(X_train, 100))
shap_values = explainer.shap_values(X_test[:50])

# 1. Summary Plot (global importance + distribution)
shap.summary_plot(shap_values, X_test, feature_names=feature_names)

# 2. Bar Plot (mean absolute SHAP values)
shap.summary_plot(shap_values, X_test, plot_type="bar", feature_names=feature_names)

# 3. Waterfall Plot (single prediction explanation)
shap.waterfall_plot(shap.Explanation(
    values=shap_values[0],
    base_values=explainer.expected_value,
    data=X_test.iloc[0],
    feature_names=feature_names
))

# 4. Force Plot (compact single explanation)
shap.force_plot(explainer.expected_value, shap_values[0], X_test.iloc[0])

# 5. Dependence Plot (feature effect + interaction)
shap.dependence_plot("feature_name", shap_values, X_test, feature_names=feature_names)

# For multi-class classification
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_test)  # Returns list of arrays, one per class

# Explain prediction for class 1
shap.summary_plot(shap_values[1], X_test, feature_names=feature_names)

# Get feature importance from SHAP
shap_importance = np.abs(shap_values).mean(axis=0)
sorted_idx = np.argsort(shap_importance)[::-1]
Interview Tip: SHAP vs Feature Importance

SHAP advantages:

  • Theoretically grounded (game theory)
  • Shows direction (positive/negative contribution)
  • Local explanations (per-prediction)
  • Handles feature interactions properly

Tree feature importance pitfalls: Biased toward high-cardinality features, doesn't show direction, can't explain individual predictions.

LIME

LIME Objective

Find interpretable model g that approximates f locally:

\[\xi(x) = \arg\min_{g \in G} \mathcal{L}(f, g, \pi_x) + \Omega(g)\]

  • \(\pi_x\): Proximity measure to x
  • \(\mathcal{L}\): Faithfulness to original model
  • \(\Omega(g)\): Complexity penalty

G is typically linear models or decision trees

How LIME Works
  1. Generate perturbed samples around x
  2. Get model predictions for perturbed samples
  3. Weight samples by proximity to x
  4. Fit interpretable model on weighted samples
  5. Use interpretable model coefficients as explanation
import lime
import lime.lime_tabular

# Create LIME explainer
explainer = lime.lime_tabular.LimeTabularExplainer(
    X_train.values,
    feature_names=feature_names,
    class_names=['Negative', 'Positive'],
    mode='classification'  # or 'regression'
)

# Explain a single prediction
idx = 0
exp = explainer.explain_instance(
    X_test.iloc[idx].values,
    model.predict_proba,
    num_features=10,
    num_samples=5000
)

# Show explanation
exp.show_in_notebook(show_table=True)

# Get explanation as list
explanation_list = exp.as_list()
for feature, weight in explanation_list:
    print(f"{feature}: {weight:.4f}")

# For text data
from lime.lime_text import LimeTextExplainer

text_explainer = LimeTextExplainer(class_names=['Negative', 'Positive'])
exp = text_explainer.explain_instance(
    text_sample,
    classifier.predict_proba,
    num_features=10
)

# For images
from lime import lime_image

image_explainer = lime_image.LimeImageExplainer()
exp = image_explainer.explain_instance(
    image,
    model.predict,
    top_labels=5,
    hide_color=0,
    num_samples=1000
)
SHAP vs LIME
AspectSHAPLIME
TheoryGame theoryLocal approximation
ConsistencyYesCan vary
Speed (trees)FastSlower
InteractionsHandles wellLimited
LIME Limitations
  • Explanations can be unstable (different runs)
  • Choice of kernel width affects results
  • Sampling can miss important regions
  • Linear approximation may not capture nonlinearity

Partial Dependence Plots

Partial Dependence Function

Marginal effect of feature(s) on prediction:

\[\hat{f}_S(x_S) = E_{X_C}[\hat{f}(x_S, X_C)] \approx \frac{1}{n}\sum_{i=1}^{n} \hat{f}(x_S, x_C^{(i)})\]

  • \(x_S\): Features of interest
  • \(x_C\): Complement features
  • Averaged over training data
ICE Plots

Individual Conditional Expectation:

One line per instance, showing how prediction changes with feature:

\[\hat{f}^{(i)}(x_S) = \hat{f}(x_S, x_C^{(i)})\]

PDP is the average of ICE curves

Reveals heterogeneity that PDP averages out

from sklearn.inspection import PartialDependenceDisplay, partial_dependence
import matplotlib.pyplot as plt

# 1. Simple PDP for single features
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
features = [0, 1, 2, 3, 4, 5]  # Feature indices

PartialDependenceDisplay.from_estimator(
    model, X_train, features,
    feature_names=feature_names,
    ax=axes.ravel()
)
plt.tight_layout()
plt.show()

# 2. 2D PDP for feature interactions
fig, ax = plt.subplots(figsize=(8, 6))
PartialDependenceDisplay.from_estimator(
    model, X_train, [(0, 1)],  # Feature pair
    feature_names=feature_names,
    ax=ax
)
plt.show()

# 3. ICE plots
fig, ax = plt.subplots(figsize=(10, 6))
PartialDependenceDisplay.from_estimator(
    model, X_train, [0],
    feature_names=feature_names,
    kind='both',  # Shows ICE + PDP
    subsample=50,  # Number of ICE lines
    ax=ax
)
plt.show()

# 4. Get raw partial dependence values
pd_results = partial_dependence(
    model, X_train, features=[0],
    kind='both'
)
print("PD values:", pd_results['average'])
print("Feature values:", pd_results['values'])

Regulated Industries

Financial Services

Regulations:

  • Fair Credit Reporting Act (FCRA)
  • Equal Credit Opportunity Act (ECOA)
  • SR 11-7 (Model Risk Management)

Requirements:

  • Adverse action reasons must be provided
  • Models must be documented and validated
  • Fair lending analysis required
Healthcare & GDPR

GDPR Article 22:

"Right to explanation" for automated decisions

Healthcare requirements:

  • Clinical decision support must be explainable
  • FDA requires transparency for medical devices
  • Doctors need to understand AI recommendations
Generating Adverse Action Reasons
def generate_adverse_action_reasons(shap_values, feature_names, top_n=4):
    """
    Generate top reasons for adverse decision (e.g., loan denial)
    Required by FCRA for credit decisions
    """
    # Get features with most negative contribution
    sorted_idx = np.argsort(shap_values)

    reasons = []
    for idx in sorted_idx[:top_n]:
        if shap_values[idx] < 0:  # Negative contribution
            reasons.append({
                'feature': feature_names[idx],
                'impact': shap_values[idx],
                'reason': generate_reason_text(feature_names[idx])
            })

    return reasons

def generate_reason_text(feature_name):
    """Map feature to human-readable reason"""
    reason_map = {
        'debt_to_income': 'Debt-to-income ratio is too high',
        'credit_score': 'Credit score is below threshold',
        'employment_length': 'Length of employment is insufficient',
        'recent_inquiries': 'Too many recent credit inquiries'
    }
    return reason_map.get(feature_name, f'Issue with {feature_name}')

Interview Questions

Simple explanation:

"SHAP values tell us how much each factor pushed the prediction up or down from the average.

Imagine the average loan approval rate is 60%. For this specific application, SHAP values show:

  • High income: +15% (pushed prediction up)
  • Short employment: -10% (pushed prediction down)
  • Good credit score: +12% (pushed prediction up)
  • High debt: -8% (pushed prediction down)

Adding these to the 60% baseline gives us 69% approval probability."

Use SHAP when:

  • Working with tree-based models (TreeExplainer is fast)
  • Need consistent, theoretically grounded explanations
  • Want both local and global insights
  • Feature interactions are important

Use LIME when:

  • Explaining text or image models
  • Need quick local explanations
  • Model API only (no access to internals)
  • Want human-readable rules

General advice: SHAP is preferred for tabular data; LIME works better for unstructured data.

Detection approaches:

  1. Correlation analysis: Check if ZIP code demographics correlate with protected attributes
  2. SHAP dependency: Plot SHAP values for ZIP code colored by race - look for patterns
  3. Disparate impact analysis: Compare approval rates across demographic groups
  4. Remove and compare: Retrain without ZIP code, check if demographic gaps decrease

Mitigation:

  • Use aggregate features (median income) instead of raw ZIP
  • Apply fairness constraints during training
  • Post-process predictions to ensure equal opportunity

Key differences:

  • Correlated features: Permutation shuffling breaks correlations, giving unrealistic data. SHAP uses conditional expectations.
  • Interactions: Permutation measures contribution including interactions. SHAP can isolate main effects.
  • Direction: SHAP shows positive/negative contribution. Permutation only shows magnitude.

Example: If features A and B are highly correlated:

  • Permutation: Both might show low importance (redundancy)
  • SHAP: One might show high importance (captures the shared effect)

Comprehensive documentation approach:

  1. Model overview: Architecture, training data, performance metrics
  2. Global explanations: SHAP summary plot, feature importance ranking
  3. Local explanations: Sample individual predictions with SHAP waterfall plots
  4. Validation: Show explanations are consistent and stable
  5. Fairness analysis: Disparate impact testing across protected groups
  6. Counterfactual examples: "What would need to change for a different outcome?"

Key principle: Demonstrate that you understand why the model makes decisions, not just that it's accurate.

Previous: Clustering Back to ML Tutorials