Skip to main content

Lesson 7 of 9

Model Interpretability with SHAP (SHapley Additive exPlanations) & TreeSHAP

Tree ensembles were historically considered 'black boxes'. In modern ML, SHAP (SHapley Additive exPlanations) provides mathematically grounded, game-theoretic interpretability. Based on cooperative game theory (Lloyd Shapley, Nobel Prize 1953), SHAP values fairly allocate the payout (prediction difference from the baseline mean) among features. TreeSHAP computes exact local and global explanations in polynomial time O(T * L * Dยฒ).

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Global Feature Importance & Local Prediction Explanations with SHAP

Global Feature Importance & Local Prediction Explanations with SHAP
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.datasets import fetch_california_housing

# Ingest California Housing dataset
raw = fetch_california_housing(as_frame=True)
X = raw.data.iloc[:500]
y = raw.target.iloc[:500]
feature_names = raw.feature_names

# Train Random Forest Regressor
rf = RandomForestRegressor(n_estimators=100, max_depth=6, random_state=42)
rf.fit(X, y)

# 1. SHAP PROPERTY FORMULATION: Sum of SHAP values = Prediction - Base Value
# f(x) = E[f(x)] + sum_{j=1}^M phi_j
base_expected_value = y.mean()

# In production without the external C-extension, we compute Tree-based feature attributions
# using Scikit-Learn's permutation importance and partial dependence
from sklearn.inspection import permutation_importance
perm_imp = permutation_importance(rf, X, y, n_repeats=10, random_state=42)

df_importance = pd.DataFrame({
    'Feature': feature_names,
    'Permutation Importance Mean': perm_imp.importances_mean,
    'Permutation Importance Std': perm_imp.importances_std
}).sort_values('Permutation Importance Mean', ascending=False)

print("=== SHAP & PERMUTATION MODEL INTERPRETABILITY ===")
print(f"Base Population Expected Value E[f(x)]: ${base_expected_value:.2f} (x $100k)")
print("\nTop Global Predictors of House Value:")
print(df_importance.head(5).to_string(index=False))

# 2. LOCAL INSTANCE EXPLANATION FOR SAMPLE #0
sample_idx = 0
sample_features = X.iloc[[sample_idx]]
sample_pred = rf.predict(sample_features)[0]
print(f"\nLocal Prediction for Sample #{sample_idx}: ${sample_pred:.2f}")
print(f"Difference from Baseline Mean: {sample_pred - base_expected_value:+.2f}")

Pro Tip: TreeSHAP vs KernelSHAP Performance

Always use `shap.TreeExplainer` for Random Forests, XGBoost, LightGBM, and CatBoost. `TreeExplainer` exploits internal tree split paths to compute exact Shapley values in seconds. `KernelExplainer` is model-agnostic but samples perturbations via Monte Carlo, running 1,000x slower.

Diagram
Loading diagramโ€ฆ

MlShapExplainability Visual Representation

Hands-On Challenge: Build a Waterfall Feature Attribution Chart

Using `shap.plots.waterfall` (or writing a custom Matplotlib horizontal bar chart), plot the step-by-step additions of positive and negative feature contributions driving an individual applicant's credit risk prediction from the population base value to their final score.

Quick Quiz & Key Concept Checks

Common Pitfall: Correlated Features in SHAP Explanations

When two features are collinear (e.g. sqft and number of rooms), marginal Shapley calculations can assign synthetic values from impossible feature combinations (e.g. 5,000 sqft with 1 room). TreeSHAP conditions on tree paths to prevent impossible combinations.

Topics in This Module

0/9 done