Skip to content

Certify a saved classifier in Analyze

Randomized smoothing turns a saved classifier into one whose predictions come with a certified radius. Run it from Analyze on a registered version, read certified accuracy and abstentions, and pick a noise level.

Advanced ~8 min6 steps

What runs in CodeSplash

You will be able to

  • Run randomized smoothing on a registered classifier from Analyze
  • Read smoothed accuracy, abstentions and the median certified radius together
  • Explain why a larger noise level certifies larger radii but abstains more

Read first

01

The same certificate, for a registered model

Read

The Robustness tab certifies a run. In Analyze, Randomized smoothing certification for a saved classifier does the same for any registered version: each row is scored in hundreds of noisy copies, the class that wins becomes the smoothed predictionRandomized smoothingA classifier that predicts the class most noisy copies of a row vote for, so its predictions can be certified., and a confidence bound on how often it wins gives a certified radiusCertified radiusThe size of change (L2, here in SD units) that provably can't flip the smoothed prediction, with probability 1 − α..

02

Read the card

Explore

On a tree for the Pima rows with noise of 0.25 SD, the smoothed model is right and certified on 0.80 of the rows, against 0.85 for the model as it is. It abstainsAbstention (smoothing)The smoothed model gives no answer when no class wins the noisy copies clearly enough; abstentions count as wrong. on 2 rows, and the median certified radius of its correct rows is 0.275 SD.

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).
The exact R script · R 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")
))
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).
The exact Python script · Python 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"),
    )
)

The curve shows certified accuracyCertified accuracyShare of rows the smoothed model gets right with a certified radius at least r; at r = 0 it is the smoothed accuracy. at every radius up to the largest these draws can certify, 0.317 SD; more estimation draws raise that ceiling.

03

Too much noise

Predict

Predict first

You raise σ from 0.25 to 2 SD. What happens to a tree's smoothed predictions?

It certifies more rowsMost rows abstain, because no class wins the noisy copies clearlyNothing changes
Reveal

Most rows abstain. With noise that large, the noisy copies land all over the feature space and no class wins most of them. Here the model abstains on 9 of 12 rows, and the card suggests a smaller σ.

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

Under Gaussian noise of σ = 2 SD, the smoothed model is right and certified on 25% of 12 rows (the model as is: 92%); it abstains on 9, and the median certified radius of its correct rows is 0.19 SD.

Smoothed accuracy (radius 0)
0.2500
Median certified radius (correct rows)
0.1903

Plots

Certified accuracy by radius (σ = 2, 12 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.25000
0.16670.0634
0.16670.1268
0.08330.1903
0.08330.2537
0.08330.3171
00.3805
00.4440
00.5074
00.5708
00.6342
00.6977
00.7611
00.8245
00.8879
00.9514
01.015
01.078
01.142
01.205
01.268
01.332
01.395
01.459
01.522
01.586
01.649
01.712
01.776
01.839
01.903
01.966
02.030
02.093
02.156
02.220
02.283
02.347
02.410
02.474
02.537

Assumptions

  • The smoothed model mostly answers — It abstains on 9 of 12 rows; the noise is large for this model, so try a smaller σ.
  • 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
89falsefalseabstains0.3358—
241falsefalseabstains0.3503—
297falsefalseabstains0.3649—
396truetrueabstains0.4405—
451falsefalseabstains0.4405—
454falsetrueabstains0.2936—
495falsefalseabstains0.2936—
511falsefalseabstains0.3075—
513falsefalseabstains0.4562—
99falsefalsefalse0.50460.0229
27falsefalsefalse0.53790.1903
41truetruetrue0.57220.3639
  • 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).
The exact R script · R 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 ee2e1aadc1788441
# 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\":12,\"certifySigma\":2,\"maxRows\":12,\"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")
))
Python

Under Gaussian noise of σ = 2 SD, the smoothed model is right and certified on 25% of 12 rows (the model as is: 92%); it abstains on 9, and the median certified radius of its correct rows is 0.19 SD.

Smoothed accuracy (radius 0)
0.2500
Median certified radius (correct rows)
0.1903

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

Assumptions

  • The smoothed model mostly answers — It abstains on 9 of 12 rows; the noise is large for this model, so try a smaller σ.
  • 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
89falsefalseabstains0.3358—
241falsefalseabstains0.3503—
297falsefalseabstains0.3649—
396truetrueabstains0.4405—
451falsefalseabstains0.4405—
454falsetrueabstains0.2936—
495falsefalseabstains0.2936—
511falsefalseabstains0.3075—
513falsefalseabstains0.4562—
99falsefalsefalse0.50460.0229
27falsefalsefalse0.53790.1903
41truetruetrue0.57220.3639
  • 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).
The exact Python script · Python 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 ee2e1aadc1788441
# 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\":12,\"certifySigma\":2,\"maxRows\":12,\"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"),
    )
)
04

Classifiers only

Read

Smoothing certifies a class. A regression model gets a card that says so:

Randomized smoothing certification for a saved classifier — learn.knn/regression_airqualityRecorded · Python and R agreeRecorded 2026-11-25 · 10 values compared
R

Randomized smoothing was not run: the method certifies classifiers; this model predicts a number.

Assumptions

  • A classifier with numeric features — Randomized smoothing certifies classifiers; this model predicts a number.
  • Features vary independently — Wind and Temp: |ρ| = 0.57.
  • Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.
  • Randomized smoothing was not run: the method certifies classifiers; this model predicts a number.
The exact R script · R 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 728891730fca2360
# Explains the saved model learn.knn/regression_airquality with its own learner code (learn.knn 1.0.0, driver mode "explain").
# k-nearest neighbors
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.knn 1.0.0 · spec 312f9d60a672f329
# Dataset: ml_airquality (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 <- "Ozone"
FEATURES <- c("solar radiation", "Wind", "Temp")
TASK <- "regression"
CLASSES <- c()
POSITIVE <- NULL
METRIC <- "rmse"
SEED <- 42
PARAMS <- list(
  k = 7,
  weights = "uniform"
)

df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_airquality.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(
    `solar radiation` = "numeric",
    Wind = "numeric",
    Temp = "numeric"
  ),
  levels = list(
  ),
  impute = "median",
  scale = "standard",
  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
# k-nearest neighbors with a pinned neighbor order (distance, then training row) — the codesplash
# twin of Python's (kknn and class::knn break ties differently).
fit_model <- function(X, y, w) {
  k_classes <- if (TASK == "regression") 0L else if (TASK == "binary") 2L else length(CLASSES)
  cs_ml_knn_fit(X, y, as.integer(PARAMS$k), PARAMS$weights, k_classes, w)
}

predict_model <- function(model, X) {
  p <- cs_ml_knn_predict(model, X)
  if (TASK == "binary") p[, 2] else p
}

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\":\"certify\",\"method\":\"explain.certify\",\"model\":\"learn.knn/regression_airquality\",\"title\":\"Randomized smoothing certification for a saved classifier\",\"version\":\"1.1.0\"},\"certifyAlpha\":0.001,\"certifyN\":256,\"certifyN0\":32,\"certifyRows\":5,\"certifySigma\":0.25,\"maxRows\":5,\"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 = "k-nearest neighbors",
  engine = cs_engine_info("stats", "nanoparquet")
))
Python

Randomized smoothing was not run: the method certifies classifiers; this model predicts a number.

Assumptions

  • A classifier with numeric features — Randomized smoothing certifies classifiers; this model predicts a number.
  • Features vary independently — Wind and Temp: |ρ| = 0.57.
  • Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.
  • Randomized smoothing was not run: the method certifies classifiers; this model predicts a number.
The exact Python script · Python 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 728891730fca2360
# Explains the saved model learn.knn/regression_airquality with its own learner code (learn.knn 1.0.0, driver mode "explain").
# k-nearest neighbors
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.knn 1.0.0 · spec 312f9d60a672f329
# Dataset: ml_airquality (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.neighbors import KNN

# %% Data and split plan
TARGET = "Ozone"
FEATURES = ["solar radiation", "Wind", "Temp"]
TASK = "regression"
CLASSES = []
POSITIVE = None
METRIC = "rmse"
SEED = 42
PARAMS = {
    "k": 7,
    "weights": "uniform",
}

df = pd.read_parquet("tests/parity/fixtures/ml_airquality.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={
        "solar radiation": "numeric",
        "Wind": "numeric",
        "Temp": "numeric",
    },
    levels={
    },
    impute="median",
    scale="standard",
    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
# k-nearest neighbors with a pinned neighbor order (distance, then training row) — the codesplash
# twin; scikit-learn's KNeighbors* (algorithm="brute") agree whenever no neighbors tie.


def fit_model(X, y, w):
    k_classes = 0 if TASK == "regression" else (2 if TASK == "binary" else len(CLASSES))
    return KNN(int(PARAMS["k"]), PARAMS["weights"], k_classes).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 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\":\"certify\",\"method\":\"explain.certify\",\"model\":\"learn.knn/regression_airquality\",\"title\":\"Randomized smoothing certification for a saved classifier\",\"version\":\"1.1.0\"},\"certifyAlpha\":0.001,\"certifyN\":256,\"certifyN0\":32,\"certifyRows\":5,\"certifySigma\":0.25,\"maxRows\":5,\"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="k-nearest neighbors",
        engine=cs.engine_info("numpy", "numpy", "pandas"),
    )
)
05

The code behind it

Read
Python
from scipy.stats import beta, norm

# CERTIFY for one row: k of n estimation draws vote for the class the selection draws picked.
def certify(k, n, sigma, alpha=0.001):
    p_low = 0.0 if k == 0 else (alpha ** (1 / n) if k == n else beta.ppf(alpha, k, n - k + 1))
    return sigma * norm.ppf(p_low) if p_low > 0.5 else None  # None: abstain
R
# CERTIFY for one row: k of n estimation draws vote for the class the selection draws picked.
certify <- function(k, n, sigma, alpha = 0.001) {
  p_low <- if (k == 0) 0 else if (k == n) alpha^(1 / n) else qbeta(alpha, k, n - k + 1)
  if (p_low > 0.5) sigma * qnorm(p_low) else NA  # NA: abstain
}
06

Check your understanding

Checkpoint

Check yourself

A row is certified with radius 0.3 SD. What does that promise?

Show the answer

Answer: a

A promise about the smoothed model. The certificate covers the smoothed classifier, only the features that got noise, and holds row by row with probability 1 − α over the draws.

Check yourself

The card says the smoothed model abstains on 9 of 12 rows. What should you try?

Show the answer

Answer: a

Less noise. Abstention means no class wins the noisy copies clearly enough. A smaller σ keeps copies closer to the row, so one class wins more often (and the radii get smaller).

Concepts in this lesson