A counterfactual explanation answers "what would have to be different for the model to decide
otherwise?". For example: "with 3 fewer support calls and one more recent login, the churn risk would drop
below 75%". Useful counterfactuals are valid (the prediction really changes), actionable (only
features the person can change, in directions they can change them), sparse (few changes),
plausible (they look like real data) and diverse (several options).
scripts/linear_counterfactual.py solves the problem exactly for linear and logistic models.
scripts/gen_dice_script.py runs DiCE for any model. scripts/cf_validate.py checks counterfactuals from
any method before anyone sees them.
Trigger Conditions
Activate this skill when the user:
- Asks what an applicant, customer or patient would need to change to get a different decision
- Needs recourse for adverse decisions (credit, insurance, hiring, fraud holds) or "what-if" explanations
- Uses or evaluates DiCE, Alibi counterfactuals or a custom search
- Wants to know whether some people have no recourse (fairness review)
Attribution ("why this score?"): shap-value-explainer. Local surrogates: lime-explanation-generator. Model documentation: model-card-writer.
Workflow
1. CONSTRAINTS -> per feature: mutable?, direction (increase/decrease), min/max, integer/binary, cost scale
2. GENERATE -> linear/logistic: python scripts/linear_counterfactual.py model.json row.json --target-prob 0.3
any model: python scripts/gen_dice_script.py --model m.joblib --train train.csv --rows rows.csv --target y --constraints c.json -o dice.py
3. VALIDATE -> python scripts/cf_validate.py --original row.json --cfs cfs.csv --train train.csv --constraints c.json \
--pred-col pred_prob --target-prob 0.5 --side below --relation "total=tenure*monthly"
4. SELECT -> 1-3 valid, plausible, diverse options; cheapest first
5. COMMUNICATE -> plain-language options, with the caveat that model inputs are not guaranteed causesConstraints Make or Break Recourse
| Feature kind | Constraint | Example |
|---|---|---|
| Immutable | "mutable": false | age, tenure so far, past defaults, region of birth |
| Monotone in time | "direction": "increase" | age, education level, account age |
| Behaviour that can improve | "direction": "decrease" + "min" | missed payments going forward, support calls, utilisation |
| Integer counts | "integer": true | number of accounts, calls |
| Binary choices | "binary": true | plan upgrade, autopay on/off |
| Hard to change | "cost_multiplier": 2-5 | income, monthly price |
| Derived features | --relation "total=a*b" in validation | total charges = tenure x monthly charges |
The cost unit is the feature's MAD (median absolute deviation), so "1" means a typical difference between people. Without constraints, counterfactuals happily suggest "be 10 years younger" or "have negative support calls". Constraint design and examples: actionability-and-constraints.md.
Methods
| Method | Models | Guarantees | Use |
|---|---|---|---|
linear_counterfactual.py | linear, logistic (any GLM score) | exact minimal MAD-L1 cost under the constraints | scorecards, logistic credit models, linear baselines |
DiCE random (gen_dice_script.py) | any classifier | diverse; not minimal | black-box models, quick options |
| DiCE genetic / kdtree | any classifier | better proximity; kdtree returns real training rows | plausibility matters |
| Alibi CFProto / Wachter | differentiable or any | gradient or prototype guided | images, neural networks |
| MILP (Ustun et al. "actionable recourse") | linear, tree ensembles | exact, with complex constraints | audits of recourse |
Verified on the fixtures:
- The linear solver matches a brute-force search exactly for four targets. Integer features are branched on floor and ceiling.
- DiCE random produced valid flips that cost 7.6-10.2 MAD units where the exact optimum was 5.5.
- For a LightGBM churn model, DiCE "flipped" a low-risk customer only by changing
total_chargeswithout changing tenure or monthly charges.cf_validate.py --relationrejects all three results.
Method details: counterfactual-methods.md.
Validation Before Showing Anyone
| Check | cf_validate.py | Why |
|---|---|---|
| prediction really changes | --pred-col + --target-prob + --side | some generators return near-misses |
| immutable / direction / bounds / integer | violations | the advice must be possible |
| unseen categories | UNSEEN | a level the model never saw |
| implausible values | outside the 1-99% training range and further out than the original | no fantasy values |
| off-manifold | nearest training row farther than max(p95 of training NN distances, the original's own) | a combination no real person has |
| derived features | RELATION | consistency between features |
| diversity | mean pairwise distance, distinct change sets | several genuinely different options |
Communicating Recourse
- Offer options, not orders: "Any one of these would change the outcome: ...".
- Use real units and directions: "3 fewer support calls in the next quarter", not "support_calls -3".
- Say what is not guaranteed: the model can change, and other factors may matter.
- A NO RECOURSE result (immutable features decide the outcome) is a fairness finding. Report it to model owners, not to the customer as advice.
- Never suggest gaming the model, and never suggest changing protected attributes or their proxies.
Wording, regulation (adverse-action notices, GDPR Art. 22, the EU AI Act) and fairness of recourse: communicating-recourse.md.
Output Format
When producing counterfactual explanations, deliver:
- Constraints - mutable features, directions, bounds, cost scales, relations.
- Counterfactuals - 1-3 validated options with the changes, cost, sparsity and new prediction.
- Validation - cf_validate.py results (violations, plausibility, validity).
- Recourse findings - essential features, no-recourse cases, groups with costlier recourse.
- Plain-language text - what the person could change, with caveats.
Scripts
python scripts/linear_counterfactual.py cf_logreg.json cf_row.json --target-prob 0.3
python scripts/linear_counterfactual.py model.json row.json --threshold 0.5 --json
python scripts/linear_counterfactual.py linear.json row.json --target-value 250000 --side aboveThe model spec holds the intercept, coefficients and a per-feature constraint block. The script prints the optimal counterfactual, diverse alternatives (the best without each used feature), single-feature options, essential features, or NO RECOURSE with the best reachable probability. Exit codes: 0 found, 1 no feasible recourse, 2 usage or read error.
python scripts/gen_dice_script.py --model model.joblib --train train.csv --rows test.csv --target churned --row 0 -o dice_run.py
python scripts/gen_dice_script.py --model m.joblib --train train.csv --rows test.csv --target churned --constraints c.json --method genetic --total 6Immutable features are excluded from features_to_vary and directions become per-row permitted_range.
Integer features are rounded, every counterfactual is re-predicted, and the script prints the
cf_validate.py command with the right --side. Verified with dice-ml on logistic and LightGBM Pipelines
(random, genetic, kdtree). Exit codes: 0 written, 2 usage error.
python scripts/cf_validate.py --original row.json --cfs cfs.csv --train train.csv --constraints c.json --pred-col pred_prob --target-prob 0.5 --side belowExit codes: 0 all usable, 1 any violation, invalid or off-manifold counterfactual, 2 usage or read error.
Additional Resources
| File | Content |
|---|---|
| actionability-and-constraints.md | designing constraints, cost scales, derived features, causal dependencies |
| counterfactual-methods.md | the exact linear solution, DiCE, Wachter, prototypes, MILP, trade-offs |
| communicating-recourse.md | wording, regulation, fairness of recourse, audits |
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.