Skip to content

DRegression models · explain.certify

Randomized smoothing certification for a saved classifier

How far can a saved classifier's inputs be pushed before its smoothed prediction could change, and on how many rows can it promise that?

Certifies predictions of a registered classifier with randomized smoothing (Cohen, Rosenfeld & Kolter 2019): each row is scored in hundreds of noisy copies (Gaussian noise on the numeric features, in SD units), the most frequent class becomes the smoothed prediction, and a Clopper–Pearson bound on how often it wins gives a certified radius — no change smaller than that radius can flip the smoothed prediction, with high probability. Rows where no class wins clearly are abstentions. Certified accuracy by radius shows how much robustness the model has to spare. It runs the model's own code in the engine that trained it; the Robustness tab does the same for a run.

Experimental Python and R agree to 6 decimals Seeded Also called randomized smoothing, certified robustness, certified radius…

A real result

Example “Tree pima”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Randomized smoothing certification for a saved classifier — learn.tree/binary_pimaRecorded · Python and R agreeRecorded 2026-11-25 · 99 values compared
R

Under Gaussian noise of σ = 0.25 SD, the smoothed model is right and certified on 80% of 20 rows (the model as is: 85%); it abstains on 2, and the median certified radius of its correct rows is 0.275 SD.

Smoothed accuracy (radius 0)
0.8000
Median certified radius (correct rows)
0.2754

Plots

Certified accuracy by radius (σ = 0.25, 20 rows)How many predictions are right and provably can't change under a change of a given size?
View data
Certified accuracyRadius (SD units)
0.80000
0.80000.0079
0.80000.0159
0.80000.0238
0.80000.0317
0.80000.0396
0.80000.0476
0.80000.0555
0.80000.0634
0.80000.0714
0.80000.0793
0.75000.0872
0.75000.0951
0.75000.1031
0.75000.1110
0.75000.1189
0.75000.1268
0.70000.1348
0.70000.1427
0.60000.1506
0.60000.1586
0.60000.1665
0.60000.1744
0.60000.1823
0.60000.1903
0.60000.1982
0.60000.2061
0.60000.2141
0.50000.2220
0.50000.2299
0.50000.2378
0.50000.2458
0.50000.2537
0.50000.2616
0.50000.2696
0.35000.2775
0.35000.2854
0.35000.2933
0.35000.3013
0.35000.3092
0.35000.3171

Assumptions

  • The smoothed model mostly answers — It abstains on 2 of 20 rows.
  • Noise covers the features — Every feature is numeric and gets noise.
  • 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.

Least robust rows first

RowActualModel (as is)SmoothedLower bound p̲Certified radius
34falsefalseabstains0.3503—
454falsetrueabstains0.2530—
46falsefalsefalse0.62570.0801
145falsefalsefalse0.70210.1326
99falsefalsefalse0.72240.1475
396truetruetrue0.72240.1475
41truetruetrue0.81130.2207
495falsefalsefalse0.81130.2207
289truefalsefalse0.83670.2452
241falsefalsefalse0.86470.2754
511falsefalsefalse0.86470.2754
513falsefalsefalse0.86470.2754
27falsefalsefalse0.89770.3171
89falsefalsefalse0.89770.3171
252falsefalsefalse0.89770.3171
263falsefalsefalse0.89770.3171
271falsefalsefalse0.89770.3171
297falsefalsefalse0.89770.3171
417falsetruetrue0.89770.3171
451falsefalsefalse0.89770.3171
  • Radii are L2 distances in standard-deviation units of the 7 numeric features the noise was added to; each holds with probability at least 0.999 over the noise draws, row by row (not for all rows at once).
Python

Under Gaussian noise of σ = 0.25 SD, the smoothed model is right and certified on 80% of 20 rows (the model as is: 85%); it abstains on 2, and the median certified radius of its correct rows is 0.275 SD.

Smoothed accuracy (radius 0)
0.8000
Median certified radius (correct rows)
0.2754

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • The smoothed model mostly answers — It abstains on 2 of 20 rows.
  • Noise covers the features — Every feature is numeric and gets noise.
  • 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.

Least robust rows first

RowActualModel (as is)SmoothedLower bound p̲Certified radius
34falsefalseabstains0.3503—
454falsetrueabstains0.2530—
46falsefalsefalse0.62570.0801
145falsefalsefalse0.70210.1326
99falsefalsefalse0.72240.1475
396truetruetrue0.72240.1475
41truetruetrue0.81130.2207
495falsefalsefalse0.81130.2207
289truefalsefalse0.83670.2452
241falsefalsefalse0.86470.2754
511falsefalsefalse0.86470.2754
513falsefalsefalse0.86470.2754
27falsefalsefalse0.89770.3171
89falsefalsefalse0.89770.3171
252falsefalsefalse0.89770.3171
263falsefalsefalse0.89770.3171
271falsefalsefalse0.89770.3171
297falsefalsefalse0.89770.3171
417falsetruetrue0.89770.3171
451falsefalsefalse0.89770.3171
  • Radii are L2 distances in standard-deviation units of the 7 numeric features the noise was added to; each holds with probability at least 0.999 over the noise draws, row by row (not for all rows at once).

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Tree pimaml_pima ·
  • Mlp penguinsml_penguins ·
  • Knn binary alphaml_pima ·
  • Tree large sigmaml_pima ·
  • Regression unsupportedml_airquality ·
  • Degenerate infml_pima ·
  • Degenerate constantml_pima ·
  • Degenerate empty after filterml_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 classifier to certify. It runs in the engine that trained it, on this dataset's rows.

Rows to certifydefault 100

The first explained rows that have the target. Each costs one prediction per noisy copy.

Noise SD (σ)default 0.25

Noise added to each numeric feature, in its training SD units. Larger σ certifies larger radii but abstains more.

Advanced

Selection drawsdefault 32

Noisy copies that pick the smoothed class (kept apart from the copies that bound it).

Chance a certificate is wrong (α)default 0.001

Each row's certificate holds with probability at least 1 − α over the noise draws.

options

Estimation drawsdefault 256

Noisy copies that bound how often the smoothed class wins; more draws certify larger radii.

Background datadefault model

Rows whose spread sets the noise scale.

  • The model's training sample(default) — Rows saved with the model version.
  • These rows — This dataset's rows.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • A classifier with numeric features

    Randomized smoothing certifies class predictions and adds noise to numeric features; other models fail this check.

  • The smoothed model mostly answers

    When it abstains on most rows, the noise is too large for this model; try a smaller σ.

    • If violated → Smaller noise — Less noise lets one class win more often, so fewer rows abstain (at the cost of smaller radii).
  • Noise covers the features

    Features without noise (categories, constants) are left as they are, so the radius says nothing about changes to them.

  • Features vary independently

    Noise is added to each feature on its own, so related features move apart in the noisy copies.

  • Rows resemble the training data

    Certificates for rows outside the training range describe extrapolation.

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.
certify_available
1 when randomized smoothing ran; 0 when the model isn't a classifier, has no numeric feature that varies, or no row has the target.
top_feature
Empty: randomized smoothing certifies rows, not features.
top_value
Empty: randomized smoothing certifies rows, not features.
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
The probability the model gives the explained class; the smoothed prediction is the class that wins the noisy copies.

Per group, level or term: certify_reason, certify_rows, certify_abstained, certify_clean_accuracy, certify_smoothed_accuracy, certify_median_radius, certify_max_radius, certify_sigma, certify_noised, certify_unchanged, certify_p_lower[<row>], certify_radius[<row>], certify_curve[<step>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses codesplash, numpy, pandas, scipy; R uses codesplashr, nanoparquet.

Default traps between the two languages

  • The noise comes from the shared Wichmann–Hill stream in the same order and each noisy copy is scored by the saved model's own learner code in each engine, so the class counts match whenever the models do. The Clopper–Pearson bound is scipy's beta.ppf in Python and qbeta in R, and Φ⁻¹ is ndtri vs qnorm; they agree to about 1e-14.
  • The Robustness tab draws its noise on the host with its own seed and SDs from the run's whole input; here the SDs come from the background rows, so the two can differ slightly for the same model.
Python

The exact script CodeSplash ran for example “Tree pima” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Randomized smoothing certification for a saved classifier
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.certify 1.1.0 · spec 7b172aef16321525
# 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\":\"certify\",\"method\":\"explain.certify\",\"model\":\"learn.tree/binary_pima\",\"title\":\"Randomized smoothing certification for a saved classifier\",\"version\":\"1.1.0\"},\"certifyAlpha\":0.001,\"certifyN\":64,\"certifyN0\":16,\"certifyRows\":20,\"certifySigma\":0.25,\"maxRows\":20,\"methods\":[\"certify\"],\"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"),
    )
)
R

The exact script CodeSplash ran for example “Tree pima” · R version 4.5.1 (2025-06-13)

# Randomized smoothing certification for a saved classifier
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.certify 1.1.0 · spec 7b172aef16321525
# 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\":\"certify\",\"method\":\"explain.certify\",\"model\":\"learn.tree/binary_pima\",\"title\":\"Randomized smoothing certification for a saved classifier\",\"version\":\"1.1.0\"},\"certifyAlpha\":0.001,\"certifyN\":64,\"certifyN0\":16,\"certifyRows\":20,\"certifySigma\":0.25,\"maxRows\":20,\"methods\":[\"certify\"],\"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

  • Cohen, J., Rosenfeld, E., & Kolter, J. Z. (2019). Certified adversarial robustness via randomized smoothing. Proceedings of the 36th ICML, PMLR 97, 1310–1320.
  • Clopper, C. J., & Pearson, E. S. (1934). The use of confidence or fiducial limits illustrated in the case of the binomial. Biometrika, 26(4), 404–413.
  • Lecuyer, M., Atlidakis, V., Geambasu, R., Hsu, D., & Jana, S. (2019). Certified robustness to adversarial examples with differential privacy. IEEE S&P 2019, 656–672.

From the CodeSplash method registry · explain.certify v1.1.0.