What a model doesn't know: noise, ignorance and calibration
A prediction without its uncertainty invites overconfidence. Two kinds of uncertainty, how to score a predictive distribution, and a map of the methods in this track by what they estimate and what they promise.
What runs in CodeSplash
- UNC003Deep ensembles for predictive uncertainty Runs in CodeSplash (Experimental)
- UNC004Monte Carlo dropout for approximate Bayesian prediction Runs in CodeSplash
- UNC005Bayes by Backprop Runs in CodeSplash
- UNC009Conformalized quantile regression (CQR) Runs in CodeSplash (Predict)
- UNC010Deep evidential regression (normal–inverse-gamma) Explained here
- Deep ensemble Experimental
You will be able to
- Tell noise in the outcome (aleatoric) from the model's ignorance (epistemic)
- Score a predictive distribution with a proper scoring rule and check its calibration
- Place ensembles, dropout passes, variational weights, evidential outputs and conformal sets on one map
- Treat any uncertainty split as a modeling summary, not a measured fact
Two kinds of not knowing
ReadA forecast of tomorrow's ozone can be wrong for two different reasons.
- Noise in the world (aleatoric uncertaintyAleatoric uncertaintyUncertainty from noise in the outcome itself, which no amount of data removes.): even with a perfect model, ozone varies for reasons the features don't capture. More data won't shrink it.
- Ignorance of the model (epistemic uncertaintyEpistemic uncertaintyUncertainty from not knowing the right model, which more data can shrink; seen as disagreement between ensemble members.): the model has seen few days like this one, so many different fits agree with the data. More relevant data would shrink it, and it grows far from the training rows.
A model that reports one number hides both. This track is about models that say how unsure they are, and about checking whether they are right to be.
Judge the whole distribution
ReadIf a model predicts a distribution , score the distribution, not only its center. A proper scoring ruleProper scoring ruleA score whose expected value is best when you report your true probability. Log loss and Brier are proper. is one that an honest forecaster can't beat by misreporting: the negative log likelihood , the Brier score for classes, the CRPS for numbers.
Then check calibration: among days given a 90% interval, about 90% should land inside. Among calibrated models, prefer the sharper one, with narrower intervals. Calibration without sharpness is easy: predict the overall spread every day.
HExplorable · Calibration and reliability
When a model says 80%, does the event happen 80% of the time?
If you make the model more overconfident, what happens to its AUC?
Above 1 the model is too extreme; below 1 it hedges. At 1 it is perfectly calibrated.
| Brier | ECE | Calibration slope | AUC |
|---|---|---|---|
| 0.175 | 0.087 | 0.50 | 0.835 |
Commit your prediction above to see the result
Make your prediction to see the result.
How much of an ECE is the binning itself? Score a perfectly calibrated model next to an overconfident one, then fix the latter with one temperature.
HExplorable · How many bins? ECE and temperature scaling
The expected calibration error depends on how you bin. How much of a model's ECE is the bins talking, and can one temperature fix the model?
Score a perfectly calibrated model with these bins on these rows. What ECE will it get?
The model's logits are this many times the truth's. Same model as Calibration and reliability.
Half the rows fit the temperature; the other half score every ECE.
More bins see finer miscalibration but hold fewer rows each.
Bin edges
Equal-width bins split [0, 1] evenly; equal-count bins put the same number of predictions in each.
Blue dots are sized by how many rows fall in the bin. Gray dots are a perfectly calibrated model on the same rows: their distance from the diagonal is pure sampling noise, and it sets a floor under any calibration error you compute with these bins.
Commit your prediction above to see the result
Make your prediction to see the result.
Disagreement as a signal
ReadThe simplest epistemic signal is disagreement. Train several networks from different starting points; where they agree, the data pinned the answer down; where they scatter, they didn't. With Gaussian members the predictive variance splits into the average member variance (noise each member sees) plus the variance of the member means (their disagreement):
Deep ensemble: cross-validated RMSE 19.205 ± 5.199 over 3 folds; RMSE on the locked test set 18.917 (n = 23).
- CV RMSE
- 19.205
- SD across folds
- 5.199
- Test RMSE
- 18.917
Cross-validation
| Fold | Repeat | n | RMSE | MAE | R² | MAPE |
|---|---|---|---|---|---|---|
| 1 | 1 | 31 | 24.963 | 15.683 | 0.6179 | 0.4199 |
| 2 | 1 | 31 | 14.855 | 11.301 | 0.7158 | 0.6206 |
| 3 | 1 | 31 | 17.796 | 13.228 | 0.7226 | 0.3323 |
Training curves
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| member 1 | 1 | 0.7835 | — |
| member 1 | 2 | 0.6736 | — |
| member 1 | 3 | 0.5884 | — |
| member 1 | 4 | 0.5219 | — |
| member 1 | 5 | 0.4692 | — |
| member 1 | 6 | 0.4263 | — |
| member 1 | 7 | 0.3903 | — |
| member 1 | 8 | 0.3591 | — |
| member 1 | 9 | 0.3313 | — |
| member 1 | 10 | 0.3059 | — |
| member 1 | 11 | 0.2820 | — |
| member 1 | 12 | 0.2592 | — |
| member 1 | 13 | 0.2369 | — |
| member 1 | 14 | 0.2147 | — |
| member 1 | 15 | 0.1920 | — |
| member 1 | 16 | 0.1684 | — |
| member 1 | 17 | 0.1438 | — |
| member 1 | 18 | 0.1182 | — |
| member 1 | 19 | 0.0922 | — |
| member 1 | 20 | 0.0663 | — |
| member 1 | 21 | 0.0412 | — |
| member 1 | 22 | 0.0173 | — |
| member 1 | 23 | −0.0049 | — |
| member 1 | 24 | −0.0256 | — |
| member 1 | 25 | −0.0457 | — |
| member 1 | 26 | −0.0653 | — |
| member 1 | 27 | −0.0847 | — |
| member 1 | 28 | −0.1046 | — |
| member 1 | 29 | −0.1248 | — |
| member 1 | 30 | −0.1445 | — |
| member 1 | 31 | −0.1633 | — |
| member 1 | 32 | −0.1824 | — |
| member 1 | 33 | −0.2046 | — |
| member 1 | 34 | −0.2286 | — |
| member 1 | 35 | −0.2496 | — |
| member 1 | 36 | −0.2672 | — |
| member 1 | 37 | −0.2878 | — |
| member 1 | 38 | −0.3084 | — |
| member 1 | 39 | −0.3212 | — |
| member 1 | 40 | −0.3386 | — |
First 40 of 480 rows.
The exact R script · R R version 4.5.1 (2025-06-13)
# Deep ensemble
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.deep_ensemble 1.1.2 · spec cdca01592a199d63
# 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 members are built by codesplashr's cs_deep_fit_ensemble twin.
# %% Data and split plan
TARGET <- "Ozone"
FEATURES <- c("solar radiation", "Wind", "Temp")
TASK <- "regression"
CLASSES <- c()
POSITIVE <- NULL
METRIC <- "rmse"
SEED <- 42
PARAMS <- list(
members = 4,
hidden_layers = c(16),
activation = "relu",
epochs = 120,
learning_rate = 0.01,
batch_size = NULL,
weight_decay = 0,
early_stopping = 0,
validation_fraction = 0.1,
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.deep_ensemble/regression_airquality/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.deep_ensemble/regression_airquality/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(
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.deep_ensemble/regression_airquality/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 deep ensemble on torch for R (float64, one thread): MEMBERS networks with different initial weights
# and batch orders (shared random stream, seed + 1000 m). For a number, each member predicts a mean and a
# variance and trains on the Gaussian negative log-likelihood; the ensemble is their equal-weight mixture.
HIDDEN <- as.integer(unlist(PARAMS$hidden_layers))
if (!length(HIDDEN)) HIDDEN <- 32L
MEMBERS <- as.integer(PARAMS$members)
Z90 <- 1.6448536269514722 # the Normal 95th percentile: a 90% interval
fit_model <- function(X, y, w) {
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)
}
fit <- cs_deep_fit_ensemble(
unname(X), target, w, TASK, o, HIDDEN,
members = MEMBERS,
activation = PARAMS$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
)
fit$mu <- mu
fit$sd <- sd
if (TASK != "multiclass") {
members <- cs_deep_ensemble_members(fit, unname(X))$mu
pr <- cs_deep_ensemble_predict(fit, unname(X))
center <- pr$mean
if (TASK == "regression") {
members <- mu + sd * members; center <- mu + sd * center; spread_sd <- sd * pr$sd
low <- center - Z90 * spread_sd; high <- center + Z90 * spread_sd
fit$epistemic_share <- cs_deep_epistemic_share(fit, unname(X))
} else {
low <- apply(members, 1, min); high <- apply(members, 1, max)
}
disagreement <- sqrt(rowMeans((members - rowMeans(members))^2))
fit$member_sd <- mean(disagreement)
fit$spread <- cs_deep_spread_rows(as.numeric(y), members, center, low, high)
fit$spread_label <- if (TASK == "regression") "Prediction" else "P(positive class)"
}
fit
}
predict_model <- function(model, X) {
p <- cs_deep_ensemble_predict(model, unname(X))$mean
if (TASK == "regression") model$mu + model$sd * p else p
}
# The mixture's predictive SD (regression).
predict_sd <- function(model, X) model$sd * cs_deep_ensemble_predict(model, unname(X))$sd
feature_importance <- function(model, names) NULL
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path)
list(list(key = "model", path = path, format = "rds"))
}
load_model <- function(directory) readRDS(file.path(directory, "model.rds"))
# 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_deep_extend_ensemble(cs_ml_result(
run,
title = "Deep ensemble",
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
), model, names_))
Deep ensemble: cross-validated RMSE 19.205 ± 5.199 over 3 folds; RMSE on the locked test set 18.917 (n = 23).
- CV RMSE
- 19.205
- SD across folds
- 5.199
- Test RMSE
- 18.917
Cross-validation
| Fold | Repeat | n | RMSE | MAE | R² | MAPE |
|---|---|---|---|---|---|---|
| 1 | 1 | 31 | 24.963 | 15.683 | 0.6179 | 0.4199 |
| 2 | 1 | 31 | 14.855 | 11.301 | 0.7158 | 0.6206 |
| 3 | 1 | 31 | 17.796 | 13.228 | 0.7226 | 0.3323 |
Training curves
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| member 1 | 1 | 0.7835 | — |
| member 1 | 2 | 0.6736 | — |
| member 1 | 3 | 0.5884 | — |
| member 1 | 4 | 0.5219 | — |
| member 1 | 5 | 0.4692 | — |
| member 1 | 6 | 0.4263 | — |
| member 1 | 7 | 0.3903 | — |
| member 1 | 8 | 0.3591 | — |
| member 1 | 9 | 0.3313 | — |
| member 1 | 10 | 0.3059 | — |
| member 1 | 11 | 0.2820 | — |
| member 1 | 12 | 0.2592 | — |
| member 1 | 13 | 0.2369 | — |
| member 1 | 14 | 0.2147 | — |
| member 1 | 15 | 0.1920 | — |
| member 1 | 16 | 0.1684 | — |
| member 1 | 17 | 0.1438 | — |
| member 1 | 18 | 0.1182 | — |
| member 1 | 19 | 0.0922 | — |
| member 1 | 20 | 0.0663 | — |
| member 1 | 21 | 0.0412 | — |
| member 1 | 22 | 0.0173 | — |
| member 1 | 23 | −0.0049 | — |
| member 1 | 24 | −0.0256 | — |
| member 1 | 25 | −0.0457 | — |
| member 1 | 26 | −0.0653 | — |
| member 1 | 27 | −0.0847 | — |
| member 1 | 28 | −0.1046 | — |
| member 1 | 29 | −0.1248 | — |
| member 1 | 30 | −0.1445 | — |
| member 1 | 31 | −0.1633 | — |
| member 1 | 32 | −0.1824 | — |
| member 1 | 33 | −0.2046 | — |
| member 1 | 34 | −0.2286 | — |
| member 1 | 35 | −0.2496 | — |
| member 1 | 36 | −0.2672 | — |
| member 1 | 37 | −0.2878 | — |
| member 1 | 38 | −0.3084 | — |
| member 1 | 39 | −0.3212 | — |
| member 1 | 40 | −0.3386 | — |
First 40 of 480 rows.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Deep ensemble
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.deep_ensemble 1.1.2 · spec cdca01592a199d63
# 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
from codesplash.deep import tabular as deeptab # twin of codesplashr::cs_deep_fit_ensemble (shared weights)
# %% Data and split plan
TARGET = "Ozone"
FEATURES = ["solar radiation", "Wind", "Temp"]
TASK = "regression"
CLASSES = []
POSITIVE = None
METRIC = "rmse"
SEED = 42
PARAMS = {
"members": 4,
"hidden_layers": [16],
"activation": "relu",
"epochs": 120,
"learning_rate": 0.01,
"batch_size": None,
"weight_decay": 0,
"early_stopping": 0,
"validation_fraction": 0.1,
"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.deep_ensemble/regression_airquality/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.deep_ensemble/regression_airquality/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(
{
"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.deep_ensemble/regression_airquality/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 deep ensemble on PyTorch (float64, one thread): MEMBERS networks with different initial weights and
# batch orders (shared random stream, seed + 1000·m). For a number, each member predicts a mean and a
# variance and trains on the Gaussian negative log-likelihood; the ensemble is their equal-weight mixture.
HIDDEN = [int(u) for u in PARAMS["hidden_layers"]] or [32]
MEMBERS = int(PARAMS["members"])
Z90 = 1.6448536269514722 # the Normal 95th percentile: a 90% interval
def fit_model(X, y, w):
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)
fit = deeptab.fit_deep_ensemble(
X, target, w, TASK, o, HIDDEN,
members=MEMBERS,
activation=PARAMS["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,
)
fit.update({"mu": mu, "sd": sd})
if TASK != "multiclass":
members, _ = deeptab.ensemble_members(fit, X)
center, spread_sd = deeptab.ensemble_predict(fit, X)
if TASK == "regression":
members, center, spread_sd = mu + sd * members, mu + sd * center, sd * spread_sd
low, high = center - Z90 * spread_sd, center + Z90 * spread_sd
fit["epistemic_share"] = deeptab.epistemic_share(fit, X)
else:
low, high = members.min(axis=1), members.max(axis=1)
disagreement = np.sqrt(np.mean((members - members.mean(axis=1)[:, None]) ** 2, axis=1))
fit["member_sd"] = float(np.mean(disagreement))
fit["spread"] = deeptab.spread_rows(np.asarray(y, dtype=np.float64), members, center, low, high)
fit["spread_label"] = "Prediction" if TASK == "regression" else "P(positive class)"
return fit
def predict_model(model, X):
p, _ = deeptab.ensemble_predict(model, X)
if TASK == "regression":
return model["mu"] + model["sd"] * p
return p
def predict_sd(model, X):
"""The mixture's predictive SD (regression)."""
return model["sd"] * deeptab.ensemble_predict(model, X)[1]
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 of every member and the target scaling
return [{"key": "model", "path": path, "format": "joblib"}]
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(
deeptab.extend_ensemble(run.result(
title="Deep ensemble",
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,
), model, names)
)
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
Here disagreement made up 7.6% of the predictive variance, and 90% intervals covered 87.1% of held-out rows.
The map of this track
Read| Method | Estimates | Promise |
|---|---|---|
| Deep ensembles | spread across independently trained networks | none built in; check coverage |
| Monte Carlo dropout | spread across random dropout masks at prediction | an approximation to a Bayesian posterior |
| Bayes by Backprop | a learned distribution over every weight | a variational approximation |
| Deep evidential regression | uncertainty parameters from one pass | contested: the split isn't identifiable |
| Conformal (CQR) | intervals from held-out errors | coverage on average, if rows are exchangeable |
Only the last row promises anything without trusting the model, and its promise is about coverage on average, not for every subgroup.
Which one promises coverage?
PredictPredict first
You must ship intervals that cover the truth 90% of the time, and you can't vouch for the model's assumptions. Which method gives that guarantee?
Reveal
Conformal prediction. It calibrates intervals on held-out errors, so the 90% holds on average whenever new rows are exchangeable with the calibration rows, whatever the model. Ensembles and Bayesian approximations can be well calibrated too, but you have to check.
A split is a summary
ReadIt's tempting to report "70% of the uncertainty is noise, 30% is the model". Treat such splits with care. The ensemble decomposition depends on how diverse the members are; dropout's depends on the dropout rate; evidential networks can produce the same predictive distribution with different "epistemic" parts.
What you can check is the total: does the predictive distribution score well and cover what it claims, in-domain and on deliberately shifted data? Use the parts to rank cases for review, not as measured quantities.
Where each idea stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| Deep ensembles (UNC003) | Runs in CodeSplash (Experimental): Deep ensemble |
| MC dropout (UNC004) | Runs as an option of Deep neural network (torch MLP) |
| Bayes by Backprop (UNC005) | Runs as an option of Deep neural network (torch MLP) (Experimental) |
| CQR (UNC009) | Runs in the Predict run page's Uncertainty tab, from two quantile runs |
| Deep evidential regression (UNC010) | Explained here |
The next lessons take each method in turn.
Check your understanding
CheckpointCheck yourself
Which uncertainty should shrink if you collect many more rows like the one you're predicting?
Show the answer
Answer: b
Noise in the outcome stays however much you collect; the model's ignorance about a region falls as the region fills with data.
Check yourself
Model A's 90% intervals cover 90% of rows and average 40 units wide. Model B's also cover 90% and average 25 units wide. Which is better?
Show the answer
Answer: b
Calibration first, then sharpness. A proper score such as CRPS rewards both at once.
Check yourself
What does a deep ensemble use as its signal of epistemic uncertainty?
Show the answer
Answer: a
Where members agree, the data pinned down the answer. Where they scatter, many fits were consistent with the data.
Check yourself
How does Monte Carlo dropout get several predictions from one trained network?
Show the answer
Answer: b
Each pass drops a different random set of units, so the outputs vary. Their spread approximates posterior uncertainty under the method's assumptions.
Check yourself
What does Bayes by Backprop learn that an ordinary network doesn't?
Show the answer
Answer: a
Each weight gets a variational Gaussian, trained by sampling weights during training.
Check yourself
What does conformalized quantile regression promise?
Show the answer
Answer: b
The guarantee is marginal: averaged over rows. It needs exchangeability, not a correct model.
Check yourself
What is contested about deep evidential regression's uncertainty split?
Show the answer
Answer: b
A single pass is cheap, but the epistemic number it reports isn't pinned down by the data. Judge the total predictive distribution instead.
Where to go next
RecapThe next lesson starts with the strongest practical baseline, deep ensembles. If proper scores or calibration are new to you, the Evaluation track's lessons on probabilistic scores and calibration come first.
Concepts in this lesson