Skip to content

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.

Applied ~13 min10 steps

What runs in CodeSplash

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

Read first

01

Two networks and one loss

Read

An 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 fϕf_\phi turns a row xx into a short code zz; the decoder gθg_\theta turns the code back into a row:

z=fϕ(x),x^=gθ(z),L=∑iℓ(xi,x^i).z = f_\phi(x), \qquad \hat x = g_\theta(z), \qquad L = \sum_i \ell(x_i, \hat x_i).

The loss ℓ\ell 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.

02

One forward pass by hand

Read

The 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.

Python
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))
R
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 WW to shrink that error.

03

Why it can't just copy

Predict

Predict first

You give an autoencoder a code as wide as the input and plenty of hidden units, with no penalty. What can go wrong?

It learns useful structureIt can learn to copy each row and nothing elseIt can't fit the data at all
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.

04

A map of iris

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

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

Plots

Autoencoder map (bottleneck coordinates 1 and 2)Which rows group together, and how well separated are the groups?
View data
speciesCoordinate 1Coordinate 2
setosa0.89940.5535
setosa0.96140.1290
setosa1.0410.3232
setosa1.0500.2386
setosa0.93460.6399
setosa0.69200.8300
setosa1.0310.4823
setosa0.92460.4699
setosa1.1110.0860
setosa0.98790.2291
setosa0.77970.7039
setosa0.98270.4750
setosa1.0280.1515
setosa1.2080.2006
setosa0.65070.9397
setosa0.59481.188
setosa0.73070.8459
setosa0.86560.5412
setosa0.61100.7550
setosa0.85580.7800
setosa0.76100.4417
setosa0.82180.6900
setosa1.1020.6698
setosa0.76230.3291
setosa0.95340.4590
setosa0.90810.1166
setosa0.84470.4406
setosa0.85410.5451
setosa0.86320.4625
setosa1.0110.3136
setosa0.97640.2207
setosa0.71210.4197
setosa0.87991.009
setosa0.74511.082
setosa0.95380.2157
setosa0.95100.3041
setosa0.76090.5356
setosa1.0020.6513
setosa1.1260.1742
setosa0.88960.4647
setosa0.91030.5495
setosa1.024−0.4486
setosa1.1320.3436
setosa0.77350.4957
setosa0.78260.7464
setosa0.95910.1226
setosa0.88040.7830
setosa1.0620.3270
setosa0.81720.7070
setosa0.93320.3872
versicolor−0.5769−0.0873
versicolor−0.3555−0.0717
versicolor−0.5746−0.1889
versicolor0.1318−0.7268
versicolor−0.3387−0.4084
versicolor−0.0251−0.3516
versicolor−0.3847−0.0073
versicolor0.4388−0.5574
versicolor−0.3375−0.3061
versicolor0.1561−0.4038

First 60 of 150 rows.

Reconstruction error distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyReconstruction error
false0.0038
false0.0104
false0.0023
false0.0084
false0.0011
false0.0008
false0.0356
false0.0021
false0.0171
false0.0120
false0.0198
false0.0095
false0.0075
false0.0252
false0.0704
false0.0247
false0.0087
false0.0031
false0.0458
false0.0058
false0.0481
false0.0086
false0.0391
false0.0086
false0.0269
false0.0186
false0.0055
false0.0109
false0.0189
false0.0081
false0.0023
false0.0369
false0.0286
false0.0141
false0.0046
false0.0149
false0.0715
false0.0061
false0.0213
false0.0072
false0.0037
false0.0231
false0.0375
false0.0341
false0.0227
false0.0039
false0.0076
false0.0108
false0.0090
false0.0046
true0.1810
false0.0220
false0.1093
false0.0026
false0.0536
false0.0116
false0.0037
false0.0193
false0.1183
false0.0575

First 60 of 150 rows.

Training loss by epochWould more data help, or is the model limited by bias or variance?
View data
EpochReconstruction lossSet
10.9193train
20.8359train
30.7698train
40.7086train
50.6472train
60.5876train
70.5328train
80.4868train
90.4519train
100.4259train
110.4032train
120.3784train
130.3499train
140.3198train
150.2915train
160.2671train
170.2466train
180.2291train
190.2146train
200.2032train
210.1949train
220.1884train
230.1821train
240.1752train
250.1676train
260.1593train
270.1502train
280.1402train
290.1297train
300.1196train
310.1108train
320.1036train
330.0981train
340.0943train
350.0919train
360.0907train
370.0900train
380.0890train
390.0872train
400.0848train
410.0821train
420.0798train
430.0780train
440.0766train
450.0754train
460.0743train
470.0734train
480.0725train
490.0713train
500.0699train
510.0683train
520.0669train
530.0656train
540.0644train
550.0632train
560.0624train
570.0619train
580.0616train
590.0613train
600.0609train

First 60 of 200 rows.

Rows reconstructed worst

RankRowReconstruction errorsepal_lengthsepal_widthpetal_lengthpetal_width
11150.27605.8002.8005.1002.400
21070.24724.9002.5004.5001.700
31010.23356.3003.30062.500
4510.181073.2004.7001.400
51370.17316.3003.4005.6002.400
61490.15546.2003.4005.4002.300
71220.15315.6002.8004.9002
8770.14146.8002.8004.8001.400
9630.139362.20041
101300.12427.20035.8001.600
11590.11836.6002.9004.6001.300
12660.11396.7003.1004.4001.400
131450.11116.7003.3005.7002.500
14530.10936.9003.1004.9001.500
15880.10926.3002.3004.4001.300
161140.09945.7002.50052
171160.09456.4003.2005.3002.300
18760.09356.60034.4001.400
191320.08927.9003.8006.4002
20850.08555.40034.5001.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")
  )
))
Python

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

RankRowReconstruction errorsepal_lengthsepal_widthpetal_lengthpetal_width
11150.27605.8002.8005.1002.400
21070.24724.9002.5004.5001.700
31010.23356.3003.30062.500
4510.181073.2004.7001.400
51370.17316.3003.4005.6002.400
61490.15546.2003.4005.4002.300
71220.15315.6002.8004.9002
8770.14146.8002.8004.8001.400
9630.139362.20041
101300.12427.20035.8001.600
11590.11836.6002.9004.6001.300
12660.11396.7003.1004.4001.400
131450.11116.7003.3005.7002.500
14530.10936.9003.1004.9001.500
15880.10926.3002.3004.4001.300
161140.09945.7002.50052
171160.09456.4003.2005.3002.300
18760.09356.60034.4001.400
191320.08927.9003.8006.4002
20850.08555.40034.5001.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.

05

Compare with PCA first

Explore

PCA 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?

0.75
How sure?
10
0.70
1
100
yoursPC1

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

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.

06

Corrupt the input, rebuild the clean row

Read

A 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?

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.

07

Denoising 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"},
    ],
})

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.

08

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.
09

Check: autoencoders

Checkpoint

Check 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.

10

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