Autoencoders: squeeze each row, then rebuild it
An encoder squeezes each row into a few numbers and a decoder rebuilds it. Read what the bottleneck keeps, why corrupting the input helps, and what reconstruction error does and doesn't tell you.
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
- Write the encoder, decoder and reconstruction loss of an autoencoder
- Explain why a bottleneck or corrupted inputs stop the network from copying its input
- Compare an autoencoder's map with PCA on held-out reconstruction and trustworthiness
- Say why low reconstruction error is not a density or a p-value
Two networks and one loss
ReadAn autoencoderAutoencoderA neural network that squeezes rows through a narrow layer and rebuilds them; the narrow layer works as a map. is two networks trained together. The encoder turns a row into a short code ; the decoder turns the code back into a row:
The loss compares each row with its rebuild. Squared error is the usual choice, and it quietly assumes Gaussian noise around the rebuilt row. Counts, categories and bounded values deserve a loss that matches them.
The code is the latent spaceLatent spaceA compact set of coordinates from which a model can rebuild data; every point decodes to something, realistic or not.. With two coordinates you can draw it as a map.
One forward pass by hand
ReadThe reference's small example uses three rows with two columns, one tanh unit in the middle and the same weights to encode and decode. The codes come out as 0.462, −0.635 and 0.197, and the mean squared rebuild error is 0.280.
import numpy as np
X = np.array([[1., .5], [-.5, 1.], [0., -.5]])
W = np.array([[.7], [-.4]])
Z = np.tanh(X @ W) # encoder: 2 columns -> 1 code
rebuilt = Z @ W.T # decoder with tied weights
print(Z.ravel(), np.mean((X - rebuilt) ** 2))X <- matrix(c(1, .5, -.5, 1, 0, -.5), ncol = 2, byrow = TRUE)
W <- matrix(c(.7, -.4), ncol = 1)
Z <- tanh(X %*% W) # encoder: 2 columns -> 1 code
rebuilt <- Z %*% t(W) # decoder with tied weights
print(c(Z, mean((X - rebuilt)^2)))The code only computes one pass. Training moves to shrink that error.
Why it can't just copy
PredictPredict first
You give an autoencoder a code as wide as the input and plenty of hidden units, with no penalty. What can go wrong?
Reveal
It can learn to copy. A network wide enough to pass every column through unchanged rebuilds perfectly and learns nothing about the data's shape. Something has to stop it: a narrow bottleneck, a penalty on the code, or a corrupted input.
A map of iris
ExploreAn autoencoder compressed 150 rows into 2 coordinates; 8 rows with reconstruction errors ≥ 0.141 are flagged as anomalies.
- Mean reconstruction error
- 0.0395
- Trustworthiness (k = 10)
- 0.9779
- Anomalies
- 8
- Threshold
- 0.1414
Plots
View data
| species | Coordinate 1 | Coordinate 2 |
|---|---|---|
| setosa | 0.8994 | 0.5535 |
| setosa | 0.9614 | 0.1290 |
| setosa | 1.041 | 0.3232 |
| setosa | 1.050 | 0.2386 |
| setosa | 0.9346 | 0.6399 |
| setosa | 0.6920 | 0.8300 |
| setosa | 1.031 | 0.4823 |
| setosa | 0.9246 | 0.4699 |
| setosa | 1.111 | 0.0860 |
| setosa | 0.9879 | 0.2291 |
| setosa | 0.7797 | 0.7039 |
| setosa | 0.9827 | 0.4750 |
| setosa | 1.028 | 0.1515 |
| setosa | 1.208 | 0.2006 |
| setosa | 0.6507 | 0.9397 |
| setosa | 0.5948 | 1.188 |
| setosa | 0.7307 | 0.8459 |
| setosa | 0.8656 | 0.5412 |
| setosa | 0.6110 | 0.7550 |
| setosa | 0.8558 | 0.7800 |
| setosa | 0.7610 | 0.4417 |
| setosa | 0.8218 | 0.6900 |
| setosa | 1.102 | 0.6698 |
| setosa | 0.7623 | 0.3291 |
| setosa | 0.9534 | 0.4590 |
| setosa | 0.9081 | 0.1166 |
| setosa | 0.8447 | 0.4406 |
| setosa | 0.8541 | 0.5451 |
| setosa | 0.8632 | 0.4625 |
| setosa | 1.011 | 0.3136 |
| setosa | 0.9764 | 0.2207 |
| setosa | 0.7121 | 0.4197 |
| setosa | 0.8799 | 1.009 |
| setosa | 0.7451 | 1.082 |
| setosa | 0.9538 | 0.2157 |
| setosa | 0.9510 | 0.3041 |
| setosa | 0.7609 | 0.5356 |
| setosa | 1.002 | 0.6513 |
| setosa | 1.126 | 0.1742 |
| setosa | 0.8896 | 0.4647 |
| setosa | 0.9103 | 0.5495 |
| setosa | 1.024 | −0.4486 |
| setosa | 1.132 | 0.3436 |
| setosa | 0.7735 | 0.4957 |
| setosa | 0.7826 | 0.7464 |
| setosa | 0.9591 | 0.1226 |
| setosa | 0.8804 | 0.7830 |
| setosa | 1.062 | 0.3270 |
| setosa | 0.8172 | 0.7070 |
| setosa | 0.9332 | 0.3872 |
| versicolor | −0.5769 | −0.0873 |
| versicolor | −0.3555 | −0.0717 |
| versicolor | −0.5746 | −0.1889 |
| versicolor | 0.1318 | −0.7268 |
| versicolor | −0.3387 | −0.4084 |
| versicolor | −0.0251 | −0.3516 |
| versicolor | −0.3847 | −0.0073 |
| versicolor | 0.4388 | −0.5574 |
| versicolor | −0.3375 | −0.3061 |
| versicolor | 0.1561 | −0.4038 |
First 60 of 150 rows.
View data
| Anomaly | Reconstruction error |
|---|---|
| false | 0.0038 |
| false | 0.0104 |
| false | 0.0023 |
| false | 0.0084 |
| false | 0.0011 |
| false | 0.0008 |
| false | 0.0356 |
| false | 0.0021 |
| false | 0.0171 |
| false | 0.0120 |
| false | 0.0198 |
| false | 0.0095 |
| false | 0.0075 |
| false | 0.0252 |
| false | 0.0704 |
| false | 0.0247 |
| false | 0.0087 |
| false | 0.0031 |
| false | 0.0458 |
| false | 0.0058 |
| false | 0.0481 |
| false | 0.0086 |
| false | 0.0391 |
| false | 0.0086 |
| false | 0.0269 |
| false | 0.0186 |
| false | 0.0055 |
| false | 0.0109 |
| false | 0.0189 |
| false | 0.0081 |
| false | 0.0023 |
| false | 0.0369 |
| false | 0.0286 |
| false | 0.0141 |
| false | 0.0046 |
| false | 0.0149 |
| false | 0.0715 |
| false | 0.0061 |
| false | 0.0213 |
| false | 0.0072 |
| false | 0.0037 |
| false | 0.0231 |
| false | 0.0375 |
| false | 0.0341 |
| false | 0.0227 |
| false | 0.0039 |
| false | 0.0076 |
| false | 0.0108 |
| false | 0.0090 |
| false | 0.0046 |
| true | 0.1810 |
| false | 0.0220 |
| false | 0.1093 |
| false | 0.0026 |
| false | 0.0536 |
| false | 0.0116 |
| false | 0.0037 |
| false | 0.0193 |
| false | 0.1183 |
| false | 0.0575 |
First 60 of 150 rows.
View data
| Epoch | Reconstruction loss | Set |
|---|---|---|
| 1 | 0.9193 | train |
| 2 | 0.8359 | train |
| 3 | 0.7698 | train |
| 4 | 0.7086 | train |
| 5 | 0.6472 | train |
| 6 | 0.5876 | train |
| 7 | 0.5328 | train |
| 8 | 0.4868 | train |
| 9 | 0.4519 | train |
| 10 | 0.4259 | train |
| 11 | 0.4032 | train |
| 12 | 0.3784 | train |
| 13 | 0.3499 | train |
| 14 | 0.3198 | train |
| 15 | 0.2915 | train |
| 16 | 0.2671 | train |
| 17 | 0.2466 | train |
| 18 | 0.2291 | train |
| 19 | 0.2146 | train |
| 20 | 0.2032 | train |
| 21 | 0.1949 | train |
| 22 | 0.1884 | train |
| 23 | 0.1821 | train |
| 24 | 0.1752 | train |
| 25 | 0.1676 | train |
| 26 | 0.1593 | train |
| 27 | 0.1502 | train |
| 28 | 0.1402 | train |
| 29 | 0.1297 | train |
| 30 | 0.1196 | train |
| 31 | 0.1108 | train |
| 32 | 0.1036 | train |
| 33 | 0.0981 | train |
| 34 | 0.0943 | train |
| 35 | 0.0919 | train |
| 36 | 0.0907 | train |
| 37 | 0.0900 | train |
| 38 | 0.0890 | train |
| 39 | 0.0872 | train |
| 40 | 0.0848 | train |
| 41 | 0.0821 | train |
| 42 | 0.0798 | train |
| 43 | 0.0780 | train |
| 44 | 0.0766 | train |
| 45 | 0.0754 | train |
| 46 | 0.0743 | train |
| 47 | 0.0734 | train |
| 48 | 0.0725 | train |
| 49 | 0.0713 | train |
| 50 | 0.0699 | train |
| 51 | 0.0683 | train |
| 52 | 0.0669 | train |
| 53 | 0.0656 | train |
| 54 | 0.0644 | train |
| 55 | 0.0632 | train |
| 56 | 0.0624 | train |
| 57 | 0.0619 | train |
| 58 | 0.0616 | train |
| 59 | 0.0613 | train |
| 60 | 0.0609 | train |
First 60 of 200 rows.
Rows reconstructed worst
| Rank | Row | Reconstruction error | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 115 | 0.2760 | 5.800 | 2.800 | 5.100 | 2.400 |
| 2 | 107 | 0.2472 | 4.900 | 2.500 | 4.500 | 1.700 |
| 3 | 101 | 0.2335 | 6.300 | 3.300 | 6 | 2.500 |
| 4 | 51 | 0.1810 | 7 | 3.200 | 4.700 | 1.400 |
| 5 | 137 | 0.1731 | 6.300 | 3.400 | 5.600 | 2.400 |
| 6 | 149 | 0.1554 | 6.200 | 3.400 | 5.400 | 2.300 |
| 7 | 122 | 0.1531 | 5.600 | 2.800 | 4.900 | 2 |
| 8 | 77 | 0.1414 | 6.800 | 2.800 | 4.800 | 1.400 |
| 9 | 63 | 0.1393 | 6 | 2.200 | 4 | 1 |
| 10 | 130 | 0.1242 | 7.200 | 3 | 5.800 | 1.600 |
| 11 | 59 | 0.1183 | 6.600 | 2.900 | 4.600 | 1.300 |
| 12 | 66 | 0.1139 | 6.700 | 3.100 | 4.400 | 1.400 |
| 13 | 145 | 0.1111 | 6.700 | 3.300 | 5.700 | 2.500 |
| 14 | 53 | 0.1093 | 6.900 | 3.100 | 4.900 | 1.500 |
| 15 | 88 | 0.1092 | 6.300 | 2.300 | 4.400 | 1.300 |
| 16 | 114 | 0.0994 | 5.700 | 2.500 | 5 | 2 |
| 17 | 116 | 0.0945 | 6.400 | 3.200 | 5.300 | 2.300 |
| 18 | 76 | 0.0935 | 6.600 | 3 | 4.400 | 1.400 |
| 19 | 132 | 0.0892 | 7.900 | 3.800 | 6.400 | 2 |
| 20 | 85 | 0.0855 | 5.400 | 3 | 4.500 | 1.500 |
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 b20a603fe1151222
# Dataset: ml_iris (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-8142/discover.autoencoder/iris_map/out-r")
FEATURES <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
sepal_length = "numeric",
sepal_width = "numeric",
petal_length = "numeric",
petal_width = "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 <- "species"
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = LABEL))[[LABEL]]
# %% Autoencoder (torch for R, float64, one thread): encoder -> linear bottleneck -> mirrored decoder
HIDDEN <- as.integer(unlist(c(8)))
LATENT <- as.integer(2)
fit <- cs_deep_fit_autoencoder(
X, HIDDEN, LATENT,
activation = "tanh",
epochs = as.integer(200),
lr = 0.02,
batch_size = NULL,
weight_decay = 0,
noise = 0,
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.05, 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-8142/discover.autoencoder/iris_map/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 150 rows into 2 coordinates; 8 rows with reconstruction errors ≥ 0.141 are flagged as anomalies.
- Mean reconstruction error
- 0.0395
- Trustworthiness (k = 10)
- 0.9779
- Anomalies
- 8
- Threshold
- 0.1414
To keep this page light, the plots are shown once, under the R tab.
Rows reconstructed worst
| Rank | Row | Reconstruction error | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 115 | 0.2760 | 5.800 | 2.800 | 5.100 | 2.400 |
| 2 | 107 | 0.2472 | 4.900 | 2.500 | 4.500 | 1.700 |
| 3 | 101 | 0.2335 | 6.300 | 3.300 | 6 | 2.500 |
| 4 | 51 | 0.1810 | 7 | 3.200 | 4.700 | 1.400 |
| 5 | 137 | 0.1731 | 6.300 | 3.400 | 5.600 | 2.400 |
| 6 | 149 | 0.1554 | 6.200 | 3.400 | 5.400 | 2.300 |
| 7 | 122 | 0.1531 | 5.600 | 2.800 | 4.900 | 2 |
| 8 | 77 | 0.1414 | 6.800 | 2.800 | 4.800 | 1.400 |
| 9 | 63 | 0.1393 | 6 | 2.200 | 4 | 1 |
| 10 | 130 | 0.1242 | 7.200 | 3 | 5.800 | 1.600 |
| 11 | 59 | 0.1183 | 6.600 | 2.900 | 4.600 | 1.300 |
| 12 | 66 | 0.1139 | 6.700 | 3.100 | 4.400 | 1.400 |
| 13 | 145 | 0.1111 | 6.700 | 3.300 | 5.700 | 2.500 |
| 14 | 53 | 0.1093 | 6.900 | 3.100 | 4.900 | 1.500 |
| 15 | 88 | 0.1092 | 6.300 | 2.300 | 4.400 | 1.300 |
| 16 | 114 | 0.0994 | 5.700 | 2.500 | 5 | 2 |
| 17 | 116 | 0.0945 | 6.400 | 3.200 | 5.300 | 2.300 |
| 18 | 76 | 0.0935 | 6.600 | 3 | 4.400 | 1.400 |
| 19 | 132 | 0.0892 | 7.900 | 3.800 | 6.400 | 2 |
| 20 | 85 | 0.0855 | 5.400 | 3 | 4.500 | 1.500 |
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 b20a603fe1151222
# Dataset: ml_iris (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-8142/discover.autoencoder/iris_map/out-python",
)
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"sepal_length": "numeric",
"sepal_width": "numeric",
"petal_length": "numeric",
"petal_width": "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 = "species"
if LABEL:
df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=[LABEL])[LABEL]
# %% Autoencoder (PyTorch, float64, one thread): encoder → linear bottleneck → mirrored decoder
HIDDEN = [int(u) for u in [8]]
LATENT = 2
fit = deep.fit_autoencoder(
X, HIDDEN, LATENT,
activation="tanh",
epochs=200,
lr=0.02,
batch_size=None,
weight_decay=0,
noise=0,
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.05, 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-8142/discover.autoencoder/iris_map/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 encoder squeezed 4 measurements into 2 coordinates. The mean squared rebuild error on the standardized columns is 0.040.
The trustworthinessTrustworthinessA 0–1 score for whether rows that look close on a map are really close in the data. of the map is 0.978: rows that are close on the map were mostly close in the data too. Open the map colored by species. The species was never shown to the network, so separation on the map is structure it found, not a label it learned.
Compare with PCA first
ExplorePCA is the linear autoencoder: with squared error and no nonlinearity, the best two-number code spans the same plane as the first two principal components. Rotate the direction below and watch the rebuild error fall as the kept variance rises.
AExplorable · Rotate to the first principal component
What direction does the first principal component point in, and why?
With this correlation, what share of the total variance will the best single direction keep?
Solid: your direction, with each point's projection onto it. Dashed: the first principal component.
Commit your prediction above to see the result
Make your prediction to see the result.
So the fair question for any autoencoder is how much it beats PCA on rows it didn't train on. If the curved network barely wins, keep PCA: it is faster, has no seed and gives the same answer in Python and R by construction.
Corrupt the input, rebuild the clean row
ReadA denoising autoencoderDenoising autoencoderAn autoencoder fed a corrupted copy of each row and trained to rebuild the clean row, so it can't learn to copy its input. adds noise to each input but still scores the rebuild against the clean row. Copying the input now copies the noise too, which costs error, so the network has to learn where rows usually lie and pull each one back toward that.
In the reference's toy version, the same weights fed noisy rows score a clean-target error of 0.288. The noise level is a study setting, not a fact about your data: try a few on validation data.
Train a small autoencoder with and without corrupted inputs.
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.
Denoising 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"},
],
})
Input noise (SD) above 0 turns on denoising training. Here every training step adds fresh noise to the standardized Pima columns. The clean rebuild error is 0.402, and 54 rows were flagged as the most poorly rebuilt tenth.
Those flags are a ranking, not a test. Some unusual rows rebuild well, and the cutoff only means something once you check it on rows with known outcomes.
What it runs, and what the error means
Read- Reconstruction error is not a likelihood. An autoencoder defines no normalized density, so its error can't be read as a probability or a p-value.
- Low error doesn't mean useful factors. Judge the code by what you use it for: a probe, a cluster check or a downstream model.
- Split before you fit. Fit the scaling on training rows, and calibrate any anomaly cutoff on separate rows.
Check: autoencoders
CheckpointCheck yourself
An autoencoder trained with squared error on standardized columns reports a mean rebuild error. What does that number measure?
Show the answer
Answer: a
It is an average squared distance. Autoencoders don't define a normalized density, so the error can't be read as a probability or a test.
Check yourself
Your two-coordinate autoencoder rebuilds held-out rows only slightly better than two principal components. What's the sensible choice?
Show the answer
Answer: b
PCA is the linear autoencoder. A curved network has to earn its extra cost on rows it didn't train on; training longer to make it win is tuning on the comparison.
Check yourself
Which design stops a plain autoencoder from learning to copy its input?
Show the answer
Answer: a
A narrow bottleneck can't carry every column through unchanged, so the network must keep what matters most. Width, depth and epochs don't force that.
Check yourself
A denoising autoencoder adds noise to each input. What does it compare the rebuild with?
Show the answer
Answer: b
The target is the clean row. Copying the noisy input would copy the noise and cost error, so the network learns to pull rows back toward where data usually lies.
Check yourself
You want evidence that a denoising autoencoder actually denoises. Which comparison shows it?
Show the answer
Answer: a
The noisy input is the baseline: doing nothing already has that error. Denoising helps only if held-out rebuilds are closer to the clean rows than the noisy inputs were.
Recap
Recap- An autoencoder encodes each row to a short code and decodes it back; the loss compares rows with their rebuilds.
- A bottleneck or corrupted inputs stop it from copying. Denoising scores the rebuild against the clean row.
- Compare with PCA on held-out rows before preferring the network.
- Reconstruction error is a distance, not a density, a probability or a test.
Concepts in this lesson