Skip to content

Networks that know their limits: dropout passes, variational weights and robust training

Get a predictive SD from a torch network with Monte Carlo dropout or variational weights, train for the worst subgroup with Group DRO, and make predictions steadier with PGD or TRADES.

Advanced ~14 min7 steps

What runs in CodeSplash

You will be able to

  • Turn dropout and prediction passes into a predictive SD, and check its coverage
  • Explain what variational weights learn and what the KL weight does
  • Choose between Group DRO, PGD and TRADES for a goal, and say what each costs

Read first

01

One network, many guesses

Read

A trained network gives one number per row. It says nothing about how sure it is. Dropout switches off a random share of hidden units at every training step. Keep it on when predicting, run the network many times, and the predictions spread out where the network learned little. That is Monte Carlo dropout.

y^=1T∑t=1Tft(x),SD^=σ^2+1T∑t=1T(ft(x)−y^)2\hat{y} = \frac{1}{T}\sum_{t=1}^{T} f_t(x), \qquad \widehat{\mathrm{SD}} = \sqrt{\hat\sigma^2 + \frac{1}{T}\sum_{t=1}^{T}\big(f_t(x) - \hat{y}\big)^2}

Here σ^2\hat\sigma^2 is the training rows' residual variance: the noise no network removes. In CodeSplash each pass switches off the same units for every row, so a row's prediction never depends on which other rows are scored with it. Both engines draw the same masks from the shared random stream.

02

Does the SD mean anything?

Predict
Deep neural network (torch MLP)Recorded · Python and R agreeRecorded 2026-11-25 · 30 values compared
R

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

FoldRepeatnRMSEMAER²MAPE
113126.37216.9720.57360.4540
213119.51115.3840.50970.9744
313119.28215.0740.67430.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
))
Python

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

FoldRepeatnRMSEMAER²MAPE
113126.37216.9720.57360.4540
213119.51115.3840.50970.9744
313119.28215.0740.67430.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,
    )
)

Ozone with a fifth of the hidden units dropped at each step and 20 prediction passes. RMSE is 21.7, against 24.6 for the plain network with early stopping.

Predict first

The run reports how often the true value falls inside the 90% interval built from that SD on held-out rows. What do you expect?

Close to 90%Well below 90%Exactly 90% by construction
Reveal

It depends on the data, so check it. Here it is 87.1%. Nothing forces 90%. Dropout's spread is an approximation, so read the coverage and the negative log-likelihood (4.49) before trusting the intervals. If coverage is off, the Uncertainty tab's conformal intervals give a guaranteed rate.

03

Variational weights

Read

Bayes by Backprop goes further: every weight gets a Normal distribution, not one value. Each training step samples one network and adds a penalty for drifting from the prior N(0, s²):

loss=mean loss+β⋅KL(q(w) ∥ N(0,s2))n\text{loss} = \text{mean loss} + \beta \cdot \frac{\mathrm{KL}\big(q(w)\,\|\,\mathcal{N}(0, s^2)\big)}{n}

Prediction passes then average networks drawn from those distributions. On Pima with four features the AUC is 0.863, against 0.837 for the plain seven-feature network. A larger KL weight (β) or a smaller Prior SD keeps weights near 0, which works like a strong L2 penalty. Variational weights are Experimental: they train more slowly and are sensitive to β.

04

Training for the worst group

Read

The average loss can hide a group the model serves badly. Group DRO weights each subgroup's loss and, at every step, moves weight toward the groups doing worst:

qg←qg eηLg∑hqh eηLh,loss=∑gqgLgq_g \leftarrow \frac{q_g\, e^{\eta L_g}}{\sum_h q_h\, e^{\eta L_h}}, \qquad \text{loss} = \sum_g q_g L_g

On penguins with island as the subgroup (not a feature), log loss is 0.0544. With early stopping, Group DRO watches the worst group's validation loss. On ozone by month the RMSE is 28.4. Judge it in Slices or Fairness by the worst group's error, not the average.

05

Steadier predictions

Read

PGD adversarial training nudges every row up to ±ε on the scaled inputs, in the direction that raises the loss most, and trains on the nudged rows. TRADES keeps the usual loss and adds β times how much predictions change inside the ±ε box. Category indicators are never nudged.

On ozone, PGD with ε = 0.1 gives RMSE 21.3. On Pima, TRADES with ε = 0.05 and β = 2 gives AUC 0.841. Expect a little less clean accuracy for steadier predictions.

GoalOption
Know how unsure each prediction isDropout + prediction passes, or variational weights
Protect the worst subgroupGroup DRO with a Subgroups column
Predictions that don't flip on tiny input changesPGD, or TRADES to control the trade-off
06

Check your understanding

Checkpoint

Check yourself

Each prediction pass switches off the same units for every row. Why?

Show the answer

Answer: a

A pass is one sampled network. Scoring row 7 alone or with a thousand others gives the same answer.

Check yourself

You set Prediction passes to 20 but leave Dropout at 0 and variational weights off. What happens?

Show the answer

Answer: b

With nothing random in the network every pass is the same, so the app asks you to choose a source of variation.

Check yourself

With variational weights, what does raising the KL weight (β) do?

Show the answer

Answer: a

β scales the distance to N(0, s²) in the loss. Larger β, weights closer to the prior.

Check yourself

Group DRO raised the average error a little. Was it worth it?

Show the answer

Answer: b

Group DRO trades some average accuracy for the worst group. Read it in Slices or Fairness.

Check yourself

What does TRADES with β = 0 train?

Show the answer

Answer: a

TRADES is the clean loss plus β times the change inside the ±ε box.

07

Try it

In the app

In Predict's Learners step, open the settings of Deep neural network (torch MLP). Set Dropout above 0 (a fifth is a good start) and Prediction passes to 20 for a numeric target, then read the coverage and the SD in Uncertainty. For Group DRO, choose a Subgroups column in Setup first, then set Robust training.

Concepts in this lesson