36 — Python Power Tools

SHAP Library#

Python✓ Mathematical
◆ The PatternTreeExplainer, force_plot, summary_plot, waterfall — the complete SHAP toolkit

The shap library implements everything from SHAP Values in production-ready code. TreeExplainer is exact and fast for tree models. The visualisations — waterfall, beeswarm, dependence — are publication-ready out of the box.

// SHAP plot types overview
# SHAP — complete reference
import shap

# 1. Choose the right explainer
explainer = shap.TreeExplainer(model)     # XGBoost, LightGBM, RF
# explainer = shap.KernelExplainer(model.predict, X_bg)
# explainer = shap.DeepExplainer(model, X_bg)

# 2. Compute SHAP values
shap_values = explainer(X_test)

# 3. Visualisations
shap.plots.waterfall(shap_values[0])       # single prediction
shap.plots.beeswarm(shap_values)            # global summary
shap.plots.bar(shap_values)                 # mean |SHAP|
shap.plots.scatter(shap_values[:,"age"])   # dependence

# 4. Interaction values (slow but powerful)
inter = explainer.shap_interaction_values(X_test)
ExplainerModelsSpeed
TreeExplainerXGBoost, LightGBM, CatBoost, RFFast, exact
KernelExplainerAny model (black-box)Slow, approximate
DeepExplainerTensorFlow, PyTorchMedium, approximate
LinearExplainerLinear/logistic regressionInstant, exact
Performance tip: For KernelExplainer, use a small background dataset (e.g., shap.kmeans(X_train, 50)) to speed things up dramatically.
← Previous
scikit-learn Evaluation Suite
Open in the full reader, with the topic sidebar →