Computes SHAP values and generates interpretability plots (waterfall, beeswarm, bar, scatter, force, heatmap) for any ML model. Use for feature importance, model debugging, bias analysis, and explainable AI.
Ships in alterlab-data-science. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
SHAP is a unified approach to explain machine learning model outputs using Shapley values from cooperative game theory. This skill provides comprehensive guidance for:
SHAP works with all model types: tree-based models (XGBoost, LightGBM, CatBoost, Random Forest), deep learning models (TensorFlow, PyTorch, Keras), linear models, and black-box models.
Trigger this skill when users ask about:
| Scenario | Use Instead |
|---|---|
| Profiling a raw dataset (distributions, missingness, correlations) before any model exists | alterlab-eda |
| Building, cross-validating, or tuning the model itself | alterlab-scikit-learn |
| Estimating the causal effect of an intervention (SHAP describes model associations, not causes) | alterlab-causal-inference |
Hand-off rule. When the request matches a row above, open your answer by naming that skill by its exact id (for example alterlab-eda) and saying in one line why it fits better, then stop applying this skill's procedure. Name it even when you also need to ask for missing input. If only part of the request is out of scope, name the skill for that part and do only the in-scope part. A brief general pointer is fine; the named skill does the work.
Decision Tree:
Tree-based model? (XGBoost, LightGBM, CatBoost, Random Forest, Gradient Boosting)
shap.TreeExplainer (fast, exact)Deep neural network? (TensorFlow, PyTorch, Keras, CNNs, RNNs, Transformers)
shap.DeepExplainer or shap.GradientExplainerLinear model? (Linear/Logistic Regression, GLMs)
shap.LinearExplainer (extremely fast)Any other model? (SVMs, custom functions, black-box models)
shap.KernelExplainer (model-agnostic but slower)Unsure?
shap.Explainer (automatically selects best algorithm)See references/explainers.md for detailed information on all explainer types.
import shap
# Example with tree-based model (XGBoost)
import xgboost as xgb
# Train model
model = xgb.XGBClassifier().fit(X_train, y_train)
# Create explainer
explainer = shap.TreeExplainer(model)
# Compute SHAP values
shap_values = explainer(X_test)
# The shap_values object contains:
# - values: SHAP values (feature attributions)
# - base_values: Expected model output (baseline)
# - data: Original feature values
For Global Understanding (entire dataset):
# Beeswarm plot - shows feature importance with value distributions
shap.plots.beeswarm(shap_values, max_display=15)
# Bar plot - clean summary of feature importance
shap.plots.bar(shap_values)
For Individual Predictions:
# Waterfall plot - detailed breakdown of single prediction
shap.plots.waterfall(shap_values[0])
# Force plot - additive force visualization
shap.plots.force(shap_values[0])
For Feature Relationships:
# Scatter plot - feature-prediction relationship
shap.plots.scatter(shap_values[:, "Feature_Name"])
# Colored by another feature to show interactions
shap.plots.scatter(shap_values[:, "Age"], color=shap_values[:, "Education"])
See references/plots.md for comprehensive guide on all plot types.
This skill supports several common workflows. Choose the workflow that matches the current task.
Goal: Understand what drives model predictions
Steps:
Example:
# Step 1-2: Setup
explainer = shap.TreeExplainer(model)
shap_values = explainer(X_test)
# Step 3: Global importance
shap.plots.beeswarm(shap_values)
# Step 4: Feature relationships
shap.plots.scatter(shap_values[:, "Most_Important_Feature"])
# Step 5: Individual explanation
shap.plots.waterfall(shap_values[0])
Goal: Identify and fix model issues
Steps:
See references/workflows.md for detailed debugging workflow.
Goal: Use SHAP insights to improve features
Steps:
See references/workflows.md for detailed feature engineering workflow.
Goal: Compare multiple models to select best interpretable option
Steps:
See references/workflows.md for detailed model comparison workflow.
Goal: Detect and analyze model bias across demographic groups
Steps:
See references/workflows.md for detailed fairness analysis workflow.
Goal: Integrate SHAP explanations into production systems
Steps:
See references/workflows.md for detailed production deployment workflow.
Definition: SHAP values quantify each feature's contribution to a prediction, measured as the deviation from the expected model output (baseline).
Properties:
Interpretation:
Example:
Baseline (expected value): 0.30
Feature contributions (SHAP values):
Age: +0.15
Income: +0.10
Education: -0.05
Final prediction: 0.30 + 0.15 + 0.10 - 0.05 = 0.50
Purpose: Represents "typical" input to establish baseline expectations
Selection:
Impact: Baseline affects SHAP value magnitudes but not relative importance
Critical Consideration: Understand what your model outputs
Example: XGBoost classifiers explain margin output (log-odds) by default. To explain probabilities, use model_output="probability" in TreeExplainer.
# 1. Setup
explainer = shap.TreeExplainer(model)
shap_values = explainer(X_test)
# 2. Global importance
shap.plots.beeswarm(shap_values)
shap.plots.bar(shap_values)
# 3. Top feature relationships
top_features = X_test.columns[np.abs(shap_values.values).mean(0).argsort()[-5:]]
for feature in top_features:
shap.plots.scatter(shap_values[:, feature])
# 4. Example predictions
for i in range(5):
shap.plots.waterfall(shap_values[i])
# Define cohorts
cohort1_mask = X_test['Group'] == 'A'
cohort2_mask = X_test['Group'] == 'B'
# Compare feature importance
shap.plots.bar({
"Group A": shap_values[cohort1_mask],
"Group B": shap_values[cohort2_mask]
})
# Find errors
errors = model.predict(X_test) != y_test
error_indices = np.where(errors)[0]
# Explain errors
for idx in error_indices[:5]:
print(f"Sample {idx}:")
shap.plots.waterfall(shap_values[idx])
# Investigate key features
shap.plots.scatter(shap_values[:, "Suspicious_Feature"])
Explainer Speed (fastest to slowest):
LinearExplainer - Nearly instantaneousTreeExplainer - Very fastDeepExplainer - Fast for neural networksGradientExplainer - Fast for neural networksKernelExplainer - Slow (use only when necessary)PermutationExplainer - Very slow but accurateFor Large Datasets:
# Compute SHAP for subset
shap_values = explainer(X_test[:1000])
# Or use batching
batch_size = 100
all_shap_values = []
for i in range(0, len(X_test), batch_size):
batch_shap = explainer(X_test[i:i+batch_size])
all_shap_values.append(batch_shap)
For Visualizations:
# Sample subset for plots
shap.plots.beeswarm(shap_values[:1000])
# Adjust transparency for dense plots
shap.plots.scatter(shap_values[:, "Feature"], alpha=0.3)
For Production:
# Cache explainer
import joblib
joblib.dump(explainer, 'explainer.pkl')
explainer = joblib.load('explainer.pkl')
# Pre-compute for batch predictions
# Only compute top N features for API responses
Problem: Using KernelExplainer for tree models (slow and unnecessary) Solution: Always use TreeExplainer for tree-based models
Problem: DeepExplainer/KernelExplainer with too few background samples Solution: Use 100-1000 representative samples
Problem: Interpreting log-odds as probabilities Solution: Check model output type; understand whether values are probabilities, log-odds, or raw outputs
Problem: Matplotlib backend issues
Solution: Ensure backend is set correctly; use plt.show() if needed
Problem: Default max_display=10 may be too many or too few
Solution: Adjust max_display parameter or use feature clustering
Problem: Computing SHAP for very large datasets Solution: Sample subset, use batching, or ensure using specialized explainer (not KernelExplainer)
show=True (default). For saving to file, pass show=False then plt.savefig(...).mlflow.log_figure(plt.gcf(), "shap_beeswarm.png") and log np.abs(shap_values.values).mean(0) per feature as metrics. Full snippet in references/workflows.md (MLOps integration).joblib, recompute SHAP at request time, return base value + per-feature contributions. Full ExplanationService class in references/workflows.md (Workflow 7).Load these on demand (via Read) for depth beyond this SKILL.md:
references/explainers.md — every explainer class (constructor params, supported models, methods, perf). Load when choosing an explainer or needing exact parameters.references/plots.md — every plot function (params, use cases, plot-selection guide). Load when picking or tuning a visualization.references/workflows.md — full step-by-step workflows (debugging, feature engineering, model comparison, fairness, deep learning, production, time series, MLOps). Load for multi-step tasks.references/theory.md — Shapley-value math, axioms, computation algorithms, conditional expectations, comparisons to LIME/permutation/Gini importance. Load for theoretical questions.Choose the right explainer: Use specialized explainers (TreeExplainer, DeepExplainer, LinearExplainer) when possible; avoid KernelExplainer unless necessary
Start global, then go local: Begin with beeswarm/bar plots for overall understanding, then dive into waterfall/scatter plots for details
Use multiple visualizations: Different plots reveal different insights; combine global (beeswarm) + local (waterfall) + relationship (scatter) views
Select appropriate background data: Use 50-1000 representative samples from training data
Understand model output units: Know whether explaining probabilities, log-odds, or raw outputs
Validate with domain knowledge: SHAP shows model behavior; use domain expertise to interpret and validate
Optimize for performance: Sample subsets for visualization, batch for large datasets, cache explainers in production
Check for data leakage: Unexpectedly high feature importance may indicate data quality issues
Consider feature correlations: Use TreeExplainer's correlation-aware options or feature clustering for redundant features
Remember SHAP shows association, not causation: Use domain knowledge for causal interpretation
The modern API used throughout this skill — the callable explainer(X) returning an Explanation object, plus the shap.plots.* namespace — requires shap >= 0.41. The current release is 0.52 (May 2026; requires Python ≥ 3.12 and NumPy ≥ 2), with 0.53 in release candidate as of 2026-09. Pin it in a uv project:
# In a uv project (adds to pyproject.toml + uv.lock):
uv add "shap>=0.41" matplotlib
# Scratch / one-off run (ephemeral env, nothing persisted):
uv run --python ">=3.12" --with "shap>=0.41" --with matplotlib python explain.py
(uv pip install works only inside an already-activated venv; prefer uv add / uv run --with so the dependency is recorded.)
Dependencies: numpy, pandas, scikit-learn, scipy, and numba are pulled in automatically. matplotlib is optional (the shap[plots] extra), so install it explicitly as above before calling shap.plots.*.
Optional: xgboost, lightgbm, catboost, tensorflow, torch (depending on model types).
This skill provides comprehensive coverage of SHAP for model interpretability across all use cases and model types.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/alterlab-data-science:alterlab-shapfrom alterlab-data-science
npx claudepluginhub alterlab-ieu/alterlab-academic-skills --plugin alterlab-data-science22 skills in this plugin
/alterlab-daskScales pandas/NumPy workflows beyond memory with Dask distributed computing — parallel DataFrames, arrays, delayed task graphs, and cluster execution. Use when existing pandas/NumPy code must run on larger-than-RAM data or across clusters, for parallel file processing, distributed ML, or integration with existing pandas code. For out-of-core analytics on a single machine prefer vaex; for in-memory speed prefer polars. Part of the AlterLab Academic Skills suite./alterlab-edaExploratory data analysis (EDA) on a scientific data file — auto-detects the format, runs structure/quality/statistics checks, and writes a markdown EDA report with downstream recommendations. Use when asked to "explore", "analyze", "summarize", "profile", or "QC" a data file, or to understand its structure/content/quality before deciding what analysis to run. Covers tabular (.csv .tsv .xlsx .parquet), arrays (.npy .npz .hdf5 .h5 .mat .fits), sequence/genomics (.fasta .fastq .sam .bam .vcf .bed .gff .gtf .h5ad), microscopy (.tif .nd2 .czi .lif .ims .dcm .nii), spectroscopy/MS (.mzML .mzXML .mgf .fid .jdx), chemistry (.pdb .cif .mol .sdf .xyz .gro), and proteomics/metabolomics (.pepXML .mzid .mzTab). For zero-shot forecasting of a series use alterlab-timesfm; to create/configure a chunked cloud array store use alterlab-zarr. Part of the AlterLab Academic Skills suite./alterlab-networkxCreates, analyzes, and visualizes complex networks and graphs in Python with NetworkX. Use when working with network/graph data structures, analyzing relationships between entities, computing graph algorithms (shortest paths, centrality, clustering), detecting communities, generating synthetic networks, or visualizing topologies — applicable to social, biological, transportation, citation, and any pairwise-relationship networks. This is classical graph analytics, not deep learning — for training graph neural networks (GCN/message passing, node/edge/graph classification on Cora-style data) use alterlab-torch-geometric instead. Part of the AlterLab Academic Skills suite./alterlab-polarsFast in-memory DataFrame analytics with Polars — lazy evaluation, parallel execution, and an Apache Arrow backend for datasets that fit in RAM. Use when pandas is too slow but data still fits in memory, for 1-100GB datasets, ETL pipelines, or a faster pandas replacement. For larger-than-RAM data prefer dask or vaex. Part of the AlterLab Academic Skills suite./alterlab-pufferlibScales reinforcement learning with PufferLib — high-throughput parallel training (PuffeRL), vectorized environments, and native multi-agent systems achieving 2-10x speedups over standard implementations. Use when scaling RL to millions of steps per second, running vectorized or multi-agent setups, building custom PufferEnv tasks, or integrating game environments (Atari, Procgen, NetHack, PettingZoo). For standard single-agent algorithm implementations (PPO/SAC/DQN) or quick prototyping prefer alterlab-stable-baselines3. Part of the AlterLab Academic Skills suite./alterlab-pymcBayesian modeling and probabilistic programming with PyMC 6 and ArviZ 1.x — hierarchical models, MCMC (NUTS via PyMC, nutpie, NumPyro, or BlackJAX), variational inference, PSIS-LOO model comparison, and prior/posterior predictive checks. Use when fitting Bayesian or hierarchical models, estimating posteriors and credible intervals, diagnosing divergences, R-hat, or ESS, running probabilistic inference, or comparing models with LOO (WAIC was removed from ArviZ 1.x). Part of the AlterLab Academic Skills suite.2 plugins in one repository ship this exact skill · first indexed Nov 9, 2026
Other plugins' skills for the same job