Monte Carlo dropout and Bayes by Backprop: one network, many guesses
Keep dropout on at prediction and average many passes, or learn a distribution for every weight and sample from it. What each approximates, which assumptions carry the Bayesian reading, and how to check the result.
What runs in CodeSplash
- UNC004Monte Carlo dropout for approximate Bayesian prediction Runs in CodeSplash
- UNC005Bayes by Backprop Runs in CodeSplash
- Deep neural network (torch MLP) Verified in Python and R
You will be able to
- Explain Monte Carlo dropout's predictive mean and variance and what the pass count controls
- Write the Bayes by Backprop objective and the reparameterized weight sample
- Name the assumptions behind each Bayesian reading and how each can understate uncertainty
- Keep dropout regularization, posterior uncertainty and conformal coverage apart
Cheaper than an ensemble
ReadAn ensemble trains networks. Two methods get many predictions from one training run:
- Monte Carlo dropoutMonte Carlo dropoutKeeping dropout on when predicting and averaging many passes; the spread across passes shows how unsure the network is. keeps dropout switched on at prediction time; every pass drops a different random set of units, so each pass is a slightly different network.
- Bayes by BackpropBayes by BackpropLearning a Normal distribution for every weight, by sampling a network each step and penalizing distance from a prior. learns a distribution for each weight and draws whole networks from it.
Both read the spread of their outputs as posterior uncertainty. Both readings rest on assumptions worth knowing before you trust the numbers.
Monte Carlo dropout
ReadWith passes giving means , the prediction is and, for a model with constant noise , the predictive variance is
Leave out and you report only the spread of the network's mean, which is narrower. In the reference's small example the latent variance is 0.0707 and the predictive variance 0.121.
controls how accurately the average is computed, not the model's capacity. Plot the estimate against and stop when it settles.
Set MC dropout beside an ensemble on the same data and see where each one admits it is unsure.
DExplorable · Ensembles and MC dropout: knowing what you don't know
Where the training data has a gap, does the model say it is unsure?
Where will the ensemble disagree with itself most: near the training data or in the gap?
Models in the ensemble, and dropout masks drawn for MC dropout.
Share of features switched off in each MC dropout pass.
Noise around the true curve sin(1.5x).
Half fall in [−3, −1), half in [1, 3): none in the middle.
Members differ by
Each member draws its own random features and, with data, its own bootstrap sample.
Ensemble · SD 0.25 in the gap, 0.07 near data
MC dropout · SD 0.10 in the gap, 0.20 near data
The shaded strip is the gap with no training data. Members disagree where nothing pins them down; a band that stays thin there is overconfident, however good it looks near the data.
Commit your prediction above to see the result
Make your prediction to see the result.
A run with prediction passes
ReadDeep neural network (torch MLP): cross-validated RMSE 21.722 ± 4.029 over 3 folds; RMSE on the locked test set 16.978 (n = 23).
- CV RMSE
- 21.722
- SD across folds
- 4.029
- Test RMSE
- 16.978
Cross-validation
| Fold | Repeat | n | RMSE | MAE | R² | MAPE |
|---|---|---|---|---|---|---|
| 1 | 1 | 31 | 26.372 | 16.972 | 0.5736 | 0.4540 |
| 2 | 1 | 31 | 19.511 | 15.384 | 0.5097 | 0.9744 |
| 3 | 1 | 31 | 19.282 | 15.074 | 0.6743 | 0.4290 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Deep neural network (torch MLP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.torch_mlp 1.4.2 · spec bbf72d4e6317b99d
# 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)
# torch for R (LibTorch); the network itself is built by codesplashr's cs_deep_* twins.
# %% Data and split plan
TARGET <- "Ozone"
FEATURES <- c("solar radiation", "Wind", "Temp")
TASK <- "regression"
CLASSES <- c()
POSITIVE <- NULL
METRIC <- "rmse"
SEED <- 42
PARAMS <- list(
hidden_layers = c(16, 8),
activation = "relu",
epochs = 120,
learning_rate = 0.01,
batch_size = NULL,
weight_decay = 0.0001,
early_stopping = 0,
validation_fraction = 0.1,
dropout = 0.2,
mc_passes = 20,
variational_weights = FALSE,
prior_scale = 1,
kl_weight = 1,
robust_training = "none",
dro_step = 0.01,
adv_epsilon = 0.1,
adv_steps = 5,
trades_beta = 6,
loss = "cross_entropy",
focal_gamma = 2,
focal_alpha = NULL,
dp_epsilon = NULL,
dp_noise_multiplier = NULL,
dp_max_grad_norm = 1,
dp_delta = NULL,
dp_sampling = "poisson",
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
label_smoothing = 0,
mixup_alpha = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_airquality.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.torch_mlp/regression_mc_dropout/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)
run$predictive <- TRUE
out <- cs_ml_out_dir("target/academy-parity/run-8142/learn.torch_mlp/regression_mc_dropout/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]
RESAMPLE <- "none"
if (RESAMPLE != "none" && TASK == "regression") {
warnings <- c(warnings, list("Resampling applies to classification only — ignored for this regression target."))
}
resampled <- NULL # the final model's resampling summary
notes <- list()
# A fit's design matrix, targets and weights: training rows only, resampled when asked
# (cs_ml_resample — the same rows in Python, from the shared random stream).
training_set <- function(X, rows, fold_id, repeat_) {
yy <- y[rows + 1L]
ww <- sample_weights(rows)
if (RESAMPLE == "none" || TASK == "regression") return(list(X = X, y = yy, w = ww))
r <- cs_ml_resample(X, yy, ww, RESAMPLE, ratio = 1, k = as.integer(5),
seed = cs_ml_resample_seed(SEED, fold_id, repeat_))
if (fold_id == 0) resampled <<- r$info
r
}
fit_on <- function(s) fit_model(s$X, s$y, s$w)
# %% Model
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
dp_epsilon = NULL,
dp_noise_multiplier = NULL,
dp_max_grad_norm = 1,
dp_delta = NULL,
dp_sampling = "poisson",
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
label_smoothing = 0,
mixup_alpha = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/learn.torch_mlp/regression_mc_dropout/out-r")
.deep_folds <- length(if (0 > 0) utils::head(plan$folds, 0) else plan$folds)
.deep_training_set <- training_set
# Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build the
# training set as _ml_learn does.
training_set <- function(X, rows, fold_id, repeat_) {
cs_deep_trainer_set_fold(as.integer(fold_id), .deep_folds, if (fold_id > 0) "cv" else "final")
.deep_training_set(X, rows, fold_id, repeat_)
}
# A dense network on torch for R (float64, one thread): hidden layers HIDDEN with ACTIVATION units, a
# linear output (1 value, 1 logit or K logits), trained by Adam from weights drawn from the shared
# random stream — Python's torch starts from the same weights and takes the same steps.
HIDDEN <- as.integer(unlist(PARAMS$hidden_layers))
if (!length(HIDDEN)) HIDDEN <- 32L
ACTIVATION <- PARAMS$activation
DROPOUT <- as.numeric(PARAMS$dropout)
PASSES <- as.integer(PARAMS$mc_passes)
VARIATIONAL <- isTRUE(PARAMS$variational_weights)
ROBUST <- PARAMS$robust_training
# Any of the options on: train with cs_deep_fit_mlp_ext (otherwise the plain network, unchanged).
EXTENDED <- DROPOUT > 0 || PASSES > 0 || VARIATIONAL || ROBUST != "none"
if (PASSES > 0 && DROPOUT == 0 && !VARIATIONAL) {
cs_error("CS_E_INVALID_OPTION", option = "Prediction passes", allowed = "0 unless dropout or variational weights are on", value = PASSES)
}
if (VARIATIONAL && DROPOUT > 0) {
cs_error("CS_E_INVALID_OPTION", option = "Dropout", allowed = "0 with variational weights (their noise replaces it)", value = DROPOUT)
}
SUBGROUPS <- NULL
if (ROBUST == "group_dro" && is.null(SUBGROUPS)) {
cs_error("CS_E_INVALID_OPTION", option = "Robust training", allowed = "Group DRO only with a Subgroups column", value = "group_dro")
}
if (ROBUST == "group_dro" && RESAMPLE != "none" && TASK != "regression") {
cs_error("CS_E_INVALID_OPTION", option = "Resampling", allowed = "none with Group DRO", value = RESAMPLE)
}
# Differential privacy (DP-SGD): with an epsilon or a noise multiplier set, every fit clips each row's
# gradient and adds noise (cs_deep_dp_*, turned on by the trainer's dp plugin above; the guarantee goes to
# dp.json). Off by default. These options can't be combined with it:
DP <- cs_deep_dp_settings(PARAMS)
if (!is.null(DP)) {
if (VARIATIONAL || ROBUST != "none") {
cs_error("CS_E_INVALID_OPTION", option = "Differential privacy", allowed = "off with variational weights or robust training", value = "on")
}
if (RESAMPLE != "none") {
cs_error("CS_E_INVALID_OPTION", option = "Differential privacy", allowed = "off with resampling (copies of a row would each count)", value = "on")
}
}
fit_model <- function(X, y, w) {
if (cs_deep_dp_enabled() && !is.null(w) && diff(range(as.numeric(w))) > 0) {
cs_error("CS_E_INVALID_OPTION", option = "Differential privacy", allowed = "off with row or class weights", value = "on")
}
if (TASK == "regression") {
# Standardize the target (training mean and population SD); predictions are mapped back.
mu <- mean(y); sd <- sqrt(mean((y - mu)^2)); if (!(sd > 0)) sd <- 1
target <- (as.numeric(y) - mu) / sd; o <- 1L
} else if (TASK == "binary") {
mu <- 0; sd <- 1
target <- as.numeric(y); o <- 1L
} else {
mu <- 0; sd <- 1
target <- cs_deep_one_hot(y, length(CLASSES)); o <- length(CLASSES)
}
if (!EXTENDED) {
fit <- cs_deep_fit_mlp(
unname(X), target, w, TASK, HIDDEN, o,
activation = ACTIVATION,
epochs = as.integer(PARAMS$epochs),
lr = PARAMS$learning_rate,
batch_size = if (is.null(PARAMS$batch_size)) NULL else as.integer(PARAMS$batch_size),
weight_decay = PARAMS$weight_decay,
early_stopping = as.integer(PARAMS$early_stopping) > 0,
validation_fraction = PARAMS$validation_fraction,
patience = max(1L, as.integer(PARAMS$early_stopping)),
seed = SEED
)
return(list(params = fit$params, mu = mu, sd = sd, history = fit$history, best_epoch = fit$best_epoch))
}
fit <- cs_deep_fit_mlp_ext(
unname(X), target, w, TASK, HIDDEN, o,
activation = ACTIVATION,
epochs = as.integer(PARAMS$epochs),
lr = PARAMS$learning_rate,
batch_size = if (is.null(PARAMS$batch_size)) NULL else as.integer(PARAMS$batch_size),
weight_decay = PARAMS$weight_decay,
early_stopping = as.integer(PARAMS$early_stopping) > 0,
validation_fraction = PARAMS$validation_fraction,
patience = max(1L, as.integer(PARAMS$early_stopping)),
seed = SEED,
dropout = DROPOUT,
variational = VARIATIONAL,
prior_scale = PARAMS$prior_scale,
kl_weight = PARAMS$kl_weight,
robust = ROBUST,
groups = if (ROBUST != "group_dro") NULL else SUBGROUPS[FIT_ROWS + 1L],
dro_step = PARAMS$dro_step,
adv_epsilon = PARAMS$adv_epsilon,
adv_steps = as.integer(PARAMS$adv_steps),
trades_beta = PARAMS$trades_beta,
mc_passes = PASSES
)
fit$mu <- mu; fit$sd <- sd; fit$extended <- TRUE
fit
}
predict_model <- function(model, X) {
p <- if (!isTRUE(model$extended)) cs_deep_mlp_predict(model$params, unname(X), ACTIVATION, TASK) else cs_deep_mlp_predict_ext(model, unname(X), TASK)$mean
if (TASK == "regression") model$mu + model$sd * p else p
}
# Predictive SD (numbers, with prediction passes): sqrt(training residual variance + spread across passes).
predict_sd <- function(model, X) model$sd * sqrt(model$noise_var + cs_deep_mlp_predict_ext(model, unname(X), TASK)$spread)
feature_importance <- function(model, names) NULL
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path) # plain numeric weights + the target scaling
hist <- file.path(directory, "history.parquet")
nanoparquet::write_parquet(cs_deep_history_frame(model$history), hist)
list(list(key = "model", path = path, format = "rds"), list(key = "history", path = hist, format = "parquet"))
}
load_model <- function(directory) readRDS(file.path(directory, "model.rds"))
# Predictive mean and SD for `rows`.
held_out <- function(model, prep, fit_rows, rows) {
X <- cs_ml_design_apply(prep, rows_of(rows))
list(mean = predict_model(model, X), sd = predict_sd(model, X))
}
# %% Cross-validation
folds <- if (0 > 0) utils::head(plan$folds, 0) else plan$folds
progress <- cs_progress("Cross-validating", total = length(folds))
for (i in seq_along(folds)) {
fold <- folds[[i]]
prep <- cs_ml_design_fit(design, rows_of(fold$train))
model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(fold$train)), fold$train, fold$id, fold$repeat_))
cs_ml_add(run, fold$id, fold$repeat_, "valid", fold$valid, y, y_index,
held_out(model, prep, fold$train, fold$valid))
cs_progress_update(progress, i, sprintf("Fold %d of %d", i, length(folds)))
}
cs_ml_lap(run, "cv_seconds")
# %% Final model
artifacts <- list()
importance <- NULL
prep <- cs_ml_design_fit(design, rows_of(plan$train))
names_ <- cs_ml_design_names(prep)
if (TRUE) {
model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(plan$train)), plan$train, 0L, 0L))
if (!is.null(resampled)) {
warnings <- c(warnings, as.list(resampled$notes))
notes <- c(notes, list(cs_ml_resample_describe(resampled)))
}
if (length(plan$test)) {
cs_ml_add(run, 0L, 0L, "test", plan$test, y, y_index,
held_out(model, prep, plan$train, plan$test))
}
importance <- feature_importance(model, names_)
artifacts[[length(artifacts) + 1L]] <- list(
key = "design", path = cs_ml_save_json(cs_ml_design_json(prep), file.path(out, "design.json")), format = "json"
)
artifacts <- c(artifacts, save_model(model, out))
cs_ml_lap(run, "final_seconds")
}
artifacts[[length(artifacts) + 1L]] <- list(key = "predictions", path = cs_ml_write(run, out), format = "parquet")
cs_progress_done(progress)
# %% Result
cs_publish(cs_ml_result(
run,
title = "Deep neural network (torch MLP)",
engine = cs_engine_info("torch", "codesplashr", "nanoparquet"),
n_features = length(names_),
n_train = length(plan$train),
n_test = length(plan$test),
params = PARAMS,
features = names_,
importance = importance,
artifacts = artifacts,
warnings = warnings,
notes = notes
))
Deep neural network (torch MLP): cross-validated RMSE 21.722 ± 4.029 over 3 folds; RMSE on the locked test set 16.978 (n = 23).
- CV RMSE
- 21.722
- SD across folds
- 4.029
- Test RMSE
- 16.978
Cross-validation
| Fold | Repeat | n | RMSE | MAE | R² | MAPE |
|---|---|---|---|---|---|---|
| 1 | 1 | 31 | 26.372 | 16.972 | 0.5736 | 0.4540 |
| 2 | 1 | 31 | 19.511 | 15.384 | 0.5097 | 0.9744 |
| 3 | 1 | 31 | 19.282 | 15.074 | 0.6743 | 0.4290 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Deep neural network (torch MLP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.torch_mlp 1.4.2 · spec bbf72d4e6317b99d
# 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.deep import core as deep # twin of codesplashr::cs_deep_* (shared initial weights, Adam written out)
from codesplash.deep import mlp_ext as mlpx # dropout, variational weights, Group DRO, PGD/TRADES (twin: cs_deep_*_ext)
from codesplash.deep import dp as deep_dp # differentially private training, DP-SGD (twin: cs_deep_dp_*)
# %% Data and split plan
TARGET = "Ozone"
FEATURES = ["solar radiation", "Wind", "Temp"]
TASK = "regression"
CLASSES = []
POSITIVE = None
METRIC = "rmse"
SEED = 42
PARAMS = {
"hidden_layers": [16, 8],
"activation": "relu",
"epochs": 120,
"learning_rate": 0.01,
"batch_size": None,
"weight_decay": 0.0001,
"early_stopping": 0,
"validation_fraction": 0.1,
"dropout": 0.2,
"mc_passes": 20,
"variational_weights": False,
"prior_scale": 1,
"kl_weight": 1,
"robust_training": "none",
"dro_step": 0.01,
"adv_epsilon": 0.1,
"adv_steps": 5,
"trades_beta": 6,
"loss": "cross_entropy",
"focal_gamma": 2,
"focal_alpha": None,
"dp_epsilon": None,
"dp_noise_multiplier": None,
"dp_max_grad_norm": 1,
"dp_delta": None,
"dp_sampling": "poisson",
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"label_smoothing": 0,
"mixup_alpha": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
}
df = pd.read_parquet("tests/parity/fixtures/ml_airquality.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.torch_mlp/regression_mc_dropout/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)
run.predictive = True
out = csml.out_dir("target/academy-parity/run-8142/learn.torch_mlp/regression_mc_dropout/out-python")
warnings = []
def sample_weights(rows):
return None if weights is None else weights[rows]
RESAMPLE = "none"
if RESAMPLE != "none" and TASK == "regression":
warnings.append("Resampling applies to classification only — ignored for this regression target.")
resampled = None # the final model's resampling summary
notes = []
def training_set(X, rows, fold_id, repeat):
"""A fit's design matrix, targets and weights: training rows only, resampled when asked
(codesplash.ml.resample — the same rows in R, from the shared random stream)."""
yy, ww = y[rows], sample_weights(rows)
if RESAMPLE == "none" or TASK == "regression":
return X, yy, ww
from codesplash.ml import resample as csres
X2, y2, w2, info = csres.resample(
X, yy, ww, RESAMPLE, ratio=1, k=5, seed=csres.resample_seed(SEED, fold_id, repeat)
)
if fold_id == 0:
global resampled
resampled = info
return X2, y2, w2
# %% Model
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"dp_epsilon": None,
"dp_noise_multiplier": None,
"dp_max_grad_norm": 1,
"dp_delta": None,
"dp_sampling": "poisson",
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"label_smoothing": 0,
"mixup_alpha": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-8142/learn.torch_mlp/regression_mc_dropout/out-python",
)
_DEEP_FOLDS = len(plan.folds[: 0] if 0 else plan.folds)
_deep_training_set = training_set
def training_set(X, rows, fold_id, repeat):
"""Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build
the training set as _ml_learn does."""
deep_trainer.set_fold(int(fold_id), _DEEP_FOLDS, "cv" if fold_id else "final")
return _deep_training_set(X, rows, fold_id, repeat)
# A dense network on PyTorch (float64, one thread): hidden layers HIDDEN with ACTIVATION units, a
# linear output (1 value, 1 logit or K logits), trained by Adam from weights drawn from the shared
# random stream — R's torch starts from the same weights and takes the same steps.
HIDDEN = [int(u) for u in PARAMS["hidden_layers"]] or [32]
ACTIVATION = PARAMS["activation"]
DROPOUT = float(PARAMS["dropout"])
PASSES = int(PARAMS["mc_passes"])
VARIATIONAL = bool(PARAMS["variational_weights"])
ROBUST = PARAMS["robust_training"]
# Any of the options on: train with codesplash.deep.mlp_ext (otherwise the plain network, unchanged).
EXTENDED = DROPOUT > 0 or PASSES > 0 or VARIATIONAL or ROBUST != "none"
if PASSES > 0 and DROPOUT == 0 and not VARIATIONAL:
cs.cs_error("CS_E_INVALID_OPTION", option="Prediction passes", allowed="0 unless dropout or variational weights are on", value=PASSES)
if VARIATIONAL and DROPOUT > 0:
cs.cs_error("CS_E_INVALID_OPTION", option="Dropout", allowed="0 with variational weights (their noise replaces it)", value=DROPOUT)
SUBGROUPS = None
if ROBUST == "group_dro" and SUBGROUPS is None:
cs.cs_error("CS_E_INVALID_OPTION", option="Robust training", allowed="Group DRO only with a Subgroups column", value="group_dro")
if ROBUST == "group_dro" and RESAMPLE != "none" and TASK != "regression":
cs.cs_error("CS_E_INVALID_OPTION", option="Resampling", allowed="none with Group DRO", value=RESAMPLE)
# Differential privacy (DP-SGD): with an ε or a noise multiplier set, every fit clips each row's gradient
# and adds noise (codesplash.deep.dp, turned on by the trainer's dp plugin above; the guarantee goes to dp.json).
# Off by default. These options can't be combined with it:
DP = deep_dp.settings(PARAMS)
if DP is not None:
if VARIATIONAL or ROBUST != "none":
cs.cs_error("CS_E_INVALID_OPTION", option="Differential privacy", allowed="off with variational weights or robust training", value="on")
if RESAMPLE != "none":
cs.cs_error("CS_E_INVALID_OPTION", option="Differential privacy", allowed="off with resampling (copies of a row would each count)", value="on")
def fit_model(X, y, w):
if deep_dp.enabled() and w is not None and float(np.ptp(np.asarray(w, dtype=np.float64))) > 0:
cs.cs_error("CS_E_INVALID_OPTION", option="Differential privacy", allowed="off with row or class weights", value="on")
if TASK == "regression":
# Standardize the target (training mean and population SD); predictions are mapped back.
mu, sd = float(np.mean(y)), float(np.std(y)) or 1.0
target, o = (np.asarray(y, dtype=np.float64) - mu) / sd, 1
elif TASK == "binary":
mu, sd = 0.0, 1.0
target, o = np.asarray(y, dtype=np.float64), 1
else:
mu, sd = 0.0, 1.0
target, o = deep.one_hot(y, len(CLASSES)), len(CLASSES)
common = dict(
activation=ACTIVATION,
epochs=int(PARAMS["epochs"]),
lr=PARAMS["learning_rate"],
batch_size=None if PARAMS["batch_size"] is None else int(PARAMS["batch_size"]),
weight_decay=PARAMS["weight_decay"],
early_stopping=int(PARAMS["early_stopping"]) > 0,
validation_fraction=PARAMS["validation_fraction"],
patience=max(1, int(PARAMS["early_stopping"])),
seed=SEED,
)
if not EXTENDED:
fit = deep.fit_mlp(X, target, w, TASK, HIDDEN, o, **common)
return {"params": fit["params"], "mu": mu, "sd": sd, "history": fit["history"], "best_epoch": fit["best_epoch"]}
fit = mlpx.fit_mlp_ext(
X, target, w, TASK, HIDDEN, o, **common,
dropout=DROPOUT,
variational=VARIATIONAL,
prior_scale=PARAMS["prior_scale"],
kl_weight=PARAMS["kl_weight"],
robust=ROBUST,
groups=None if ROBUST != "group_dro" else SUBGROUPS[FIT_ROWS],
dro_step=PARAMS["dro_step"],
adv_epsilon=PARAMS["adv_epsilon"],
adv_steps=int(PARAMS["adv_steps"]),
trades_beta=PARAMS["trades_beta"],
mc_passes=PASSES,
)
fit.update({"mu": mu, "sd": sd, "extended": True})
return fit
def predict_model(model, X):
if not model.get("extended"):
p = deep.mlp_predict(model["params"], X, ACTIVATION, TASK)
else:
p, _ = mlpx.mlp_predict_ext(model, X, TASK)
if TASK == "regression":
return model["mu"] + model["sd"] * p
return p
def predict_sd(model, X):
"""Predictive SD (numbers, with prediction passes): √(training residual variance + spread across passes)."""
_, spread = mlpx.mlp_predict_ext(model, X, TASK)
return model["sd"] * np.sqrt(model["noise_var"] + spread)
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) # plain numpy weights + the target scaling
hist = os.path.join(directory, "history.parquet")
deep.history_frame(model["history"]).to_parquet(hist, index=False)
return [{"key": "model", "path": path, "format": "joblib"}, {"key": "history", "path": hist, "format": "parquet"}]
def load_model(directory):
import joblib
return joblib.load(os.path.join(directory, "model.joblib"))
def held_out(model, prep, fit_rows, rows):
"""Predictive mean and SD for `rows`."""
X = prep.transform(df.iloc[rows])
return predict_model(model, X), predict_sd(model, X)
# %% Cross-validation
folds = plan.folds[: 0] if 0 else plan.folds
progress = cs.progress("Cross-validating", total=len(folds))
for i, fold in enumerate(folds):
prep = design.fit(df.iloc[fold.train])
model = fit_model(*training_set(prep.transform(df.iloc[fold.train]), fold.train, fold.id, fold.repeat))
run.add(fold.id, fold.repeat, "valid", fold.valid, y, y_index, held_out(model, prep, fold.train, fold.valid))
progress.update(i + 1, f"Fold {i + 1} of {len(folds)}")
run.lap("cv_seconds")
# %% Final model
artifacts = []
importance = None
prep = design.fit(df.iloc[plan.train])
names = prep.names
if True:
model = fit_model(*training_set(prep.transform(df.iloc[plan.train]), plan.train, 0, 0))
if resampled is not None:
from codesplash.ml import resample as csres
warnings.extend(resampled["notes"])
notes.append(csres.describe(resampled))
if len(plan.test):
run.add(0, 0, "test", plan.test, y, y_index, held_out(model, prep, plan.train, plan.test))
importance = feature_importance(model, names)
artifacts.append({"key": "design", "path": csml.save_json(prep.to_json(), os.path.join(out, "design.json")), "format": "json"})
artifacts.extend(save_model(model, out))
run.lap("final_seconds")
artifacts.append({"key": "predictions", "path": run.write(out), "format": "parquet"})
progress.done()
# %% Result
cs.publish(
run.result(
title="Deep neural network (torch MLP)",
engine=cs.engine_info("torch", "codesplash", "numpy", "pandas"),
n_features=len(names),
n_train=len(plan.train),
n_test=len(plan.test),
params=PARAMS,
features=names,
importance=importance,
artifacts=artifacts,
warnings=warnings,
notes=notes,
)
)
With dropout during training and 20 passes at prediction, the 90% intervals covered 87.1% of held-out rows: close to the target, which you only know because you checked.
The Bayesian reading needs dropout to have been part of training, at the same places and rate. Switching dropout on in a network trained without it, or changing the rate afterwards, gives random outputs with no posterior behind them. Check that repeated passes really differ, and that batch-normalization statistics don't change between passes.
Bayes by Backprop
ReadBayes by Backprop gives each weight a Gaussian with mean and scale , and minimizes
Gradients flow through samples , : the reparameterization trick. With a per-row loss, the KL term is divided by once. In the reference's example the mean NLL is −0.0471, the KL 2.94 and the per-row objective 0.935.
What the variational posterior misses
ReadDeep neural network (torch MLP): cross-validated ROC AUC 0.863 ± 0.042 over 3 folds; ROC AUC on the locked test set 0.819 (n = 106).
- CV ROC AUC
- 0.8626
- SD across folds
- 0.0421
- Test ROC AUC
- 0.8193
Cross-validation
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 142 | 0.8974 | 0.4094 | 0.7958 | 0.7184 |
| 2 | 1 | 142 | 0.8159 | 0.5067 | 0.7676 | 0.7457 |
| 3 | 1 | 142 | 0.8746 | 0.4272 | 0.7958 | 0.7744 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Deep neural network (torch MLP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.torch_mlp 1.4.2 · spec 52f3ff99a151f53f
# 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)
# torch for R (LibTorch); the network itself is built by codesplashr's cs_deep_* twins.
# %% Data and split plan
TARGET <- "diabetic"
FEATURES <- c("glu", "bmi", "age", "ped")
TASK <- "binary"
CLASSES <- c("false", "true")
POSITIVE <- "true"
METRIC <- "roc_auc"
SEED <- 42
PARAMS <- list(
hidden_layers = c(8),
activation = "relu",
epochs = 60,
learning_rate = 0.01,
batch_size = 128,
weight_decay = 0.0001,
early_stopping = 0,
validation_fraction = 0.1,
dropout = 0,
mc_passes = 10,
variational_weights = TRUE,
prior_scale = 0.5,
kl_weight = 1,
robust_training = "none",
dro_step = 0.01,
adv_epsilon = 0.1,
adv_steps = 5,
trades_beta = 6,
loss = "cross_entropy",
focal_gamma = 2,
focal_alpha = NULL,
dp_epsilon = NULL,
dp_noise_multiplier = NULL,
dp_max_grad_norm = 1,
dp_delta = NULL,
dp_sampling = "poisson",
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
label_smoothing = 0,
mixup_alpha = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.torch_mlp/binary_bayes_by_backprop/folds.parquet") # host-written folds: identical in Python and R
design <- cs_ml_design(
df, FEATURES,
kinds = list(
glu = "numeric",
bmi = "numeric",
age = "numeric",
ped = "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("target/academy-parity/run-8142/learn.torch_mlp/binary_bayes_by_backprop/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]
RESAMPLE <- "none"
if (RESAMPLE != "none" && TASK == "regression") {
warnings <- c(warnings, list("Resampling applies to classification only — ignored for this regression target."))
}
resampled <- NULL # the final model's resampling summary
notes <- list()
# A fit's design matrix, targets and weights: training rows only, resampled when asked
# (cs_ml_resample — the same rows in Python, from the shared random stream).
training_set <- function(X, rows, fold_id, repeat_) {
yy <- y[rows + 1L]
ww <- sample_weights(rows)
if (RESAMPLE == "none" || TASK == "regression") return(list(X = X, y = yy, w = ww))
r <- cs_ml_resample(X, yy, ww, RESAMPLE, ratio = 1, k = as.integer(5),
seed = cs_ml_resample_seed(SEED, fold_id, repeat_))
if (fold_id == 0) resampled <<- r$info
r
}
fit_on <- function(s) fit_model(s$X, s$y, s$w)
# %% Model
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
dp_epsilon = NULL,
dp_noise_multiplier = NULL,
dp_max_grad_norm = 1,
dp_delta = NULL,
dp_sampling = "poisson",
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
label_smoothing = 0,
mixup_alpha = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/learn.torch_mlp/binary_bayes_by_backprop/out-r")
.deep_folds <- length(if (0 > 0) utils::head(plan$folds, 0) else plan$folds)
.deep_training_set <- training_set
# Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build the
# training set as _ml_learn does.
training_set <- function(X, rows, fold_id, repeat_) {
cs_deep_trainer_set_fold(as.integer(fold_id), .deep_folds, if (fold_id > 0) "cv" else "final")
.deep_training_set(X, rows, fold_id, repeat_)
}
# A dense network on torch for R (float64, one thread): hidden layers HIDDEN with ACTIVATION units, a
# linear output (1 value, 1 logit or K logits), trained by Adam from weights drawn from the shared
# random stream — Python's torch starts from the same weights and takes the same steps.
HIDDEN <- as.integer(unlist(PARAMS$hidden_layers))
if (!length(HIDDEN)) HIDDEN <- 32L
ACTIVATION <- PARAMS$activation
DROPOUT <- as.numeric(PARAMS$dropout)
PASSES <- as.integer(PARAMS$mc_passes)
VARIATIONAL <- isTRUE(PARAMS$variational_weights)
ROBUST <- PARAMS$robust_training
# Any of the options on: train with cs_deep_fit_mlp_ext (otherwise the plain network, unchanged).
EXTENDED <- DROPOUT > 0 || PASSES > 0 || VARIATIONAL || ROBUST != "none"
if (PASSES > 0 && DROPOUT == 0 && !VARIATIONAL) {
cs_error("CS_E_INVALID_OPTION", option = "Prediction passes", allowed = "0 unless dropout or variational weights are on", value = PASSES)
}
if (VARIATIONAL && DROPOUT > 0) {
cs_error("CS_E_INVALID_OPTION", option = "Dropout", allowed = "0 with variational weights (their noise replaces it)", value = DROPOUT)
}
SUBGROUPS <- NULL
if (ROBUST == "group_dro" && is.null(SUBGROUPS)) {
cs_error("CS_E_INVALID_OPTION", option = "Robust training", allowed = "Group DRO only with a Subgroups column", value = "group_dro")
}
if (ROBUST == "group_dro" && RESAMPLE != "none" && TASK != "regression") {
cs_error("CS_E_INVALID_OPTION", option = "Resampling", allowed = "none with Group DRO", value = RESAMPLE)
}
# Differential privacy (DP-SGD): with an epsilon or a noise multiplier set, every fit clips each row's
# gradient and adds noise (cs_deep_dp_*, turned on by the trainer's dp plugin above; the guarantee goes to
# dp.json). Off by default. These options can't be combined with it:
DP <- cs_deep_dp_settings(PARAMS)
if (!is.null(DP)) {
if (VARIATIONAL || ROBUST != "none") {
cs_error("CS_E_INVALID_OPTION", option = "Differential privacy", allowed = "off with variational weights or robust training", value = "on")
}
if (RESAMPLE != "none") {
cs_error("CS_E_INVALID_OPTION", option = "Differential privacy", allowed = "off with resampling (copies of a row would each count)", value = "on")
}
}
fit_model <- function(X, y, w) {
if (cs_deep_dp_enabled() && !is.null(w) && diff(range(as.numeric(w))) > 0) {
cs_error("CS_E_INVALID_OPTION", option = "Differential privacy", allowed = "off with row or class weights", value = "on")
}
if (TASK == "regression") {
# Standardize the target (training mean and population SD); predictions are mapped back.
mu <- mean(y); sd <- sqrt(mean((y - mu)^2)); if (!(sd > 0)) sd <- 1
target <- (as.numeric(y) - mu) / sd; o <- 1L
} else if (TASK == "binary") {
mu <- 0; sd <- 1
target <- as.numeric(y); o <- 1L
} else {
mu <- 0; sd <- 1
target <- cs_deep_one_hot(y, length(CLASSES)); o <- length(CLASSES)
}
if (!EXTENDED) {
fit <- cs_deep_fit_mlp(
unname(X), target, w, TASK, HIDDEN, o,
activation = ACTIVATION,
epochs = as.integer(PARAMS$epochs),
lr = PARAMS$learning_rate,
batch_size = if (is.null(PARAMS$batch_size)) NULL else as.integer(PARAMS$batch_size),
weight_decay = PARAMS$weight_decay,
early_stopping = as.integer(PARAMS$early_stopping) > 0,
validation_fraction = PARAMS$validation_fraction,
patience = max(1L, as.integer(PARAMS$early_stopping)),
seed = SEED
)
return(list(params = fit$params, mu = mu, sd = sd, history = fit$history, best_epoch = fit$best_epoch))
}
fit <- cs_deep_fit_mlp_ext(
unname(X), target, w, TASK, HIDDEN, o,
activation = ACTIVATION,
epochs = as.integer(PARAMS$epochs),
lr = PARAMS$learning_rate,
batch_size = if (is.null(PARAMS$batch_size)) NULL else as.integer(PARAMS$batch_size),
weight_decay = PARAMS$weight_decay,
early_stopping = as.integer(PARAMS$early_stopping) > 0,
validation_fraction = PARAMS$validation_fraction,
patience = max(1L, as.integer(PARAMS$early_stopping)),
seed = SEED,
dropout = DROPOUT,
variational = VARIATIONAL,
prior_scale = PARAMS$prior_scale,
kl_weight = PARAMS$kl_weight,
robust = ROBUST,
groups = if (ROBUST != "group_dro") NULL else SUBGROUPS[FIT_ROWS + 1L],
dro_step = PARAMS$dro_step,
adv_epsilon = PARAMS$adv_epsilon,
adv_steps = as.integer(PARAMS$adv_steps),
trades_beta = PARAMS$trades_beta,
mc_passes = PASSES
)
fit$mu <- mu; fit$sd <- sd; fit$extended <- TRUE
fit
}
predict_model <- function(model, X) {
p <- if (!isTRUE(model$extended)) cs_deep_mlp_predict(model$params, unname(X), ACTIVATION, TASK) else cs_deep_mlp_predict_ext(model, unname(X), TASK)$mean
if (TASK == "regression") model$mu + model$sd * p else p
}
# Predictive SD (numbers, with prediction passes): sqrt(training residual variance + spread across passes).
predict_sd <- function(model, X) model$sd * sqrt(model$noise_var + cs_deep_mlp_predict_ext(model, unname(X), TASK)$spread)
feature_importance <- function(model, names) NULL
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path) # plain numeric weights + the target scaling
hist <- file.path(directory, "history.parquet")
nanoparquet::write_parquet(cs_deep_history_frame(model$history), hist)
list(list(key = "model", path = path, format = "rds"), list(key = "history", path = hist, format = "parquet"))
}
load_model <- function(directory) readRDS(file.path(directory, "model.rds"))
# %% Cross-validation
folds <- if (0 > 0) utils::head(plan$folds, 0) else plan$folds
progress <- cs_progress("Cross-validating", total = length(folds))
for (i in seq_along(folds)) {
fold <- folds[[i]]
prep <- cs_ml_design_fit(design, rows_of(fold$train))
model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(fold$train)), fold$train, fold$id, fold$repeat_))
cs_ml_add(run, fold$id, fold$repeat_, "valid", fold$valid, y, y_index,
predict_model(model, cs_ml_design_apply(prep, rows_of(fold$valid))))
cs_progress_update(progress, i, sprintf("Fold %d of %d", i, length(folds)))
}
cs_ml_lap(run, "cv_seconds")
# %% Final model
artifacts <- list()
importance <- NULL
prep <- cs_ml_design_fit(design, rows_of(plan$train))
names_ <- cs_ml_design_names(prep)
if (TRUE) {
model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(plan$train)), plan$train, 0L, 0L))
if (!is.null(resampled)) {
warnings <- c(warnings, as.list(resampled$notes))
notes <- c(notes, list(cs_ml_resample_describe(resampled)))
}
if (length(plan$test)) {
cs_ml_add(run, 0L, 0L, "test", plan$test, y, y_index,
predict_model(model, cs_ml_design_apply(prep, rows_of(plan$test))))
}
importance <- feature_importance(model, names_)
artifacts[[length(artifacts) + 1L]] <- list(
key = "design", path = cs_ml_save_json(cs_ml_design_json(prep), file.path(out, "design.json")), format = "json"
)
artifacts <- c(artifacts, save_model(model, out))
cs_ml_lap(run, "final_seconds")
}
artifacts[[length(artifacts) + 1L]] <- list(key = "predictions", path = cs_ml_write(run, out), format = "parquet")
cs_progress_done(progress)
# %% Result
cs_publish(cs_ml_result(
run,
title = "Deep neural network (torch MLP)",
engine = cs_engine_info("torch", "codesplashr", "nanoparquet"),
n_features = length(names_),
n_train = length(plan$train),
n_test = length(plan$test),
params = PARAMS,
features = names_,
importance = importance,
artifacts = artifacts,
warnings = warnings,
notes = notes
))
Deep neural network (torch MLP): cross-validated ROC AUC 0.863 ± 0.042 over 3 folds; ROC AUC on the locked test set 0.819 (n = 106).
- CV ROC AUC
- 0.8626
- SD across folds
- 0.0421
- Test ROC AUC
- 0.8193
Cross-validation
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 142 | 0.8974 | 0.4094 | 0.7958 | 0.7184 |
| 2 | 1 | 142 | 0.8159 | 0.5067 | 0.7676 | 0.7457 |
| 3 | 1 | 142 | 0.8746 | 0.4272 | 0.7958 | 0.7744 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Deep neural network (torch MLP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.torch_mlp 1.4.2 · spec 52f3ff99a151f53f
# 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.deep import core as deep # twin of codesplashr::cs_deep_* (shared initial weights, Adam written out)
from codesplash.deep import mlp_ext as mlpx # dropout, variational weights, Group DRO, PGD/TRADES (twin: cs_deep_*_ext)
from codesplash.deep import dp as deep_dp # differentially private training, DP-SGD (twin: cs_deep_dp_*)
# %% Data and split plan
TARGET = "diabetic"
FEATURES = ["glu", "bmi", "age", "ped"]
TASK = "binary"
CLASSES = ["false", "true"]
POSITIVE = "true"
METRIC = "roc_auc"
SEED = 42
PARAMS = {
"hidden_layers": [8],
"activation": "relu",
"epochs": 60,
"learning_rate": 0.01,
"batch_size": 128,
"weight_decay": 0.0001,
"early_stopping": 0,
"validation_fraction": 0.1,
"dropout": 0,
"mc_passes": 10,
"variational_weights": True,
"prior_scale": 0.5,
"kl_weight": 1,
"robust_training": "none",
"dro_step": 0.01,
"adv_epsilon": 0.1,
"adv_steps": 5,
"trades_beta": 6,
"loss": "cross_entropy",
"focal_gamma": 2,
"focal_alpha": None,
"dp_epsilon": None,
"dp_noise_multiplier": None,
"dp_max_grad_norm": 1,
"dp_delta": None,
"dp_sampling": "poisson",
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"label_smoothing": 0,
"mixup_alpha": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
}
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.torch_mlp/binary_bayes_by_backprop/folds.parquet") # host-written folds: identical in Python and R
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"glu": "numeric",
"bmi": "numeric",
"age": "numeric",
"ped": "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("target/academy-parity/run-8142/learn.torch_mlp/binary_bayes_by_backprop/out-python")
warnings = []
def sample_weights(rows):
return None if weights is None else weights[rows]
RESAMPLE = "none"
if RESAMPLE != "none" and TASK == "regression":
warnings.append("Resampling applies to classification only — ignored for this regression target.")
resampled = None # the final model's resampling summary
notes = []
def training_set(X, rows, fold_id, repeat):
"""A fit's design matrix, targets and weights: training rows only, resampled when asked
(codesplash.ml.resample — the same rows in R, from the shared random stream)."""
yy, ww = y[rows], sample_weights(rows)
if RESAMPLE == "none" or TASK == "regression":
return X, yy, ww
from codesplash.ml import resample as csres
X2, y2, w2, info = csres.resample(
X, yy, ww, RESAMPLE, ratio=1, k=5, seed=csres.resample_seed(SEED, fold_id, repeat)
)
if fold_id == 0:
global resampled
resampled = info
return X2, y2, w2
# %% Model
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"dp_epsilon": None,
"dp_noise_multiplier": None,
"dp_max_grad_norm": 1,
"dp_delta": None,
"dp_sampling": "poisson",
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"label_smoothing": 0,
"mixup_alpha": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-8142/learn.torch_mlp/binary_bayes_by_backprop/out-python",
)
_DEEP_FOLDS = len(plan.folds[: 0] if 0 else plan.folds)
_deep_training_set = training_set
def training_set(X, rows, fold_id, repeat):
"""Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build
the training set as _ml_learn does."""
deep_trainer.set_fold(int(fold_id), _DEEP_FOLDS, "cv" if fold_id else "final")
return _deep_training_set(X, rows, fold_id, repeat)
# A dense network on PyTorch (float64, one thread): hidden layers HIDDEN with ACTIVATION units, a
# linear output (1 value, 1 logit or K logits), trained by Adam from weights drawn from the shared
# random stream — R's torch starts from the same weights and takes the same steps.
HIDDEN = [int(u) for u in PARAMS["hidden_layers"]] or [32]
ACTIVATION = PARAMS["activation"]
DROPOUT = float(PARAMS["dropout"])
PASSES = int(PARAMS["mc_passes"])
VARIATIONAL = bool(PARAMS["variational_weights"])
ROBUST = PARAMS["robust_training"]
# Any of the options on: train with codesplash.deep.mlp_ext (otherwise the plain network, unchanged).
EXTENDED = DROPOUT > 0 or PASSES > 0 or VARIATIONAL or ROBUST != "none"
if PASSES > 0 and DROPOUT == 0 and not VARIATIONAL:
cs.cs_error("CS_E_INVALID_OPTION", option="Prediction passes", allowed="0 unless dropout or variational weights are on", value=PASSES)
if VARIATIONAL and DROPOUT > 0:
cs.cs_error("CS_E_INVALID_OPTION", option="Dropout", allowed="0 with variational weights (their noise replaces it)", value=DROPOUT)
SUBGROUPS = None
if ROBUST == "group_dro" and SUBGROUPS is None:
cs.cs_error("CS_E_INVALID_OPTION", option="Robust training", allowed="Group DRO only with a Subgroups column", value="group_dro")
if ROBUST == "group_dro" and RESAMPLE != "none" and TASK != "regression":
cs.cs_error("CS_E_INVALID_OPTION", option="Resampling", allowed="none with Group DRO", value=RESAMPLE)
# Differential privacy (DP-SGD): with an ε or a noise multiplier set, every fit clips each row's gradient
# and adds noise (codesplash.deep.dp, turned on by the trainer's dp plugin above; the guarantee goes to dp.json).
# Off by default. These options can't be combined with it:
DP = deep_dp.settings(PARAMS)
if DP is not None:
if VARIATIONAL or ROBUST != "none":
cs.cs_error("CS_E_INVALID_OPTION", option="Differential privacy", allowed="off with variational weights or robust training", value="on")
if RESAMPLE != "none":
cs.cs_error("CS_E_INVALID_OPTION", option="Differential privacy", allowed="off with resampling (copies of a row would each count)", value="on")
def fit_model(X, y, w):
if deep_dp.enabled() and w is not None and float(np.ptp(np.asarray(w, dtype=np.float64))) > 0:
cs.cs_error("CS_E_INVALID_OPTION", option="Differential privacy", allowed="off with row or class weights", value="on")
if TASK == "regression":
# Standardize the target (training mean and population SD); predictions are mapped back.
mu, sd = float(np.mean(y)), float(np.std(y)) or 1.0
target, o = (np.asarray(y, dtype=np.float64) - mu) / sd, 1
elif TASK == "binary":
mu, sd = 0.0, 1.0
target, o = np.asarray(y, dtype=np.float64), 1
else:
mu, sd = 0.0, 1.0
target, o = deep.one_hot(y, len(CLASSES)), len(CLASSES)
common = dict(
activation=ACTIVATION,
epochs=int(PARAMS["epochs"]),
lr=PARAMS["learning_rate"],
batch_size=None if PARAMS["batch_size"] is None else int(PARAMS["batch_size"]),
weight_decay=PARAMS["weight_decay"],
early_stopping=int(PARAMS["early_stopping"]) > 0,
validation_fraction=PARAMS["validation_fraction"],
patience=max(1, int(PARAMS["early_stopping"])),
seed=SEED,
)
if not EXTENDED:
fit = deep.fit_mlp(X, target, w, TASK, HIDDEN, o, **common)
return {"params": fit["params"], "mu": mu, "sd": sd, "history": fit["history"], "best_epoch": fit["best_epoch"]}
fit = mlpx.fit_mlp_ext(
X, target, w, TASK, HIDDEN, o, **common,
dropout=DROPOUT,
variational=VARIATIONAL,
prior_scale=PARAMS["prior_scale"],
kl_weight=PARAMS["kl_weight"],
robust=ROBUST,
groups=None if ROBUST != "group_dro" else SUBGROUPS[FIT_ROWS],
dro_step=PARAMS["dro_step"],
adv_epsilon=PARAMS["adv_epsilon"],
adv_steps=int(PARAMS["adv_steps"]),
trades_beta=PARAMS["trades_beta"],
mc_passes=PASSES,
)
fit.update({"mu": mu, "sd": sd, "extended": True})
return fit
def predict_model(model, X):
if not model.get("extended"):
p = deep.mlp_predict(model["params"], X, ACTIVATION, TASK)
else:
p, _ = mlpx.mlp_predict_ext(model, X, TASK)
if TASK == "regression":
return model["mu"] + model["sd"] * p
return p
def predict_sd(model, X):
"""Predictive SD (numbers, with prediction passes): √(training residual variance + spread across passes)."""
_, spread = mlpx.mlp_predict_ext(model, X, TASK)
return model["sd"] * np.sqrt(model["noise_var"] + spread)
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) # plain numpy weights + the target scaling
hist = os.path.join(directory, "history.parquet")
deep.history_frame(model["history"]).to_parquet(hist, index=False)
return [{"key": "model", "path": path, "format": "joblib"}, {"key": "history", "path": hist, "format": "parquet"}]
def load_model(directory):
import joblib
return joblib.load(os.path.join(directory, "model.joblib"))
# %% Cross-validation
folds = plan.folds[: 0] if 0 else plan.folds
progress = cs.progress("Cross-validating", total=len(folds))
for i, fold in enumerate(folds):
prep = design.fit(df.iloc[fold.train])
model = fit_model(*training_set(prep.transform(df.iloc[fold.train]), fold.train, fold.id, fold.repeat))
run.add(fold.id, fold.repeat, "valid", fold.valid, y, y_index, predict_model(model, prep.transform(df.iloc[fold.valid])))
progress.update(i + 1, f"Fold {i + 1} of {len(folds)}")
run.lap("cv_seconds")
# %% Final model
artifacts = []
importance = None
prep = design.fit(df.iloc[plan.train])
names = prep.names
if True:
model = fit_model(*training_set(prep.transform(df.iloc[plan.train]), plan.train, 0, 0))
if resampled is not None:
from codesplash.ml import resample as csres
warnings.extend(resampled["notes"])
notes.append(csres.describe(resampled))
if len(plan.test):
run.add(0, 0, "test", plan.test, y, y_index, predict_model(model, prep.transform(df.iloc[plan.test])))
importance = feature_importance(model, names)
artifacts.append({"key": "design", "path": csml.save_json(prep.to_json(), os.path.join(out, "design.json")), "format": "json"})
artifacts.extend(save_model(model, out))
run.lap("final_seconds")
artifacts.append({"key": "predictions", "path": run.write(out), "format": "parquet"})
progress.done()
# %% Result
cs.publish(
run.result(
title="Deep neural network (torch MLP)",
engine=cs.engine_info("torch", "codesplash", "numpy", "pandas"),
n_features=len(names),
n_train=len(plan.train),
n_test=len(plan.test),
params=PARAMS,
features=names,
importance=importance,
artifacts=artifacts,
warnings=warnings,
notes=notes,
)
)
The run's held-out log loss was 0.448. The prior, the likelihood and the mean-field family (independent weights) are real assumptions: mean-field fits tend to understate tails and miss correlated weights. A weight's variational SD is not a standard error. A good ELBO can sit beside poor calibration, and a KL weight other than 1 defines a different objective; say so.
Three different things
PredictPredict first
A colleague says: "The network uses dropout, so its prediction intervals are calibrated." Is that right?
Reveal
No. Dropout during training is regularization. Dropout at prediction is an approximate posterior. Calibration is a property you measure, or enforce with conformal prediction. Each can hold without the others.
Where each idea stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| MC dropout (UNC004) | Runs as an option of Deep neural network (torch MLP): Dropout with Prediction passes |
| Bayes by Backprop (UNC005) | Runs as an option of Deep neural network (torch MLP): Variational weights (Bayes by Backprop) (Experimental) |
Check your understanding
CheckpointCheck yourself
What does raising the number of prediction passes T do?
Show the answer
Answer: b
T is an integration budget. Plot the estimate against T and stop once it is stable.
Check yourself
You switch dropout on at prediction time in a network that was trained without dropout. What do the passes give you?
Show the answer
Answer: b
The Bayesian reading needs the same dropout placement and rate in training and prediction.
Check yourself
Your MC-dropout intervals leave out the noise variance σ². What do they describe?
Show the answer
Answer: a
New observations vary around the mean by the noise too. State which convention you report.
Check yourself
Why does Bayes by Backprop write each weight as ?
Show the answer
Answer: b
Sampling ε outside the parameters lets backpropagation train the distribution, not only one weight value.
Check yourself
A weight's variational SD is small. Can you report it as the weight's standard error?
Show the answer
Answer: b
Mean-field variational fits often understate spread. Judge the method by predictive scores and coverage.
Check yourself
A Bayes by Backprop model reaches a good ELBO. What still needs checking?
Show the answer
Answer: a
The ELBO measures optimization of an approximate objective, not whether the uncertainty is right.
Do it on your own data
In the appIn Predict, choose Deep neural network (torch MLP), set Dropout above zero and Prediction passes to 20 or more, or switch on Variational weights. Compare the intervals' coverage with a Deep ensemble on the same split.
Concepts in this lesson