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.
What this skill does
# 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)
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.