shap▌
davila7/claude-code-templates · updated Apr 8, 2026
MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.
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 (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:
-
Tree-based model? (XGBoost, LightGBM, CatBoost, Random Forest, Gradient Boosting)
- Use
shap.TreeExplainer(fast, exact)
- Use
-
Deep neural network? (TensorFlow, PyTorch, Keras, CNNs, RNNs, Transformers)
- Use
shap.DeepExplainerorshap.GradientExplainer
- Use
-
Linear model? (Linear/Logistic Regression, GLMs)
- Use
shap.LinearExplainer(extremely fast)
- Use
-
Any other model? (SVMs, custom functions, black-box models)
- Use
shap.KernelExplainer(model-agnostic but slower)
- Use
-
Unsure?
- Use
shap.Explainer(automatically selects best algorithm)
- Use
See references/explainers.md for detailed information on all explainer types.
Step 2: Compute SHAP Values
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):
# 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.
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:
- Train model and create appropriate explainer
- Compute SHAP values for test set
- Generate global importance plots (beeswarm or bar)
- Examine top feature relationships (scatter plots)
- Explain specific predictions (waterfall plots)
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])
Workflow 2: Model Debugging
Goal: Identify and fix model issues
Steps:
- Compute SHAP values
- Identify prediction errors
- Explain misclassified samples
- Check for unexpected feature importance (data leakage)
- Validate feature relationships make sense
- Check feature interactions
See references/workflows.md for detailed debugging workflow.
Workflow 3: Feature Engineering
Goal: Use SHAP insights to improve features
Steps:
- Compute SHAP values for baseline model
- Identify nonlinear relationships (candidates for transformation)
- Identify feature interactions (candidates for interaction terms)
- Engineer new features
- Retrain and compare SHAP values
- 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:
- Train multiple models
- Compute SHAP values for each
- Compare global feature importance
- Check consistency of feature rankings
- Analyze specific predictions across models
- 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:
- Identify protected attributes (gender, race, age, etc.)
- Compute SHAP values
- Compare feature importance across groups
- Check protected attribute SHAP importance
- Identify proxy features
- 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:
- Train and save model
- Create and save explainer
- Build explanation service
- Create API endpoints for predictions with explanations
- Implement caching and optimization
- 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
# 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
# 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
# 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):
LinearExplainer- Nearly instantaneousTreeExplainer- Very fastDeepExplainer- Fast for neural networksGradientExplainer-
How to use shap on Cursor
AI-first code editor with Composer
Prerequisites
Before installing skills in Cursor, ensure your development environment meets these requirements:
- ›Cursor installed and configured on your development machine
- ›Node.js version 16.0+ with npm package manager (verify with
node --version) - ›Active project directory or workspace where you want to add shap
Execute installation command
Execute the skills CLI command in your project's root directory to begin installation:
The skills CLI fetches shap from GitHub repository davila7/claude-code-templates and configures it for Cursor.
Select Cursor when prompted
The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:
Verify installation
Confirm successful installation by checking the skill directory location:
Reload or restart Cursor to activate shap. Access the skill through slash commands (e.g., /shap) or your agent's skill management interface.
Security & Verification Notice
We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.
Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.
List & Monetize Your Skill
Submit your Claude Code skill and start earning
Use Cases▌
User Story & Requirements Generation
Create detailed user stories, acceptance criteria, and feature specs
Example
Generate user stories for 'password reset feature' with acceptance criteria, edge cases, and test scenarios
Reduce spec writing time by 50%, ensure comprehensive coverage
Competitive Analysis
Research competitors, compare features, identify gaps
Example
Analyze 5 competitor products, create feature comparison matrix, suggest differentiation opportunities
Complete competitive research in 2 hours instead of 2 days
Roadmap Prioritization
Evaluate features using frameworks (RICE, ICE, Kano) and create prioritized backlogs
Example
Score 20 feature ideas using RICE framework, generate prioritized roadmap with rationale
Make data-driven prioritization decisions faster
Stakeholder Communication
Draft PRDs, status updates, and stakeholder presentations
Example
Create executive summary of Q3 roadmap, monthly progress report, feature launch announcement
Save 3-5 hours/week on communication overhead
Implementation Guide▌
Prerequisites
- ›Claude Desktop or compatible AI client
- ›Access to product documentation and roadmap tools (Jira, Notion, etc.)
- ›Understanding of product management frameworks (RICE, Jobs-to-be-Done, etc.)
- ›Stakeholder contact information and communication channels
Time Estimate
30-60 minutes to see productivity improvements
Installation Steps
- 1.Install product management skill
- 2.Start with user story generation for known feature
- 3.Progress to competitive analysis: research 2-3 competitors
- 4.Use for roadmap prioritization: apply RICE/ICE scoring
- 5.Draft stakeholder communications and refine based on feedback
- 6.Build template library for recurring PM tasks
- 7.Share effective prompts with product team
Common Pitfalls
- ⚠Not validating competitive research—verify facts before sharing
- ⚠Accepting user stories without involving engineering team
- ⚠Over-relying on frameworks without qualitative judgment
- ⚠Not customizing outputs to company culture and communication style
- ⚠Skipping stakeholder validation of generated requirements
Best Practices▌
✓ Do
- +Validate research and competitive analysis with real data
- +Collaborate with engineering when generating technical requirements
- +Customize frameworks and templates to your company context
- +Use skill for first drafts, refine with stakeholder input
- +Document successful prompt patterns for PM tasks
- +Combine AI efficiency with human judgment and intuition
✗ Don't
- −Don't publish competitive analysis without fact-checking
- −Don't finalize user stories without engineering review
- −Don't make prioritization decisions solely on AI scoring
- −Don't skip customer validation of generated requirements
- −Don't ignore company-specific context and culture
💡 Pro Tips
- ★Provide context: company goals, constraints, customer feedback
- ★Ask for alternatives: 'Show 3 ways to prioritize this roadmap'
- ★Request stakeholder-specific formatting: 'Executive summary vs. engineering spec'
- ★Use skill for 70% generation + 30% customization to company needs
When to Use This▌
✓ Use When
Use for user story writing, competitive research, roadmap prioritization, stakeholder communication, and PRD drafting. Best for reducing repetitive documentation and research work.
✗ Avoid When
Avoid for strategic product vision (requires deep customer empathy), pricing decisions (needs market and financial expertise), or when face-to-face customer discovery is more valuable than speed.
Learning Path▌
- 1Basic: user stories, feature specs, status updates
- 2Intermediate: competitive analysis, prioritization frameworks, PRDs
- 3Advanced: product strategy, go-to-market planning, OKR setting
- 4Expert: product vision, market positioning, business model innovation
Discussion
Product Hunt–style comments (not star reviews)- No comments yet — start the thread.
Ratings
4.5★★★★★50 reviews- ★★★★★Shikha Mishra· Dec 12, 2024
shap has been reliable in day-to-day use. Documentation quality is above average for community skills.
- ★★★★★Chen Bansal· Dec 12, 2024
Solid pick for teams standardizing on skills: shap is focused, and the summary matches what you get after install.
- ★★★★★Ganesh Mohane· Dec 8, 2024
shap is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.
- ★★★★★Benjamin Kapoor· Dec 8, 2024
Registry listing for shap matched our evaluation — installs cleanly and behaves as described in the markdown.
- ★★★★★Olivia Ndlovu· Dec 4, 2024
Keeps context tight: shap is the kind of skill you can hand to a new teammate without a long onboarding doc.
- ★★★★★Anika Diallo· Nov 27, 2024
shap fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.
- ★★★★★Benjamin Lopez· Nov 27, 2024
shap reduced setup friction for our internal harness; good balance of opinion and flexibility.
- ★★★★★Anaya Huang· Nov 23, 2024
I recommend shap for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.
- ★★★★★Yash Thakker· Nov 3, 2024
Solid pick for teams standardizing on skills: shap is focused, and the summary matches what you get after install.
- ★★★★★Daniel Liu· Nov 3, 2024
shap has been reliable in day-to-day use. Documentation quality is above average for community skills.
showing 1-10 of 50