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.
What runs in CodeSplash
- DNN031Autoencoder Runs in CodeSplash
- DNN032Denoising autoencoder Runs in CodeSplash
- Autoencoder (neural map and reconstruction anomalies) Verified in Python and R
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
The question
ReadThe 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.
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.
Check the gradients first
ExploreBefore trusting a hand-written backward pass, compare it with central differences, , for a few weights in every layer. The two should agree to many digits.
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))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.
The honest baseline
PredictPredict first
What is the simplest baseline a denoiser has to beat on held-out rows?
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.
The lab in CodeSplash
ExploreAn 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
View data
| Group | Coordinate 1 | Coordinate 2 |
|---|---|---|
| All rows | 0.5936 | −0.2121 |
| All rows | 0.0618 | 2.425 |
| All rows | 0.0479 | 0.2491 |
| All rows | −0.8882 | −0.1805 |
| All rows | 0.8593 | −0.5498 |
| All rows | 0.3242 | 1.224 |
| All rows | 0.5122 | −0.6150 |
| All rows | 0.7181 | −1.049 |
| All rows | 0.4099 | 2.124 |
| All rows | −0.7599 | −1.039 |
| All rows | −0.5342 | −3.447 |
| All rows | 0.1371 | 1.858 |
| All rows | 0.0703 | 1.494 |
| All rows | 1.081 | 1.584 |
| All rows | −0.4530 | −1.457 |
| All rows | 1.009 | −0.1328 |
| All rows | 1.235 | −1.586 |
| All rows | −0.3712 | 2.127 |
| All rows | 0.2749 | 0.2103 |
| All rows | 1.043 | −0.5452 |
| All rows | 1.166 | −0.2177 |
| All rows | 0.4622 | −0.0105 |
| All rows | 0.6878 | 0.2415 |
| All rows | 1.205 | −0.5850 |
| All rows | 0.1713 | −0.5661 |
| All rows | 0.0601 | 1.284 |
| All rows | 1.298 | −1.071 |
| All rows | −0.0616 | −0.6353 |
| All rows | −0.0797 | 0.2308 |
| All rows | 0.2467 | −0.4494 |
| All rows | −0.1649 | −1.510 |
| All rows | 0.3610 | −0.2558 |
| All rows | 0.2953 | −0.2635 |
| All rows | 0.6288 | −0.2794 |
| All rows | −0.2738 | −0.3765 |
| All rows | 0.5433 | 2.951 |
| All rows | 0.6913 | −0.3714 |
| All rows | 1.487 | −1.234 |
| All rows | 0.5438 | −0.2629 |
| All rows | 0.2049 | −0.5209 |
| All rows | −0.5316 | 2.404 |
| All rows | 0.7225 | −1.683 |
| All rows | 0.9632 | −0.2238 |
| All rows | 1.254 | −0.5754 |
| All rows | 0.3216 | −0.4508 |
| All rows | 0.6410 | −0.2006 |
| All rows | −0.0444 | 0.1077 |
| All rows | 0.6303 | −2.101 |
| All rows | −0.0168 | −0.0116 |
| All rows | −1.322 | −1.755 |
| All rows | 0.8820 | −0.0910 |
| All rows | 0.6715 | −0.6787 |
| All rows | −0.0840 | 1.660 |
| All rows | 0.0214 | −0.5509 |
| All rows | 0.3752 | −0.3366 |
| All rows | 0.3585 | 0.1239 |
| All rows | 0.2635 | −0.1814 |
| All rows | 1.429 | −1.524 |
| All rows | 0.0683 | −1.278 |
| All rows | −0.7907 | 1.351 |
First 60 of 532 rows.
View data
| Anomaly | Reconstruction error |
|---|---|
| false | 0.2317 |
| false | 0.7999 |
| false | 0.6093 |
| false | 0.3046 |
| false | 0.1760 |
| false | 0.3587 |
| false | 0.3050 |
| true | 1.345 |
| true | 0.9606 |
| false | 0.3585 |
| true | 1.191 |
| false | 0.1993 |
| true | 1.708 |
| false | 0.8269 |
| false | 0.5220 |
| false | 0.1729 |
| false | 0.2984 |
| false | 0.3168 |
| false | 0.4157 |
| false | 0.3472 |
| false | 0.0718 |
| false | 0.3731 |
| false | 0.3413 |
| false | 0.1142 |
| false | 0.2233 |
| false | 0.7513 |
| false | 0.0598 |
| false | 0.3201 |
| false | 0.2947 |
| false | 0.1062 |
| false | 0.5160 |
| false | 0.2441 |
| false | 0.1925 |
| false | 0.5424 |
| false | 0.3393 |
| false | 0.3009 |
| false | 0.3914 |
| false | 0.2314 |
| false | 0.5319 |
| false | 0.2044 |
| false | 0.2402 |
| false | 0.3842 |
| false | 0.3297 |
| false | 0.1470 |
| false | 0.2700 |
| false | 0.3017 |
| false | 0.1765 |
| true | 1.635 |
| false | 0.3998 |
| false | 0.4317 |
| false | 0.1319 |
| false | 0.1270 |
| false | 0.0781 |
| false | 0.1575 |
| false | 0.1334 |
| false | 0.6604 |
| false | 0.2616 |
| false | 0.3082 |
| false | 0.4164 |
| true | 0.9406 |
First 60 of 532 rows.
View data
| Epoch | Reconstruction loss | Set |
|---|---|---|
| 1 | 1.083 | train |
| 2 | 0.7967 | train |
| 3 | 0.6777 | train |
| 4 | 0.6402 | train |
| 5 | 0.6361 | train |
| 6 | 0.6114 | train |
| 7 | 0.5946 | train |
| 8 | 0.5762 | train |
| 9 | 0.5637 | train |
| 10 | 0.5507 | train |
| 11 | 0.5345 | train |
| 12 | 0.5240 | train |
| 13 | 0.5110 | train |
| 14 | 0.5028 | train |
| 15 | 0.4960 | train |
| 16 | 0.4921 | train |
| 17 | 0.4906 | train |
| 18 | 0.4862 | train |
| 19 | 0.4852 | train |
| 20 | 0.4842 | train |
| 21 | 0.4829 | train |
| 22 | 0.4813 | train |
| 23 | 0.4810 | train |
| 24 | 0.4799 | train |
| 25 | 0.4805 | train |
| 26 | 0.4778 | train |
| 27 | 0.4770 | train |
| 28 | 0.4764 | train |
| 29 | 0.4767 | train |
| 30 | 0.4753 | train |
| 31 | 0.4738 | train |
| 32 | 0.4733 | train |
| 33 | 0.4731 | train |
| 34 | 0.4744 | train |
| 35 | 0.4747 | train |
| 36 | 0.4718 | train |
| 37 | 0.4695 | train |
| 38 | 0.4689 | train |
| 39 | 0.4700 | train |
| 40 | 0.4698 | train |
| 41 | 0.4695 | train |
| 42 | 0.4673 | train |
| 43 | 0.4661 | train |
| 44 | 0.4649 | train |
| 45 | 0.4636 | train |
| 46 | 0.4625 | train |
| 47 | 0.4613 | train |
| 48 | 0.4595 | train |
| 49 | 0.4593 | train |
| 50 | 0.4584 | train |
| 51 | 0.4586 | train |
| 52 | 0.4573 | train |
| 53 | 0.4563 | train |
| 54 | 0.4566 | train |
| 55 | 0.4550 | train |
| 56 | 0.4537 | train |
| 57 | 0.4515 | train |
| 58 | 0.4495 | train |
| 59 | 0.4466 | train |
| 60 | 0.4470 | train |
First 60 of 100 rows.
Rows reconstructed worst
| Rank | Row | Reconstruction error | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 157 | 4.694 | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 2 | 257 | 2.161 | 1 | 88 | 30 | 42 | 55 | 0.4960 | 26 |
| 3 | 296 | 1.789 | 4 | 197 | 70 | 39 | 36.700 | 2.329 | 31 |
| 4 | 505 | 1.748 | 7 | 187 | 50 | 33 | 33.900 | 0.8260 | 34 |
| 5 | 13 | 1.708 | 1 | 189 | 60 | 23 | 30.100 | 0.3980 | 59 |
| 6 | 208 | 1.708 | 1 | 103 | 30 | 38 | 43.300 | 0.1830 | 33 |
| 7 | 48 | 1.635 | 2 | 92 | 76 | 20 | 24.200 | 1.698 | 28 |
| 8 | 358 | 1.635 | 5 | 103 | 108 | 37 | 39.200 | 0.3050 | 65 |
| 9 | 491 | 1.616 | 10 | 68 | 106 | 23 | 35.500 | 0.2850 | 47 |
| 10 | 111 | 1.610 | 4 | 189 | 110 | 31 | 28.500 | 0.6800 | 37 |
| 11 | 205 | 1.543 | 2 | 197 | 70 | 45 | 30.500 | 0.1580 | 53 |
| 12 | 279 | 1.531 | 0 | 129 | 110 | 46 | 67.100 | 0.3190 | 26 |
| 13 | 417 | 1.502 | 0 | 173 | 78 | 32 | 46.500 | 1.159 | 58 |
| 14 | 347 | 1.442 | 8 | 118 | 72 | 19 | 23.100 | 1.476 | 46 |
| 15 | 218 | 1.438 | 4 | 111 | 72 | 47 | 37.100 | 1.390 | 56 |
| 16 | 396 | 1.359 | 0 | 189 | 104 | 25 | 34.300 | 0.4350 | 41 |
| 17 | 398 | 1.358 | 0 | 180 | 78 | 63 | 59.400 | 2.420 | 25 |
| 18 | 280 | 1.346 | 1 | 128 | 98 | 41 | 32 | 1.321 | 33 |
| 19 | 8 | 1.345 | 1 | 193 | 50 | 16 | 25.900 | 0.6550 | 24 |
| 20 | 116 | 1.259 | 0 | 137 | 84 | 27 | 27.300 | 0.2310 | 59 |
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")
)
))
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
| Rank | Row | Reconstruction error | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 157 | 4.694 | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 2 | 257 | 2.161 | 1 | 88 | 30 | 42 | 55 | 0.4960 | 26 |
| 3 | 296 | 1.789 | 4 | 197 | 70 | 39 | 36.700 | 2.329 | 31 |
| 4 | 505 | 1.748 | 7 | 187 | 50 | 33 | 33.900 | 0.8260 | 34 |
| 5 | 13 | 1.708 | 1 | 189 | 60 | 23 | 30.100 | 0.3980 | 59 |
| 6 | 208 | 1.708 | 1 | 103 | 30 | 38 | 43.300 | 0.1830 | 33 |
| 7 | 48 | 1.635 | 2 | 92 | 76 | 20 | 24.200 | 1.698 | 28 |
| 8 | 358 | 1.635 | 5 | 103 | 108 | 37 | 39.200 | 0.3050 | 65 |
| 9 | 491 | 1.616 | 10 | 68 | 106 | 23 | 35.500 | 0.2850 | 47 |
| 10 | 111 | 1.610 | 4 | 189 | 110 | 31 | 28.500 | 0.6800 | 37 |
| 11 | 205 | 1.543 | 2 | 197 | 70 | 45 | 30.500 | 0.1580 | 53 |
| 12 | 279 | 1.531 | 0 | 129 | 110 | 46 | 67.100 | 0.3190 | 26 |
| 13 | 417 | 1.502 | 0 | 173 | 78 | 32 | 46.500 | 1.159 | 58 |
| 14 | 347 | 1.442 | 8 | 118 | 72 | 19 | 23.100 | 1.476 | 46 |
| 15 | 218 | 1.438 | 4 | 111 | 72 | 47 | 37.100 | 1.390 | 56 |
| 16 | 396 | 1.359 | 0 | 189 | 104 | 25 | 34.300 | 0.4350 | 41 |
| 17 | 398 | 1.358 | 0 | 180 | 78 | 63 | 59.400 | 2.420 | 25 |
| 18 | 280 | 1.346 | 1 | 128 | 98 | 41 | 32 | 1.321 | 33 |
| 19 | 8 | 1.345 | 1 | 193 | 50 | 16 | 25.900 | 0.6550 | 24 |
| 20 | 116 | 1.259 | 0 | 137 | 84 | 27 | 27.300 | 0.2310 | 59 |
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.
- The do-nothing baseline
Returning the noisy test rows unchanged is a denoiser too. Store its mean squared error against the clean
testrows (averaged over every cell) innoisy_mse.Show a solution
Pythonnoisy_mse = np.mean((test_noisy - test) ** 2)Rnoisy_mse <- mean((test_noisy - test)^2) - PCA with the same bottleneck
Fit PCA with two components on
train_noisy(center with its column means), projecttest_noisyonto those two components and back, and store the mean squared error againsttestinpca_mse.Show a solution
Pythonm = 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)Rm <- 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) - The trained denoiser
Store the mean squared error of
denoise(test_noisy)against the cleantestrows indae_mse. Does it beat both baselines?Show a solution
Pythondae_mse = np.mean((denoise(test_noisy) - test) ** 2)Rdae_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?
Units in the bottleneck; the input has 16 numbers.
Train on x + σε, still scored against the clean x.
Commit your prediction above to see the result
Make your prediction to see the result.
What one run shows
ReflectA 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.
Check: the lab
CheckpointCheck 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 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.
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