pythonintermediate
SHAP Model Explainability in Python
Explain ML model predictions globally and locally using SHAP values with tree-based models.
pythonPress ⌘/Ctrl + Shift + C to copy
import shap
import numpy as np
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import load_breast_cancer
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
model = GradientBoostingClassifier(n_estimators=100, random_state=42)
model.fit(X, y)
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X)
# Global feature importance
importance = np.abs(shap_values).mean(axis=0)
top5_idx = np.argsort(importance)[::-1][:5]
print('Top 5 features:')
for idx in top5_idx:
print(f' {X.columns[idx]}: {importance[idx]:.4f}')
# Local explanation for first sample
print('\nFirst sample SHAP values:')
for col, val in zip(X.columns, shap_values[0]):
if abs(val) > 0.01:
print(f' {col}: {val:+.4f}')Use Cases
- model interpretability
- compliance
- debugging ML models
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonintermediate
LIME Local Model Explanation
Generate local interpretable explanations for any black-box classifier using LIME.
Best for: black-box explanation
#lime#explainability
pythonintermediate
Custom sklearn Pipeline with Transformer
Build a custom scikit-learn Pipeline with a custom BaseEstimator Transformer for data preprocessing.
Best for: custom preprocessing
#sklearn#pipeline
pythonintermediate
AutoML with FLAML for Fast Tuning
Run automated machine learning with FLAML to find the best model and hyperparameters efficiently.
Best for: automated ML
#automl#flaml
pythonintermediate
XGBoost with Early Stopping and SHAP
Train an XGBoost model with early stopping and explain predictions using native SHAP integration.
Best for: classification
#xgboost#early-stopping