Skip to content

Deep ensembles: disagreement as uncertainty

Train several networks independently and average their predictive distributions. Why the average is a mixture, how to score it, where member diversity comes from, and why a confident consensus can still be wrong far from the data.

Advanced ~12 min9 steps

What runs in CodeSplash

You will be able to

  • Combine members as a mixture and score it with the mixture log likelihood
  • Split predictive variance into average member noise and member disagreement
  • Say where diversity comes from and what collapses it
  • Choose the ensemble size and validate disagreement as a ranking signal

Read first

01

Several networks, one answer

Read

A deep ensembleDeep ensembleSeveral networks trained from different starting weights; their spread shows where the model is unsure. trains MM networks on the same data, each from its own random start and its own shuffling of the rows. Each member predicts a full distribution, for numbers a mean μm(x)\mu_m(x) and a variance σm2(x)\sigma_m^2(x). The ensemble's prediction is their average:

p(y∣x)=1M∑m=1Mpm(y∣x).p(y\mid x)=\frac1M\sum_{m=1}^M p_m(y\mid x).

That average is a mixture, not one member with averaged parameters. It can be wider than any member and even have two peaks when members disagree about where the answer is.

02

Mean and variance of the mixture

Read

For Gaussian members the mixture's mean is μˉ=1M∑mμm\bar\mu=\frac1M\sum_m\mu_m, and its variance adds two parts: the average member variance (the noise each member expects) and the spread of member means (their disagreement).

In the reference's three-member example, members predict means between 0.80.8 and 1.21.2 for the first row; the mixture mean is 1 and its variance 0.160. Score it with the mixture's log likelihood, computed with log-sum-exp over members, not by averaging members' log scores: the example's mixture NLL is 0.226.

03

Where diversity comes from

Read

Members differ because of random initialization and random mini-batch order; bootstrapped rows are optional. That's usually enough for networks, whose loss surfaces have many good, different minima.

Diversity can collapse. Fine-tune every member from the same pretrained network along the same path, or adapt only a shared head, and the members agree for reasons that have nothing to do with the data. Errors can also stay correlated when every member shares the same misspecification, such as a missing feature.

Leave a gap in the training data and compare members that differ with members that don't.

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?

How sure?
8

Models in the ensemble, and dropout masks drawn for MC dropout.

0.30

Share of features switched off in each MC dropout pass.

0.20

Noise around the true curve sin(1.5x).

60

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 first; the figure appears when you commit.

Make your prediction to see the result.

04

Far from the data

Predict

Predict first

An ensemble of house-price networks sees a property twice as large as any in the training data. What do the members do?

They disagree, flagging the caseThey can agree and still be wrong
Reveal

They can agree and still be wrong. Networks often extrapolate the same trend, so disagreement stays low exactly where it matters. Disagreement is a ranking signal to validate on deliberately shifted data, not a guarantee.

05

A run in CodeSplash

Read
Deep ensembleRecorded · Python and R agreeRecorded 2026-11-25 · 34 values compared · largest relative difference 9.5e-10
R

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

FoldRepeatnRMSEMAER²MAPE
113124.96315.6830.61790.4199
213114.85511.3010.71580.6206
313117.79613.2280.72260.3323

Training curves

NetworkEpochTraining lossValidation loss
member 110.7835—
member 120.6736—
member 130.5884—
member 140.5219—
member 150.4692—
member 160.4263—
member 170.3903—
member 180.3591—
member 190.3313—
member 1100.3059—
member 1110.2820—
member 1120.2592—
member 1130.2369—
member 1140.2147—
member 1150.1920—
member 1160.1684—
member 1170.1438—
member 1180.1182—
member 1190.0922—
member 1200.0663—
member 1210.0412—
member 1220.0173—
member 123−0.0049—
member 124−0.0256—
member 125−0.0457—
member 126−0.0653—
member 127−0.0847—
member 128−0.1046—
member 129−0.1248—
member 130−0.1445—
member 131−0.1633—
member 132−0.1824—
member 133−0.2046—
member 134−0.2286—
member 135−0.2496—
member 136−0.2672—
member 137−0.2878—
member 138−0.3084—
member 139−0.3212—
member 140−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_))
Python

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

FoldRepeatnRMSEMAER²MAPE
113124.96315.6830.61790.4199
213114.85511.3010.71580.6206
313117.79613.2280.72260.3323

Training curves

NetworkEpochTraining lossValidation loss
member 110.7835—
member 120.6736—
member 130.5884—
member 140.5219—
member 150.4692—
member 160.4263—
member 170.3903—
member 180.3591—
member 190.3313—
member 1100.3059—
member 1110.2820—
member 1120.2592—
member 1130.2369—
member 1140.2147—
member 1150.1920—
member 1160.1684—
member 1170.1438—
member 1180.1182—
member 1190.0922—
member 1200.0663—
member 1210.0412—
member 1220.0173—
member 123−0.0049—
member 124−0.0256—
member 125−0.0457—
member 126−0.0653—
member 127−0.0847—
member 128−0.1046—
member 129−0.1248—
member 130−0.1445—
member 131−0.1633—
member 132−0.1824—
member 133−0.2046—
member 134−0.2286—
member 135−0.2496—
member 136−0.2672—
member 137−0.2878—
member 138−0.3084—
member 139−0.3212—
member 140−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.

With 4 members, the held-out 90% intervals covered 87.1% of rows and the CRPS was 9.76. On chick weights, where noise grows with time, disagreement was only 3.1% of the predictive variance: most of the uncertainty was noise each member could see.

06

How many members?

Read

Add members until the predictions and the disagreement stop changing, within your compute budget; a handful often gets most of the benefit. Keep each member's output, so you can see who disagreed.

Then check what matters: mixture NLL, Brier score or CRPS, interval coverage and width, and risk–coverage curves (accuracy as you abstain on the most uncertain cases), on in-domain rows and on a shifted set chosen in advance. If the mixture variance hides two peaks, a Gaussian interval around it misleads.

07

Where it stands in CodeSplash

Read
EntryIn CodeSplash
Deep ensembles (UNC003)Runs in CodeSplash (Experimental): Deep ensemble, with mixture intervals and the disagreement share
08

Check your understanding

Checkpoint

Check yourself

How should you compute an ensemble's log score for a held-out row?

Show the answer

Answer: b

The ensemble's prediction is the mixture, so score the mixture. Averaging log scores scores something else and is always worse.

Check yourself

An ensemble's predictive variance is mostly average member variance, with little disagreement. What does that suggest?

Show the answer

Answer: a

Member variance captures noise; spread of means captures disagreement. Treat the split as a summary: it depends on how diverse the members are.

Check yourself

All members are fine-tuned from the same pretrained network with the same data order. What happens to the uncertainty estimate?

Show the answer

Answer: b

Members need independent randomness. Shared starts and paths make them agree for reasons unrelated to the data.

Check yourself

Can you rely on ensemble disagreement to flag every out-of-distribution input?

Show the answer

Answer: b

Disagreement is useful but not guaranteed. A confident consensus far from the training data can still be wrong.

09

Do it on your own data

In the app

In Predict, choose Deep ensemble as the learner, read its interval coverage and disagreement share, and compare its CRPS or log loss with a single Deep neural network (torch MLP) on the same split.

Concepts in this lesson