Skip to content

Counterfactuals in Analyze: what would change the prediction?

A counterfactual is a small change to a row that moves a saved model's prediction across its target. Find several with DiCE, keep them to changes a person could make, and read the card.

Advanced ~12 min9 steps

What runs in CodeSplash

You will be able to

  • Say what a counterfactual explanation is and what it does not claim
  • Tell DiCE's several different options from the greedy smallest change
  • Limit options to feasible changes with fixed, increase-only, decrease-only and allowed values
  • Read the share of rows with a change, the features changed per option and the distance between options

Read first

01

The question a person asks

Read

Anchors say what keeps a prediction where it is. A counterfactualCounterfactual explanationThe smallest feature changes that would move this row's prediction across its target. answers the question people actually ask about a decision: what would have to be different for the model to say something else? "If glucose were 118 instead of 151, this model would no longer flag the person."

For a classifier, a change counts only when it flips the label the model gives the row. A row is labeled positive when its probability is at least the decision threshold, so a row that scores exactly 0.5 is already positive and needs a change that takes it below 0.5. If you committed a threshold on the model's Evaluation tab, the search uses that one, the same threshold scoring uses.

02

Several ways, not one

Predict

Predict first

DiCE returns several counterfactuals per row, picked to be far from each other. Why several?

So the person can pick a change they could actually makeBecause one counterfactual is always wrongTo average them into a single answer
Reveal

So there is a change the person can act on. One smallest change may touch something nobody can change. Diverse counterfactualsDiverse counterfactualsSeveral different changes that would each move a prediction across its target, chosen to be close to the row and far apart. offer different routes to the target: each is valid on its own, close to the row, and unlike the others.

03

Read the card

Explore

For a tree model on the Pima rows, three rows get 3.0 options each on average, and 1.00 of the rows have at least one. An option changes 1.1 features on average, at a mean distance of 0.32 (each numeric change over the feature's training range, plus 1 per changed category). glu is the feature the options change most often.

Counterfactuals for a saved model (DiCE) — learn.tree/binary_pimaRecorded · Python and R agreeRecorded 2026-11-25 · 58 values compared
R

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

RowOptionScore nowScore afterChangesDistance
29710.06060.8000ped: 0.089 → 0.9050.3495
29720.06060.6000age: 24 → 47.5; glu: 117 → 130.50.4874
29730.06060.6667glu: 117 → 169.50.3723
45410.80000.3750bmi: 30.1 → 29.250.0174
45420.80000glu: 143 → 84.50.4149
45430.80000.2593ped: 0.892 → 0.16650.3107
51110.25931glu: 141 → 169.50.2021
51120.25931age: 22 → 47.50.4250
51130.25931bp: 84 → 580.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.
The exact R script · R 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")
))
Python

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

RowOptionScore nowScore afterChangesDistance
29710.06060.8000ped: 0.089 → 0.9050.3495
29720.06060.6000age: 24 → 47.5; glu: 117 → 130.50.4874
29730.06060.6667glu: 117 → 169.50.3723
45410.80000.3750bmi: 30.1 → 29.250.0174
45420.80000glu: 143 → 84.50.4149
45430.80000.2593ped: 0.892 → 0.16650.3107
51110.25931glu: 141 → 169.50.2021
51120.25931age: 22 → 47.50.4250
51130.25931bp: 84 → 580.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.
The exact Python script · Python 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"),
    )
)
04

Changes a person could make

Explore

Nobody can lower their age or their number of pregnancies. Hold them fixed, let glucose and BMI only fall, and keep blood pressure between 50 and 90 — the limitsLimits on changesFeatures an option may never change, may only raise or lower, or may set only to some values; others are never tried. are applied before any candidate is tried, so impossible changes never appear. With these limits 1.00 of the rows still have a change, now changing 1.0 features per option.

Counterfactuals for a saved model (DiCE) — learn.tree/binary_pimaRecorded · Python and R agreeRecorded 2026-11-25 · 49 values compared
R

For 3 of 3 rows the model's P(true) can be moved across its target: 2.0 different options per row on average, each changing 1.0 features (mean distance 0.28); ped changes most often.

Rows with a change found
1
Options per row
2
Features changed per option
1
Mean distance from the row
0.2831
Mean distance between options
0.4999

Assumptions

  • A change found for every row — 3 of 3 rows.
  • Several different options — 2 of 3 rows got fewer than 3 options: few distinct valid changes were left; draw more candidates.
  • 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

RowOptionScore nowScore afterChangesDistance
29710.06060.8000ped: 0.089 → 0.9050.3495
45410.80000.3750bmi: 30.1 → 29.250.0174
45420.80000glu: 143 → 84.50.4149
45430.80000.2593ped: 0.892 → 0.16650.3107
51110.25930.8000ped: 0.433 → 0.9050.2021
51120.25931bp: 84 → 580.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. Held fixed: age, npreg. Allowed changes: only down: glu, bmi; bp in [50, 90].
The exact R script · R 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 e8afc36ee56e9174
# 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\"},\"cfDecrease\":[\"glu\",\"bmi\"],\"cfGrid\":9,\"cfMaxChanges\":4,\"cfRanges\":[\"bp:50:90\"],\"cfRows\":3,\"diceCandidates\":200,\"diceCount\":3,\"diceDiversity\":\"maxmin\",\"diceProximity\":0.5,\"diceRows\":3,\"immutable\":[\"age\",\"npreg\"],\"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")
))
Python

For 3 of 3 rows the model's P(true) can be moved across its target: 2.0 different options per row on average, each changing 1.0 features (mean distance 0.28); ped changes most often.

Rows with a change found
1
Options per row
2
Features changed per option
1
Mean distance from the row
0.2831
Mean distance between options
0.4999

Assumptions

  • A change found for every row — 3 of 3 rows.
  • Several different options — 2 of 3 rows got fewer than 3 options: few distinct valid changes were left; draw more candidates.
  • 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

RowOptionScore nowScore afterChangesDistance
29710.06060.8000ped: 0.089 → 0.9050.3495
45410.80000.3750bmi: 30.1 → 29.250.0174
45420.80000glu: 143 → 84.50.4149
45430.80000.2593ped: 0.892 → 0.16650.3107
51110.25930.8000ped: 0.433 → 0.9050.2021
51120.25931bp: 84 → 580.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. Held fixed: age, npreg. Allowed changes: only down: glu, bmi; bp in [50, 90].
The exact Python script · Python 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 e8afc36ee56e9174
# 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\"},\"cfDecrease\":[\"glu\",\"bmi\"],\"cfGrid\":9,\"cfMaxChanges\":4,\"cfRanges\":[\"bp:50:90\"],\"cfRows\":3,\"diceCandidates\":200,\"diceCount\":3,\"diceDiversity\":\"maxmin\",\"diceProximity\":0.5,\"diceRows\":3,\"immutable\":[\"age\",\"npreg\"],\"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"),
    )
)
06

When nothing works

Reflect

A baseline model that gives every row the same class probabilities can't be moved by any change. The card says no row got one (0 of the rows), and its first check fails. What would you tell someone whose decision came from a model like that?

Counterfactuals for a saved model (DiCE) — learn.dummy/multiclass_most_frequentRecorded · Python and R agreeRecorded 2026-11-25 · 26 values compared
R

No change of at most 4 features moves the model's P(Gentoo) across its target for these 2 rows.

Rows with a change found
0
Options per row
0
Features changed per option
—
Mean distance from the row
—
Mean distance between options
—

Assumptions

  • A change found for every row — 0 of 2 rows; no change of at most 4 features reaches the target for the others. Allow more changes or fewer constraints.
  • Several different options — No row has a change, so there are no options to compare.
  • Features vary independently — No pair of numeric features to compare.
  • Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.

Different ways to move the P(Gentoo) across its target

RowOptionScore nowScore afterChangesDistance
128—0—No valid change found—
296—0—No valid change found—
  • 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.
The exact R script · R 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 f23502f6c5f51d04
# Explains the saved model learn.dummy/multiclass_most_frequent with its own learner code (learn.dummy 1.0.1, driver mode "explain").
# Baseline (no features)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.dummy 1.0.1 · spec 924044f687a25953
# Dataset: ml_penguins (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 <- "species"
FEATURES <- c("island")
TASK <- "multiclass"
CLASSES <- c("Adelie", "Chinstrap", "Gentoo")
POSITIVE <- NULL
METRIC <- "accuracy"
SEED <- 42
PARAMS <- list(
  regression_strategy = "mean",
  class_strategy = "most_frequent"
)

df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.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(
    island = "categorical"
  ),
  levels = list(
    island = c("Biscoe", "Dream", "Torgersen")
  ),
  impute = "none",
  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
# Baselines that ignore the features (scikit-learn's DummyRegressor / DummyClassifier rules): the
# training mean (weighted) or median, or the weighted class shares / the most frequent class (ties to
# the first class).
fit_model <- function(X, y, w) {
  w <- if (is.null(w)) rep(1, length(y)) else w
  if (TASK == "regression") {
    value <- if (PARAMS$regression_strategy == "median") stats::median(y) else sum(w * y) / sum(w)
    return(list(value = value))
  }
  k <- if (TASK == "binary") 2L else length(CLASSES)
  share <- vapply(seq_len(k) - 1L, function(c) sum(w[y == c]), numeric(1))
  share <- share / sum(share)
  if (PARAMS$class_strategy == "most_frequent") {
    top <- which.max(share)
    share <- rep(0, k); share[top] <- 1
  }
  list(value = share)
}

predict_model <- function(model, X) {
  n <- nrow(X)
  if (TASK == "regression") return(rep(model$value, n))
  if (TASK == "binary") return(rep(model$value[2], n))
  matrix(model$value, nrow = n, ncol = length(model$value), byrow = TRUE)
}

feature_importance <- function(model, names) NULL

save_model <- function(model, directory) {
  path <- file.path(directory, "model.rds")
  saveRDS(model, path)
  list(list(key = "model", path = path, format = "rds"))
}

load_model <- function(directory) readRDS(file.path(directory, "model.rds"))

# %% Explain the model
REQUEST <- jsonlite::fromJSON("{\"analyze\":{\"kind\":\"counterfactual\",\"method\":\"explain.counterfactual\",\"model\":\"learn.dummy/multiclass_most_frequent\",\"title\":\"Counterfactuals for a saved model (DiCE)\",\"version\":\"1.1.0\"},\"cfGrid\":9,\"cfMaxChanges\":4,\"cfRows\":2,\"class\":\"Gentoo\",\"diceCandidates\":30,\"diceCount\":3,\"diceDiversity\":\"maxmin\",\"diceProximity\":0.5,\"diceRows\":2,\"maxRows\":2,\"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 = "Baseline (no features)",
  engine = cs_engine_info("stats", "nanoparquet")
))
Python

No change of at most 4 features moves the model's P(Gentoo) across its target for these 2 rows.

Rows with a change found
0
Options per row
0
Features changed per option
—
Mean distance from the row
—
Mean distance between options
—

Assumptions

  • A change found for every row — 0 of 2 rows; no change of at most 4 features reaches the target for the others. Allow more changes or fewer constraints.
  • Several different options — No row has a change, so there are no options to compare.
  • Features vary independently — No pair of numeric features to compare.
  • Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.

Different ways to move the P(Gentoo) across its target

RowOptionScore nowScore afterChangesDistance
128—0—No valid change found—
296—0—No valid change found—
  • 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.
The exact Python script · Python 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 f23502f6c5f51d04
# Explains the saved model learn.dummy/multiclass_most_frequent with its own learner code (learn.dummy 1.0.1, driver mode "explain").
# Baseline (no features)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.dummy 1.0.1 · spec 924044f687a25953
# Dataset: ml_penguins (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 sklearn.dummy import DummyClassifier, DummyRegressor

# %% Data and split plan
TARGET = "species"
FEATURES = ["island"]
TASK = "multiclass"
CLASSES = ["Adelie", "Chinstrap", "Gentoo"]
POSITIVE = None
METRIC = "accuracy"
SEED = 42
PARAMS = {
    "regression_strategy": "mean",
    "class_strategy": "most_frequent",
}

df = pd.read_parquet("tests/parity/fixtures/ml_penguins.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={
        "island": "categorical",
    },
    levels={
        "island": ["Biscoe", "Dream", "Torgersen"],
    },
    impute="none",
    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
# Baselines that ignore the features: the training mean/median, or the class shares / the most
# frequent class (ties → the first class).


def fit_model(X, y, w):
    if TASK == "regression":
        model = DummyRegressor(strategy=PARAMS["regression_strategy"])
    else:
        model = DummyClassifier(strategy=PARAMS["class_strategy"])
    return model.fit(X, y, sample_weight=w)


def predict_model(model, X):
    if TASK == "regression":
        return model.predict(X)
    if TASK == "binary":
        return csml.full_proba(model, X, 2)[:, 1]
    return csml.full_proba(model, X, len(CLASSES))


def feature_importance(model, names):
    return None


def save_model(model, directory):
    import joblib

    path = os.path.join(directory, "model.joblib")
    joblib.dump(model, path)
    return [{"key": "model", "path": path, "format": "joblib"}]


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.dummy/multiclass_most_frequent\",\"title\":\"Counterfactuals for a saved model (DiCE)\",\"version\":\"1.1.0\"},\"cfGrid\":9,\"cfMaxChanges\":4,\"cfRows\":2,\"class\":\"Gentoo\",\"diceCandidates\":30,\"diceCount\":3,\"diceDiversity\":\"maxmin\",\"diceProximity\":0.5,\"diceRows\":2,\"maxRows\":2,\"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="Baseline (no features)",
        engine=cs.engine_info("scikit-learn", "numpy", "pandas"),
    )
)
07

Describes the model, not the world

Read

A counterfactual says what this model would predict for a changed row. It doesn't say that changing the feature in real life would change the outcome — glucose may fall for reasons that also change other features — and options that change one feature while keeping a related one can describe people who don't exist. Read them as a statement about the model, and check the card's Features vary independently row.

08

The code behind it

Read
Python
# The distance DiCE keeps small: numeric changes over the feature's training range, plus 1 per changed category.
def distance(row, option, ranges, numeric):
    total = 0.0
    for feature, new in option.items():
        total += abs(new - row[feature]) / ranges[feature] if feature in numeric else float(new != row[feature])
    return total
R
# The distance DiCE keeps small: numeric changes over the feature's training range, plus 1 per changed category.
distance <- function(row, option, ranges, numeric) {
  total <- 0
  for (feature in names(option)) {
    new <- option[[feature]]
    total <- total + if (feature %in% numeric) abs(new - row[[feature]]) / ranges[[feature]] else as.numeric(new != row[[feature]])
  }
  total
}
09

Check your understanding

Checkpoint

Check yourself

An option says: "glucose 151 → 118 and the model no longer flags this person." What does it show?

Show the answer

Answer: a

A statement about the model. A counterfactual describes the model's behavior near one row. Whether the change would alter the real outcome is a causal question it can't answer.

Check yourself

The options keep suggesting a smaller number of pregnancies. How do you stop that?

Show the answer

Answer: a

Say which changes are possible. Fixed features are never drawn, so no option changes them. More candidates or another search would still try them.

Check yourself

The card's "A change found for every row" check warns that two of five rows got no change. What is a sensible next step?

Show the answer

Answer: a

The search has limits. No change was found within the most features changed and the limits you set. Allowing more changes, more candidates or fewer limits widens the search; a model that truly can't be moved (like a baseline) fails for every row.

Concepts in this lesson