SHAP splits each prediction into additive contributions: prediction = base value + sum of SHAP values.
That property makes SHAP the standard for both global ("what drives the model?") and local ("why this
customer?") explanations. It also makes errors easy to check. Most bad SHAP reports come from the wrong
output space, a background nobody chose deliberately, one-hot columns read separately, or SHAP read as
causation. scripts/gen_shap_script.py writes a script that computes SHAP correctly for the saved model
and exports two CSVs. scripts/shap_summary.py reads them for the global picture and
scripts/explain_row.py explains single predictions.
Trigger Conditions
Activate this skill when the user:
- Wants to explain a tabular model or individual predictions with SHAP
- Shares SHAP values or a summary/beeswarm/waterfall/dependence plot and asks what it means
- Needs reason codes for a decision (credit, fraud, churn outreach) or a stakeholder-ready explanation
- Sees SHAP values that do not add up, or explanations that contradict domain knowledge
Model-agnostic importance comparisons: feature-importance-reporter; average effect curves: partial-dependence-plot-builder; local surrogate explanations: lime-explanation-generator; "what would change the decision": counterfactual-explanation-generator.
Workflow
1. GENERATE -> python scripts/gen_shap_script.py --model model.joblib --data test.csv --target y --group -o explain.py
2. COMPUTE -> python explain.py (shap_values.csv + shap_features.csv, additivity asserted)
3. GLOBAL -> python scripts/shap_summary.py shap_values.csv --features shap_features.csv
4. LOCAL -> python scripts/explain_row.py shap_values.csv --features shap_features.csv --row 17 --link logit
5. SANITY -> directions vs domain knowledge; leakage if one feature dominates; correlated groups
6. REPORT -> global drivers, interactions, example explanations, caveatsChoosing the Explainer
| Model | Explainer | Output space | Notes |
|---|---|---|---|
| LightGBM, XGBoost, sklearn GBM | TreeExplainer | raw margin (log-odds for classifiers) | exact, fast |
| HistGradientBoosting | TreeExplainer(feature_perturbation="tree_path_dependent") | log-odds | interventional mode misses the baseline in shap 0.54 (verified) |
| Random forest, extra trees, decision tree | TreeExplainer | probability | sklearn forests average probabilities |
| CatBoost | model.get_feature_importance(Pool, type="ShapValues") | log-odds | handles categorical features natively |
| Linear / logistic | LinearExplainer(model, background) | log-odds | SHAP_j = coef_j x (x_j - mean_j) for independent features |
| Anything else (SVM, k-NN, stacks) | PermutationExplainer(f, Independent(background)) | probability | model-agnostic, cost grows with features x background |
Interventional versus tree_path_dependent. Interventional SHAP with a background sample answers "relative to these reference rows". Tree-path-dependent SHAP uses the tree's training cover and needs no background, but it spreads credit onto correlated features differently. Use interventional with 100-1000 representative rows (not only positives, not the test row itself) unless the model rules it out.
Output space. Log-odds are additive and probabilities are not. Explain in log-odds and convert the base
and the final value to probabilities for the reader (explain_row.py --link logit). Per-feature probability
contributions depend on the order in which they are added.
Explainer details, backgrounds, multiclass, pipelines: computing-shap.md.
Reading SHAP
| Question | Read | Script output |
|---|---|---|
| What drives the model overall? | mean |SHAP| | rank, share |
| Which way does a feature push? | value vs SHAP correlation | rho, direction |
| Is the effect simple? | spread of SHAP at a fixed value | spread %, partner |
| Does missingness matter? | SHAP of rows with missing values | mean SHAP of missing |
| Why this prediction? | waterfall | explain_row.py |
Rules that prevent the classic misreadings:
- SHAP is not causal. It shows how this model uses inputs. Changing a feature in the world may not change the outcome, and features the model never saw get no credit.
- Correlated features share credit. Two near-duplicate features each look half as important. Group them (sum their SHAP) before ranking, or drop one and refit.
- One dominant feature is a red flag. Check it with target-leakage-detector.
- Mean |SHAP| depends on the rows explained. Explain a representative sample of production-like data, not the training set or only positives.
- One-hot columns belong together.
--groupsums them back to the input column, and additivity still holds. - Interaction attribution is approximate. The partner reported is a hint. Confirm it with SHAP interaction values for trees, or a 2-D partial dependence plot.
Plot reading (beeswarm, dependence, waterfall, force) and stakeholder wording: reading-shap.md. Reason codes, adverse-action notices and monitoring explanations over time: shap-in-production.md.
Output Format
When explaining a model with SHAP, deliver:
- Setup - model, explainer, background (size and source), output space, rows explained.
- Checks - additivity, constant base value, grouped columns.
- Global drivers - top features with share and direction, interactions worth noting, missing-value effects.
- Local examples - two or three waterfalls (typical high, typical low, a surprising case) in plain language.
- Caveats - correlated groups, non-causal reading, data the explanation covers, anything that looked like leakage.
Scripts
python scripts/gen_shap_script.py --model model.joblib --data test.csv --target churned -o explain.py
python scripts/gen_shap_script.py --model pipe.joblib --data test.csv --drop customer_id --group --rows 2000
python scripts/gen_shap_script.py --model rf.joblib --data x.csv --perturbation tree_path_dependent --class 2Verified for LightGBM, XGBoost, random forest, HistGradientBoosting, CatBoost with categorical features, a logistic-regression Pipeline with one-hot grouping, and an SVC Pipeline (permutation path). The script asserts additivity before writing. Exit codes: 0 written, 2 usage error.
python scripts/shap_summary.py shap_values.csv --features shap_features.csv --top 10Importance, share, signed mean, direction, spread, interaction partner, missing-value effect, additivity and base-value checks. Exit codes: 0 summarised, 1 additivity failed, 2 usage or read error.
python scripts/explain_row.py shap_values.csv --features shap_features.csv --row 17 --link logit --label "churn probability"
python scripts/explain_row.py shap_values.csv --features shap_features.csv --select highest --top 5Text waterfall with cumulative log-odds and probabilities, and a plain-language summary. Exit codes: 0
explained, 1 additivity mismatch, 2 usage or read error. Both readers share scripts/_shap_io.py (CSV
loading, row alignment).
Additional Resources
| File | Content |
|---|---|
| computing-shap.md | explainers per model, background data, interventional vs path-dependent, output spaces, multiclass, pipelines, cost |
| reading-shap.md | plot types, interactions, correlated features, pitfalls, wording for stakeholders |
| shap-in-production.md | reason codes, adverse-action notices, explanation monitoring, latency and storage |
anomaly-detection-model-builder
Build and evaluate anomaly detection for tabular, sensor and transaction data with few or no labels: define the anomaly type (point, contextual, collective), choose detectors (robust z-score/MAD and IQR rules, Mahalanobis with robust covariance, k-NN distance, LOF, Isolation Forest, one-class SVM, PCA reconstruction / autoencoders, forecasting residuals for time series), combine them by rank, explain each alert by its deviating features, set thresholds from an alert budget or the score distribution, and evaluate with precision@k, PR-AUC and recall on known incidents, or detector agreement when no labels exist. Includes pure-Python detectors (robust z, Mahalanobis, kNN, Isolation Forest, ensemble) and an evaluation script.
catboost-model-builder
Build CatBoost models that use its strengths correctly: raw categorical columns as cat_features (ordered target statistics, no manual encoding), text_features, Pool construction with NaN-safe categories, ordered boosting and has_time for temporal data, symmetric (oblivious) trees, overfitting detector with eval_set and use_best_model, losses for classification, regression (Quantile, Poisson, Tweedie) and ranking (YetiRank), class weights, monotone constraints, feature importance (PredictionValuesChange, LossFunctionChange) and SHAP values, GPU training and model export. Plans cat/text/numeric columns from a CSV and generates a runnable training script, and checks parameter sets for the conflicts CatBoost rejects (iterations vs n_estimators, Bayesian bootstrap with subsample, multiple class-weight options, depth > 16, use_best_model without eval_set).
categorical-encoding-selector
Choose and implement the right encoding for every categorical column given the model family and the data: one-hot (with infrequent-level grouping and handle_unknown), ordinal with an explicit order, cross-fitted target encoding (scikit-learn TargetEncoder, CatBoost ordered statistics, category_encoders inside CV), frequency/count encoding, feature hashing, native categorical support in LightGBM, HistGradientBoosting, XGBoost and CatBoost, prefix levels for codes (zip3, NAICS-2), and embeddings. Measures cardinality, rare-level share, unseen-level rate on a time-ordered holdout and target signal per column, emits the ColumnTransformer, and quantifies target-encoding leakage (in-sample vs out-of-fold vs holdout AUC).
classification-model-selector
Choose the right classification algorithm for tabular, text or mixed data and prove the choice with a fair bake-off: logistic regression (L2, L1, elastic net), linear SVM, naive Bayes, k-NN, RBF SVM, decision trees, random forest, extra trees, HistGradientBoosting, LightGBM, XGBoost, CatBoost, explainable boosting machines (EBM/GAM), points scorecards and MLPs, matched to data size, width, categorical and high-cardinality share, missingness, class imbalance, text, and constraints such as interpretability, monotonic constraints, calibrated probabilities, latency budgets and tiny deployable models. Ranks candidates with starting hyperparameters and cautions, then generates a bake-off script running every candidate on identical CV folds with per-fold metrics, fit time and prediction latency.
clustering-algorithm-selector
Choose the right clustering algorithm and check that clustering makes sense at all: cluster tendency (Hopkins statistic with a correlated-features caveat, nearest-neighbour isolation), then k-means / MiniBatchKMeans, Gaussian mixtures with BIC, agglomerative (Ward, average, complete, single) with dendrograms, DBSCAN, HDBSCAN, OPTICS, spectral clustering, BIRCH, mean shift, k-prototypes and k-modes for mixed or categorical data, and Gower distance, matched to data size, expected shapes, noise, varying density, known k, soft memberships, hierarchy and streaming. Covers preprocessing (scaling, encoding, dimensionality, distance metrics), validation (internal indices, bootstrap stability, external labels, business profiling) and assigning new points.
collaborative-filtering-implementer
Implement collaborative filtering recommenders that beat popularity: item-based kNN with cosine, Jaccard or asymmetric similarity, shrinkage, neighbourhood size, positive-only or mean-centred rating signals and 'because you liked X' explanations; implicit ALS with confidence weighting, BPR pairwise ranking and the closed-form EASE model in plain NumPy, tuned on a temporal validation split by recall@k and NDCG@k and refit on all data; plus user-kNN, explicit matrix factorisation, the implicit/LightFM libraries, hyperparameter ranges, cold-start fallbacks, scaling with sparse matrices and approximate nearest neighbours. Produces top-k lists in the format of the recommendation evaluator.