DRegression models · explain.anchors
Anchors for a saved model
For one row, which short rule on its own values keeps a saved model's prediction in place, how often does it hold, and how many rows does it cover?
Explains single predictions of a registered model version with anchors: a short rule built from the row's own values ("glucose > 140 AND age > 41") such that rows keeping the rule almost always get the same prediction. Beam search with KL-LUCB confidence bounds (Ribeiro, Singh & Guestrin 2018) draws perturbed rows that keep the rule, asks the model, and stops when a bound says the precision is above the target; among the rules that pass it keeps the one that covers the most training rows. The 12.7 greedy search, which measures a rule on the training rows themselves, is one option away. It runs the model's own code in the engine that trained it.
A real result
Example “Beam tree pima”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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)
| Row | Prediction | Rule | Precision | Precision, lower bound | Coverage | Model calls |
|---|---|---|---|---|---|---|
| 297 | false | 114 < glu ≤ 142 AND ped ≤ 0.254 AND age ≤ 24 | 0.9817 | 0.9351 | 0.0188 | 8,900 |
| 454 | true | npreg ≤ 1 AND glu > 142 AND bp > 80 AND ped > 0.6595 | 0.8367 | 0.6231 | 0.0094 | 10,000 |
| 511 | false | 114 < glu ≤ 142 AND 22 < skin ≤ 29 AND 0.399 < ped ≤ 0.6595 AND age ≤ 24 | 1 | 0.9032 | 0.0047 | 10,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.
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)
| Row | Prediction | Rule | Precision | Precision, lower bound | Coverage | Model calls |
|---|---|---|---|---|---|---|
| 297 | false | 114 < glu ≤ 142 AND ped ≤ 0.254 AND age ≤ 24 | 0.9817 | 0.9351 | 0.0188 | 8,900 |
| 454 | true | npreg ≤ 1 AND glu > 142 AND bp > 80 AND ped > 0.6595 | 0.8367 | 0.6231 | 0.0094 | 10,000 |
| 511 | false | 114 < glu ≤ 142 AND 22 < skin ≤ 29 AND 0.399 < ped ≤ 0.6595 AND age ≤ 24 | 1 | 0.9032 | 0.0047 | 10,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.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Beam tree pimaml_pima ·
- Beam knn airqualityml_airquality ·
- Beam mlp penguinsml_penguins ·
- Greedy tree pimaml_pima ·
- Budget tree pimaml_pima ·
- Constant model dummyml_pima ·
- Degenerate infml_pima ·
- Degenerate constantml_pima ·
In the guides
Where it sits in the decision guides
- Interpretable ML (trees, GAMs, SHAP, LIME) · DS & ML Decision Guide · Explain — why is it happening?
Choices you make
statistics
- Modeldefault —
The registered model version to explain. It runs in the engine that trained it, on this dataset's rows.
- Rows to explaindefault 5
The first rows of the explained sample each get their own rule. Time grows in proportion.
- Precision target (%)default 95
How often rows that keep the rule must get the row's prediction before the search accepts it.
- Searchdefault beam
How rules are found and how their precision is measured.
- Beam search with confidence bounds(default) — Draws perturbed rows that keep each candidate rule and stops on KL confidence bounds (Ribeiro et al. 2018).
- Greedy on the training rows — Adds the most precise condition at a time and measures precision on the training rows themselves (no draws).
options
- Beam widthdefault 4
How many of the most precise rules of each size are extended by one more condition.
- Most conditionsdefault 4
The longest rule the search tries.
- Background datadefault model
Where perturbed rows and coverage come from.
- The model's training sample(default) — Rows saved with the model version; perturbed rows then look like training data.
- These rows — This dataset's rows; pick it when the new data differ from the training data.
Advanced
- Draws per batchdefault 100
Perturbed rows drawn for a rule each time its estimate needs to be sharper.
- Confidence (δ)default 0.1
Chance a confidence bound is wrong; smaller values need more draws.
- Bound tolerance (ε)default 0.15
How close the bounds of competing rules must come before the search picks the best ones.
- Model calls per rowdefault 10000
The most perturbed rows scored for one explained row; the search stops with its estimates so far when it runs out.
- Same prediction within (SD)default 0.25
Numeric predictions: a perturbed row counts as the same when its prediction is this many training SDs from the row's.
- Rows behind a rule (greedy)default 10
Greedy search only: a condition is tried only if at least this many training rows keep the rule.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Rules reach the precision
Each rule should pass the precision target with confidence; a rule that doesn't is the most precise one found within the limits.
- If violated → Longer rules, wider beam — Longer rules can hold the prediction more tightly; a wider beam keeps more candidates alive.
Within the sampling budget
A row that used all its model calls stopped early, so its precision bound is rough.
- If violated → More model calls — A larger budget lets the bounds tighten before the search stops.
Features vary independently
Perturbed rows swap values feature by feature, so strongly related features create unlikely rows.
- If violated → Accumulated local effects — ALE compares predictions within narrow bins of the data, so related features never create unlikely rows.
Rows resemble the training data
Explanations of rows outside the training range describe extrapolation, not learned patterns.
What it reports
- n_explained
- How many rows of this dataset the explanation looked at (the first rows of the explained sample).
- n_background
- Rows standing for the training data: the model's saved training sample, or this dataset's rows when chosen.
- n_features
- How many features the saved model reads.
- anchor_n
- How many rows got a rule.
- anchor_reached_share
- Share of rules whose precision clears the target with confidence; the rest are the most precise rules found within the limits.
- anchor_precision_mean
- Average over the explained rows of each rule's precision: how often rows keeping the rule get the same prediction.
- anchor_coverage_mean
- Average share of training rows that satisfy each row's rule; a rule that covers few rows describes a narrow corner of the data.
- anchor_size_mean
- Average number of conditions in the rules; 0 means the prediction holds almost everywhere without any condition.
- anchor_samples_total
- How many perturbed rows the model scored for all explained rows together; 0 for the greedy search, which draws none.
- anchor_budget_rows
- The most perturbed rows scored for one explained row; a row that used it all stopped with rough bounds.
- top_feature
- The feature that appears in the most anchor rules (ties: design order), and the share of rules that use it.
- top_value
- The feature that appears in the most anchor rules (ties: design order), and the share of rules that use it.
- max_abs_corr
- The largest |Spearman ρ| between two numeric features in the background rows; above 0.7 the card warns that features move together.
- outside_share
- Asking a model about feature combinations it never saw, as shuffling or fixing a correlated feature does; answers are guesses, not patterns.
- score_label
- What a rule holds in place: the predicted class, or a numeric prediction within the tolerance.
Per group, level or term: anchor_precision[<row>], anchor_low[<row>], anchor_coverage[<row>], anchor_size[<row>], anchor_support[<row>], anchor_reached[<row>], anchor_samples[<row>], anchor_budget_hit[<row>], anchor_uses[<feature>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses codesplash, numpy, pandas; R uses codesplashr, nanoparquet.
Default traps between the two languages
- The explanation runs the saved model's own learner code in each engine, so the engines agree as closely as their models do. Perturbed rows come from the shared Wichmann–Hill stream in the same order, precision is a ratio of counts, and every sort breaks ties by position, so with the same predictions both engines take the same search path and report the same rules and counts.
- The reference implementation (anchor-exp) estimates coverage from 10,000 draws; here coverage is the exact share of background rows that keep the rule. Its KL-LUCB ties go to array order; here they go to candidate order, written out the same way in both engines. It stops sampling the empty rule at τ − ε but then asks its bound to clear τ, so small batches can miss a model that predicts one class everywhere; here the empty rule is judged like every other rule.
The exact script CodeSplash ran for example “Beam tree pima” · 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"),
)
)
The exact script CodeSplash ran for example “Beam tree pima” · 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")
))
Sources
- Ribeiro, M. T., Singh, S., & Guestrin, C. (2018). Anchors: High-precision model-agnostic explanations. Proceedings of the AAAI Conference on Artificial Intelligence, 32(1), 1527–1535.
- Kaufmann, E., & Kalyanakrishnan, S. (2013). Information complexity in bandit subset selection. Proceedings of COLT 2013, PMLR 30, 228–251.
- Molnar, C. (2022). Interpretable Machine Learning (2nd ed.), ch. 9.4 Scoped rules (anchors).
From the CodeSplash method registry · explain.anchors v1.1.0.