Skip to content
v0.1.3latest release121 skills4 categories6 sub-categories247 tested scripts397 reference docsContact us

counterfactual-explanation-generator

Generate counterfactual explanations and algorithmic recourse: the smallest realistic change to a row's features that changes the model's decision. Solves exact minimal-cost recourse for linear and logistic models (MAD-scaled L1 cost, immutable features, increase/decrease directions, bounds, integer and binary features, diverse alternatives, features every counterfactual must change, and a no-recourse finding when immutable features decide), generates DiCE counterfactuals for any scikit-learn model with constraints turned into permitted ranges and every result re-predicted, and validates counterfactuals from any method for constraint violations, implausible values, off-manifold rows, broken derived-feature relations and failure to flip the prediction. Use when someone asks what a customer or applicant would need to change to get a different outcome, wants counterfactual or what-if explanations, recourse for adverse decisions, or DiCE.

AI & Machine Learning / Classical Machine Learningv1.0.0Updated OCT 25 20263 references3 scripts

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

text
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 causes

Constraints Make or Break Recourse

Feature kindConstraintExample
Immutable"mutable": falseage, 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": truenumber of accounts, calls
Binary choices"binary": trueplan upgrade, autopay on/off
Hard to change"cost_multiplier": 2-5income, monthly price
Derived features--relation "total=a*b" in validationtotal 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

MethodModelsGuaranteesUse
linear_counterfactual.pylinear, logistic (any GLM score)exact minimal MAD-L1 cost under the constraintsscorecards, logistic credit models, linear baselines
DiCE random (gen_dice_script.py)any classifierdiverse; not minimalblack-box models, quick options
DiCE genetic / kdtreeany classifierbetter proximity; kdtree returns real training rowsplausibility matters
Alibi CFProto / Wachterdifferentiable or anygradient or prototype guidedimages, neural networks
MILP (Ustun et al. "actionable recourse")linear, tree ensemblesexact, with complex constraintsaudits 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_charges without changing tenure or monthly charges. cf_validate.py --relation rejects all three results.

Method details: counterfactual-methods.md.

Validation Before Showing Anyone

Checkcf_validate.pyWhy
prediction really changes--pred-col + --target-prob + --sidesome generators return near-misses
immutable / direction / bounds / integerviolationsthe advice must be possible
unseen categoriesUNSEENa level the model never saw
implausible valuesoutside the 1-99% training range and further out than the originalno fantasy values
off-manifoldnearest training row farther than max(p95 of training NN distances, the original's own)a combination no real person has
derived featuresRELATIONconsistency between features
diversitymean pairwise distance, distinct change setsseveral 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:

  1. Constraints - mutable features, directions, bounds, cost scales, relations.
  2. Counterfactuals - 1-3 validated options with the changes, cost, sparsity and new prediction.
  3. Validation - cf_validate.py results (violations, plausibility, validity).
  4. Recourse findings - essential features, no-recourse cases, groups with costlier recourse.
  5. Plain-language text - what the person could change, with caveats.

Scripts

bash
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 above

The 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.

bash
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 6

Immutable 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.

bash
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

Exit codes: 0 all usable, 1 any violation, invalid or off-manifold counterfactual, 2 usage or read error.

Additional Resources

FileContent
actionability-and-constraints.mddesigning constraints, cost scales, derived features, causal dependencies
counterfactual-methods.mdthe exact linear solution, DiCE, Wachter, prototypes, MILP, trade-offs
communicating-recourse.mdwording, regulation, fairness of recourse, audits
More in Classical Machine Learning

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.