DRegression models · explain.counterfactual
Counterfactuals for a saved model (DiCE)
For each row, which small changes would move a saved model's prediction across its target, and which different ways are there to get there?
Finds counterfactual explanations for rows of a registered model version: changes to a row's feature values that would move its prediction across the target (the other side of the decision threshold for a classifier, so its label flips: 0.5, or the threshold committed on a binary model's Evaluation tab; one SD further for a numeric prediction, or a target you set). By default it gives several different options per row in the style of DiCE (Mothilal, Sharma & Tan 2020): candidate changes drawn at random, kept when they reach the target, stripped of the changes they don't need, then picked to be close to the row and far from each other. The greedy search, which adds the single most useful change at a time, is one option away. You can hold features fixed, let some only rise or only fall, and limit the values a feature may take, so the options stay ones a person could act on. It runs the model's own code in the engine that trained it; the ML Studio Explain tab runs the same searches for a run.
A real result
Example “Dice tree pima”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
For 3 of 3 rows the model's P(true) can be moved across its target: 3.0 different options per row on average, each changing 1.1 features (mean distance 0.32); glu changes most often.
- Rows with a change found
- 1
- Options per row
- 3
- Features changed per option
- 1.111
- Mean distance from the row
- 0.3202
- Mean distance between options
- 0.6191
Assumptions
- A change found for every row — 3 of 3 rows.
- Several different options — Every row with a change has 3 options.
- Features vary independently — skin and bmi: |ρ| = 0.69.
- Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.
Different ways to move the P(true) across its target
| Row | Option | Score now | Score after | Changes | Distance |
|---|---|---|---|---|---|
| 297 | 1 | 0.0606 | 0.8000 | ped: 0.089 → 0.905 | 0.3495 |
| 297 | 2 | 0.0606 | 0.6000 | age: 24 → 47.5; glu: 117 → 130.5 | 0.4874 |
| 297 | 3 | 0.0606 | 0.6667 | glu: 117 → 169.5 | 0.3723 |
| 454 | 1 | 0.8000 | 0.3750 | bmi: 30.1 → 29.25 | 0.0174 |
| 454 | 2 | 0.8000 | 0 | glu: 143 → 84.5 | 0.4149 |
| 454 | 3 | 0.8000 | 0.2593 | ped: 0.892 → 0.1665 | 0.3107 |
| 511 | 1 | 0.2593 | 1 | glu: 141 → 169.5 | 0.2021 |
| 511 | 2 | 0.2593 | 1 | age: 22 → 47.5 | 0.4250 |
| 511 | 3 | 0.2593 | 1 | bp: 84 → 58 | 0.3023 |
- Diverse counterfactuals are several different changes that would each move this model's prediction across its target, picked to be close to the row and far from each other. They describe the model, not what would happen in the world.
For 3 of 3 rows the model's P(true) can be moved across its target: 3.0 different options per row on average, each changing 1.1 features (mean distance 0.32); glu changes most often.
- Rows with a change found
- 1
- Options per row
- 3
- Features changed per option
- 1.111
- Mean distance from the row
- 0.3202
- Mean distance between options
- 0.6191
Assumptions
- A change found for every row — 3 of 3 rows.
- Several different options — Every row with a change has 3 options.
- Features vary independently — skin and bmi: |ρ| = 0.69.
- Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.
Different ways to move the P(true) across its target
| Row | Option | Score now | Score after | Changes | Distance |
|---|---|---|---|---|---|
| 297 | 1 | 0.0606 | 0.8000 | ped: 0.089 → 0.905 | 0.3495 |
| 297 | 2 | 0.0606 | 0.6000 | age: 24 → 47.5; glu: 117 → 130.5 | 0.4874 |
| 297 | 3 | 0.0606 | 0.6667 | glu: 117 → 169.5 | 0.3723 |
| 454 | 1 | 0.8000 | 0.3750 | bmi: 30.1 → 29.25 | 0.0174 |
| 454 | 2 | 0.8000 | 0 | glu: 143 → 84.5 | 0.4149 |
| 454 | 3 | 0.8000 | 0.2593 | ped: 0.892 → 0.1665 | 0.3107 |
| 511 | 1 | 0.2593 | 1 | glu: 141 → 169.5 | 0.2021 |
| 511 | 2 | 0.2593 | 1 | age: 22 → 47.5 | 0.4250 |
| 511 | 3 | 0.2593 | 1 | bp: 84 → 58 | 0.3023 |
- Diverse counterfactuals are several different changes that would each move this model's prediction across its target, picked to be close to the row and far from each other. They describe the model, not what would happen in the world.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Dice tree pimaml_pima ·
- Dice knn airqualityml_airquality ·
- Dice mlp penguinsml_penguins ·
- Greedy tree pimaml_pima ·
- Constraints tree pimaml_pima ·
- Dpp tree pimaml_pima ·
- Greedy target knn airqualityml_airquality ·
- Constant model dummyml_penguins ·
In the guides
Where it sits in the decision guides
- Interpretable ML (trees, GAMs, SHAP, LIME) · DS & ML Decision Guide · Explain — why is it happening?
Choices you make
statistics
- Modeldefault —
The registered model version to explain. It runs in the engine that trained it, on this dataset's rows.
- Rows to explaindefault 5
The first rows of the explained sample each get their own changes. Multiclass models explain rows not yet in the class.
- Searchdefault dice
How the changes are found.
- Several different options (DiCE)(default) — Draws candidate changes, keeps the ones that reach the target and picks options close to the row and far from each other.
- One smallest change (greedy) — Adds the change that moves the prediction most per unit of distance until it reaches the target.
- Options per rowdefault 3
How many different options each row gets (DiCE search).
options
- Most features changeddefault 4
The most features one option may change.
- Never changedefault —
Features no option may change, separated by commas (for example age, sex).
- Only increasedefault —
Numeric features options may only raise, separated by commas.
- Only decreasedefault —
Numeric features options may only lower, separated by commas.
- Allowed valuesdefault —
Limits per feature, separated by semicolons: glu:70:140 for a number range, type=a|b for the levels a category may take.
- Target for numeric predictionsdefault —
The prediction a numeric model should reach. Empty: one SD above the row's own (one SD lower risk for survival models).
- Background datadefault model
Where candidate values and feature ranges come from.
- The model's training sample(default) — Rows saved with the model version.
- These rows — This dataset's rows.
Advanced
- Diversitydefault maxmin
How DiCE spreads the options apart.
- Farthest from the nearest option(default) — Each next option is the valid candidate farthest from the options already picked, less the closeness weight times its distance.
- Determinant of distances (DiCE) — Each next option maximizes the determinant of the options' inverse-distance kernel, as DiCE's own diversity term.
- Closeness weightdefault 0.5
How much distance from the row counts against an option when DiCE spreads options apart.
- Candidates per rowdefault 200
Random candidate changes DiCE scores for each row; more find more options and take longer.
- Values tried per featuredefault 9
New values come from this many training quantiles of each numeric feature (categories try their levels).
- Class to explaindefault —
Multiclass models: the class whose probability should cross 0.5, empty for the first class.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
A change found for every row
Each row should get at least one change that reaches the target within the most features changed; otherwise allow more changes or fewer constraints.
- If violated → More changes and candidates — Allowing more features to change and drawing more candidates reaches the target for more rows.
Several different options
DiCE should find as many distinct options as asked; fewer means few valid changes were left after removing duplicates.
- If violated → More candidates — More random candidates leave more distinct valid changes to pick from.
Features vary independently
Options change some features and keep the rest, so related features (weight and BMI) can end up in combinations that never occur.
Rows resemble the training data
Changes for rows outside the training range describe extrapolation, not learned patterns.
What it reports
- n_explained
- Rows of this dataset the search looked at, the training rows standing for the data, and the features the model reads.
- n_background
- Rows of this dataset the search looked at, the training rows standing for the data, and the features the model reads.
- n_features
- Rows of this dataset the search looked at, the training rows standing for the data, and the features the model reads.
- cf_search
- dice: several options from random candidates (the default); greedy: one smallest change, adding the most useful change at a time.
- cf_n
- Share of the explained rows for which some change moves the prediction across its target within the most features allowed.
- cf_found_share
- Share of the explained rows for which some change moves the prediction across its target within the most features allowed.
- cf_options_mean
- Average number of different changes found per explained row; the greedy search finds at most one.
- cf_changes_mean
- Mean number of features each of a row's options changes; fewer changes are easier to act on.
- cf_distance_mean
- How far an option moves the row: each numeric change over the feature's training range, plus 1 per changed category.
- top_feature
- The feature the most options change, and the share of options that change it.
- top_value
- The feature the most options change, and the share of options that change it.
- max_abs_corr
- The largest |Spearman ρ| between two numeric features in the background rows; above 0.7 the card warns that features move together.
- outside_share
- Asking a model about feature combinations it never saw, as shuffling or fixing a correlated feature does; answers are guesses, not patterns.
- score_label
- What the changes move across its target: P(class) past 0.5, or a numeric prediction to the target you set (one SD by default).
Per group, level or term: cf_diversity_mean, cf_valid_share_mean, dice_found[<row>], dice_valid_share[<row>], dice_diversity[<row>], dice_proximity[<row>], dice_sparsity[<row>], dice_after[<row>|<option>], dice_distance[<row>|<option>], dice_changes[<row>|<option>], cf_before[<row>], cf_after[<row>], cf_reached[<row>], cf_changes[<row>], cf_distance[<row>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses codesplash, numpy, pandas; R uses codesplashr, nanoparquet.
Default traps between the two languages
- The search runs the saved model's own learner code in each engine, so the engines agree as closely as their models do. DiCE's candidates come from the shared Wichmann–Hill stream (seed + 21, one stream across rows) in the same order, candidate values are the same type-7 training quantiles, and every pick breaks ties by distance rounded to 10 decimals and then draw order, so with the same predictions both engines keep the same options.
- The reference DiCE (dice-ml) draws candidate values uniformly from a feature's range and repairs sparsity by moving each feature back toward the row in steps; here values are training quantiles or levels, and unneeded changes are dropped in one backward pass (last drawn first). Both keep options valid; they can differ in which options they find.
The exact script CodeSplash ran for example “Dice tree pima” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Counterfactuals for a saved model (DiCE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.counterfactual 1.1.0 · spec 78db835db0d34eaa
# Explains the saved model learn.tree/binary_pima with its own learner code (learn.tree 1.0.0, driver mode "explain").
# Decision tree (CART)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.tree 1.0.0 · spec 2c9409d7e5211ff1
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml.tree import CART, tree_json
# %% Data and split plan
TARGET = "diabetic"
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
TASK = "binary"
CLASSES = ["false", "true"]
POSITIVE = "true"
METRIC = "roc_auc"
SEED = 42
PARAMS = {
"max_depth": 6,
"min_samples_split": 10,
"min_samples_leaf": 5,
"criterion": "gini",
"min_impurity_decrease": 0,
"ccp_alpha": 0,
}
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("model-python/folds.parquet") # host-written folds: identical in Python and R
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"npreg": "numeric",
"glu": "numeric",
"bp": "numeric",
"skin": "numeric",
"bmi": "numeric",
"ped": "numeric",
"age": "numeric",
},
levels={
},
impute="median",
scale="none",
indicators=False,
)
y, y_index = csml.encode_target(df[TARGET], TASK, CLASSES, POSITIVE)
weights = csml.class_weights(y_index, TASK, "none", plan.train)
run = csml.LearnerRun(TASK, CLASSES, POSITIVE, METRIC)
out = csml.out_dir("explain-out-python")
warnings = []
def sample_weights(rows):
return None if weights is None else weights[rows]
# %% Model
# CART with scikit-learn's DecisionTree rules and a deterministic split search (features in design
# order) — the codesplash twin, identical in Python and R.
def fit_model(X, y, w):
k = 0 if TASK == "regression" else (2 if TASK == "binary" else len(CLASSES))
model = CART(
TASK,
k,
criterion=PARAMS["criterion"],
max_depth=PARAMS["max_depth"],
min_samples_split=int(PARAMS["min_samples_split"]),
min_samples_leaf=int(PARAMS["min_samples_leaf"]),
min_impurity_decrease=PARAMS["min_impurity_decrease"],
ccp_alpha=PARAMS["ccp_alpha"],
)
return model.fit(X, y, w)
def predict_model(model, X):
p = model.predict(X)
return p[:, 1] if TASK == "binary" else p
def feature_importance(model, names):
return model.importances(names)
def save_model(model, directory):
import joblib
path = os.path.join(directory, "model.joblib")
joblib.dump(model, path)
if TASK == "binary":
classes = [[c for c in CLASSES if c != POSITIVE][0], POSITIVE] # probabilities: [other, positive]
else:
classes = CLASSES or None
return [{"key": "model", "path": path, "format": "joblib"}, tree_json(directory, model, names, classes)]
def load_model(directory):
import joblib
return joblib.load(os.path.join(directory, "model.joblib"))
# %% Explain the model
import json
from codesplash.ml import explain as csx
REQUEST = json.loads("{\"analyze\":{\"kind\":\"counterfactual\",\"method\":\"explain.counterfactual\",\"model\":\"learn.tree/binary_pima\",\"title\":\"Counterfactuals for a saved model (DiCE)\",\"version\":\"1.1.0\"},\"cfGrid\":9,\"cfMaxChanges\":4,\"cfRows\":3,\"diceCandidates\":200,\"diceCount\":3,\"diceDiversity\":\"maxmin\",\"diceProximity\":0.5,\"diceRows\":3,\"maxRows\":3,\"methods\":[\"dice\"],\"modelDir\":\"model-python/out\",\"rows\":\"auto\"}") or {}
model_dir = REQUEST.get("modelDir") or out
with open(os.path.join(model_dir, "design.json"), encoding="utf-8") as fh:
prep = csml.FittedDesign.from_json(fh.read())
model = load_model(model_dir)
explainer = csx.Explainer(predict_model, model, prep, TASK, CLASSES, POSITIVE, METRIC, cls=REQUEST.get("class"))
rows = csx.explain_rows(plan, REQUEST.get("rows") or "auto", int(REQUEST.get("maxRows") or 1000), SEED)
cs.publish(
csx.explain(
explainer,
df,
rows,
plan.train,
y,
y_index,
REQUEST,
SEED,
model_dir,
out,
warnings=warnings,
title="Decision tree (CART)",
engine=cs.engine_info("numpy", "numpy", "pandas"),
)
)
The exact script CodeSplash ran for example “Dice tree pima” · R version 4.5.1 (2025-06-13)
# Counterfactuals for a saved model (DiCE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.counterfactual 1.1.0 · spec 78db835db0d34eaa
# Explains the saved model learn.tree/binary_pima with its own learner code (learn.tree 1.0.0, driver mode "explain").
# Decision tree (CART)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.tree 1.0.0 · spec 2c9409d7e5211ff1
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data and split plan
TARGET <- "diabetic"
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
TASK <- "binary"
CLASSES <- c("false", "true")
POSITIVE <- "true"
METRIC <- "roc_auc"
SEED <- 42
PARAMS <- list(
max_depth = 6,
min_samples_split = 10,
min_samples_leaf = 5,
criterion = "gini",
min_impurity_decrease = 0,
ccp_alpha = 0
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("model-r/folds.parquet") # host-written folds: identical in Python and R
design <- cs_ml_design(
df, FEATURES,
kinds = list(
npreg = "numeric",
glu = "numeric",
bp = "numeric",
skin = "numeric",
bmi = "numeric",
ped = "numeric",
age = "numeric"
),
levels = list(
),
impute = "median",
scale = "none",
indicators = FALSE
)
target <- cs_ml_encode_target(df[[TARGET]], TASK, CLASSES, POSITIVE)
y <- target$fit
y_index <- target$index
weights <- cs_ml_class_weights(y_index, TASK, "none", plan$train)
run <- cs_ml_run(TASK, CLASSES, POSITIVE, METRIC)
out <- cs_ml_out_dir("explain-out-r")
warnings <- list()
sample_weights <- function(rows) if (is.null(weights)) NULL else weights[rows + 1L]
rows_of <- function(rows) df[rows + 1L, , drop = FALSE]
# %% Model
# CART with scikit-learn's DecisionTree rules and a deterministic split search (features in design
# order) — the codesplash twin, identical in R and Python (rpart differs: surrogates, cp scaling,
# internal cross-validation).
fit_model <- function(X, y, w) {
k <- if (TASK == "regression") 0L else if (TASK == "binary") 2L else length(CLASSES)
cs_ml_cart_fit(X, y, TASK, k, criterion = PARAMS$criterion, max_depth = PARAMS$max_depth,
min_samples_split = as.integer(PARAMS$min_samples_split),
min_samples_leaf = as.integer(PARAMS$min_samples_leaf),
min_impurity_decrease = PARAMS$min_impurity_decrease, ccp_alpha = PARAMS$ccp_alpha, w = w)
}
predict_model <- function(model, X) {
p <- cs_ml_cart_predict(model, X)
if (TASK == "binary") p[, 2] else p
}
feature_importance <- function(model, names) cs_ml_cart_importances(model, names)
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path)
classes <- if (TASK == "binary") c(setdiff(CLASSES, POSITIVE)[1], POSITIVE) else if (length(CLASSES)) CLASSES else NULL
list(list(key = "model", path = path, format = "rds"), cs_ml_tree_json(directory, model, names_, classes))
}
load_model <- function(directory) readRDS(file.path(directory, "model.rds"))
# %% Explain the model
REQUEST <- jsonlite::fromJSON("{\"analyze\":{\"kind\":\"counterfactual\",\"method\":\"explain.counterfactual\",\"model\":\"learn.tree/binary_pima\",\"title\":\"Counterfactuals for a saved model (DiCE)\",\"version\":\"1.1.0\"},\"cfGrid\":9,\"cfMaxChanges\":4,\"cfRows\":3,\"diceCandidates\":200,\"diceCount\":3,\"diceDiversity\":\"maxmin\",\"diceProximity\":0.5,\"diceRows\":3,\"maxRows\":3,\"methods\":[\"dice\"],\"modelDir\":\"model-r/out\",\"rows\":\"auto\"}", simplifyVector = FALSE)
if (is.null(REQUEST)) REQUEST <- list()
model_dir <- if (is.null(REQUEST$modelDir)) out else REQUEST$modelDir
prep <- cs_ml_design_from_json(paste(readLines(file.path(model_dir, "design.json"), warn = FALSE), collapse = "\n"))
# S3 predict methods (ranger, e1071, …) need their package's namespace loaded.
for (pkg in c("stats")) {
suppressWarnings(suppressPackageStartupMessages(requireNamespace(pkg, quietly = TRUE)))
}
model <- load_model(model_dir)
explainer <- cs_ml_explainer(predict_model, model, prep, TASK, CLASSES, POSITIVE, METRIC, cls = REQUEST$class)
rows <- cs_ml_explain_rows(plan, if (is.null(REQUEST$rows)) "auto" else REQUEST$rows,
as.integer(if (is.null(REQUEST$maxRows)) 1000 else REQUEST$maxRows), SEED)
cs_publish(cs_ml_explain(
explainer, df, rows, plan$train, y, y_index, REQUEST, SEED, model_dir, out,
warnings = warnings,
title = "Decision tree (CART)",
engine = cs_engine_info("stats", "nanoparquet")
))
Sources
- Mothilal, R. K., Sharma, A., & Tan, C. (2020). Explaining machine learning classifiers through diverse counterfactual explanations. Proceedings of FAT* 2020, 607–617.
- Wachter, S., Mittelstadt, B., & Russell, C. (2018). Counterfactual explanations without opening the black box: Automated decisions and the GDPR. Harvard Journal of Law & Technology, 31(2), 841–887.
- Karimi, A.-H., Barthe, G., Schölkopf, B., & Valera, I. (2022). A survey of algorithmic recourse: Contrastive explanations and consequential recommendations. ACM Computing Surveys, 55(5), 95.
- Molnar, C. (2022). Interpretable Machine Learning (2nd ed.), ch. 9.3 Counterfactual explanations.
From the CodeSplash method registry · explain.counterfactual v1.1.0.