Skip to content

Lab: train and validate a denoising autoencoder

The reference's first deep-learning lab, step by step. State the question, split before scaling, check gradients by finite differences, and beat the honest baseline, which is doing nothing to the noisy rows.

Advanced ~16 min8 steps

What runs in CodeSplash

You will be able to

  • Design a denoising study with training-only scaling, a fixed budget and a locked test set
  • Check a hand-written gradient against central differences
  • Compare held-out denoised error with the noisy-input baseline
  • List what one seed and one synthetic dataset can and can't show

Read first

01

The question

Read

The lab asks one narrow question: can a small network with a two-number bottleneck denoise rows that lie near a curved two-dimensional surface in three dimensions?

Everything else is a study setting, chosen in advance and written down: the widths, the tanh hidden layers, the noise level, the number of steps, the batch size. The bottleneck size and the noise level are choices, not facts the study discovers. A good lab says that plainly.

02

The design

Read
  • Split into training and held-out rows before anything else.
  • Scale with means and SDs from training rows only.
  • Corrupt each training input with fresh Gaussian noise; the target stays the clean row.
  • Budget: a fixed number of steps and minibatch size, so nothing is tuned on the test rows.
  • Score the test rows once, after training.

Splitting after scaling would let the test rows' means leak into training. With a fixed budget, the test score can't be the result of stopping when it looked best.

03

Check the gradients first

Explore

Before trusting a hand-written backward pass, compare it with central differences, (L(w+h)−L(w−h))/2h\big(L(w + h) - L(w - h)\big) / 2h, for a few weights in every layer. The two should agree to many digits.

Python
import numpy as np
rng = np.random.default_rng(0)
s = rng.uniform(-1, 1, 200)
X = np.column_stack([s, s**2, np.sin(2 * s)])        # rows near a curve in 3-D
X = (X - X.mean(0)) / X.std(0)                        # use training rows' stats in a real study
noisy = X + 0.25 * rng.standard_normal(X.shape)
W1, W2 = 0.5 * rng.standard_normal((3, 2)), 0.5 * rng.standard_normal((2, 3))

def loss(W1, W2):
    return np.mean((np.tanh(noisy @ W1) @ W2 - X) ** 2)   # clean target

H = np.tanh(noisy @ W1)
grad = 2 * H.T @ (H @ W2 - X) / X.size                 # analytic dL/dW2
h, D = 1e-6, np.zeros_like(W2); D[0, 0] = 1e-6
print(grad[0, 0], (loss(W1, W2 + D) - loss(W1, W2 - D)) / (2 * h))
print("do-nothing baseline", np.mean((noisy - X) ** 2))
R
set.seed(0)
s <- runif(200, -1, 1)
X <- scale(cbind(s, s^2, sin(2 * s)))                 # use training rows' stats in a real study
noisy <- X + 0.25 * matrix(rnorm(length(X)), nrow(X))
W1 <- matrix(0.5 * rnorm(6), 3, 2); W2 <- matrix(0.5 * rnorm(6), 2, 3)

loss <- function(W1, W2) mean((tanh(noisy %*% W1) %*% W2 - X)^2)   # clean target

H <- tanh(noisy %*% W1)
grad <- 2 * t(H) %*% (H %*% W2 - X) / length(X)        # analytic dL/dW2
h <- 1e-6; D <- matrix(0, 2, 3); D[1, 1] <- h
print(c(grad[1, 1], (loss(W1, W2 + D) - loss(W1, W2 - D)) / (2 * h)))
print(c(baseline = mean((noisy - X)^2)))

The two engines use different random generators, so their numbers differ. Each should agree with itself.

04

The honest baseline

Predict

Predict first

What is the simplest baseline a denoiser has to beat on held-out rows?

Zero errorThe error of the noisy rows themselvesThe error of PCA
Reveal

The noisy rows themselves. Returning the input unchanged already has an error: the noise. A denoiser that can't beat that is doing harm. PCA with the same bottleneck is the next baseline to beat.

05

The lab in CodeSplash

Explore
Autoencoder (neural map and reconstruction anomalies)Recorded · Python and R agreeRecorded 2026-11-25 · 32 values compared
R

An autoencoder compressed 532 rows into 2 coordinates; 54 rows with reconstruction errors ≥ 0.858 are flagged as anomalies.

Mean reconstruction error
0.4018
Trustworthiness (k = 10)
0.8673
Anomalies
54
Threshold
0.8576

Plots

Autoencoder map (bottleneck coordinates 1 and 2)Which rows group together, and how well separated are the groups?
View data
GroupCoordinate 1Coordinate 2
All rows0.5936−0.2121
All rows0.06182.425
All rows0.04790.2491
All rows−0.8882−0.1805
All rows0.8593−0.5498
All rows0.32421.224
All rows0.5122−0.6150
All rows0.7181−1.049
All rows0.40992.124
All rows−0.7599−1.039
All rows−0.5342−3.447
All rows0.13711.858
All rows0.07031.494
All rows1.0811.584
All rows−0.4530−1.457
All rows1.009−0.1328
All rows1.235−1.586
All rows−0.37122.127
All rows0.27490.2103
All rows1.043−0.5452
All rows1.166−0.2177
All rows0.4622−0.0105
All rows0.68780.2415
All rows1.205−0.5850
All rows0.1713−0.5661
All rows0.06011.284
All rows1.298−1.071
All rows−0.0616−0.6353
All rows−0.07970.2308
All rows0.2467−0.4494
All rows−0.1649−1.510
All rows0.3610−0.2558
All rows0.2953−0.2635
All rows0.6288−0.2794
All rows−0.2738−0.3765
All rows0.54332.951
All rows0.6913−0.3714
All rows1.487−1.234
All rows0.5438−0.2629
All rows0.2049−0.5209
All rows−0.53162.404
All rows0.7225−1.683
All rows0.9632−0.2238
All rows1.254−0.5754
All rows0.3216−0.4508
All rows0.6410−0.2006
All rows−0.04440.1077
All rows0.6303−2.101
All rows−0.0168−0.0116
All rows−1.322−1.755
All rows0.8820−0.0910
All rows0.6715−0.6787
All rows−0.08401.660
All rows0.0214−0.5509
All rows0.3752−0.3366
All rows0.35850.1239
All rows0.2635−0.1814
All rows1.429−1.524
All rows0.0683−1.278
All rows−0.79071.351

First 60 of 532 rows.

Reconstruction error distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyReconstruction error
false0.2317
false0.7999
false0.6093
false0.3046
false0.1760
false0.3587
false0.3050
true1.345
true0.9606
false0.3585
true1.191
false0.1993
true1.708
false0.8269
false0.5220
false0.1729
false0.2984
false0.3168
false0.4157
false0.3472
false0.0718
false0.3731
false0.3413
false0.1142
false0.2233
false0.7513
false0.0598
false0.3201
false0.2947
false0.1062
false0.5160
false0.2441
false0.1925
false0.5424
false0.3393
false0.3009
false0.3914
false0.2314
false0.5319
false0.2044
false0.2402
false0.3842
false0.3297
false0.1470
false0.2700
false0.3017
false0.1765
true1.635
false0.3998
false0.4317
false0.1319
false0.1270
false0.0781
false0.1575
false0.1334
false0.6604
false0.2616
false0.3082
false0.4164
true0.9406

First 60 of 532 rows.

Training loss by epochWould more data help, or is the model limited by bias or variance?
View data
EpochReconstruction lossSet
11.083train
20.7967train
30.6777train
40.6402train
50.6361train
60.6114train
70.5946train
80.5762train
90.5637train
100.5507train
110.5345train
120.5240train
130.5110train
140.5028train
150.4960train
160.4921train
170.4906train
180.4862train
190.4852train
200.4842train
210.4829train
220.4813train
230.4810train
240.4799train
250.4805train
260.4778train
270.4770train
280.4764train
290.4767train
300.4753train
310.4738train
320.4733train
330.4731train
340.4744train
350.4747train
360.4718train
370.4695train
380.4689train
390.4700train
400.4698train
410.4695train
420.4673train
430.4661train
440.4649train
450.4636train
460.4625train
470.4613train
480.4595train
490.4593train
500.4584train
510.4586train
520.4573train
530.4563train
540.4566train
550.4550train
560.4537train
570.4515train
580.4495train
590.4466train
600.4470train

First 60 of 100 rows.

Rows reconstructed worst

RankRowReconstruction errornpregglubpskinbmipedage
11574.6942197709934.7000.575062
22572.1611883042550.496026
32961.7894197703936.7002.32931
45051.7487187503333.9000.826034
5131.7081189602330.1000.398059
62081.7081103303843.3000.183033
7481.635292762024.2001.69828
83581.63551031083739.2000.305065
94911.61610681062335.5000.285047
101111.61041891103128.5000.680037
112051.5432197704530.5000.158053
122791.53101291104667.1000.319026
134171.5020173783246.5001.15958
143471.4428118721923.1001.47646
152181.4384111724737.1001.39056
163961.35901891042534.3000.435041
173981.3580180786359.4002.42025
182801.34611289841321.32133
1981.3451193501625.9000.655024
201161.2590137842727.3000.231059
The exact R script · R R version 4.5.1 (2025-06-13)
# Autoencoder (neural map and reconstruction anomalies)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.autoencoder 1.1.0 · spec b559d45f3f81088e
# 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)  # cs_deep_*: torch networks with shared initial weights (twin of codesplash.deep)

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE <- "median"
SCALE <- "standard"
# 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,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-97231/discover.autoencoder/pima_denoising/out-r")
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = FEATURES))
warnings <- list()
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 = IMPUTE,
  scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df))  # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
LABEL <- NULL
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = LABEL))[[LABEL]]

# %% Autoencoder (torch for R, float64, one thread): encoder -> linear bottleneck -> mirrored decoder
HIDDEN <- as.integer(unlist(c(12)))
LATENT <- as.integer(2)
fit <- cs_deep_fit_autoencoder(
  X, HIDDEN, LATENT,
  activation = "tanh",
  epochs = as.integer(100),
  lr = 0.01,
  batch_size = 128,
  weight_decay = 0.0001,
  noise = 0.2,
  seed = 42
)
Z <- fit$embedding  # n x LATENT bottleneck coordinates
errors <- fit$error  # mean squared reconstruction error per row (standardized features)

# %% Anomalies by reconstruction error
RULE <- "share"
flagged <- cs_ml_flag(errors, RULE, 0.1, 1)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-errors, rows)  # largest error first, ties by row

# %% Neighborhood preservation of the map (same rows in both engines)
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(10L, length(sample) - 2L)
trust <- cs_ml_trustworthiness(X[sample, , drop = FALSE], Z[sample, , drop = FALSE], k_eval)

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-97231/discover.autoencoder/pima_denoising/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(LATENT)) emb[[paste0("dim_", j)]] <- Z[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
nanoparquet::write_parquet(data.frame(row = as.integer(rows), score = errors, anomaly = flags), file.path(out, "labels.parquet"))
nanoparquet::write_parquet(cs_deep_history_frame(fit$history), file.path(out, "history.parquet"))

# %% Result
history <- cs_deep_history_frame(fit$history)
values <- list(
  n = length(rows), n_features = ncol(X), latent_dim = LATENT, recon_mse = mean(errors),
  error_check = cs_ml_checksum(errors, rows), n_flagged = sum(flags), threshold = threshold,
  final_loss = history$loss[nrow(history)], epochs_run = fit$epochs_run, trustworthiness = trust
)
for (j in seq_len(LATENT)) values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(Z[, j], rows)
for (rank in seq_len(min(10L, length(ord)))) {
  values[[sprintf("top_row[%d]", rank)]] <- rows[ord[rank]]
  values[[sprintf("top_error[%d]", rank)]] <- errors[ord[rank]]
}
top <- utils::head(ord, 20L)
table_rows <- lapply(seq_along(top), function(rank) {
  i <- top[rank]
  r <- list(rank = rank, row = rows[i] + 1L, error = errors[i])
  for (f in FEATURES) {
    v <- df[[f]][rows[i] + 1L]
    r[[f]] <- if (is.na(v)) NULL else if (is.numeric(v)) v else as.character(v)
  }
  r
})
pick <- cs_ml_sample_rows(length(rows), 5000)
groups <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
  g <- df[[LABEL]][rows[pick] + 1L]
  ifelse(is.na(g), "(missing)", as.character(g))
}
charts <- list()
if (LATENT >= 2L) {
  charts[[length(charts) + 1L]] <- cs_chart("map", "cluster-scatter", "Autoencoder map (bottleneck coordinates 1 and 2)", list(
    x = cs_col("Coordinate 1", Z[pick, 1], "numeric"),
    y = cs_col("Coordinate 2", Z[pick, 2], "numeric"),
    cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
  ), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ",")))
}
charts[[length(charts) + 1L]] <- cs_chart("errors", "anomaly-scores", "Reconstruction error distribution", list(
  score = cs_col("Reconstruction error", errors, "numeric"),
  anomaly = cs_col("Anomaly", flags, "boolean")
), controls = list(threshold = threshold))
charts[[length(charts) + 1L]] <- cs_chart("training", "learning-curve", "Training loss by epoch", list(
  n = cs_col("Epoch", history$epoch, "numeric"),
  score = cs_col("Reconstruction loss", history$loss, "numeric"),
  set = cs_col("Set", rep("train", nrow(history)), "categorical")
))
cs_publish(list(
  title = "Autoencoder (neural map and reconstruction anomalies)",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(rows),
  summary = sprintf("An autoencoder compressed %d rows into %d coordinate%s; %d rows with reconstruction errors ≥ %s are flagged as anomalies.",
                    length(rows), LATENT, if (LATENT != 1L) "s" else "", sum(flags), format(signif(threshold, 3))),
  statistics = list(
    list(key = "recon_mse", label = "Mean reconstruction error", value = mean(errors)),
    list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = trust),
    list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer"),
    list(key = "threshold", label = "Threshold", value = threshold)
  ),
  tables = list(list(
    key = "top", title = "Rows reconstructed worst",
    columns = c(list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
                     list(key = "error", label = "Reconstruction error", type = "number")),
                lapply(FEATURES, function(f) list(key = f, label = f))),
    rows = table_rows
  )),
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(
    list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"),
    list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"),
    list(key = "history", path = file.path(out, "history.parquet"), format = "parquet")
  )
))
Python

An autoencoder compressed 532 rows into 2 coordinates; 54 rows with reconstruction errors ≥ 0.858 are flagged as anomalies.

Mean reconstruction error
0.4018
Trustworthiness (k = 10)
0.8673
Anomalies
54
Threshold
0.8576

To keep this page light, the plots are shown once, under the R tab.

Rows reconstructed worst

RankRowReconstruction errornpregglubpskinbmipedage
11574.6942197709934.7000.575062
22572.1611883042550.496026
32961.7894197703936.7002.32931
45051.7487187503333.9000.826034
5131.7081189602330.1000.398059
62081.7081103303843.3000.183033
7481.635292762024.2001.69828
83581.63551031083739.2000.305065
94911.61610681062335.5000.285047
101111.61041891103128.5000.680037
112051.5432197704530.5000.158053
122791.53101291104667.1000.319026
134171.5020173783246.5001.15958
143471.4428118721923.1001.47646
152181.4384111724737.1001.39056
163961.35901891042534.3000.435041
173981.3580180786359.4002.42025
182801.34611289841321.32133
1981.3451193501625.9000.655024
201161.2590137842727.3000.231059
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Autoencoder (neural map and reconstruction anomalies)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.autoencoder 1.1.0 · spec b559d45f3f81088e
# 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.ml import anomaly as csanom
from codesplash.ml import embed as csembed

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE = "median"
SCALE = "standard"
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,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-97231/discover.autoencoder/pima_denoising/out-python",
)
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "npreg": "numeric",
        "glu": "numeric",
        "bp": "numeric",
        "skin": "numeric",
        "bmi": "numeric",
        "ped": "numeric",
        "age": "numeric",
    },
    levels={
    },
    impute=IMPUTE,
    scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df)  # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
LABEL = None
if LABEL:
    df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=[LABEL])[LABEL]

# %% Autoencoder (PyTorch, float64, one thread): encoder → linear bottleneck → mirrored decoder
HIDDEN = [int(u) for u in [12]]
LATENT = 2
fit = deep.fit_autoencoder(
    X, HIDDEN, LATENT,
    activation="tanh",
    epochs=100,
    lr=0.01,
    batch_size=128,
    weight_decay=0.0001,
    noise=0.2,
    seed=42,
)
Z = fit["embedding"]  # n × LATENT bottleneck coordinates
errors = fit["error"]  # mean squared reconstruction error per row (standardized features)

# %% Anomalies by reconstruction error
RULE = "share"
flags, threshold = csanom.flag(errors, RULE, 0.1, 1)
order = np.lexsort((rows, -errors))  # largest error first, ties by row

# %% Neighborhood preservation of the map (same rows in both engines)
sample = csembed.sample_rows(len(rows))
k_eval = min(10, len(sample) - 2)
trust = csembed.trustworthiness(X[sample], Z[sample], k_eval)

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-97231/discover.autoencoder/pima_denoising/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64), **{f"dim_{j + 1}": Z[:, j] for j in range(LATENT)}})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
pd.DataFrame({"row": rows.astype(np.int64), "score": errors, "anomaly": flags}).to_parquet(os.path.join(out, "labels.parquet"), index=False)
deep.history_frame(fit["history"]).to_parquet(os.path.join(out, "history.parquet"), index=False)

# %% Result
values = {
    "n": len(rows),
    "n_features": int(X.shape[1]),
    "latent_dim": LATENT,
    "recon_mse": float(np.mean(errors)),
    "error_check": csembed.checksum(errors, rows),
    "n_flagged": int(flags.sum()),
    "threshold": float(threshold),
    "final_loss": float(fit["history"][-1]["loss"]),
    "epochs_run": int(fit["epochs_run"]),
    "trustworthiness": trust,
}
for j in range(LATENT):
    values[f"emb_check[{j + 1}]"] = csembed.checksum(Z[:, j], rows)
for rank, i in enumerate(order[:10], start=1):
    values[f"top_row[{rank}]"] = int(rows[i])
    values[f"top_error[{rank}]"] = float(errors[i])
top = order[:20]
table_rows = []
for rank, i in enumerate(top, start=1):
    r = {"rank": rank, "row": int(rows[i]) + 1, "error": float(errors[i])}
    for f in FEATURES:
        v = df[f].iloc[rows[i]]
        r[f] = None if pd.isna(v) else (v if isinstance(v, (int, float)) else str(v))  # None, NaN, pd.NA, NaT
    table_rows.append(r)
pick = csembed.sample_rows(len(rows), 5000)
groups = [("All rows" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = []
if LATENT >= 2:
    charts.append(cs.chart("map", "cluster-scatter", "Autoencoder map (bottleneck coordinates 1 and 2)", {
        "x": cs.col("Coordinate 1", Z[pick, 0], "numeric"),
        "y": cs.col("Coordinate 2", Z[pick, 1], "numeric"),
        "cluster": cs.col(LABEL or "Group", groups, "categorical"),
    }, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown."))
charts.append(cs.chart("errors", "anomaly-scores", "Reconstruction error distribution", {
    "score": cs.col("Reconstruction error", errors, "numeric"),
    "anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold)}))
charts.append(cs.chart("training", "learning-curve", "Training loss by epoch", {
    "n": cs.col("Epoch", [h["epoch"] for h in fit["history"]], "numeric"),
    "score": cs.col("Reconstruction loss", [h["loss"] for h in fit["history"]], "numeric"),
    "set": cs.col("Set", ["train"] * len(fit["history"]), "categorical"),
}))
cs.publish({
    "title": "Autoencoder (neural map and reconstruction anomalies)",
    "engine": cs.engine_info("torch", "numpy", "pandas"),
    "n": len(rows),
    "summary": f"An autoencoder compressed {len(rows)} rows into {LATENT} coordinate{'s' if LATENT != 1 else ''}; {int(flags.sum())} rows with reconstruction errors ≥ {threshold:.3g} are flagged as anomalies.",
    "statistics": [
        {"key": "recon_mse", "label": "Mean reconstruction error", "value": float(np.mean(errors))},
        {"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": trust},
        {"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
        {"key": "threshold", "label": "Threshold", "value": float(threshold)},
    ],
    "tables": [{
        "key": "top",
        "title": "Rows reconstructed worst",
        "columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
                    {"key": "error", "label": "Reconstruction error", "type": "number"}] + [{"key": f, "label": f} for f in FEATURES],
        "rows": table_rows,
    }],
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [
        {"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
        {"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"},
        {"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet"},
    ],
})

The same recipe runs on a real table: Input noise (SD) adds fresh noise every step, and the loss compares rebuilds with clean rows. On Pima the clean rebuild error is 0.402 after 100 epochs, and the map's trustworthiness is 0.867.

Compare that with iris, a cleaner, lower-dimensional table, where a plain autoencoder reaches 0.040. Errors on different tables aren't comparable as quality scores; each needs its own baselines.

Notebook exercise · ~15 min

Does the denoiser beat doing nothing?

Score a small denoising autoencoder on held-out rows against two baselines, the noisy rows themselves and PCA with the same bottleneck.

  1. The do-nothing baseline

    Returning the noisy test rows unchanged is a denoiser too. Store its mean squared error against the clean test rows (averaged over every cell) in noisy_mse.

    Show a solution
    Python
    noisy_mse = np.mean((test_noisy - test) ** 2)
    R
    noisy_mse <- mean((test_noisy - test)^2)
  2. PCA with the same bottleneck

    Fit PCA with two components on train_noisy (center with its column means), project test_noisy onto those two components and back, and store the mean squared error against test in pca_mse.

    Show a solution
    Python
    m = train_noisy.mean(0)
    V = np.linalg.svd(train_noisy - m, full_matrices=False)[2][:2].T
    pca_mse = np.mean(((test_noisy - m) @ V @ V.T + m - test) ** 2)
    R
    m <- colMeans(train_noisy)
    V <- svd(sweep(train_noisy, 2, m))$v[, 1:2]
    pca_mse <- mean((sweep(sweep(test_noisy, 2, m) %*% V %*% t(V), 2, m, "+") - test)^2)
  3. The trained denoiser

    Store the mean squared error of denoise(test_noisy) against the clean test rows in dae_mse. Does it beat both baselines?

    Show a solution
    Python
    dae_mse = np.mean((denoise(test_noisy) - test) ** 2)
    R
    dae_mse <- mean((denoise(test_noisy) - test)^2)

In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.

The same lab, small enough to train in the page.

DExplorable · Denoising autoencoder: bottleneck and noise

What stops an autoencoder from simply copying its input?

How much of the noise added to a new curve will this autoencoder pass through?

How sure?
3

Units in the bottleneck; the input has 16 numbers.

0.30

Train on x + σε, still scored against the clean x.

300
0.30
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.

06

What one run shows

Reflect

A single synthetic dataset and one seed show that the code works and that it can beat the baseline. They don't show the method is better than others in general.

Write down which of these you'd run next, and why: a noise sweep chosen on a validation split; PCA and a wide network with no bottleneck as comparisons; several seeds for an uncertainty range; corruption the model never saw, to test the noise assumption.

07

Check: the lab

Checkpoint

Check yourself

Why fit the scaling on training rows only?

Show the answer

Answer: a

Scaling is part of the model. Fit it on training rows, then apply the same means and SDs to held-out rows.

Check yourself

A central-difference check disagrees with your analytic gradient in the fourth digit for one weight. What's the likeliest explanation?

Show the answer

Answer: a

With a step near 10−610^{-6} in double precision, central differences usually agree with a correct gradient to many digits. A disagreement that large points to the derivative code.

Check yourself

The held-out denoised error is higher than the error of the noisy inputs. What does that mean?

Show the answer

Answer: b

The noisy input is the do-nothing baseline. Rescoring the test rows after more training would also turn the test set into a tuning set.

Check yourself

One seed on one synthetic dataset gives a clear win over the noisy baseline. Which claim is supported?

Show the answer

Answer: a

One run supports a narrow claim about that setup. Comparisons, other seeds and other noise levels are needed for anything broader.

08

Recap

Recap
  • Fix the question and the settings first; the bottleneck and noise level are choices.
  • Split, then scale with training statistics; corrupt inputs but score against clean rows.
  • Check gradients by central differences before training.
  • Beat the noisy-input baseline on held-out rows, then PCA; one seed supports only a narrow claim.

Concepts in this lesson