[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73JERT21FNX4R7VS4AJBRZH":3,"skill-same:01M73JERT21FNX4R7VS4AJBRZH":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73JERT21FNX4R7VS4AJBRZH","shap-model-explainability",null,"Model interpretability via SHAP (Shapley values from game theory). Covers explainer choice (Tree, Deep, Linear, Kernel, Gradient, Permutation), feature attribution, and plots (waterfall, beeswarm, bar, scatter, force, heatmap). Use to explain ML predictions, rank features, debug models, audit fairness, or compare models. Works with tree, deep, linear, and black-box models.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fshap-model-explainability\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: shap-model-explainability\ndescription: \"Model interpretability via SHAP (Shapley values from game theory). Covers explainer choice (Tree, Deep, Linear, Kernel, Gradient, Permutation), feature attribution, and plots (waterfall, beeswarm, bar, scatter, force, heatmap). Use to explain ML predictions, rank features, debug models, audit fairness, or compare models. Works with tree, deep, linear, and black-box models.\"\nlicense: MIT\n---\n\n# SHAP Model Explainability\n\n## Overview\n\nSHAP (SHapley Additive exPlanations) is a unified framework for explaining machine learning model predictions using Shapley values from cooperative game theory. It quantifies each feature's contribution to individual predictions and provides both local (per-instance) and global (dataset-level) explanations with theoretical guarantees of consistency and additivity.\n\n## When to Use\n\n- Explaining which features drive a model's predictions (global importance)\n- Understanding why a model made a specific prediction (local explanation)\n- Debugging model behavior and identifying data leakage\n- Analyzing model fairness across demographic groups\n- Comparing feature importance across multiple models\n- Generating interpretable model explanations for stakeholders\n- For tree-based model interpretation, prefer SHAP over permutation importance or Gini importance (more accurate, instance-level)\n- For deep learning interpretation on images, consider GradCAM; use SHAP for tabular\u002Fstructured data\n\n## Prerequisites\n\n```bash\npip install shap matplotlib\n# Optional: xgboost lightgbm tensorflow torch (depending on model)\n```\n\n## Quick Start\n\n```python\nimport shap\nimport xgboost as xgb\nfrom sklearn.model_selection import train_test_split\n\n# Load example data\nX, y = shap.datasets.adult()\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n\n# Train model\nmodel = xgb.XGBClassifier(n_estimators=100).fit(X_train, y_train)\n\n# Explain: select explainer → compute → visualize\nexplainer = shap.TreeExplainer(model)\nshap_values = explainer(X_test)\n\nshap.plots.beeswarm(shap_values)   # Global importance\nshap.plots.waterfall(shap_values[0])  # Single prediction\nprint(f\"Base value: {shap_values.base_values[0]:.3f}\")\nprint(f\"SHAP values shape: {shap_values.values.shape}\")  # (n_samples, n_features)\n```\n\n## Workflow\n\n### Step 1: Select the Right Explainer\n\nChoose based on model type:\n\n| Model Type | Explainer | Speed | Exactness |\n|-----------|-----------|-------|-----------|\n| Tree-based (XGBoost, LightGBM, RF, CatBoost) | `TreeExplainer` | Fast | Exact |\n| Linear (LogReg, GLM, Ridge) | `LinearExplainer` | Instant | Exact |\n| Deep learning (TensorFlow, PyTorch) | `DeepExplainer` | Fast | Approximate |\n| Deep learning (gradient-based) | `GradientExplainer` | Fast | Approximate |\n| Any model (black-box) | `KernelExplainer` | Slow | Approximate |\n| Any model (permutation-based) | `PermutationExplainer` | Very slow | Exact |\n| **Unsure?** | `shap.Explainer` | Auto | Auto |\n\n```python\n# Tree-based models (most common)\nexplainer = shap.TreeExplainer(model)\n\n# Linear models\nexplainer = shap.LinearExplainer(model, X_train)\n\n# Deep learning\nexplainer = shap.DeepExplainer(model, X_train[:100])\n\n# Any model (model-agnostic, slower)\nexplainer = shap.KernelExplainer(model.predict, shap.kmeans(X_train, 50))\n\n# Auto-select\nexplainer = shap.Explainer(model, X_train)\n```\n\n### Step 2: Compute SHAP Values\n\n```python\nshap_values = explainer(X_test)\n\n# shap_values object contains:\n# .values      — SHAP values array (n_samples, n_features)\n# .base_values — Expected model output (baseline)\n# .data        — Original feature values\n\n# Verify additivity: prediction = base_value + sum(SHAP values)\nprint(f\"  {shap_values.base_values[0]:.3f} + {shap_values.values[0].sum():.3f} = \"\n      f\"{shap_values.base_values[0] + shap_values.values[0].sum():.3f}\")\n```\n\n### Step 3: Global Explanations\n\n```python\n# Beeswarm: feature importance + value distributions (most informative)\nshap.plots.beeswarm(shap_values, max_display=15)\n\n# Bar: clean mean |SHAP| importance\nshap.plots.bar(shap_values)\n```\n\n### Step 4: Local Explanations (Individual Predictions)\n\n```python\n# Waterfall: detailed breakdown of one prediction\nshap.plots.waterfall(shap_values[0])\n\n# Force: additive force visualization\nshap.plots.force(shap_values[0])\n```\n\n### Step 5: Feature Relationships\n\n```python\n# Scatter: how a feature affects predictions\nshap.plots.scatter(shap_values[:, \"Age\"])\n\n# Colored by interaction feature\nshap.plots.scatter(shap_values[:, \"Age\"], color=shap_values[:, \"Education-Num\"])\n```\n\n### Step 6: Advanced Visualizations\n\n```python\n# Heatmap: multi-sample SHAP grid\nshap.plots.heatmap(shap_values[:100])\n\n# Decision plot: cumulative SHAP paths\nshap.plots.decision(shap_values.base_values[0], shap_values.values[:10],\n                     feature_names=X_test.columns.tolist())\n\n# Cohort comparison\nimport numpy as np\nmask_a = X_test[\"Age\"] \u003C 40\nshap.plots.bar({\n    \"Under 40\": shap_values[mask_a],\n    \"40+\": shap_values[~mask_a]\n})\n```\n\n## Key Parameters\n\n| Parameter | Explainer\u002FFunction | Default | Effect |\n|-----------|-------------------|---------|--------|\n| `feature_perturbation` | TreeExplainer | `\"tree_path_dependent\"` | `\"interventional\"` for causal interpretation (requires background data) |\n| `model_output` | TreeExplainer | `\"raw\"` | `\"probability\"` to explain probabilities instead of log-odds |\n| `data` (background) | KernelExplainer, DeepExplainer | Required | 100-1000 representative samples; use `shap.kmeans(X, 50)` for efficiency |\n| `nsamples` | KernelExplainer | `\"auto\"` | Higher = more accurate but slower; minimum 2×features |\n| `max_display` | All plot functions | 10 | Number of features shown in plots |\n| `alpha` | scatter\u002Fbeeswarm | 1.0 | Point transparency for dense datasets |\n| `show` | All plot functions | True | Set `False` to get matplotlib figure for saving |\n| `clustering` | beeswarm | None | `shap.utils.hclust(...)` to cluster correlated features |\n\n## Key Concepts\n\n### SHAP Value Properties\n\nSHAP values have three theoretical guarantees (unique among explanation methods):\n\n- **Additivity**: `prediction = base_value + sum(SHAP values)` — exact decomposition\n- **Consistency**: If a feature becomes more important in the model, its SHAP value increases\n- **Missingness**: Features not present receive zero attribution\n\n**Interpretation**: Positive SHAP → pushes prediction higher; Negative → lower; Magnitude → strength of impact.\n\n### Model Output Types\n\nUnderstand what your model outputs — SHAP explains the output space:\n\n- **Regression**: SHAP values in target units (e.g., dollars, temperature)\n- **Classification (log-odds)**: Default for tree classifiers. Use `model_output=\"probability\"` for probability explanations\n- **Classification (probability)**: SHAP values sum to probability deviation from baseline\n\n### SHAP vs Other Methods\n\n| Method | Local | Global | Consistent | Model-agnostic |\n|--------|-------|--------|-----------|----------------|\n| SHAP | Yes | Yes | Yes | Yes |\n| Permutation importance | No | Yes | No | Yes |\n| Gini\u002Fsplit importance | No | Yes | No | Trees only |\n| LIME | Yes | No | No | Yes |\n| Integrated Gradients | Yes | No | Partial | NN only |\n\n### Interaction Values (TreeExplainer only)\n\n```python\nshap_interaction = explainer.shap_interaction_values(X_test)\n# Shape: (n_samples, n_features, n_features)\n# Diagonal = main effects; off-diagonal = pairwise interactions\n```\n\n### Background Data Selection\n\nBackground data establishes the baseline (expected model output). Selection affects SHAP magnitudes but not relative importance.\n\n- Random sample from training data: 100-500 samples\n- Use `shap.kmeans(X_train, 50)` for efficient summarization\n- For TreeExplainer with `tree_path_dependent`: no background data needed (uses tree structure)\n- For DeepExplainer\u002FKernelExplainer: 100-1000 samples balance accuracy vs speed\n\n## Common Recipes\n\n### Recipe: Model Debugging\n\n```python\nimport numpy as np\n\n# Find misclassified samples\npredictions = model.predict(X_test)\nerrors = predictions != y_test\nerror_indices = np.where(errors)[0]\n\n# Explain errors\nfor idx in error_indices[:3]:\n    print(f\"Sample {idx}: predicted={predictions[idx]}, actual={y_test.iloc[idx]}\")\n    shap.plots.waterfall(shap_values[idx])\n\n# Check for data leakage: unexpected high-importance features\nmean_abs_shap = np.abs(shap_values.values).mean(0)\ntop_features = X_test.columns[mean_abs_shap.argsort()[-5:]]\nprint(f\"Top features (check for leakage): {list(top_features)}\")\n```\n\n### Recipe: Fairness Analysis\n\n```python\n# Compare SHAP distributions across groups\ngroup_a = shap_values[X_test[\"Sex\"] == 0]\ngroup_b = shap_values[X_test[\"Sex\"] == 1]\n\nshap.plots.bar({\"Female\": group_a, \"Male\": group_b})\n\n# Check protected attribute importance\nsex_importance = np.abs(shap_values[:, \"Sex\"].values).mean()\ntotal_importance = np.abs(shap_values.values).mean()\nprint(f\"Sex contribution: {sex_importance\u002Ftotal_importance:.1%} of total importance\")\n```\n\n### Recipe: Production Caching\n\n```python\nimport joblib\n\n# Save explainer for reuse\njoblib.dump(explainer, 'explainer.pkl')\nexplainer = joblib.load('explainer.pkl')\n\n# Batch computation for API responses\ndef explain_batch(X_batch, explainer, top_n=5):\n    sv = explainer(X_batch)\n    results = []\n    for i in range(len(X_batch)):\n        top_idx = np.abs(sv.values[i]).argsort()[-top_n:]\n        results.append({\n            'prediction': sv.base_values[i] + sv.values[i].sum(),\n            'top_features': {X_batch.columns[j]: sv.values[i][j] for j in top_idx}\n        })\n    return results\n```\n\n### Recipe: MLflow Integration\n\n```python\nimport mlflow\nimport matplotlib.pyplot as plt\n\nwith mlflow.start_run():\n    model = xgb.XGBClassifier().fit(X_train, y_train)\n    explainer = shap.TreeExplainer(model)\n    shap_values = explainer(X_test)\n\n    shap.plots.beeswarm(shap_values, show=False)\n    mlflow.log_figure(plt.gcf(), \"shap_beeswarm.png\")\n    plt.close()\n\n    for feat, imp in zip(X_test.columns, np.abs(shap_values.values).mean(0)):\n        mlflow.log_metric(f\"shap_{feat}\", imp)\n```\n\n## Expected Outputs\n\n| Output | Type | Description |\n|--------|------|-------------|\n| `shap_values` | `shap.Explanation` | Object with `.values` `(n_samples, n_features)`, `.base_values` (baseline), `.data` (input features) |\n| Waterfall plot | matplotlib figure | Single-instance explanation showing feature contributions from base value to prediction |\n| Beeswarm plot | matplotlib figure | Global summary: feature importance × direction for all samples |\n| Bar plot | matplotlib figure | Mean absolute SHAP values per feature (global importance ranking) |\n| Force plot | HTML\u002Fmatplotlib | Interactive or static visualization of a single prediction |\n| `mean_abs_shap` | `pd.Series` | Per-feature mean absolute SHAP value for ranking and reporting |\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| Very slow computation | Using KernelExplainer for tree model | Use `TreeExplainer` for tree-based models |\n| Slow on large dataset | Computing all samples at once | Sample subset: `explainer(X_test[:1000])` or batch |\n| SHAP values don't sum to prediction | Wrong model output type | Check `model_output` parameter; verify additivity |\n| Log-odds vs probability confusion | Tree classifier defaults to log-odds | Use `TreeExplainer(model, model_output=\"probability\")` |\n| Plots too cluttered | Too many features shown | Set `max_display=10` or use feature clustering |\n| DeepExplainer error | Background data too small | Use 100-1000 background samples |\n| Memory error | Large dataset + many features | Reduce background data with `shap.kmeans(X, 50)` |\n| Force plot not rendering | Missing JS in notebook | Run `shap.initjs()` at notebook start |\n| Inconsistent importance across runs | KernelExplainer sampling variance | Increase `nsamples` or use deterministic explainer |\n| Negative importance for relevant feature | Feature interactions or correlations | Use `feature_perturbation=\"interventional\"` or scatter plots |\n\n## Bundled Resources\n\n- `references\u002Ftheory.md` — Mathematical foundations: Shapley value formula, key properties (additivity, symmetry, dummy, monotonicity), computation algorithms (Tree SHAP, Kernel SHAP, Deep SHAP, Linear SHAP), conditional expectations (interventional vs observational), comparison with LIME\u002FDeepLIFT\u002FLRP\u002FIntegrated Gradients, interaction values, theoretical limitations\n\nNot migrated from original: `references\u002Fexplainers.md` (340 lines) — detailed constructor parameters, methods, and performance benchmarks for each explainer class. Explainer selection guide and common usage are covered inline in Workflow Step 1 and Key Parameters.\n\nNot migrated from original: `references\u002Fplots.md` (508 lines) — comprehensive parameter reference for all 9 plot types with advanced customization (violin, decision, feature clustering). Main plot types are covered inline in Workflow Steps 3-6.\n\nNot migrated from original: `references\u002Fworkflows.md` (606 lines) — detailed step-by-step workflows for feature engineering, model comparison, deep learning explanation, production deployment, and time series. Core patterns are covered in Common Recipes; consult original for extended workflows.\n\n## Best Practices\n\n1. **Choose specialized explainers first** — `TreeExplainer` > `LinearExplainer` > `DeepExplainer` > `KernelExplainer`. Only use model-agnostic explainers when no specialized one exists\n2. **Start global, then go local** — begin with beeswarm\u002Fbar for overall importance, then waterfall\u002Fscatter for individual predictions and feature relationships\n3. **Use multiple visualizations** — different plots reveal different insights; combine global (beeswarm) + local (waterfall) + relationship (scatter)\n4. **Select appropriate background data** — 100-500 representative samples from training data; use `shap.kmeans()` for efficiency\n5. **Validate with domain knowledge** — unexpectedly high feature importance may indicate data leakage, not true predictive power\n6. **Remember SHAP shows association, not causation** — a feature's high SHAP importance means the model uses it, not that it causally affects the outcome\n7. **Consider feature correlations** — correlated features share SHAP importance; use `feature_perturbation=\"interventional\"` for causal interpretation or feature clustering for grouped importance\n\n## References\n\n- Lundberg & Lee (2017). \"A Unified Approach to Interpreting Model Predictions\" (NeurIPS)\n- Lundberg et al. (2020). \"From local explanations to global understanding with explainable AI for trees\" (Nature Machine Intelligence)\n- Official documentation: https:\u002F\u002Fshap.readthedocs.io\u002F\n- GitHub: https:\u002F\u002Fgithub.com\u002Fshap\u002Fshap\n\n## Related Skills\n\n- **scikit-learn-machine-learning** — model training for SHAP analysis\n- **matplotlib-scientific-plotting** — custom SHAP plot styling and export\n- **statistical-analysis** — statistical testing to complement SHAP interpretation\n","# SHAP Model Explainability\n\n## Overview\n\nSHAP (SHapley Additive exPlanations) is a unified framework for explaining machine learning model predictions using Shapley values from cooperative game theory. It quantifies each feature's contribution to individual predictions and provides both local (per-instance) and global (dataset-level) explanations with theoretical guarantees of consistency and additivity.\n\n## When to Use\n\n- Explaining which features drive a model's predictions (global importance)\n- Understanding why a model made a specific prediction (local explanation)\n- Debugging model behavior and identifying data leakage\n- Analyzing model fairness across demographic groups\n- Comparing feature importance across multiple models\n- Generating interpretable model explanations for stakeholders\n- For tree-based model interpretation, prefer SHAP over permutation importance or Gini importance (more accurate, instance-level)\n- For deep learning interpretation on images, consider GradCAM; use SHAP for tabular\u002Fstructured data\n\n## Prerequisites\n\n```bash\npip install shap matplotlib\n# Optional: xgboost lightgbm tensorflow torch (depending on model)\n```\n\n## Quick Start\n\n```python\nimport shap\nimport xgboost as xgb\nfrom sklearn.model_selection import train_test_split\n\n# Load example data\nX, y = shap.datasets.adult()\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n\n# Train model\nmodel = xgb.XGBClassifier(n_estimators=100).fit(X_train, y_train)\n\n# Explain: select explainer → compute → visualize\nexplainer = shap.TreeExplainer(model)\nshap_values = explainer(X_test)\n\nshap.plots.beeswarm(shap_values)   # Global importance\nshap.plots.waterfall(shap_values[0])  # Single prediction\nprint(f\"Base value: {shap_values.base_values[0]:.3f}\")\nprint(f\"SHAP values shape: {shap_values.values.shape}\")  # (n_samples, n_features)\n```\n\n## Workflow\n\n### Step 1: Select the Right Explainer\n\nChoose based on model type:\n\n| Model Type | Explainer | Speed | Exactness |\n|-----------|-----------|-------|-----------|\n| Tree-based (XGBoost, LightGBM, RF, CatBoost) | `TreeExplainer` | Fast | Exact |\n| Linear (LogReg, GLM, Ridge) | `LinearExplainer` | Instant | Exact |\n| Deep learning (TensorFlow, PyTorch) | `DeepExplainer` | Fast | Approximate |\n| Deep learning (gradient-based) | `GradientExplainer` | Fast | Approximate |\n| Any model (black-box) | `KernelExplainer` | Slow | Approximate |\n| Any model (permutation-based) | `PermutationExplainer` | Very slow | Exact |\n| **Unsure?** | `shap.Explainer` | Auto | Auto |\n\n```python\n# Tree-based models (most common)\nexplainer = shap.TreeExplainer(model)\n\n# Linear models\nexplainer = shap.LinearExplainer(model, X_train)\n\n# Deep learning\nexplainer = shap.DeepExplainer(model, X_train[:100])\n\n# Any model (model-agnostic, slower)\nexplainer = shap.KernelExplainer(model.predict, shap.kmeans(X_train, 50))\n\n# Auto-select\nexplainer = shap.Explainer(model, X_train)\n```\n\n### Step 2: Compute SHAP Values\n\n```python\nshap_values = explainer(X_test)\n\n# shap_values object contains:\n# .values      — SHAP values array (n_samples, n_features)\n# .base_values — Expected model output (baseline)\n# .data        — Original feature values\n\n# Verify additivity: prediction = base_value + sum(SHAP values)\nprint(f\"  {shap_values.base_values[0]:.3f} + {shap_values.values[0].sum():.3f} = \"\n      f\"{shap_values.base_values[0] + shap_values.values[0].sum():.3f}\")\n```\n\n### Step 3: Global Explanations\n\n```python\n# Beeswarm: feature importance + value distributions (most informative)\nshap.plots.beeswarm(shap_values, max_display=15)\n\n# Bar: clean mean |SHAP| importance\nshap.plots.bar(shap_values)\n```\n\n### Step 4: Local Explanations (Individual Predictions)\n\n```python\n# Waterfall: detailed breakdown of one prediction\nshap.plots.waterfall(shap_values[0])\n\n# Force: additive force visualization\nshap.plots.force(shap_values[0])\n```\n\n### Step 5: Feature Relationships\n\n```python\n# Scatter: how a feature affects predictions\nshap.plots.scatter(shap_values[:, \"Age\"])\n\n# Colored by interaction feature\nshap.plots.scatter(shap_values[:, \"Age\"], color=shap_values[:, \"Education-Num\"])\n```\n\n### Step 6: Advanced Visualizations\n\n```python\n# Heatmap: multi-sample SHAP grid\nshap.plots.heatmap(shap_values[:100])\n\n# Decision plot: cumulative SHAP paths\nshap.plots.decision(shap_values.base_values[0], shap_values.values[:10],\n                     feature_names=X_test.columns.tolist())\n\n# Cohort comparison\nimport numpy as np\nmask_a = X_test[\"Age\"] \u003C 40\nshap.plots.bar({\n    \"Under 40\": shap_values[mask_a],\n    \"40+\": shap_values[~mask_a]\n})\n```\n\n## Key Parameters\n\n| Parameter | Explainer\u002FFunction | Default | Effect |\n|-----------|-------------------|---------|--------|\n| `feature_perturbation` | TreeExplainer | `\"tree_path_dependent\"` | `\"interventional\"` for causal interpretation (requires background data) |\n| `model_output` | TreeExplainer | `\"raw\"` | `\"probability\"` to explain probabilities instead of log-odds |\n| `data` (background) | KernelExplainer, DeepExplainer | Required | 100-1000 representative samples; use `shap.kmeans(X, 50)` for efficiency |\n| `nsamples` | KernelExplainer | `\"auto\"` | Higher = more accurate but slower; minimum 2×features |\n| `max_display` | All plot functions | 10 | Number of features shown in plots |\n| `alpha` | scatter\u002Fbeeswarm | 1.0 | Point transparency for dense datasets |\n| `show` | All plot functions | True | Set `False` to get matplotlib figure for saving |\n| `clustering` | beeswarm | None | `shap.utils.hclust(...)` to cluster correlated features |\n\n## Key Concepts\n\n### SHAP Value Properties\n\nSHAP values have three theoretical guarantees (unique among explanation methods):\n\n- **Additivity**: `prediction = base_value + sum(SHAP values)` — exact decomposition\n- **Consistency**: If a feature becomes more important in the model, its SHAP value increases\n- **Missingness**: Features not present receive zero attribution\n\n**Interpretation**: Positive SHAP → pushes prediction higher; Negative → lower; Magnitude → strength of impact.\n\n### Model Output Types\n\nUnderstand what your model outputs — SHAP explains the output space:\n\n- **Regression**: SHAP values in target units (e.g., dollars, temperature)\n- **Classification (log-odds)**: Default for tree classifiers. Use `model_output=\"probability\"` for probability explanations\n- **Classification (probability)**: SHAP values sum to probability deviation from baseline\n\n### SHAP vs Other Methods\n\n| Method | Local | Global | Consistent | Model-agnostic |\n|--------|-------|--------|-----------|----------------|\n| SHAP | Yes | Yes | Yes | Yes |\n| Permutation importance | No | Yes | No | Yes |\n| Gini\u002Fsplit importance | No | Yes | No | Trees only |\n| LIME | Yes | No | No | Yes |\n| Integrated Gradients | Yes | No | Partial | NN only |\n\n### Interaction Values (TreeExplainer only)\n\n```python\nshap_interaction = explainer.shap_interaction_values(X_test)\n# Shape: (n_samples, n_features, n_features)\n# Diagonal = main effects; off-diagonal = pairwise interactions\n```\n\n### Background Data Selection\n\nBackground data establishes the baseline (expected model output). Selection affects SHAP magnitudes but not relative importance.\n\n- Random sample from training data: 100-500 samples\n- Use `shap.kmeans(X_train, 50)` for efficient summarization\n- For TreeExplainer with `tree_path_dependent`: no background data needed (uses tree structure)\n- For DeepExplainer\u002FKernelExplainer: 100-1000 samples balance accuracy vs speed\n\n## Common Recipes\n\n### Recipe: Model Debugging\n\n```python\nimport numpy as np\n\n# Find misclassified samples\npredictions = model.predict(X_test)\nerrors = predictions != y_test\nerror_indices = np.where(errors)[0]\n\n# Explain errors\nfor idx in error_indices[:3]:\n    print(f\"Sample {idx}: predicted={predictions[idx]}, actual={y_test.iloc[idx]}\")\n    shap.plots.waterfall(shap_values[idx])\n\n# Check for data leakage: unexpected high-importance features\nmean_abs_shap = np.abs(shap_values.values).mean(0)\ntop_features = X_test.columns[mean_abs_shap.argsort()[-5:]]\nprint(f\"Top features (check for leakage): {list(top_features)}\")\n```\n\n### Recipe: Fairness Analysis\n\n```python\n# Compare SHAP distributions across groups\ngroup_a = shap_values[X_test[\"Sex\"] == 0]\ngroup_b = shap_values[X_test[\"Sex\"] == 1]\n\nshap.plots.bar({\"Female\": group_a, \"Male\": group_b})\n\n# Check protected attribute importance\nsex_importance = np.abs(shap_values[:, \"Sex\"].values).mean()\ntotal_importance = np.abs(shap_values.values).mean()\nprint(f\"Sex contribution: {sex_importance\u002Ftotal_importance:.1%} of total importance\")\n```\n\n### Recipe: Production Caching\n\n```python\nimport joblib\n\n# Save explainer for reuse\njoblib.dump(explainer, 'explainer.pkl')\nexplainer = joblib.load('explainer.pkl')\n\n# Batch computation for API responses\ndef explain_batch(X_batch, explainer, top_n=5):\n    sv = explainer(X_batch)\n    results = []\n    for i in range(len(X_batch)):\n        top_idx = np.abs(sv.values[i]).argsort()[-top_n:]\n        results.append({\n            'prediction': sv.base_values[i] + sv.values[i].sum(),\n            'top_features': {X_batch.columns[j]: sv.values[i][j] for j in top_idx}\n        })\n    return results\n```\n\n### Recipe: MLflow Integration\n\n```python\nimport mlflow\nimport matplotlib.pyplot as plt\n\nwith mlflow.start_run():\n    model = xgb.XGBClassifier().fit(X_train, y_train)\n    explainer = shap.TreeExplainer(model)\n    shap_values = explainer(X_test)\n\n    shap.plots.beeswarm(shap_values, show=False)\n    mlflow.log_figure(plt.gcf(), \"shap_beeswarm.png\")\n    plt.close()\n\n    for feat, imp in zip(X_test.columns, np.abs(shap_values.values).mean(0)):\n        mlflow.log_metric(f\"shap_{feat}\", imp)\n```\n\n## Expected Outputs\n\n| Output | Type | Description |\n|--------|------|-------------|\n| `shap_values` | `shap.Explanation` | Object with `.values` `(n_samples, n_features)`, `.base_values` (baseline), `.data` (input features) |\n| Waterfall plot | matplotlib figure | Single-instance explanation showing feature contributions from base value to prediction |\n| Beeswarm plot | matplotlib figure | Global summary: feature importance × direction for all samples |\n| Bar plot | matplotlib figure | Mean absolute SHAP values per feature (global importance ranking) |\n| Force plot | HTML\u002Fmatplotlib | Interactive or static visualization of a single prediction |\n| `mean_abs_shap` | `pd.Series` | Per-feature mean absolute SHAP value for ranking and reporting |\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| Very slow computation | Using KernelExplainer for tree model | Use `TreeExplainer` for tree-based models |\n| Slow on large dataset | Computing all samples at once | Sample subset: `explainer(X_test[:1000])` or batch |\n| SHAP values don't sum to prediction | Wrong model output type | Check `model_output` parameter; verify additivity |\n| Log-odds vs probability confusion | Tree classifier defaults to log-odds | Use `TreeExplainer(model, model_output=\"probability\")` |\n| Plots too cluttered | Too many features shown | Set `max_display=10` or use feature clustering |\n| DeepExplainer error | Background data too small | Use 100-1000 background samples |\n| Memory error | Large dataset + many features | Reduce background data with `shap.kmeans(X, 50)` |\n| Force plot not rendering | Missing JS in notebook | Run `shap.initjs()` at notebook start |\n| Inconsistent importance across runs | KernelExplainer sampling variance | Increase `nsamples` or use deterministic explainer |\n| Negative importance for relevant feature | Feature interactions or correlations | Use `feature_perturbation=\"interventional\"` or scatter plots |\n\n## Bundled Resources\n\n- `references\u002Ftheory.md` — Mathematical foundations: Shapley value formula, key properties (additivity, symmetry, dummy, monotonicity), computation algorithms (Tree SHAP, Kernel SHAP, Deep SHAP, Linear SHAP), conditional expectations (interventional vs observational), comparison with LIME\u002FDeepLIFT\u002FLRP\u002FIntegrated Gradients, interaction values, theoretical limitations\n\nNot migrated from original: `references\u002Fexplainers.md` (340 lines) — detailed constructor parameters, methods, and performance benchmarks for each explainer class. Explainer selection guide and common usage are covered inline in Workflow Step 1 and Key Parameters.\n\nNot migrated from original: `references\u002Fplots.md` (508 lines) — comprehensive parameter reference for all 9 plot types with advanced customization (violin, decision, feature clustering). Main plot types are covered inline in Workflow Steps 3-6.\n\nNot migrated from original: `references\u002Fworkflows.md` (606 lines) — detailed step-by-step workflows for feature engineering, model comparison, deep learning explanation, production deployment, and time series. Core patterns are covered in Common Recipes; consult original for extended workflows.\n\n## Best Practices\n\n1. **Choose specialized explainers first** — `TreeExplainer` > `LinearExplainer` > `DeepExplainer` > `KernelExplainer`. Only use model-agnostic explainers when no specialized one exists\n2. **Start global, then go local** — begin with beeswarm\u002Fbar for overall importance, then waterfall\u002Fscatter for individual predictions and feature relationships\n3. **Use multiple visualizations** — different plots reveal different insights; combine global (beeswarm) + local (waterfall) + relationship (scatter)\n4. **Select appropriate background data** — 100-500 representative samples from training data; use `shap.kmeans()` for efficiency\n5. **Validate with domain knowledge** — unexpectedly high feature importance may indicate data leakage, not true predictive power\n6. **Remember SHAP shows association, not causation** — a feature's high SHAP importance means the model uses it, not that it causally affects the outcome\n7. **Consider feature correlations** — correlated features share SHAP importance; use `feature_perturbation=\"interventional\"` for causal interpretation or feature clustering for grouped importance\n\n## References\n\n- Lundberg & Lee (2017). \"A Unified Approach to Interpreting Model Predictions\" (NeurIPS)\n- Lundberg et al. (2020). \"From local explanations to global understanding with explainable AI for trees\" (Nature Machine Intelligence)\n- Official documentation: https:\u002F\u002Fshap.readthedocs.io\u002F\n- GitHub: https:\u002F\u002Fgithub.com\u002Fshap\u002Fshap\n\n## Related Skills\n\n- **scikit-learn-machine-learning** — model training for SHAP analysis\n- **matplotlib-scientific-plotting** — custom SHAP plot styling and export\n- **statistical-analysis** — statistical testing to complement SHAP interpretation\n",{"name":5,"license":15,"description":7},"master","63f17866001c5ca854bf2fa0b678ce277133de5b","skills\u002Fawesome-skills\u002Fshap-model-explainability",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill shap-model-explainability",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill shap-model-explainability",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill shap-model-explainability","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fshap-model-explainability\u002FSKILL.md",true,[],[49,57,64,71,78,85],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":56},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":56},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":56},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":56},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":56},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":56},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]