Master SHAP, LIME, and feature importance techniques
Model interpretability helps us understand why a model makes certain predictions. This is crucial for:
Models that are inherently explainable:
Coefficients/rules directly explain predictions
Explain any model after training:
Model-agnostic techniques
Global: Overall model behavior
Local: Individual prediction
Often a trade-off exists:
Modern view: Post-hoc methods can explain complex models without sacrificing performance
Sum of impurity decrease weighted by samples:
\[\text{Importance}_j = \sum_{t \in T_j} \frac{n_t}{n} \Delta i(t)\]
Measure performance drop when feature is shuffled:
\[\text{PI}_j = s - \frac{1}{K}\sum_{k=1}^{K} s_{j,k}\]
Retrain without each feature:
\[\text{DCI}_j = s_{\text{all}} - s_{\text{-}j}\]
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 (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?"
\[\phi_i = \sum_{S \subseteq N \setminus \{i\}} \frac{|S|!(|N|-|S|-1)!}{|N|!} [f(S \cup \{i\}) - f(S)]\]
Key properties:
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]
SHAP advantages:
Tree feature importance pitfalls: Biased toward high-cardinality features, doesn't show direction, can't explain individual predictions.
Find interpretable model g that approximates f locally:
\[\xi(x) = \arg\min_{g \in G} \mathcal{L}(f, g, \pi_x) + \Omega(g)\]
G is typically linear models or decision trees
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
)
| Aspect | SHAP | LIME |
|---|---|---|
| Theory | Game theory | Local approximation |
| Consistency | Yes | Can vary |
| Speed (trees) | Fast | Slower |
| Interactions | Handles well | Limited |
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)})\]
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'])
Regulations:
Requirements:
GDPR Article 22:
"Right to explanation" for automated decisions
Healthcare requirements:
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}')
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:
Adding these to the 60% baseline gives us 69% approval probability."
Use SHAP when:
Use LIME when:
General advice: SHAP is preferred for tabular data; LIME works better for unstructured data.
Detection approaches:
Mitigation:
Key differences:
Example: If features A and B are highly correlated:
Comprehensive documentation approach:
Key principle: Demonstrate that you understand why the model makes decisions, not just that it's accurate.