Skip to content

Anchors in Analyze: rules that hold a prediction, found by sampling

An anchor is a short rule on a row's own values that almost always keeps a model's prediction. Read its precision, confidence bound, coverage and budget, and keep counterfactuals to feasible changes.

Advanced ~12 min9 steps

What runs in CodeSplash

You will be able to

  • Explain how an anchor's precision is measured on perturbed rows that keep the rule
  • Read precision, its lower confidence bound, coverage and the sampling budget together
  • Tell the beam search from the greedy search and say when each fits
  • Limit counterfactuals to feasible changes with direction and range constraints

Read first

01

A rule instead of a number

Read

SHAP and LIME give every feature a number. An anchorAnchorA short rule built from a row's own values that keeps its prediction for most rows that satisfy it. answers in a different form: "as long as glucose is above 140 and age above 41, this model says diabetic", together with how often that rule holds and how many people it covers.

02

How precision is measured

Predict

Predict first

The beam search judges a candidate rule by its precision. Which rows does it count?

On the training rows that already satisfy the ruleOn perturbed rows: training rows whose values that break the rule are swapped for values that keep itOn the explained row alone
Reveal

Perturbed rows. Each perturbed rowPerturbed row (anchors)A training row whose values that break the rule are swapped for values from training rows that keep it. starts as a random training row; where it breaks the rule, that feature's value is swapped for one from a training row that keeps it. Precision is the share of these rows the model gives the explained row's prediction. The greedy search (one option away) counts the training rows that already satisfy the rule instead, with no draws.

03

Bounds decide when to stop

Read

Precision from a few hundred draws is uncertain, so the search keeps a KL confidence boundKL confidence boundThe range of rates q whose Kullback–Leibler distance from an observed share is small enough; tighter than Hoeffding's near 0 or 1. on it. A rule counts as an anchor when the lower bound clears the target (95% by default). Among the rules of each length, KL-LUCBKL-LUCBA sampling rule that keeps drawing for the two candidates whose KL confidence bounds still overlap until the best ones are clear. keeps drawing only for the candidates whose bounds still overlap, then keeps the most precise few (the beam) and tries one more condition on each.

04

Read the card

Explore

On a tree model for the Pima rows, three rows get rules with mean precision 0.94; 0.67 of them clear the target with confidence. Each rule covers only 0.011 of the training rows on average, and glu appears in the most rules.

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"),
    )
)

A tree splits finely, so a rule that holds its prediction tightly is long and narrow. The card's Within the sampling budget row says 2 rows used all 10,000 of their model calls: their bounds are rough, and a larger budget would sharpen them.

05

When no condition is needed

Explore

A baseline model that predicts the same class for everyone needs no rule at all: the empty rule keeps the prediction everywhere, so the anchor has 0 conditions and covers all rows (mean coverage 1.00).

Anchors for a saved model — learn.dummy/binary_prior_balancedRecorded · Python and R agreeRecorded 2026-11-25 · 32 values compared
R

Across 2 rows, anchors of 0.0 conditions on average hold the prediction with mean precision 1.00 and cover 100% of the training rows; 100% reach 95% with confidence.

Mean precision
1
Mean coverage
1

Assumptions

  • Rules reach the precision — 100% of the 2 rules are above 95% with confidence.
  • Within the sampling budget — 120 model calls in all.
  • 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.

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

RowPredictionRulePrecisionPrecision, lower boundCoverageModel calls
454false(no condition needed)10.9404160
511false(no condition needed)10.9404160
  • 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 689ee43606198318
# Explains the saved model learn.dummy/binary_prior_balanced 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 69011b83589e6f3c
# 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("glu")
TASK <- "binary"
CLASSES <- c("false", "true")
POSITIVE <- "true"
METRIC <- "roc_auc"
SEED <- 42
PARAMS <- list(
  regression_strategy = "mean",
  class_strategy = "prior"
)

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(
    glu = "numeric"
  ),
  levels = list(
  ),
  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, "balanced", 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\":\"anchors\",\"method\":\"explain.anchors\",\"model\":\"learn.dummy/binary_prior_balanced\",\"title\":\"Anchors for a saved model\",\"version\":\"1.1.0\"},\"anchorBatch\":30,\"anchorBeam\":4,\"anchorBudget\":10000,\"anchorDelta\":0.1,\"anchorEpsilon\":0.15,\"anchorMaxSize\":4,\"anchorMinSupport\":10,\"anchorPrecision\":95,\"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 = "Baseline (no features)",
  engine = cs_engine_info("stats", "nanoparquet")
))
Python

Across 2 rows, anchors of 0.0 conditions on average hold the prediction with mean precision 1.00 and cover 100% of the training rows; 100% reach 95% with confidence.

Mean precision
1
Mean coverage
1

Assumptions

  • Rules reach the precision — 100% of the 2 rules are above 95% with confidence.
  • Within the sampling budget — 120 model calls in all.
  • 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.

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

RowPredictionRulePrecisionPrecision, lower boundCoverageModel calls
454false(no condition needed)10.9404160
511false(no condition needed)10.9404160
  • 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 689ee43606198318
# Explains the saved model learn.dummy/binary_prior_balanced 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 69011b83589e6f3c
# 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 sklearn.dummy import DummyClassifier, DummyRegressor

# %% Data and split plan
TARGET = "diabetic"
FEATURES = ["glu"]
TASK = "binary"
CLASSES = ["false", "true"]
POSITIVE = "true"
METRIC = "roc_auc"
SEED = 42
PARAMS = {
    "regression_strategy": "mean",
    "class_strategy": "prior",
}

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={
        "glu": "numeric",
    },
    levels={
    },
    impute="none",
    scale="none",
    indicators=False,
)
y, y_index = csml.encode_target(df[TARGET], TASK, CLASSES, POSITIVE)
weights = csml.class_weights(y_index, TASK, "balanced", 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\":\"anchors\",\"method\":\"explain.anchors\",\"model\":\"learn.dummy/binary_prior_balanced\",\"title\":\"Anchors for a saved model\",\"version\":\"1.1.0\"},\"anchorBatch\":30,\"anchorBeam\":4,\"anchorBudget\":10000,\"anchorDelta\":0.1,\"anchorEpsilon\":0.15,\"anchorMaxSize\":4,\"anchorMinSupport\":10,\"anchorPrecision\":95,\"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="Baseline (no features)",
        engine=cs.engine_info("scikit-learn", "numpy", "pandas"),
    )
)
06

A budget that runs out

Reflect

With a 99% target and only 150 model calls per row, 2 rows stop early. The rules shown are then the most precise ones found so far, not anchors that cleared the target. When would you rather raise the budget, and when would a lower target be the honest answer?

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"),
    )
)
07

Counterfactuals a person could act on

Read

Anchors say what keeps a prediction; counterfactuals say what would change it. In Predict's Explain tab, the settings of Counterfactuals and Diverse counterfactuals now accept feasibility limitsCounterfactual feasibilityLimits on the changes a counterfactual may suggest: features that can only go up or down, and the values each may take.: features that may only increase or only decrease, and the values each may take (one line per feature, income:0:80000 or region=north|south). Changes that break them are never tried. Diversity can also pick options by the determinant of their similarityDeterminant diversity (DiCE)Picks options that together enlarge the determinant of their similarity matrix, so they differ from each other as a set., as DiCE does, instead of by the distance to the nearest option already picked. Each row reports its options' proximity and sparsity.

08

The code behind it

Read
Python
import math

# The KL lower bound an anchor's precision must clear: the smallest q with n·KL(p̂, q) ≤ β.
def kl(p, q):
    p, q = min(max(p, 1e-7), 1 - 2**-53), min(max(q, 1e-7), 1 - 2**-53)
    return p * math.log(p / q) + (1 - p) * math.log((1 - p) / (1 - q))

def kl_lower(p_hat, n, beta, steps=16):
    lo, hi = max(0.0, p_hat - math.sqrt(beta / n / 2)), p_hat
    for _ in range(steps):
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if kl(p_hat, mid) > beta / n else (lo, mid)
    return lo
R
# The KL lower bound an anchor's precision must clear: the smallest q with n·KL(p̂, q) ≤ β.
kl <- function(p, q) {
  p <- min(max(p, 1e-7), 1 - 2^-53); q <- min(max(q, 1e-7), 1 - 2^-53)
  p * log(p / q) + (1 - p) * log((1 - p) / (1 - q))
}
kl_lower <- function(p_hat, n, beta, steps = 16) {
  lo <- max(0, p_hat - sqrt(beta / n / 2)); hi <- p_hat
  for (i in seq_len(steps)) {
    mid <- (lo + hi) / 2
    if (kl(p_hat, mid) > beta / n) lo <- mid else hi <- mid
  }
  lo
}
09

Check your understanding

Checkpoint

Check yourself

An anchor reads "glucose > 140 AND age > 41" with precision 0.97 and coverage 0.04. What does the coverage tell you?

Show the answer

Answer: a

A narrow corner. Precision says how reliably the rule keeps the prediction; coverage says how many rows the rule reaches. A precise rule with low coverage is a local explanation, not a summary of the model.

Check yourself

A row's rule shows precision 1.00 but the card says it doesn't reach the 95% target. How can that be?

Show the answer

Answer: a

The bound, not the estimate, decides. Ten out of ten hits is precision 1.00, but its lower bound is far below 0.95. A larger sampling budget draws more rows and tightens it.

Check yourself

The card warns that two rows used their whole sampling budget. What should you do first?

Show the answer

Answer: a

Give the bounds room. When the budget runs out, the search stops with the most precise rule so far and rough bounds. More model calls, a smaller beam or a lower target let it finish.

Check yourself

A counterfactual suggests lowering someone's age by ten years. How do you stop that?

Show the answer

Answer: a

Say which changes are possible. Direction limits and allowed values are applied before any candidate is tried, so impossible changes never appear. A counterfactual still describes the model, not what would happen in the world.

Concepts in this lesson