Skip to content

Rules and recourse: anchors and diverse counterfactuals

Two explanations you can read as rules: an anchor (conditions that keep a prediction) and counterfactuals (changes that flip it). Learn the bounds behind anchors, the objective behind DiCE, and why neither is advice.

Advanced ~14 min10 steps

What runs in CodeSplash

You will be able to

  • Define an anchor's precision and coverage, and why its search needs confidence bounds
  • Write DiCE's objective of validity, proximity and diversity
  • Explain feasibility constraints and why a counterfactual isn't a recommendation

Read first

01

Two readable answers

Read

Attribution scores are hard to act on. Two explainers answer in rules instead:

  • An anchor says: as long as these conditions hold, the model almost always gives this prediction, for example "glucose > 150 and age > 40 → high risk".
  • A counterfactual says: this change would have flipped the prediction, for example "with glucose below 120, the prediction would be low risk".

One describes what holds a prediction in place, the other what moves it.

02

Anchors: precision and coverage

Read

An anchorAnchorA short rule built from a row's own values that keeps its prediction for most rows that satisfy it. AA is a rule on the row's own values. With perturbed rows ZZ drawn to satisfy the rule,

prec(A)=Pr⁡Z{f(Z)=f(x)∣A(Z)=1},cov(A)=Pr⁡Z{A(Z)=1}.\mathrm{prec}(A)=\Pr_Z\{f(Z)=f(x)\mid A(Z)=1\},\qquad \mathrm{cov}(A)=\Pr_Z\{A(Z)=1\}.

The search looks for a short rule with precisionAnchor precisionShare of training rows satisfying an anchor that get the same prediction as the explained row. above a target (often 0.95) and as much coverageAnchor coverageShare of all training rows that satisfy an anchor; short rules cover more rows. as possible. A rule matching only the row itself has perfect precision and useless coverage.

Reference · EXP016 · Runs in CodeSplashAnchors: high-precision rule explanationsFind an interpretable rule whose satisfaction makes a model’s prediction stable with high precision under a declared perturbation distribution, while seeking useful coverage.
03

Why the bound matters

Read

Precision is estimated from samples, and the search tries many rules, so a rule can pass by luck. Anchors accept a rule only when a lower confidence bound on its precision clears the target. In the reference's example 198 of 200 samples agree, an estimate of 0.99, with a lower bound of 0.969: it passes a fixed check at 0.95.

But one post-selection interval isn't a guarantee for the whole search; adaptive bounds (KL-LUCB in beam search) spend the confidence budget across candidates. And high precision means the model keeps its answer, not that the answer is right.

04

Anchors in CodeSplash

Read

Anchors for a saved model runs greedy or beam search with confidence bounds on perturbation samples.

Anchors for a saved model — learn.tree/binary_pimaRecorded · Python and R agreeRecorded 2026-11-25 · 46 values compared
R

Across 3 rows, anchors of 3.7 conditions on average hold the prediction with mean precision 0.94 and cover 1% of the training rows; 67% reach 95% with confidence.

Mean precision
0.9395
Mean coverage
0.0110

Assumptions

  • Rules reach the precision — 67% of the 3 rules are above 95% with confidence; the others are the most precise rules found within the limits.
  • Within the sampling budget — 28900 model calls in all; 2 rows used the whole budget, so their bounds are rough.
  • 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.

Anchors: rules that hold the prediction in place (beam search)

RowPredictionRulePrecisionPrecision, lower boundCoverageModel calls
297false114 < glu ≤ 142 AND ped ≤ 0.254 AND age ≤ 240.98170.93510.01888,900
454truenpreg ≤ 1 AND glu > 142 AND bp > 80 AND ped > 0.65950.83670.62310.009410,000
511false114 < glu ≤ 142 AND 22 < skin ≤ 29 AND 0.399 < ped ≤ 0.6595 AND age ≤ 2410.90320.004710,000
  • Precision is the share of perturbed rows that keep the rule and get the row's predicted class: each perturbed row is a training row whose values that break the rule are swapped for values that keep it. Coverage is the share of the 426 training rows that satisfy the rule. The search stops when a confidence bound says the precision is above 95%. Anchors describe this model's behavior, not causes.
The exact R script · R R version 4.5.1 (2025-06-13)
# Anchors for a saved model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.anchors 1.1.0 · spec 84d51cab0d7f96e1
# 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\":\"anchors\",\"method\":\"explain.anchors\",\"model\":\"learn.tree/binary_pima\",\"title\":\"Anchors for a saved model\",\"version\":\"1.1.0\"},\"anchorBatch\":100,\"anchorBeam\":4,\"anchorBudget\":10000,\"anchorDelta\":0.1,\"anchorEpsilon\":0.15,\"anchorMaxSize\":4,\"anchorMinSupport\":10,\"anchorPrecision\":95,\"anchorRows\":3,\"anchorSearch\":\"beam\",\"anchorTolerance\":0.25,\"maxRows\":3,\"methods\":[\"anchors\"],\"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

Across 3 rows, anchors of 3.7 conditions on average hold the prediction with mean precision 0.94 and cover 1% of the training rows; 67% reach 95% with confidence.

Mean precision
0.9395
Mean coverage
0.0110

Assumptions

  • Rules reach the precision — 67% of the 3 rules are above 95% with confidence; the others are the most precise rules found within the limits.
  • Within the sampling budget — 28900 model calls in all; 2 rows used the whole budget, so their bounds are rough.
  • 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.

Anchors: rules that hold the prediction in place (beam search)

RowPredictionRulePrecisionPrecision, lower boundCoverageModel calls
297false114 < glu ≤ 142 AND ped ≤ 0.254 AND age ≤ 240.98170.93510.01888,900
454truenpreg ≤ 1 AND glu > 142 AND bp > 80 AND ped > 0.65950.83670.62310.009410,000
511false114 < glu ≤ 142 AND 22 < skin ≤ 29 AND 0.399 < ped ≤ 0.6595 AND age ≤ 2410.90320.004710,000
  • Precision is the share of perturbed rows that keep the rule and get the row's predicted class: each perturbed row is a training row whose values that break the rule are swapped for values that keep it. Coverage is the share of the 426 training rows that satisfy the rule. The search stops when a confidence bound says the precision is above 95%. Anchors describe this model's behavior, not causes.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Anchors for a saved model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.anchors 1.1.0 · spec 84d51cab0d7f96e1
# 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\":\"anchors\",\"method\":\"explain.anchors\",\"model\":\"learn.tree/binary_pima\",\"title\":\"Anchors for a saved model\",\"version\":\"1.1.0\"},\"anchorBatch\":100,\"anchorBeam\":4,\"anchorBudget\":10000,\"anchorDelta\":0.1,\"anchorEpsilon\":0.15,\"anchorMaxSize\":4,\"anchorMinSupport\":10,\"anchorPrecision\":95,\"anchorRows\":3,\"anchorSearch\":\"beam\",\"anchorTolerance\":0.25,\"maxRows\":3,\"methods\":[\"anchors\"],\"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"),
    )
)

With beam search, the anchors' mean precision is 0.94, but mean coverage is only 0.011, after 28,900 model calls. With a budget of a few hundred calls, the search stops early:

Anchors for a saved model — learn.tree/binary_pimaRecorded · Python and R agreeRecorded 2026-11-25 · 38 values compared
R

Across 2 rows, anchors of 1.5 conditions on average hold the prediction with mean precision 1.00 and cover 19% of the training rows; 0% reach 99% with confidence.

Mean precision
1
Mean coverage
0.1937

Assumptions

  • Rules reach the precision — 0% of the 2 rules are above 99% with confidence; the others are the most precise rules found within the limits.
  • Within the sampling budget — 300 model calls in all; 2 rows used the whole budget, so their bounds are rough.
  • 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.

Anchors: rules that hold the prediction in place (beam search)

RowPredictionRulePrecisionPrecision, lower boundCoverageModel calls
454trueglu > 142 AND ped > 0.659510.25970.0845150
511falseage ≤ 2410.46280.3028150
  • Precision is the share of perturbed rows that keep the rule and get the row's predicted class: each perturbed row is a training row whose values that break the rule are swapped for values that keep it. Coverage is the share of the 426 training rows that satisfy the rule. The search stops when a confidence bound says the precision is above 99%. Anchors describe this model's behavior, not causes.
The exact R script · R R version 4.5.1 (2025-06-13)
# Anchors for a saved model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.anchors 1.1.0 · spec 387394e953ca4186
# 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\":\"anchors\",\"method\":\"explain.anchors\",\"model\":\"learn.tree/binary_pima\",\"title\":\"Anchors for a saved model\",\"version\":\"1.1.0\"},\"anchorBatch\":20,\"anchorBeam\":4,\"anchorBudget\":150,\"anchorDelta\":0.1,\"anchorEpsilon\":0.15,\"anchorMaxSize\":4,\"anchorMinSupport\":10,\"anchorPrecision\":99,\"anchorRows\":2,\"anchorSearch\":\"beam\",\"anchorTolerance\":0.25,\"maxRows\":2,\"methods\":[\"anchors\"],\"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

Across 2 rows, anchors of 1.5 conditions on average hold the prediction with mean precision 1.00 and cover 19% of the training rows; 0% reach 99% with confidence.

Mean precision
1
Mean coverage
0.1937

Assumptions

  • Rules reach the precision — 0% of the 2 rules are above 99% with confidence; the others are the most precise rules found within the limits.
  • Within the sampling budget — 300 model calls in all; 2 rows used the whole budget, so their bounds are rough.
  • 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.

Anchors: rules that hold the prediction in place (beam search)

RowPredictionRulePrecisionPrecision, lower boundCoverageModel calls
454trueglu > 142 AND ped > 0.659510.25970.0845150
511falseage ≤ 2410.46280.3028150
  • Precision is the share of perturbed rows that keep the rule and get the row's predicted class: each perturbed row is a training row whose values that break the rule are swapped for values that keep it. Coverage is the share of the 426 training rows that satisfy the rule. The search stops when a confidence bound says the precision is above 99%. Anchors describe this model's behavior, not causes.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Anchors for a saved model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.anchors 1.1.0 · spec 387394e953ca4186
# 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\":\"anchors\",\"method\":\"explain.anchors\",\"model\":\"learn.tree/binary_pima\",\"title\":\"Anchors for a saved model\",\"version\":\"1.1.0\"},\"anchorBatch\":20,\"anchorBeam\":4,\"anchorBudget\":150,\"anchorDelta\":0.1,\"anchorEpsilon\":0.15,\"anchorMaxSize\":4,\"anchorMinSupport\":10,\"anchorPrecision\":99,\"anchorRows\":2,\"anchorSearch\":\"beam\",\"anchorTolerance\":0.25,\"maxRows\":2,\"methods\":[\"anchors\"],\"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"),
    )
)

Its 2 rows ran out of budget, so their precision estimates rest on few samples. Report the budget with the rule.

05

Counterfactuals with DiCE

Read

A single counterfactual is often the cheapest change on paper and the least realistic in life. DiCEDiverse counterfactualsSeveral different changes that would each move a prediction across its target, chosen to be close to the row and far apart. looks for kk counterfactuals at once, trading three goals:

min⁡c1,…,ck 1k∑iℓ(f(ci),y∗)+λ1k∑id(ci,x)−λ2 det⁡K,Kij=11+d(ci,cj).\min_{c_1,\ldots,c_k}\ \frac1k\sum_i\ell\big(f(c_i),y^*\big)+\frac{\lambda_1}{k}\sum_i d(c_i,x)-\lambda_2\,\det K,\qquad K_{ij}=\frac{1}{1+d(c_i,c_j)} .

Validity (each one reaches the target prediction), proximity (close to the row) and diversity (the determinant rewards options that differ from each other). In the reference's example all three candidates are valid, and the diversity determinant is 0.306.

Reference · EXP011 · Runs in CodeSplashDiCE: diverse counterfactual explanationsFind several alternative inputs that change a fixed model’s prediction while balancing proximity, diversity and declared feasibility constraints.
06

Feasible changes only

Read

A counterfactual that lowers someone's age, or changes a feature the person can't control, isn't recourse. Feasibility constraintsCounterfactual feasibilityLimits on the changes a counterfactual may suggest: features that can only go up or down, and the values each may take. fix immutable features, allow only increases or only decreases, and keep values in permitted ranges. Compare constrained with unconstrained results to see which "cheap" changes were impossible.

Even feasible counterfactuals describe the model. Changing a feature may not change the real outcome, correlated features may move together in reality, and a model retrained next month may answer differently. No counterfactual is a guaranteed result.

07

Predict: a perfect anchor

Predict

Predict first

An anchor uses all seven features with exact equality and has precision 1. Is it a good explanation?

A great explanation: perfect precisionPossibly useless: perfect precision with tiny coverage
Reveal

Possibly useless. A rule that matches only this row "holds" the prediction by construction. Its coverage is near zero, so it says nothing about how the model behaves on other rows. Good anchors are short, precise and cover a meaningful share of the data.

08

Where they stand in CodeSplash

Read
EntryIn CodeSplash
Anchors (EXP016)Runs in CodeSplash: Anchors for a saved model (Analyze; greedy or beam search with KL-LUCB bounds and a budget) and the Explain tab; Python ≡ R
DiCE (EXP011)Runs in CodeSplash: Counterfactuals for a saved model (Analyze; DiCE or greedy search, with fixed, increase-only and decrease-only features, allowed values and determinant diversity) and the Predict Explain tab ("Diverse counterfactuals"); Python ≡ R
09

Check your understanding

Checkpoint

Check yourself

Why does the anchor search accept a rule only when a lower confidence bound on its precision clears the target?

Show the answer

Answer: b

Bounds turn "looks precise" into "precise with stated confidence". A single post-selection interval still understates the search's adaptivity.

Check yourself

An anchor has precision 0.98 for the prediction "high risk". What does that tell you about whether the patients it covers really are high risk?

Show the answer

Answer: b

Anchors describe the model's behavior under the perturbation distribution. Accuracy needs labels.

Check yourself

What does DiCE's determinant term reward?

Show the answer

Answer: b

Validity, proximity and diversity pull against each other; DiCE balances them with λ1\lambda_1 and λ2\lambda_2.

Check yourself

A loan model's counterfactual says "be ten years younger". What should the explanation have done?

Show the answer

Answer: b

Feasibility constraints separate model gaming from recourse. Show which candidates the constraints removed.

10

Recap

Recap
  • Anchors: rules with high precision and useful coverage, accepted by a confidence bound within a budget.
  • Precision is agreement with the model, not correctness.
  • DiCE balances validity, proximity and diversity; feasibility constraints keep options realistic.
  • Counterfactuals describe the model, never guaranteed real-world outcomes.

Concepts in this lesson