Skip to content

The multilayer perceptron, layer by layer

Build a dense network from affine layers and activations, name every shape, count its parameters, and read what a trained one does and doesn't promise.

Applied ~12 min8 steps

What runs in CodeSplash

You will be able to

  • Write one layer as an affine map followed by an activation, with every shape named
  • Count a dense network's weights and biases from its layer widths
  • Say what an MLP is good for, and what a good training score doesn't show

Read first

01

One layer: weights, bias, bend

Read

A multilayer perceptronNeural networkLayers of units, each a weighted sum passed through a non-linear activation, trained by gradient descent. is a chain of layers. Each takes a batch of rows, shape B × d, multiplies it by a weight matrix of shape d × h, adds one bias per output, and bends every value with an activationActivation functionThe non-linear bend inside a hidden unit. Without it, a stack of layers is one big linear model.:

H=ϕ(XW+b)H = \phi(XW + b)

The next layer reads H, now B × h. The last layer has no bend for a number, one logistic output for yes/no, or a softmaxSoftmaxTurns a vector of scores into probabilities: exponentiate each, divide by the total. Subtracting the max first keeps it stable. over K outputs for classes. Without the bends the chain would collapse into one linear model.

02

A forward pass you can check

Read

The program below pushes two rows through three ReLU units and a two-class softmax. The first row gets probabilities 0.345 and 0.655; the second 0.550 and 0.450. Each row sums to one, and the program checks that.

These weights are made up and nothing was trained, so the probabilities say nothing about any data. A passing check like this one tests the arithmetic, not the model.

Python
import numpy as np

def softmax(z):
    e = np.exp(z - z.max(axis=1, keepdims=True))  # subtract the row max: no overflow
    return e / e.sum(axis=1, keepdims=True)

x = np.array([[1., -1.], [0., 2.]])                     # 2 rows × 2 inputs
W1 = np.array([[.5, -.2, .4], [.3, .1, -.6]])           # 2 inputs → 3 hidden units
W2 = np.array([[.2, -.1], [.4, .3], [-.2, .5]])         # 3 hidden → 2 classes
h = np.maximum(0, x @ W1)                               # ReLU, shape 2 × 3
p = softmax(h @ W2)                                     # shape 2 × 2
assert np.allclose(p.sum(axis=1), 1)
print(p)
R
softmax <- function(z) { e <- exp(z - apply(z, 1, max)); e / rowSums(e) }

x  <- matrix(c(1, -1, 0, 2), 2, byrow = TRUE)                 # 2 rows × 2 inputs
W1 <- matrix(c(.5, -.2, .4, .3, .1, -.6), 2, byrow = TRUE)    # 2 inputs → 3 hidden units
W2 <- matrix(c(.2, -.1, .4, .3, -.2, .5), 3, byrow = TRUE)    # 3 hidden → 2 classes
h <- pmax(x %*% W1, 0)                                        # ReLU, 2 × 3
p <- softmax(h %*% W2)                                        # 2 × 2
stopifnot(all(abs(rowSums(p) - 1) < 1e-10))
print(p)
03

How many parameters?

Predict

Predict first

A network reads 7 numeric columns, has hidden layers of 16 and 8 units and one output for a yes/no target. How many weights and biases does it learn?

31161273896
Reveal

273. Each layer has inputs × outputs weights plus one bias per output: (7 × 16 + 16) + (16 × 8 + 8) + (8 × 1 + 1). Widths, not rows, set the count, which is why a wide network can have more parameters than a small table has rows.

04

Count them live

Explore

DExplorable · Neural network playground

How do hidden units combine straight lines into curved boundaries?

Each hidden unit can draw one straight line. How accurate will this network be on new data?

0.70
How sure?

Data

4
2

Activation

0.50
500
0.000
0.10
120
Simulating…

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.

The playground's network reads 2 inputs and has one output. With Hidden layers at 2 and Units per hidden layer at 4 it learns 37 parameters: (2 × 4 + 4) + (4 × 4 + 4) + (4 × 1 + 1). Predict the count before you change either setting, then check Parameters.

05

Train that network

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

Deep neural network (torch MLP): cross-validated ROC AUC 0.837 ± 0.032 over 3 folds; ROC AUC on the locked test set 0.798 (n = 106).

CV ROC AUC
0.8365
SD across folds
0.0318
Test ROC AUC
0.7980

Cross-validation

FoldRepeatnROC AUClog lossaccuracybalanced accuracy
111420.85520.47430.72540.6496
211420.79980.59100.76060.7404
311420.85460.45090.79580.7897
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 d818e821457ce417
# 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("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
TASK <- "binary"
CLASSES <- c("false", "true")
POSITIVE <- "true"
METRIC <- "roc_auc"
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,
  mc_passes = 0,
  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_pima.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.torch_mlp/binary_pima/folds.parquet")  # host-written folds: identical in Python and R
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    npreg = "numeric",
    glu = "numeric",
    bp = "numeric",
    skin = "numeric",
    bmi = "numeric",
    ped = "numeric",
    age = "numeric"
  ),
  levels = list(
  ),
  impute = "median",
  scale = "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_pima/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_pima/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
))
Python

Deep neural network (torch MLP): cross-validated ROC AUC 0.837 ± 0.032 over 3 folds; ROC AUC on the locked test set 0.798 (n = 106).

CV ROC AUC
0.8365
SD across folds
0.0318
Test ROC AUC
0.7980

Cross-validation

FoldRepeatnROC AUClog lossaccuracybalanced accuracy
111420.85520.47430.72540.6496
211420.79980.59100.76060.7404
311420.85460.45090.79580.7897
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 d818e821457ce417
# 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 = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
TASK = "binary"
CLASSES = ["false", "true"]
POSITIVE = "true"
METRIC = "roc_auc"
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,
    "mc_passes": 0,
    "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_pima.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.torch_mlp/binary_pima/folds.parquet")  # host-written folds: identical in Python and R
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "npreg": "numeric",
        "glu": "numeric",
        "bp": "numeric",
        "skin": "numeric",
        "bmi": "numeric",
        "ped": "numeric",
        "age": "numeric",
    },
    levels={
    },
    impute="median",
    scale="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_pima/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_pima/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,
    )
)

This run trains exactly that shape on Pima's seven columns with Adam. Cross-validated AUC is 0.837, against 0.857 for logistic regression on the same folds.

An MLP is a general tabular baseline and the head of most bigger models. Capacity lets it memorize a small table, so always compare it with a linear baseline, look at a learning curve and calibration, and repeat with several starting seeds.

06

What runs here

Read
EntryIn CodeSplash
Multilayer perceptron (DNN001)Runs in CodeSplash: Neural network (MLP) and Deep neural network (torch MLP), and inside the deep ensemble and TabM
07

Check: the MLP

Checkpoint

Check yourself

A batch of 32 rows with 10 features enters a dense layer of 64 units. What shape leaves the layer?

Show the answer

Answer: a

The weights are 10 × 64, so XW is 32 × 64: one row per input row, one column per unit. The bias adds one value per column.

Check yourself

You remove every activation from a five-layer MLP. What can it still learn?

Show the answer

Answer: a

A product of matrices is one matrix, so five affine layers make one affine map. The bends between layers are what let a network curve.

Check yourself

A colleague says a wide enough MLP can approximate any smooth function, so it must beat a linear model on your 300 rows. What's wrong with the argument?

Show the answer

Answer: b

Being able to represent a function doesn't mean finite, noisy data will find it. Held-out error, a linear baseline and several seeds decide.

08

Recap

Recap
  • A layer is H = φ(XW + b): shapes B × d in, d × h weights, B × h out.
  • Parameters per layer are inputs × outputs plus one bias per output.
  • A check on a forward pass tests arithmetic; a held-out comparison against a linear baseline tests the model.
  • In CodeSplash, Neural network (MLP), Deep neural network (torch MLP), the deep ensemble and TabM all run this architecture.

Concepts in this lesson