shap
Model interpretability and explainability using SHAP (SHapley Additive exPlanations). Use this skill when explaining machine learning model predictions, computing feature importance, generating SHAP plots (waterfall, beeswarm, bar, scatter, force, heatmap), debugging models, analyzing model bias or fairness, comparing models, or implementing explainable AI. Works with tree-based models (XGBoost, LightGBM, Random Forest), deep learning (TensorFlow, PyTorch), linear models, and any black-box model.
Overview
Model interpretability and explainability using SHAP (SHapley Additive exPlanations). Use this skill when explaining machine learning model predictions, computing feature importance, generating SHAP plots (waterfall, beeswarm, bar, scatter, force, heatmap), debugging models, analyzing model bias or fairness, comparing models, or implementing explainable AI. Works with tree-based models (XGBoost, LightGBM, Random Forest), deep learning (TensorFlow, PyTorch), linear models, and any black-box model.
Source: https://github.com/DenDen047/claude-scientific-skills · MIT LICENSE · © 2025 K-Dense Inc.
System prompt
The instruction block that defines the agent's role, rules and output format.
# SHAP (SHapley Additive exPlanations)
## Overview
SHAP is a unified approach to explain machine learning model outputs using Shapley values from cooperative game theory. This skill provides comprehensive guidance for:
- Computing SHAP values for any model type
- Creating visualizations to understand feature importance
- Debugging and validating model behavior
- Analyzing fairness and bias
- Implementing explainable AI in production
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.
## When to Use This Skill
**Trigger this skill when users ask about**:
- "Explain which features are most important in my model"
- "Generate SHAP plots" (waterfall, beeswarm, bar, scatter, force, heatmap, etc.)
- "Why did my model make this prediction?"
- "Calculate SHAP values for my model"
- "Visualize feature importance using SHAP"
- "Debug my model's behavior" or "validate my model"
- "Check my model for bias" or "analyze fairness"
- "Compare feature importance across models"
- "Implement explainable AI" or "add explanations to my model"
- "Understand feature interactions"
- "Create model interpretation dashboard"
## Quick Start Guide
### Step 1: Select the Right Explainer
**Decision Tree**:
1. **Tree-based model?** (XGBoost, LightGBM, CatBoost, Random Forest, Gradient Boosting)
- Use `shap.TreeExplainer` (fast, exact)
2. **Deep neural network?** (TensorFlow, PyTorch, Keras, CNNs, RNNs, Transformers)
- Use `shap.DeepExplainer` or `shap.GradientExplainer`
3. **Linear model?** (Linear/Logistic Regression, GLMs)
- Use `shap.LinearExplainer` (extremely fast)
4. **Any other model?** (SVMs, custom functions, black-box models)
- Use `shap.KernelExplainer` (model-agnostic but slower)
5. **Unsure?**
- Use `shap.Explainer` (automatically selects best algorithm)
**See `references/explainers.md` for detailed information on all explainer types.**
### Step 2: Compute SHAP Values
```python
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
```
### Step 3: Visualize Results
**For Global Understanding** (entire dataset):
```python
# 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**:
```python
# 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**:
```python
# 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.**
## Core Workflows
This skill supports several common workflows. Choose the workflow that matches the current task.
### Workflow 1: Basic Model Explanation
**Goal**: Understand what drives model predictions
**Steps**:
1. Train model and create appropriate explainer
2. Compute SHAP values for test set
3. Generate global importance plots (beeswarm or bar)
4. Examine top feature relationships (scatter plots)
5. Explain specific predictions (waterfall plots)
**Example**:
```python
# 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])
```
### Workflow 2: Model Debugging
**Goal**: Identify and fix model issues
**Steps**:
1. Compute SHAP values
2. Identify prediction errors
3. Explain misclassified samples
4. Check for unexpected feature importance (data leakage)
5. Validate feature relationships make sense
6. Check feature interactions
**See `references/workflows.md` for detailed debugging workflow.**
### Workflow 3: Feature Engineering
**Goal**: Use SHAP insights to improve features
**Steps**:
1. Compute SHAP values for baseline model
2. Identify nonlinear relationships (candidates for transformation)
3. Identify feature interactions (candidates for interaction terms)
4. Engineer new features
5. Retrain and compare SHAP values
6. Validate improvements
**See `references/workflows.md` for detailed feature engineering workflow.**
### Workflow 4: Model Comparison
**Goal**: Compare multiple models to select best interpretable option
**Steps**:
1. Train multiple models
2. Compute SHAP values for each
3. Compare global feature importance
4. Check consistency of feature rankings
5. Analyze specific predictions across models
6. Select based on accuracy, interpretability, and consistency
**See `references/workflows.md` for detailed model comparison workflow.**
### Workflow 5: Fairness and Bias Analysis
**Goal**: Detect and analyze model bias across demographic groups
**Steps**:
1. Identify protected attributes (gender, race, age, etc.)
2. Compute SHAP values
3. Compare feature importance across groups
4. Check protected attribute SHAP importance
5. Identify proxy features
6. Implement mitigation strategies if bias found
**See `references/workflows.md` for detailed fairness analysis workflow.**
### Workflow 6: Production Deployment
**Goal**: Integrate SHAP explanations into production systems
**Steps**:
1. Train and save model
2. Create and save explainer
3. Build explanation service
4. Create API endpoints for predictions with explanations
5. Implement caching and optimization
6. Monitor explanation quality
**See `references/workflows.md` for detailed production deployment workflow.**
## Key Concepts
### SHAP Values
**Definition**: SHAP values quantify each feature's contribution to a prediction, measured as the deviation from the expected model output (baseline).
**Properties**:
- **Additivity**: SHAP values sum to difference between prediction and baseline
- **Fairness**: Based on Shapley values from game theory
- **Consistency**: If a feature becomes more important, its SHAP value increases
**Interpretation**:
- Positive SHAP value → Feature pushes prediction higher
- Negative SHAP value → Feature pushes prediction lower
- Magnitude → Strength of feature's impact
- Sum of SHAP values → Total prediction change from baseline
**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
```
### Background Data / Baseline
**Purpose**: Represents "typical" input to establish baseline expectations
**Selection**:
- Random sample from training data (50-1000 samples)
- Or use kmeans to select representative samples
- For DeepExplainer/KernelExplainer: 100-1000 samples balances accuracy and speed
**Impact**: Baseline affects SHAP value magnitudes but not relative importance
### Model Output Types
**Critical Consideration**: Understand what your model outputs
- **Raw output**: For regression or tree margins
- **Probability**: For classification probability
- **Log-odds**: For logistic regression (before sigmoid)
**Example**: XGBoost classifiers explain margin output (log-odds) by default. To explain probabilities, use `model_output="probability"` in TreeExplainer.
## Common Patterns
### Pattern 1: Complete Model Analysis
```python
# 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])
```
### Pattern 2: Cohort Comparison
```python
# 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]
})
```
### Pattern 3: Debugging Errors
```python
# 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"])
```
## Performance Optimization
### Speed Considerations
**Explainer Speed** (fastest to slowest):
1. `LinearExplainer` - Nearly instantaneous
2. `TreeExplainer` - Very fast
3. `DeepExplainer` - Fast for neural networks
4. `GradientExplainer` - Fast for neural networks
5. `KernelExplainer` - Slow (use only when necessary)
6. `PermutationExplainer` - Very slow but accurate
### Optimization Strategies
**For Large Datasets**:
```python
# 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**:
```python
# 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**:
```python
# 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
```
## Troubleshooting
### Issue: Wrong explainer choice
**Problem**: Using KernelExplainer for tree models (slow and unnecessary)
**Solution**: Always use TreeExplainer for tree-based models
### Issue: Insufficient background data
**Problem**: DeepExplainer/KernelExplainer with too few background samples
**Solution**: Use 100-1000 representative samples
### Issue: Confusing units
**Problem**: Interpreting log-odds as probabilities
**Solution**: Check model output type; understand whether values are probabilities, log-odds, or raw outputs
### Issue: Plots don't display
**Problem**: Matplotlib backend issues
**Solution**: Ensure backend is set correctly; use `plt.show()` if needed
### Issue: Too many features cluttering plots
**Problem**: Default max_display=10 may be too many or too few
**Solution**: Adjust `max_display` parameter or use feature clustering
### Issue: Slow computation
**Problem**: Computing SHAP for very large datasets
**Solution**: Sample subset, use batching, or ensure using specialized explainer (not KernelExplainer)
## Integration with Other Tools
### Jupyter Notebooks
- Interactive force plots work seamlessly
- Inline plot display with `show=True` (default)
- Combine with markdown for narrative explanations
### MLflow / Experiment Tracking
```python
import mlflow
with mlflow.start_run():
# Train model
model = train_model(X_train, y_train)
# Compute SHAP
explainer = shap.TreeExplainer(model)
shap_values = explainer(X_test)
# Log plots
shap.plots.beeswarm(shap_values, show=False)
mlflow.log_figure(plt.gcf(), "shap_beeswarm.png")
plt.close()
# Log feature importance metrics
mean_abs_shap = np.abs(shap_values.values).mean(axis=0)
for feature, importance in zip(X_test.columns, mean_abs_shap):
mlflow.log_metric(f"shap_{feature}", importance)
```
### Production APIs
```python
class ExplanationService:
def __init__(self, model_path, explainer_path):
self.model = joblib.load(model_path)
self.explainer = joblib.load(explainer_path)
def predict_with_explanation(self, X):
prediction = self.model.predict(X)
shap_values = self.explainer(X)
return {
'prediction': prediction[0],
'base_value': shap_values.base_values[0],
'feature_contributions': dict(zip(X.columns, shap_values.values[0]))
}
```
## Reference Documentation
This skill includes comprehensive reference documentation organized by topic:
### references/explainers.md
Complete guide to all explainer classes:
- `TreeExplainer` - Fast, exact explanations for tree-based models
- `DeepExplainer` - Deep learning models (TensorFlow, PyTorch)
- `KernelExplainer` - Model-agnostic (works with any model)
- `LinearExplainer` - Fast explanations for linear models
- `GradientExplainer` - Gradient-based for neural networks
- `PermutationExplainer` - Exact but slow for any model
Includes: Constructor parameters, methods, supported models, when to use, examples, performance considerations.
### references/plots.md
Comprehensive visualization guide:
- **Waterfall plots** - Individual prediction breakdowns
- **Beeswarm plots** - Global importance with value distributions
- **Bar plots** - Clean feature importance summaries
- **Scatter plots** - Feature-prediction relationships and interactions
- **Force plots** - Interactive additive force visualizations
- **Heatmap plots** - Multi-sample comparison grids
- **Violin plots** - Distribution-focused alternatives
- **Decision plots** - Multiclass prediction paths
Includes: Parameters, use cases, examples, best practices, plot selection guide.
### references/workflows.md
Detailed workflows and best practices:
- Basic model explanation workflow
- Model debugging and validation
- Feature engineering guidance
- Model comparison and selection
- Fairness and bias analysis
- Deep learning model explanation
- Production deployment
- Time series model explanation
- Common pitfalls and solutions
- Advanced techniques
- MLOps integration
Includes: Step-by-step instructions, code examples, decision criteria, troubleshooting.
### references/theory.md
Theoretical foundations:
- Shapley values from game theory
- Mathematical formulas and properties
- Connection to other explanation methods (LIME, DeepLIFT, etc.)
- SHAP computation algorithms (Tree SHAP, Kernel SHAP, etc.)
- Conditional expectations and baseline selection
- Interpreting SHAP values
- Interaction values
- Theoretical limitations and considerations
Includes: Mathematical foundations, proofs, comparisons, advanced topics.
## Usage Guidelines
**When to load reference files**:
- Load `explainers.md` when user needs detailed information about specific explainer types or parameters
- Load `plots.md` when user needs detailed visualization guidance or exploring plot options
- Load `workflows.md` when user has complex multi-step tasks (debugging, fairness analysis, production deployment)
- Load `theory.md` when user asks about theoretical foundations, Shapley values, or mathematical details
**Default approach** (without loading references):
- Use this SKILL.md for basic explanations and quick start
- Provide standard workflows and common patterns
- Reference files are available if more detail is needed
**Loading references**:
```python
# To load reference files, use the Read tool with appropriate file path:
# /path/to/shap/references/explainers.md
# /path/to/shap/references/plots.md
# /path/to/shap/references/workflows.md
# /path/to/shap/references/theory.md
```
## Best Practices Summary
1. **Choose the right explainer**: Use specialized explainers (TreeExplainer, DeepExplainer, LinearExplainer) when possible; avoid KernelExplainer unless necessary
2. **Start global, then go local**: Begin with beeswarm/bar plots for overall understanding, then dive into waterfall/scatter plots for details
3. **Use multiple visualizations**: Different plots reveal different insights; combine global (beeswarm) + local (waterfall) + relationship (scatter) views
4. **Select appropriate background data**: Use 50-1000 representative samples from training data
5. **Understand model output units**: Know whether explaining probabilities, log-odds, or raw outputs
6. **Validate with domain knowledge**: SHAP shows model behavior; use domain expertise to interpret and validate
7. **Optimize for performance**: Sample subsets for visualization, batch for large datasets, cache explainers in production
8. **Check for data leakage**: Unexpectedly high feature importance may indicate data quality issues
9. **Consider feature correlations**: Use TreeExplainer's correlation-aware options or feature clustering for redundant features
10. **Remember SHAP shows association, not causation**: Use domain knowledge for causal interpretation
## Installation
```bash
# Basic installation
uv pip install shap
# With visualization dependencies
uv pip install shap matplotlib
# Latest version
uv pip install -U shap
```
**Dependencies**: numpy, pandas, scikit-learn, matplotlib, scipy
**Optional**: xgboost, lightgbm, tensorflow, torch (depending on model types)
## Additional Resources
- **Official Documentation**: https://shap.readthedocs.io/
- **GitHub Repository**: https://github.com/slundberg/shap
- **Original Paper**: Lundberg & Lee (2017) - "A Unified Approach to Interpreting Model Predictions"
- **Nature MI Paper**: Lundberg et al. (2020) - "From local explanations to global understanding with explainable AI for trees"
This skill provides comprehensive coverage of SHAP for model interpretability across all use cases and model types. User prompt template
Fill in the variables and send it to run the skill: {{variables}}
Variables
| Name | Required | Description | Example |
|---|
Full skill configuration
The standard .aiskill file in JSON and YAML.
{
"format": "aiskill/v1",
"skill": {
"name": "shap",
"slug": "shap",
"version": "1.0.0",
"description": "Model interpretability and explainability using SHAP (SHapley Additive exPlanations). Use this skill when explaining machine learning model predictions, computing feature importance, generating SHAP plots (waterfall, beeswarm, bar, scatter, force, heatmap), debugging models, analyzing model bias or fairness, comparing models, or implementing explainable AI. Works with tree-based models (XGBoost, LightGBM, Random Forest), deep learning (TensorFlow, PyTorch), linear models, and any black-box model.",
"category": "Research",
"tags": [
"research-science"
],
"platforms": [
"chatgpt",
"claude-code",
"cursor"
],
"tested_environment": "Agent Skills convention (SKILL.md) — works with Claude Code, Cursor, ChatGPT/Codex and compatible agents",
"license": "MIT LICENSE"
},
"prompts": {
"system": "# SHAP (SHapley Additive exPlanations)\r\n\r\n## Overview\r\n\r\nSHAP is a unified approach to explain machine learning model outputs using Shapley values from cooperative game theory. This skill provides comprehensive guidance for:\r\n\r\n- Computing SHAP values for any model type\r\n- Creating visualizations to understand feature importance\r\n- Debugging and validating model behavior\r\n- Analyzing fairness and bias\r\n- Implementing explainable AI in production\r\n\r\nSHAP 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.\r\n\r\n## When to Use This Skill\r\n\r\n**Trigger this skill when users ask about**:\r\n- \"Explain which features are most important in my model\"\r\n- \"Generate SHAP plots\" (waterfall, beeswarm, bar, scatter, force, heatmap, etc.)\r\n- \"Why did my model make this prediction?\"\r\n- \"Calculate SHAP values for my model\"\r\n- \"Visualize feature importance using SHAP\"\r\n- \"Debug my model's behavior\" or \"validate my model\"\r\n- \"Check my model for bias\" or \"analyze fairness\"\r\n- \"Compare feature importance across models\"\r\n- \"Implement explainable AI\" or \"add explanations to my model\"\r\n- \"Understand feature interactions\"\r\n- \"Create model interpretation dashboard\"\r\n\r\n## Quick Start Guide\r\n\r\n### Step 1: Select the Right Explainer\r\n\r\n**Decision Tree**:\r\n\r\n1. **Tree-based model?** (XGBoost, LightGBM, CatBoost, Random Forest, Gradient Boosting)\r\n - Use `shap.TreeExplainer` (fast, exact)\r\n\r\n2. **Deep neural network?** (TensorFlow, PyTorch, Keras, CNNs, RNNs, Transformers)\r\n - Use `shap.DeepExplainer` or `shap.GradientExplainer`\r\n\r\n3. **Linear model?** (Linear/Logistic Regression, GLMs)\r\n - Use `shap.LinearExplainer` (extremely fast)\r\n\r\n4. **Any other model?** (SVMs, custom functions, black-box models)\r\n - Use `shap.KernelExplainer` (model-agnostic but slower)\r\n\r\n5. **Unsure?**\r\n - Use `shap.Explainer` (automatically selects best algorithm)\r\n\r\n**See `references/explainers.md` for detailed information on all explainer types.**\r\n\r\n### Step 2: Compute SHAP Values\r\n\r\n```python\r\nimport shap\r\n\r\n# Example with tree-based model (XGBoost)\r\nimport xgboost as xgb\r\n\r\n# Train model\r\nmodel = xgb.XGBClassifier().fit(X_train, y_train)\r\n\r\n# Create explainer\r\nexplainer = shap.TreeExplainer(model)\r\n\r\n# Compute SHAP values\r\nshap_values = explainer(X_test)\r\n\r\n# The shap_values object contains:\r\n# - values: SHAP values (feature attributions)\r\n# - base_values: Expected model output (baseline)\r\n# - data: Original feature values\r\n```\r\n\r\n### Step 3: Visualize Results\r\n\r\n**For Global Understanding** (entire dataset):\r\n```python\r\n# Beeswarm plot - shows feature importance with value distributions\r\nshap.plots.beeswarm(shap_values, max_display=15)\r\n\r\n# Bar plot - clean summary of feature importance\r\nshap.plots.bar(shap_values)\r\n```\r\n\r\n**For Individual Predictions**:\r\n```python\r\n# Waterfall plot - detailed breakdown of single prediction\r\nshap.plots.waterfall(shap_values[0])\r\n\r\n# Force plot - additive force visualization\r\nshap.plots.force(shap_values[0])\r\n```\r\n\r\n**For Feature Relationships**:\r\n```python\r\n# Scatter plot - feature-prediction relationship\r\nshap.plots.scatter(shap_values[:, \"Feature_Name\"])\r\n\r\n# Colored by another feature to show interactions\r\nshap.plots.scatter(shap_values[:, \"Age\"], color=shap_values[:, \"Education\"])\r\n```\r\n\r\n**See `references/plots.md` for comprehensive guide on all plot types.**\r\n\r\n## Core Workflows\r\n\r\nThis skill supports several common workflows. Choose the workflow that matches the current task.\r\n\r\n### Workflow 1: Basic Model Explanation\r\n\r\n**Goal**: Understand what drives model predictions\r\n\r\n**Steps**:\r\n1. Train model and create appropriate explainer\r\n2. Compute SHAP values for test set\r\n3. Generate global importance plots (beeswarm or bar)\r\n4. Examine top feature relationships (scatter plots)\r\n5. Explain specific predictions (waterfall plots)\r\n\r\n**Example**:\r\n```python\r\n# Step 1-2: Setup\r\nexplainer = shap.TreeExplainer(model)\r\nshap_values = explainer(X_test)\r\n\r\n# Step 3: Global importance\r\nshap.plots.beeswarm(shap_values)\r\n\r\n# Step 4: Feature relationships\r\nshap.plots.scatter(shap_values[:, \"Most_Important_Feature\"])\r\n\r\n# Step 5: Individual explanation\r\nshap.plots.waterfall(shap_values[0])\r\n```\r\n\r\n### Workflow 2: Model Debugging\r\n\r\n**Goal**: Identify and fix model issues\r\n\r\n**Steps**:\r\n1. Compute SHAP values\r\n2. Identify prediction errors\r\n3. Explain misclassified samples\r\n4. Check for unexpected feature importance (data leakage)\r\n5. Validate feature relationships make sense\r\n6. Check feature interactions\r\n\r\n**See `references/workflows.md` for detailed debugging workflow.**\r\n\r\n### Workflow 3: Feature Engineering\r\n\r\n**Goal**: Use SHAP insights to improve features\r\n\r\n**Steps**:\r\n1. Compute SHAP values for baseline model\r\n2. Identify nonlinear relationships (candidates for transformation)\r\n3. Identify feature interactions (candidates for interaction terms)\r\n4. Engineer new features\r\n5. Retrain and compare SHAP values\r\n6. Validate improvements\r\n\r\n**See `references/workflows.md` for detailed feature engineering workflow.**\r\n\r\n### Workflow 4: Model Comparison\r\n\r\n**Goal**: Compare multiple models to select best interpretable option\r\n\r\n**Steps**:\r\n1. Train multiple models\r\n2. Compute SHAP values for each\r\n3. Compare global feature importance\r\n4. Check consistency of feature rankings\r\n5. Analyze specific predictions across models\r\n6. Select based on accuracy, interpretability, and consistency\r\n\r\n**See `references/workflows.md` for detailed model comparison workflow.**\r\n\r\n### Workflow 5: Fairness and Bias Analysis\r\n\r\n**Goal**: Detect and analyze model bias across demographic groups\r\n\r\n**Steps**:\r\n1. Identify protected attributes (gender, race, age, etc.)\r\n2. Compute SHAP values\r\n3. Compare feature importance across groups\r\n4. Check protected attribute SHAP importance\r\n5. Identify proxy features\r\n6. Implement mitigation strategies if bias found\r\n\r\n**See `references/workflows.md` for detailed fairness analysis workflow.**\r\n\r\n### Workflow 6: Production Deployment\r\n\r\n**Goal**: Integrate SHAP explanations into production systems\r\n\r\n**Steps**:\r\n1. Train and save model\r\n2. Create and save explainer\r\n3. Build explanation service\r\n4. Create API endpoints for predictions with explanations\r\n5. Implement caching and optimization\r\n6. Monitor explanation quality\r\n\r\n**See `references/workflows.md` for detailed production deployment workflow.**\r\n\r\n## Key Concepts\r\n\r\n### SHAP Values\r\n\r\n**Definition**: SHAP values quantify each feature's contribution to a prediction, measured as the deviation from the expected model output (baseline).\r\n\r\n**Properties**:\r\n- **Additivity**: SHAP values sum to difference between prediction and baseline\r\n- **Fairness**: Based on Shapley values from game theory\r\n- **Consistency**: If a feature becomes more important, its SHAP value increases\r\n\r\n**Interpretation**:\r\n- Positive SHAP value → Feature pushes prediction higher\r\n- Negative SHAP value → Feature pushes prediction lower\r\n- Magnitude → Strength of feature's impact\r\n- Sum of SHAP values → Total prediction change from baseline\r\n\r\n**Example**:\r\n```\r\nBaseline (expected value): 0.30\r\nFeature contributions (SHAP values):\r\n Age: +0.15\r\n Income: +0.10\r\n Education: -0.05\r\nFinal prediction: 0.30 + 0.15 + 0.10 - 0.05 = 0.50\r\n```\r\n\r\n### Background Data / Baseline\r\n\r\n**Purpose**: Represents \"typical\" input to establish baseline expectations\r\n\r\n**Selection**:\r\n- Random sample from training data (50-1000 samples)\r\n- Or use kmeans to select representative samples\r\n- For DeepExplainer/KernelExplainer: 100-1000 samples balances accuracy and speed\r\n\r\n**Impact**: Baseline affects SHAP value magnitudes but not relative importance\r\n\r\n### Model Output Types\r\n\r\n**Critical Consideration**: Understand what your model outputs\r\n\r\n- **Raw output**: For regression or tree margins\r\n- **Probability**: For classification probability\r\n- **Log-odds**: For logistic regression (before sigmoid)\r\n\r\n**Example**: XGBoost classifiers explain margin output (log-odds) by default. To explain probabilities, use `model_output=\"probability\"` in TreeExplainer.\r\n\r\n## Common Patterns\r\n\r\n### Pattern 1: Complete Model Analysis\r\n\r\n```python\r\n# 1. Setup\r\nexplainer = shap.TreeExplainer(model)\r\nshap_values = explainer(X_test)\r\n\r\n# 2. Global importance\r\nshap.plots.beeswarm(shap_values)\r\nshap.plots.bar(shap_values)\r\n\r\n# 3. Top feature relationships\r\ntop_features = X_test.columns[np.abs(shap_values.values).mean(0).argsort()[-5:]]\r\nfor feature in top_features:\r\n shap.plots.scatter(shap_values[:, feature])\r\n\r\n# 4. Example predictions\r\nfor i in range(5):\r\n shap.plots.waterfall(shap_values[i])\r\n```\r\n\r\n### Pattern 2: Cohort Comparison\r\n\r\n```python\r\n# Define cohorts\r\ncohort1_mask = X_test['Group'] == 'A'\r\ncohort2_mask = X_test['Group'] == 'B'\r\n\r\n# Compare feature importance\r\nshap.plots.bar({\r\n \"Group A\": shap_values[cohort1_mask],\r\n \"Group B\": shap_values[cohort2_mask]\r\n})\r\n```\r\n\r\n### Pattern 3: Debugging Errors\r\n\r\n```python\r\n# Find errors\r\nerrors = model.predict(X_test) != y_test\r\nerror_indices = np.where(errors)[0]\r\n\r\n# Explain errors\r\nfor idx in error_indices[:5]:\r\n print(f\"Sample {idx}:\")\r\n shap.plots.waterfall(shap_values[idx])\r\n\r\n # Investigate key features\r\n shap.plots.scatter(shap_values[:, \"Suspicious_Feature\"])\r\n```\r\n\r\n## Performance Optimization\r\n\r\n### Speed Considerations\r\n\r\n**Explainer Speed** (fastest to slowest):\r\n1. `LinearExplainer` - Nearly instantaneous\r\n2. `TreeExplainer` - Very fast\r\n3. `DeepExplainer` - Fast for neural networks\r\n4. `GradientExplainer` - Fast for neural networks\r\n5. `KernelExplainer` - Slow (use only when necessary)\r\n6. `PermutationExplainer` - Very slow but accurate\r\n\r\n### Optimization Strategies\r\n\r\n**For Large Datasets**:\r\n```python\r\n# Compute SHAP for subset\r\nshap_values = explainer(X_test[:1000])\r\n\r\n# Or use batching\r\nbatch_size = 100\r\nall_shap_values = []\r\nfor i in range(0, len(X_test), batch_size):\r\n batch_shap = explainer(X_test[i:i+batch_size])\r\n all_shap_values.append(batch_shap)\r\n```\r\n\r\n**For Visualizations**:\r\n```python\r\n# Sample subset for plots\r\nshap.plots.beeswarm(shap_values[:1000])\r\n\r\n# Adjust transparency for dense plots\r\nshap.plots.scatter(shap_values[:, \"Feature\"], alpha=0.3)\r\n```\r\n\r\n**For Production**:\r\n```python\r\n# Cache explainer\r\nimport joblib\r\njoblib.dump(explainer, 'explainer.pkl')\r\nexplainer = joblib.load('explainer.pkl')\r\n\r\n# Pre-compute for batch predictions\r\n# Only compute top N features for API responses\r\n```\r\n\r\n## Troubleshooting\r\n\r\n### Issue: Wrong explainer choice\r\n**Problem**: Using KernelExplainer for tree models (slow and unnecessary)\r\n**Solution**: Always use TreeExplainer for tree-based models\r\n\r\n### Issue: Insufficient background data\r\n**Problem**: DeepExplainer/KernelExplainer with too few background samples\r\n**Solution**: Use 100-1000 representative samples\r\n\r\n### Issue: Confusing units\r\n**Problem**: Interpreting log-odds as probabilities\r\n**Solution**: Check model output type; understand whether values are probabilities, log-odds, or raw outputs\r\n\r\n### Issue: Plots don't display\r\n**Problem**: Matplotlib backend issues\r\n**Solution**: Ensure backend is set correctly; use `plt.show()` if needed\r\n\r\n### Issue: Too many features cluttering plots\r\n**Problem**: Default max_display=10 may be too many or too few\r\n**Solution**: Adjust `max_display` parameter or use feature clustering\r\n\r\n### Issue: Slow computation\r\n**Problem**: Computing SHAP for very large datasets\r\n**Solution**: Sample subset, use batching, or ensure using specialized explainer (not KernelExplainer)\r\n\r\n## Integration with Other Tools\r\n\r\n### Jupyter Notebooks\r\n- Interactive force plots work seamlessly\r\n- Inline plot display with `show=True` (default)\r\n- Combine with markdown for narrative explanations\r\n\r\n### MLflow / Experiment Tracking\r\n```python\r\nimport mlflow\r\n\r\nwith mlflow.start_run():\r\n # Train model\r\n model = train_model(X_train, y_train)\r\n\r\n # Compute SHAP\r\n explainer = shap.TreeExplainer(model)\r\n shap_values = explainer(X_test)\r\n\r\n # Log plots\r\n shap.plots.beeswarm(shap_values, show=False)\r\n mlflow.log_figure(plt.gcf(), \"shap_beeswarm.png\")\r\n plt.close()\r\n\r\n # Log feature importance metrics\r\n mean_abs_shap = np.abs(shap_values.values).mean(axis=0)\r\n for feature, importance in zip(X_test.columns, mean_abs_shap):\r\n mlflow.log_metric(f\"shap_{feature}\", importance)\r\n```\r\n\r\n### Production APIs\r\n```python\r\nclass ExplanationService:\r\n def __init__(self, model_path, explainer_path):\r\n self.model = joblib.load(model_path)\r\n self.explainer = joblib.load(explainer_path)\r\n\r\n def predict_with_explanation(self, X):\r\n prediction = self.model.predict(X)\r\n shap_values = self.explainer(X)\r\n\r\n return {\r\n 'prediction': prediction[0],\r\n 'base_value': shap_values.base_values[0],\r\n 'feature_contributions': dict(zip(X.columns, shap_values.values[0]))\r\n }\r\n```\r\n\r\n## Reference Documentation\r\n\r\nThis skill includes comprehensive reference documentation organized by topic:\r\n\r\n### references/explainers.md\r\nComplete guide to all explainer classes:\r\n- `TreeExplainer` - Fast, exact explanations for tree-based models\r\n- `DeepExplainer` - Deep learning models (TensorFlow, PyTorch)\r\n- `KernelExplainer` - Model-agnostic (works with any model)\r\n- `LinearExplainer` - Fast explanations for linear models\r\n- `GradientExplainer` - Gradient-based for neural networks\r\n- `PermutationExplainer` - Exact but slow for any model\r\n\r\nIncludes: Constructor parameters, methods, supported models, when to use, examples, performance considerations.\r\n\r\n### references/plots.md\r\nComprehensive visualization guide:\r\n- **Waterfall plots** - Individual prediction breakdowns\r\n- **Beeswarm plots** - Global importance with value distributions\r\n- **Bar plots** - Clean feature importance summaries\r\n- **Scatter plots** - Feature-prediction relationships and interactions\r\n- **Force plots** - Interactive additive force visualizations\r\n- **Heatmap plots** - Multi-sample comparison grids\r\n- **Violin plots** - Distribution-focused alternatives\r\n- **Decision plots** - Multiclass prediction paths\r\n\r\nIncludes: Parameters, use cases, examples, best practices, plot selection guide.\r\n\r\n### references/workflows.md\r\nDetailed workflows and best practices:\r\n- Basic model explanation workflow\r\n- Model debugging and validation\r\n- Feature engineering guidance\r\n- Model comparison and selection\r\n- Fairness and bias analysis\r\n- Deep learning model explanation\r\n- Production deployment\r\n- Time series model explanation\r\n- Common pitfalls and solutions\r\n- Advanced techniques\r\n- MLOps integration\r\n\r\nIncludes: Step-by-step instructions, code examples, decision criteria, troubleshooting.\r\n\r\n### references/theory.md\r\nTheoretical foundations:\r\n- Shapley values from game theory\r\n- Mathematical formulas and properties\r\n- Connection to other explanation methods (LIME, DeepLIFT, etc.)\r\n- SHAP computation algorithms (Tree SHAP, Kernel SHAP, etc.)\r\n- Conditional expectations and baseline selection\r\n- Interpreting SHAP values\r\n- Interaction values\r\n- Theoretical limitations and considerations\r\n\r\nIncludes: Mathematical foundations, proofs, comparisons, advanced topics.\r\n\r\n## Usage Guidelines\r\n\r\n**When to load reference files**:\r\n- Load `explainers.md` when user needs detailed information about specific explainer types or parameters\r\n- Load `plots.md` when user needs detailed visualization guidance or exploring plot options\r\n- Load `workflows.md` when user has complex multi-step tasks (debugging, fairness analysis, production deployment)\r\n- Load `theory.md` when user asks about theoretical foundations, Shapley values, or mathematical details\r\n\r\n**Default approach** (without loading references):\r\n- Use this SKILL.md for basic explanations and quick start\r\n- Provide standard workflows and common patterns\r\n- Reference files are available if more detail is needed\r\n\r\n**Loading references**:\r\n```python\r\n# To load reference files, use the Read tool with appropriate file path:\r\n# /path/to/shap/references/explainers.md\r\n# /path/to/shap/references/plots.md\r\n# /path/to/shap/references/workflows.md\r\n# /path/to/shap/references/theory.md\r\n```\r\n\r\n## Best Practices Summary\r\n\r\n1. **Choose the right explainer**: Use specialized explainers (TreeExplainer, DeepExplainer, LinearExplainer) when possible; avoid KernelExplainer unless necessary\r\n\r\n2. **Start global, then go local**: Begin with beeswarm/bar plots for overall understanding, then dive into waterfall/scatter plots for details\r\n\r\n3. **Use multiple visualizations**: Different plots reveal different insights; combine global (beeswarm) + local (waterfall) + relationship (scatter) views\r\n\r\n4. **Select appropriate background data**: Use 50-1000 representative samples from training data\r\n\r\n5. **Understand model output units**: Know whether explaining probabilities, log-odds, or raw outputs\r\n\r\n6. **Validate with domain knowledge**: SHAP shows model behavior; use domain expertise to interpret and validate\r\n\r\n7. **Optimize for performance**: Sample subsets for visualization, batch for large datasets, cache explainers in production\r\n\r\n8. **Check for data leakage**: Unexpectedly high feature importance may indicate data quality issues\r\n\r\n9. **Consider feature correlations**: Use TreeExplainer's correlation-aware options or feature clustering for redundant features\r\n\r\n10. **Remember SHAP shows association, not causation**: Use domain knowledge for causal interpretation\r\n\r\n## Installation\r\n\r\n```bash\r\n# Basic installation\r\nuv pip install shap\r\n\r\n# With visualization dependencies\r\nuv pip install shap matplotlib\r\n\r\n# Latest version\r\nuv pip install -U shap\r\n```\r\n\r\n**Dependencies**: numpy, pandas, scikit-learn, matplotlib, scipy\r\n\r\n**Optional**: xgboost, lightgbm, tensorflow, torch (depending on model types)\r\n\r\n## Additional Resources\r\n\r\n- **Official Documentation**: https://shap.readthedocs.io/\r\n- **GitHub Repository**: https://github.com/slundberg/shap\r\n- **Original Paper**: Lundberg & Lee (2017) - \"A Unified Approach to Interpreting Model Predictions\"\r\n- **Nature MI Paper**: Lundberg et al. (2020) - \"From local explanations to global understanding with explainable AI for trees\"\r\n\r\nThis skill provides comprehensive coverage of SHAP for model interpretability across all use cases and model types.",
"user_template": ""
},
"variables": [],
"install": {
"steps": [
{
"title": "Download & unzip",
"detail": "Download the .zip package from SkillVault and unzip it. The shap/ folder contains SKILL.md plus any companion scripts, references and assets."
},
{
"title": "Copy into your agent skills directory",
"detail": "Move the folder into your agent's skills directory — e.g. ~/.claude/skills/ (Claude Code), .codex/skills/, .cursor/skills/ or your project's .claude/skills/ folder — then restart or reload the session."
},
{
"title": "Use it",
"detail": "Describe the task in natural language; the agent loads the skill automatically when the request matches the skill description."
}
]
},
"usage": {
"steps": []
},
"metadata": {
"author": "SkillVault",
"source": "https://skillvault.top/skills/shap",
"exported_at": "2026-11-03T07:41:49.484Z"
}
} format: aiskill/v1
skill:
name: shap
slug: shap
version: 1.0.0
description: >-
Model interpretability and explainability using SHAP (SHapley Additive exPlanations). Use this
skill when explaining machine learning model predictions, computing feature importance,
generating SHAP plots (waterfall, beeswarm, bar, scatter, force, heatmap), debugging models,
analyzing model bias or fairness, comparing models, or implementing explainable AI. Works with
tree-based models (XGBoost, LightGBM, Random Forest), deep learning (TensorFlow, PyTorch),
linear models, and any black-box model.
category: Research
tags:
- research-science
platforms:
- chatgpt
- claude-code
- cursor
tested_environment: >-
Agent Skills convention (SKILL.md) — works with Claude Code, Cursor, ChatGPT/Codex and
compatible agents
license: MIT LICENSE
prompts:
system: "# SHAP (SHapley Additive exPlanations)\r\n\r\n## Overview\r\n\r\nSHAP is a unified approach to explain machine learning model outputs using Shapley values from cooperative game theory. This skill provides comprehensive guidance for:\r\n\r\n- Computing SHAP values for any model type\r\n- Creating visualizations to understand feature importance\r\n- Debugging and validating model behavior\r\n- Analyzing fairness and bias\r\n- Implementing explainable AI in production\r\n\r\nSHAP 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.\r\n\r\n## When to Use This Skill\r\n\r\n**Trigger this skill when users ask about**:\r\n- \"Explain which features are most important in my model\"\r\n- \"Generate SHAP plots\" (waterfall, beeswarm, bar, scatter, force, heatmap, etc.)\r\n- \"Why did my model make this prediction?\"\r\n- \"Calculate SHAP values for my model\"\r\n- \"Visualize feature importance using SHAP\"\r\n- \"Debug my model's behavior\" or \"validate my model\"\r\n- \"Check my model for bias\" or \"analyze fairness\"\r\n- \"Compare feature importance across models\"\r\n- \"Implement explainable AI\" or \"add explanations to my model\"\r\n- \"Understand feature interactions\"\r\n- \"Create model interpretation dashboard\"\r\n\r\n## Quick Start Guide\r\n\r\n### Step 1: Select the Right Explainer\r\n\r\n**Decision Tree**:\r\n\r\n1. **Tree-based model?** (XGBoost, LightGBM, CatBoost, Random Forest, Gradient Boosting)\r\n - Use `shap.TreeExplainer` (fast, exact)\r\n\r\n2. **Deep neural network?** (TensorFlow, PyTorch, Keras, CNNs, RNNs, Transformers)\r\n - Use `shap.DeepExplainer` or `shap.GradientExplainer`\r\n\r\n3. **Linear model?** (Linear/Logistic Regression, GLMs)\r\n - Use `shap.LinearExplainer` (extremely fast)\r\n\r\n4. **Any other model?** (SVMs, custom functions, black-box models)\r\n - Use `shap.KernelExplainer` (model-agnostic but slower)\r\n\r\n5. **Unsure?**\r\n - Use `shap.Explainer` (automatically selects best algorithm)\r\n\r\n**See `references/explainers.md` for detailed information on all explainer types.**\r\n\r\n### Step 2: Compute SHAP Values\r\n\r\n```python\r\nimport shap\r\n\r\n# Example with tree-based model (XGBoost)\r\nimport xgboost as xgb\r\n\r\n# Train model\r\nmodel = xgb.XGBClassifier().fit(X_train, y_train)\r\n\r\n# Create explainer\r\nexplainer = shap.TreeExplainer(model)\r\n\r\n# Compute SHAP values\r\nshap_values = explainer(X_test)\r\n\r\n# The shap_values object contains:\r\n# - values: SHAP values (feature attributions)\r\n# - base_values: Expected model output (baseline)\r\n# - data: Original feature values\r\n```\r\n\r\n### Step 3: Visualize Results\r\n\r\n**For Global Understanding** (entire dataset):\r\n```python\r\n# Beeswarm plot - shows feature importance with value distributions\r\nshap.plots.beeswarm(shap_values, max_display=15)\r\n\r\n# Bar plot - clean summary of feature importance\r\nshap.plots.bar(shap_values)\r\n```\r\n\r\n**For Individual Predictions**:\r\n```python\r\n# Waterfall plot - detailed breakdown of single prediction\r\nshap.plots.waterfall(shap_values[0])\r\n\r\n# Force plot - additive force visualization\r\nshap.plots.force(shap_values[0])\r\n```\r\n\r\n**For Feature Relationships**:\r\n```python\r\n# Scatter plot - feature-prediction relationship\r\nshap.plots.scatter(shap_values[:, \"Feature_Name\"])\r\n\r\n# Colored by another feature to show interactions\r\nshap.plots.scatter(shap_values[:, \"Age\"], color=shap_values[:, \"Education\"])\r\n```\r\n\r\n**See `references/plots.md` for comprehensive guide on all plot types.**\r\n\r\n## Core Workflows\r\n\r\nThis skill supports several common workflows. Choose the workflow that matches the current task.\r\n\r\n### Workflow 1: Basic Model Explanation\r\n\r\n**Goal**: Understand what drives model predictions\r\n\r\n**Steps**:\r\n1. Train model and create appropriate explainer\r\n2. Compute SHAP values for test set\r\n3. Generate global importance plots (beeswarm or bar)\r\n4. Examine top feature relationships (scatter plots)\r\n5. Explain specific predictions (waterfall plots)\r\n\r\n**Example**:\r\n```python\r\n# Step 1-2: Setup\r\nexplainer = shap.TreeExplainer(model)\r\nshap_values = explainer(X_test)\r\n\r\n# Step 3: Global importance\r\nshap.plots.beeswarm(shap_values)\r\n\r\n# Step 4: Feature relationships\r\nshap.plots.scatter(shap_values[:, \"Most_Important_Feature\"])\r\n\r\n# Step 5: Individual explanation\r\nshap.plots.waterfall(shap_values[0])\r\n```\r\n\r\n### Workflow 2: Model Debugging\r\n\r\n**Goal**: Identify and fix model issues\r\n\r\n**Steps**:\r\n1. Compute SHAP values\r\n2. Identify prediction errors\r\n3. Explain misclassified samples\r\n4. Check for unexpected feature importance (data leakage)\r\n5. Validate feature relationships make sense\r\n6. Check feature interactions\r\n\r\n**See `references/workflows.md` for detailed debugging workflow.**\r\n\r\n### Workflow 3: Feature Engineering\r\n\r\n**Goal**: Use SHAP insights to improve features\r\n\r\n**Steps**:\r\n1. Compute SHAP values for baseline model\r\n2. Identify nonlinear relationships (candidates for transformation)\r\n3. Identify feature interactions (candidates for interaction terms)\r\n4. Engineer new features\r\n5. Retrain and compare SHAP values\r\n6. Validate improvements\r\n\r\n**See `references/workflows.md` for detailed feature engineering workflow.**\r\n\r\n### Workflow 4: Model Comparison\r\n\r\n**Goal**: Compare multiple models to select best interpretable option\r\n\r\n**Steps**:\r\n1. Train multiple models\r\n2. Compute SHAP values for each\r\n3. Compare global feature importance\r\n4. Check consistency of feature rankings\r\n5. Analyze specific predictions across models\r\n6. Select based on accuracy, interpretability, and consistency\r\n\r\n**See `references/workflows.md` for detailed model comparison workflow.**\r\n\r\n### Workflow 5: Fairness and Bias Analysis\r\n\r\n**Goal**: Detect and analyze model bias across demographic groups\r\n\r\n**Steps**:\r\n1. Identify protected attributes (gender, race, age, etc.)\r\n2. Compute SHAP values\r\n3. Compare feature importance across groups\r\n4. Check protected attribute SHAP importance\r\n5. Identify proxy features\r\n6. Implement mitigation strategies if bias found\r\n\r\n**See `references/workflows.md` for detailed fairness analysis workflow.**\r\n\r\n### Workflow 6: Production Deployment\r\n\r\n**Goal**: Integrate SHAP explanations into production systems\r\n\r\n**Steps**:\r\n1. Train and save model\r\n2. Create and save explainer\r\n3. Build explanation service\r\n4. Create API endpoints for predictions with explanations\r\n5. Implement caching and optimization\r\n6. Monitor explanation quality\r\n\r\n**See `references/workflows.md` for detailed production deployment workflow.**\r\n\r\n## Key Concepts\r\n\r\n### SHAP Values\r\n\r\n**Definition**: SHAP values quantify each feature's contribution to a prediction, measured as the deviation from the expected model output (baseline).\r\n\r\n**Properties**:\r\n- **Additivity**: SHAP values sum to difference between prediction and baseline\r\n- **Fairness**: Based on Shapley values from game theory\r\n- **Consistency**: If a feature becomes more important, its SHAP value increases\r\n\r\n**Interpretation**:\r\n- Positive SHAP value → Feature pushes prediction higher\r\n- Negative SHAP value → Feature pushes prediction lower\r\n- Magnitude → Strength of feature's impact\r\n- Sum of SHAP values → Total prediction change from baseline\r\n\r\n**Example**:\r\n```\r\nBaseline (expected value): 0.30\r\nFeature contributions (SHAP values):\r\n Age: +0.15\r\n Income: +0.10\r\n Education: -0.05\r\nFinal prediction: 0.30 + 0.15 + 0.10 - 0.05 = 0.50\r\n```\r\n\r\n### Background Data / Baseline\r\n\r\n**Purpose**: Represents \"typical\" input to establish baseline expectations\r\n\r\n**Selection**:\r\n- Random sample from training data (50-1000 samples)\r\n- Or use kmeans to select representative samples\r\n- For DeepExplainer/KernelExplainer: 100-1000 samples balances accuracy and speed\r\n\r\n**Impact**: Baseline affects SHAP value magnitudes but not relative importance\r\n\r\n### Model Output Types\r\n\r\n**Critical Consideration**: Understand what your model outputs\r\n\r\n- **Raw output**: For regression or tree margins\r\n- **Probability**: For classification probability\r\n- **Log-odds**: For logistic regression (before sigmoid)\r\n\r\n**Example**: XGBoost classifiers explain margin output (log-odds) by default. To explain probabilities, use `model_output=\"probability\"` in TreeExplainer.\r\n\r\n## Common Patterns\r\n\r\n### Pattern 1: Complete Model Analysis\r\n\r\n```python\r\n# 1. Setup\r\nexplainer = shap.TreeExplainer(model)\r\nshap_values = explainer(X_test)\r\n\r\n# 2. Global importance\r\nshap.plots.beeswarm(shap_values)\r\nshap.plots.bar(shap_values)\r\n\r\n# 3. Top feature relationships\r\ntop_features = X_test.columns[np.abs(shap_values.values).mean(0).argsort()[-5:]]\r\nfor feature in top_features:\r\n shap.plots.scatter(shap_values[:, feature])\r\n\r\n# 4. Example predictions\r\nfor i in range(5):\r\n shap.plots.waterfall(shap_values[i])\r\n```\r\n\r\n### Pattern 2: Cohort Comparison\r\n\r\n```python\r\n# Define cohorts\r\ncohort1_mask = X_test['Group'] == 'A'\r\ncohort2_mask = X_test['Group'] == 'B'\r\n\r\n# Compare feature importance\r\nshap.plots.bar({\r\n \"Group A\": shap_values[cohort1_mask],\r\n \"Group B\": shap_values[cohort2_mask]\r\n})\r\n```\r\n\r\n### Pattern 3: Debugging Errors\r\n\r\n```python\r\n# Find errors\r\nerrors = model.predict(X_test) != y_test\r\nerror_indices = np.where(errors)[0]\r\n\r\n# Explain errors\r\nfor idx in error_indices[:5]:\r\n print(f\"Sample {idx}:\")\r\n shap.plots.waterfall(shap_values[idx])\r\n\r\n # Investigate key features\r\n shap.plots.scatter(shap_values[:, \"Suspicious_Feature\"])\r\n```\r\n\r\n## Performance Optimization\r\n\r\n### Speed Considerations\r\n\r\n**Explainer Speed** (fastest to slowest):\r\n1. `LinearExplainer` - Nearly instantaneous\r\n2. `TreeExplainer` - Very fast\r\n3. `DeepExplainer` - Fast for neural networks\r\n4. `GradientExplainer` - Fast for neural networks\r\n5. `KernelExplainer` - Slow (use only when necessary)\r\n6. `PermutationExplainer` - Very slow but accurate\r\n\r\n### Optimization Strategies\r\n\r\n**For Large Datasets**:\r\n```python\r\n# Compute SHAP for subset\r\nshap_values = explainer(X_test[:1000])\r\n\r\n# Or use batching\r\nbatch_size = 100\r\nall_shap_values = []\r\nfor i in range(0, len(X_test), batch_size):\r\n batch_shap = explainer(X_test[i:i+batch_size])\r\n all_shap_values.append(batch_shap)\r\n```\r\n\r\n**For Visualizations**:\r\n```python\r\n# Sample subset for plots\r\nshap.plots.beeswarm(shap_values[:1000])\r\n\r\n# Adjust transparency for dense plots\r\nshap.plots.scatter(shap_values[:, \"Feature\"], alpha=0.3)\r\n```\r\n\r\n**For Production**:\r\n```python\r\n# Cache explainer\r\nimport joblib\r\njoblib.dump(explainer, 'explainer.pkl')\r\nexplainer = joblib.load('explainer.pkl')\r\n\r\n# Pre-compute for batch predictions\r\n# Only compute top N features for API responses\r\n```\r\n\r\n## Troubleshooting\r\n\r\n### Issue: Wrong explainer choice\r\n**Problem**: Using KernelExplainer for tree models (slow and unnecessary)\r\n**Solution**: Always use TreeExplainer for tree-based models\r\n\r\n### Issue: Insufficient background data\r\n**Problem**: DeepExplainer/KernelExplainer with too few background samples\r\n**Solution**: Use 100-1000 representative samples\r\n\r\n### Issue: Confusing units\r\n**Problem**: Interpreting log-odds as probabilities\r\n**Solution**: Check model output type; understand whether values are probabilities, log-odds, or raw outputs\r\n\r\n### Issue: Plots don't display\r\n**Problem**: Matplotlib backend issues\r\n**Solution**: Ensure backend is set correctly; use `plt.show()` if needed\r\n\r\n### Issue: Too many features cluttering plots\r\n**Problem**: Default max_display=10 may be too many or too few\r\n**Solution**: Adjust `max_display` parameter or use feature clustering\r\n\r\n### Issue: Slow computation\r\n**Problem**: Computing SHAP for very large datasets\r\n**Solution**: Sample subset, use batching, or ensure using specialized explainer (not KernelExplainer)\r\n\r\n## Integration with Other Tools\r\n\r\n### Jupyter Notebooks\r\n- Interactive force plots work seamlessly\r\n- Inline plot display with `show=True` (default)\r\n- Combine with markdown for narrative explanations\r\n\r\n### MLflow / Experiment Tracking\r\n```python\r\nimport mlflow\r\n\r\nwith mlflow.start_run():\r\n# Train model\r\n model = train_model(X_train, y_train)\r\n\r\n # Compute SHAP\r\n explainer = shap.TreeExplainer(model)\r\n shap_values = explainer(X_test)\r\n\r\n # Log plots\r\n shap.plots.beeswarm(shap_values, show=False)\r\n mlflow.log_figure(plt.gcf(), \"shap_beeswarm.png\")\r\n plt.close()\r\n\r\n # Log feature importance metrics\r\n mean_abs_shap = np.abs(shap_values.values).mean(axis=0)\r\n for feature, importance in zip(X_test.columns, mean_abs_shap):\r\n mlflow.log_metric(f\"shap_{feature}\", importance)\r\n```\r\n\r\n### Production APIs\r\n```python\r\nclass ExplanationService:\r\n def __init__(self, model_path, explainer_path):\r\n self.model = joblib.load(model_path)\r\n self.explainer = joblib.load(explainer_path)\r\n\r\n def predict_with_explanation(self, X):\r\n prediction = self.model.predict(X)\r\n shap_values = self.explainer(X)\r\n\r\n return {\r\n 'prediction': prediction[0],\r\n 'base_value': shap_values.base_values[0],\r\n 'feature_contributions': dict(zip(X.columns, shap_values.values[0]))\r\n }\r\n```\r\n\r\n## Reference Documentation\r\n\r\nThis skill includes comprehensive reference documentation organized by topic:\r\n\r\n### references/explainers.md\r\nComplete guide to all explainer classes:\r\n- `TreeExplainer` - Fast, exact explanations for tree-based models\r\n- `DeepExplainer` - Deep learning models (TensorFlow, PyTorch)\r\n- `KernelExplainer` - Model-agnostic (works with any model)\r\n- `LinearExplainer` - Fast explanations for linear models\r\n- `GradientExplainer` - Gradient-based for neural networks\r\n- `PermutationExplainer` - Exact but slow for any model\r\n\r\nIncludes: Constructor parameters, methods, supported models, when to use, examples, performance considerations.\r\n\r\n### references/plots.md\r\nComprehensive visualization guide:\r\n- **Waterfall plots** - Individual prediction breakdowns\r\n- **Beeswarm plots** - Global importance with value distributions\r\n- **Bar plots** - Clean feature importance summaries\r\n- **Scatter plots** - Feature-prediction relationships and interactions\r\n- **Force plots** - Interactive additive force visualizations\r\n- **Heatmap plots** - Multi-sample comparison grids\r\n- **Violin plots** - Distribution-focused alternatives\r\n- **Decision plots** - Multiclass prediction paths\r\n\r\nIncludes: Parameters, use cases, examples, best practices, plot selection guide.\r\n\r\n### references/workflows.md\r\nDetailed workflows and best practices:\r\n- Basic model explanation workflow\r\n- Model debugging and validation\r\n- Feature engineering guidance\r\n- Model comparison and selection\r\n- Fairness and bias analysis\r\n- Deep learning model explanation\r\n- Production deployment\r\n- Time series model explanation\r\n- Common pitfalls and solutions\r\n- Advanced techniques\r\n- MLOps integration\r\n\r\nIncludes: Step-by-step instructions, code examples, decision criteria, troubleshooting.\r\n\r\n### references/theory.md\r\nTheoretical foundations:\r\n- Shapley values from game theory\r\n- Mathematical formulas and properties\r\n- Connection to other explanation methods (LIME, DeepLIFT, etc.)\r\n- SHAP computation algorithms (Tree SHAP, Kernel SHAP, etc.)\r\n- Conditional expectations and baseline selection\r\n- Interpreting SHAP values\r\n- Interaction values\r\n- Theoretical limitations and considerations\r\n\r\nIncludes: Mathematical foundations, proofs, comparisons, advanced topics.\r\n\r\n## Usage Guidelines\r\n\r\n**When to load reference files**:\r\n- Load `explainers.md` when user needs detailed information about specific explainer types or parameters\r\n- Load `plots.md` when user needs detailed visualization guidance or exploring plot options\r\n- Load `workflows.md` when user has complex multi-step tasks (debugging, fairness analysis, production deployment)\r\n- Load `theory.md` when user asks about theoretical foundations, Shapley values, or mathematical details\r\n\r\n**Default approach** (without loading references):\r\n- Use this SKILL.md for basic explanations and quick start\r\n- Provide standard workflows and common patterns\r\n- Reference files are available if more detail is needed\r\n\r\n**Loading references**:\r\n```python\r\n# To load reference files, use the Read tool with appropriate file path:\r\n# /path/to/shap/references/explainers.md\r\n# /path/to/shap/references/plots.md\r\n# /path/to/shap/references/workflows.md\r\n# /path/to/shap/references/theory.md\r\n```\r\n\r\n## Best Practices Summary\r\n\r\n1. **Choose the right explainer**: Use specialized explainers (TreeExplainer, DeepExplainer, LinearExplainer) when possible; avoid KernelExplainer unless necessary\r\n\r\n2. **Start global, then go local**: Begin with beeswarm/bar plots for overall understanding, then dive into waterfall/scatter plots for details\r\n\r\n3. **Use multiple visualizations**: Different plots reveal different insights; combine global (beeswarm) + local (waterfall) + relationship (scatter) views\r\n\r\n4. **Select appropriate background data**: Use 50-1000 representative samples from training data\r\n\r\n5. **Understand model output units**: Know whether explaining probabilities, log-odds, or raw outputs\r\n\r\n6. **Validate with domain knowledge**: SHAP shows model behavior; use domain expertise to interpret and validate\r\n\r\n7. **Optimize for performance**: Sample subsets for visualization, batch for large datasets, cache explainers in production\r\n\r\n8. **Check for data leakage**: Unexpectedly high feature importance may indicate data quality issues\r\n\r\n9. **Consider feature correlations**: Use TreeExplainer's correlation-aware options or feature clustering for redundant features\r\n\r\n10. **Remember SHAP shows association, not causation**: Use domain knowledge for causal interpretation\r\n\r\n## Installation\r\n\r\n```bash\r\n# Basic installation\r\nuv pip install shap\r\n\r\n# With visualization dependencies\r\nuv pip install shap matplotlib\r\n\r\n# Latest version\r\nuv pip install -U shap\r\n```\r\n\r\n**Dependencies**: numpy, pandas, scikit-learn, matplotlib, scipy\r\n\r\n**Optional**: xgboost, lightgbm, tensorflow, torch (depending on model types)\r\n\r\n## Additional Resources\r\n\r\n- **Official Documentation**: https://shap.readthedocs.io/\r\n- **GitHub Repository**: https://github.com/slundberg/shap\r\n- **Original Paper**: Lundberg & Lee (2017) - \"A Unified Approach to Interpreting Model Predictions\"\r\n- **Nature MI Paper**: Lundberg et al. (2020) - \"From local explanations to global understanding with explainable AI for trees\"\r\n\r\nThis skill provides comprehensive coverage of SHAP for model interpretability across all use cases and model types."
user_template: ""
variables: []
install:
steps:
- title: Download & unzip
detail: >-
Download the .zip package from SkillVault and unzip it. The shap/ folder contains SKILL.md
plus any companion scripts, references and assets.
- title: Copy into your agent skills directory
detail: >-
Move the folder into your agent's skills directory — e.g. ~/.claude/skills/ (Claude Code),
.codex/skills/, .cursor/skills/ or your project's .claude/skills/ folder — then restart or
reload the session.
- title: Use it
detail: >-
Describe the task in natural language; the agent loads the skill automatically when the
request matches the skill description.
usage:
steps: []
metadata:
author: SkillVault
source: https://skillvault.top/skills/shap
exported_at: "2026-11-03T07:41:49.484Z"
Installation guide
- 1
Download & unzip
Download the .zip package from SkillVault and unzip it. The shap/ folder contains SKILL.md plus any companion scripts, references and assets.
- 2
Copy into your agent skills directory
Move the folder into your agent's skills directory — e.g. ~/.claude/skills/ (Claude Code), .codex/skills/, .cursor/skills/ or your project's .claude/skills/ folder — then restart or reload the session.
- 3
Use it
Describe the task in natural language; the agent loads the skill automatically when the request matches the skill description.
How to use
Platform compatibility
ChatGPT GPTs
OpenAI
Paste the system prompt into the GPT "Instructions" field and keep the user template as your starter message.
Official docsClaude Code
Anthropic
Save the exported .aiskill JSON as a skill file in your project or paste the system prompt into CLAUDE.md / a slash-command markdown file.
Official docsCursor
Anysphere
Copy the system prompt into .cursor/rules/*.mdc (or Project Rules in Settings) and reference the user template in your agent prompts.
Official docsRelated skills
aeon
This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.
astropy
Comprehensive Python library for astronomy and astrophysics. This skill should be used when working with astronomical data including celestial coordinates, physical units, FITS files, cosmological calculations, time systems, tables, world coordinate systems (WCS), and astronomical data analysis. Use when tasks involve coordinate transformations, unit conversions, FITS file manipulation, cosmological distance calculations, time scale conversions, or astronomical data processing.
bgpt-paper-search
Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.