Certified robustness: randomized smoothing and the radius it guarantees
Vote over noisy copies of an input and you can prove that no change smaller than a radius flips the vote, with a stated confidence. The bound, the radius, abstention, the noise trade-off, and exactly what the certificate covers.
What runs in CodeSplash
- ROB003Randomized smoothing certification Runs in CodeSplash (Experimental)
- Randomized smoothing certification for a saved classifier Experimental
You will be able to
- Define the smoothed classifier and the certified L2 radius
- Explain why the class guess and the probability bound use separate noise draws
- Read abstentions and the certified-accuracy curve, and the effect of the noise level σ
- Say what a certificate covers (the smoothed model, an L2 ball, a per-row confidence) and what it doesn't
From "no attack found" to a proof
ReadThe last two lessons could only say an attack failed. Randomized smoothingRandomized smoothingA classifier that predicts the class most noisy copies of a row vote for, so its predictions can be certified. gives a guarantee instead. Build a new classifier that, for input , asks the original model about many noisy copies and returns the most common answer:
Because the noise blurs the decision boundary, a small shift of can only move the vote a little, and that "little" can be bounded.
The certified radius
ReadIf class wins the vote with probability at least and every other class has at most , then no change to with L2 length below
can change 's answer. With this simplifies to .
The probabilities are estimated from noise draws, so is a one-sided lower confidence bound (Clopper–Pearson). In the reference's example, 900 votes out of 1,000 give = 0.867 and, with , a certified radiusCertified radiusThe size of change (L2, here in SD units) that provably can't flip the smoothed prediction, with probability 1 − α. of 0.279.
Move a point toward the boundary and change σ and n: the certified radius follows p̲, and the bound never goes past σ·Φ⁻¹(α^(1/n)).
DExplorable · A certificate by randomized smoothing
Can you prove that no small change flips a prediction, not just fail to find one?
Double σ. What happens to the largest radius these draws could ever certify?
The smoothed classifier votes over Gaussian noise of this SD. Larger σ certifies larger radii but blurs the boundary.
Noisy copies used to bound the top class's probability.
Noisy copies used only to pick the guess (kept apart so the bound stays valid).
Each certificate holds with probability at least 1 − α over the draws.
The point whose certificate is drawn.
The point whose certificate is drawn.
Commit your prediction above to see the result
Make your prediction to see the result.
Two samples, one honest bound
ReadThe procedure draws noise twice. A small selection sample picks the likely class; a separate, larger estimation sample bounds its probability. Using the same draws for both would let the guess flatter its own bound.
If doesn't exceed one half, abstainsAbstention (smoothing)The smoothed model gives no answer when no class wins the noisy copies clearly enough; abstentions count as wrong.: it declines to answer rather than guessing. Abstention is a valid output, not an error, and it counts against certified accuracy at every radius.
More noise, bigger radius?
PredictPredict first
You raise σ from 0.25 to 2 when certifying a tree model on the diabetes data. What happens?
Reveal
Some radii grow, but most rows abstain. With = 2, 9 of 12 rows abstained and smoothed accuracy fell to 25.0%. Heavy noise drowns the signal the base model needs.
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
View data
| Certified accuracy | Radius (SD units) |
|---|---|
| 0.2500 | 0 |
| 0.1667 | 0.0634 |
| 0.1667 | 0.1268 |
| 0.0833 | 0.1903 |
| 0.0833 | 0.2537 |
| 0.0833 | 0.3171 |
| 0 | 0.3805 |
| 0 | 0.4440 |
| 0 | 0.5074 |
| 0 | 0.5708 |
| 0 | 0.6342 |
| 0 | 0.6977 |
| 0 | 0.7611 |
| 0 | 0.8245 |
| 0 | 0.8879 |
| 0 | 0.9514 |
| 0 | 1.015 |
| 0 | 1.078 |
| 0 | 1.142 |
| 0 | 1.205 |
| 0 | 1.268 |
| 0 | 1.332 |
| 0 | 1.395 |
| 0 | 1.459 |
| 0 | 1.522 |
| 0 | 1.586 |
| 0 | 1.649 |
| 0 | 1.712 |
| 0 | 1.776 |
| 0 | 1.839 |
| 0 | 1.903 |
| 0 | 1.966 |
| 0 | 2.030 |
| 0 | 2.093 |
| 0 | 2.156 |
| 0 | 2.220 |
| 0 | 2.283 |
| 0 | 2.347 |
| 0 | 2.410 |
| 0 | 2.474 |
| 0 | 2.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
| Row | Actual | Model (as is) | Smoothed | Lower bound p̲ | Certified radius |
|---|---|---|---|---|---|
| 89 | false | false | abstains | 0.3358 | — |
| 241 | false | false | abstains | 0.3503 | — |
| 297 | false | false | abstains | 0.3649 | — |
| 396 | true | true | abstains | 0.4405 | — |
| 451 | false | false | abstains | 0.4405 | — |
| 454 | false | true | abstains | 0.2936 | — |
| 495 | false | false | abstains | 0.2936 | — |
| 511 | false | false | abstains | 0.3075 | — |
| 513 | false | false | abstains | 0.4562 | — |
| 99 | false | false | false | 0.5046 | 0.0229 |
| 27 | false | false | false | 0.5379 | 0.1903 |
| 41 | true | true | true | 0.5722 | 0.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")
))
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
| Row | Actual | Model (as is) | Smoothed | Lower bound p̲ | Certified radius |
|---|---|---|---|---|---|
| 89 | false | false | abstains | 0.3358 | — |
| 241 | false | false | abstains | 0.3503 | — |
| 297 | false | false | abstains | 0.3649 | — |
| 396 | true | true | abstains | 0.4405 | — |
| 451 | false | false | abstains | 0.4405 | — |
| 454 | false | true | abstains | 0.2936 | — |
| 495 | false | false | abstains | 0.2936 | — |
| 511 | false | false | abstains | 0.3075 | — |
| 513 | false | false | abstains | 0.4562 | — |
| 99 | false | false | false | 0.5046 | 0.0229 |
| 27 | false | false | false | 0.5379 | 0.1903 |
| 41 | true | true | true | 0.5722 | 0.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"),
)
)
Reading a certificate run
ReadUnder 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
View data
| Certified accuracy | Radius (SD units) |
|---|---|
| 0.8000 | 0 |
| 0.8000 | 0.0079 |
| 0.8000 | 0.0159 |
| 0.8000 | 0.0238 |
| 0.8000 | 0.0317 |
| 0.8000 | 0.0396 |
| 0.8000 | 0.0476 |
| 0.8000 | 0.0555 |
| 0.8000 | 0.0634 |
| 0.8000 | 0.0714 |
| 0.8000 | 0.0793 |
| 0.7500 | 0.0872 |
| 0.7500 | 0.0951 |
| 0.7500 | 0.1031 |
| 0.7500 | 0.1110 |
| 0.7500 | 0.1189 |
| 0.7500 | 0.1268 |
| 0.7000 | 0.1348 |
| 0.7000 | 0.1427 |
| 0.6000 | 0.1506 |
| 0.6000 | 0.1586 |
| 0.6000 | 0.1665 |
| 0.6000 | 0.1744 |
| 0.6000 | 0.1823 |
| 0.6000 | 0.1903 |
| 0.6000 | 0.1982 |
| 0.6000 | 0.2061 |
| 0.6000 | 0.2141 |
| 0.5000 | 0.2220 |
| 0.5000 | 0.2299 |
| 0.5000 | 0.2378 |
| 0.5000 | 0.2458 |
| 0.5000 | 0.2537 |
| 0.5000 | 0.2616 |
| 0.5000 | 0.2696 |
| 0.3500 | 0.2775 |
| 0.3500 | 0.2854 |
| 0.3500 | 0.2933 |
| 0.3500 | 0.3013 |
| 0.3500 | 0.3092 |
| 0.3500 | 0.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
| Row | Actual | Model (as is) | Smoothed | Lower bound p̲ | Certified radius |
|---|---|---|---|---|---|
| 34 | false | false | abstains | 0.3503 | — |
| 454 | false | true | abstains | 0.2530 | — |
| 46 | false | false | false | 0.6257 | 0.0801 |
| 145 | false | false | false | 0.7021 | 0.1326 |
| 99 | false | false | false | 0.7224 | 0.1475 |
| 396 | true | true | true | 0.7224 | 0.1475 |
| 41 | true | true | true | 0.8113 | 0.2207 |
| 495 | false | false | false | 0.8113 | 0.2207 |
| 289 | true | false | false | 0.8367 | 0.2452 |
| 241 | false | false | false | 0.8647 | 0.2754 |
| 511 | false | false | false | 0.8647 | 0.2754 |
| 513 | false | false | false | 0.8647 | 0.2754 |
| 27 | false | false | false | 0.8977 | 0.3171 |
| 89 | false | false | false | 0.8977 | 0.3171 |
| 252 | false | false | false | 0.8977 | 0.3171 |
| 263 | false | false | false | 0.8977 | 0.3171 |
| 271 | false | false | false | 0.8977 | 0.3171 |
| 297 | false | false | false | 0.8977 | 0.3171 |
| 417 | false | true | true | 0.8977 | 0.3171 |
| 451 | false | false | false | 0.8977 | 0.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")
))
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
| Row | Actual | Model (as is) | Smoothed | Lower bound p̲ | Certified radius |
|---|---|---|---|---|---|
| 34 | false | false | abstains | 0.3503 | — |
| 454 | false | true | abstains | 0.2530 | — |
| 46 | false | false | false | 0.6257 | 0.0801 |
| 145 | false | false | false | 0.7021 | 0.1326 |
| 99 | false | false | false | 0.7224 | 0.1475 |
| 396 | true | true | true | 0.7224 | 0.1475 |
| 41 | true | true | true | 0.8113 | 0.2207 |
| 495 | false | false | false | 0.8113 | 0.2207 |
| 289 | true | false | false | 0.8367 | 0.2452 |
| 241 | false | false | false | 0.8647 | 0.2754 |
| 511 | false | false | false | 0.8647 | 0.2754 |
| 513 | false | false | false | 0.8647 | 0.2754 |
| 27 | false | false | false | 0.8977 | 0.3171 |
| 89 | false | false | false | 0.8977 | 0.3171 |
| 252 | false | false | false | 0.8977 | 0.3171 |
| 263 | false | false | false | 0.8977 | 0.3171 |
| 271 | false | false | false | 0.8977 | 0.3171 |
| 297 | false | false | false | 0.8977 | 0.3171 |
| 417 | false | true | true | 0.8977 | 0.3171 |
| 451 | false | false | false | 0.8977 | 0.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"),
)
)
At , 2 of 20 rows abstained and the median certified radius was 0.275. Report certified accuracy against radius: the share of rows that are correct and certified at least that far, with the abstention rate, σ, the sample sizes and the run time.
Base models trained with noise (Gaussian augmentation) certify much better, but the certificate is always for the exact deployed model, noise and preprocessing; retraining or quantizing means certifying again.
What the certificate covers
Read- The smoothed classifier , not the base model : deploying without the voting carries no guarantee.
- An L2 ball in the scaled feature space, not rotations, semantic edits or a shifted population.
- Each row, with probability at least over the noise. Certifying a thousand rows doesn't make the statement simultaneous; a claim about all rows at once needs a multiplicity correction.
Plugging the observed vote share into the radius formula without a confidence bound gives a number that looks like a certificate and isn't one.
Where it stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| Randomized smoothing certification (ROB003) | Runs in CodeSplash (Experimental): the run page's Robustness tab (Certify predictions), and Randomized smoothing certification for a saved classifier in Analyze |
Check your understanding
CheckpointCheck yourself
Which model does a randomized-smoothing certificate apply to?
Show the answer
Answer: b
The guarantee comes from the voting. Serving the base model alone carries none.
Check yourself
Why does the radius use a lower confidence bound on the top class's probability rather than its observed vote share?
Show the answer
Answer: a
Using the raw share produces a number that looks like a certificate without its confidence guarantee.
Check yourself
The smoothed classifier abstains on a row. How should that row count?
Show the answer
Answer: b
Report the abstention rate beside certified accuracy. Dropping abstentions would flatter the results.
Check yourself
You certify 500 rows, each at 99.9% confidence. Can you say all 500 certificates hold together with 99.9% confidence?
Show the answer
Answer: b
Per-row confidence and simultaneous confidence are different claims. Say which one you report.
Do it on your own data
In the appOpen a classification run's Robustness tab and use Certify predictions with two values of σ, or certify a saved classifier from Analyze. Read certified accuracy and abstentions together, and record σ and the sample sizes with the result.
Concepts in this lesson