Skip to content

CDiscover · discover.autoencoder

Autoencoder (neural map and reconstruction anomalies)

What low-dimensional structure do the rows share — and which rows does it reconstruct worst?

A neural network that squeezes every row through a narrow bottleneck and rebuilds it: the bottleneck coordinates are a nonlinear map of the data (like PCA, but bent), and the rows it rebuilds worst are anomaly candidates. Optional input noise makes it a denoising autoencoder. Trained by Adam on torch in both engines from the same initial weights, so Python and R give the same map and scores to about seven significant digits.

Verified in Python and R Python and R agree to 6 decimals

A real result

Example “Iris map”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Iris mapml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Penguins mixed missing reluml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass, sex · label: species
  • Pima denoisingml_pima · features: npreg, glu, bp, skin, bmi, ped, age
  • Iris train onecycle clip emaml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species

In the guides

Where it sits in the decision guides

  • Representation visualization (t-SNE, UMAP) · DS & ML Decision Guide · Describe — summarize and visualize
  • Anomaly detection · DS & ML Decision Guide · Discover — find structure without labels
  • Representation learning (autoencoders, contrastive) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Featuresnumeric / categorical / boolean · 2–500 columns
Columns used to describe each row. Numbers are standardized; categories become indicator columns.
Color points bycategorical / boolean · 0–1 column
Optional column used only to color the points; it does not affect the layout.

Choices you make

model

Bottleneck sizedefault 2

Coordinates per row in the map (2 draws directly as a scatter).

Encoder layers (units)default 32

Units in each encoder layer, input side first; the decoder mirrors them. Empty = no hidden layer (a linear autoencoder ≈ PCA).

Activationdefault tanh

Nonlinearity in the network's hidden layers.

  • tanh(default) — An S-shaped unit with outputs from −1 to 1; a steady choice for small networks on scaled inputs.
  • ReLU — Passes positive signals and zeroes the rest; trains fast and suits most networks.
  • Sigmoid (logistic) — An S-shaped unit with outputs from 0 to 1; trains slowly in deep networks, so keep it for shallow ones.
Epochsdefault 300

Training passes over the data. Too few underfits; too many can memorize the data, anomalies included.

Learning ratedefault 0.01

Adam's step size.

Batch sizedefault —

Rows per gradient step; batches follow a seeded shuffle each epoch (the same in Python and R).

Input noise (SD)default 0

Above 0 trains a denoising autoencoder: Gaussian noise with this SD (on the standardized features) is added to the inputs at every step.

Advanced

L2 penalty (λ)default 0

Adds ½·λ·Σw² over the weight matrices to the reconstruction loss.

Optimizerdefault default

How the weights are updated. The method's own choice is the usual one.

  • Method's own(default) — Adam or AdamW, as the method describes; the usual choice.
  • Adam — Adam without decoupled weight decay (an AdamW method's weight decay is then not applied).
  • AdamW — Adam with decoupled weight decay; on an Adam method it adds decay 0.01 on weight matrices.
  • SGD with momentum — Plain gradient steps with momentum 0.9; often needs a larger learning rate and a schedule.
Learning-rate scheduledefault none

How the learning rate changes over training.

  • Constant(default) — The same learning rate every epoch (the method's default).
  • Cosine — Falls smoothly from the learning rate toward 0 over the epochs.
  • Step — Divides the learning rate by 10 after each third of the epochs.
  • One cycle — Rises from a 25th of the learning rate to the full rate over the first 30% of steps, then falls far below it.
  • Reduce on plateau — Divides the learning rate by 10 after 10 epochs without improvement in the validation loss.
Warm-up epochsdefault 0

Epochs at the start that ramp the learning rate up linearly; 0 = no warm-up.

Gradient clippingdefault 0

Largest gradient size (L2 norm over all weights) before a step; larger gradients are scaled down. 0 = off.

Weight average (EMA)default 0

Keeps a moving average of the weights (for example 0.99) and uses it for validation and the result. 0 = off.

Weight average from epoch (SWA)default 0

Averages the weights at the end of every epoch from this one on and returns the average. 0 = off; not with EMA.

Record every stepdefault off

Saves the loss, learning rate and gradient size after every batch in the training history, not only per epoch.

Compute profiledefault parity

Where and how precisely the network trains. Parity matches the other engine; the faster profiles can give slightly different numbers.

  • Parity(default) — Double precision on one CPU thread: the same numbers in Python and R, run after run (the default).
  • Faster CPU — Single precision on all performance cores; repeatable on this Mac, results differ slightly from Parity.
  • Apple GPU — Single precision on the Apple GPU (macOS 15 or later); results can differ slightly. Falls back to Faster CPU without a GPU.
Checkpoint every (epochs)default —

Saves the training state this often and when training ends, so a stopped run can resume where it was. Automatic saves about every 30 seconds; 0 = off. Each save holds the weights and the optimizer's state, so a large text encoder tuned on every layer can take 1–2 GB per fold.

options

Flag anomalies bydefault share

Flag a fixed share of the most unusual rows, or every row whose score passes a cutoff.

  • Share of rows (the largest errors)(default) — Flags a set share of rows with the largest errors; pick it when you know how many you can review.
  • Error cutoff — Flags rows above the error you set; pick it when you know a meaningful threshold.
Share flaggeddefault 0.05

Share of rows to flag as anomalies (0.05 flags the most unusual 5%).

Error cutoffdefault 1

Mean squared reconstruction error per standardized feature; about 1 means the row is rebuilt no better than by its column means.

What it reports

n
How many independent units the analysis used; it sets precision and power.
n_features
How many independent units the analysis used; it sets precision and power.
latent_dim
A compact set of coordinates from which a model can rebuild data; every point decodes to something, realistic or not.
recon_mse
A neural network that squeezes rows through a narrow layer and rebuilds them; the narrow layer works as a map.
error_check
An order-sensitive weighted average of a per-row column, Σ(row + 1)·v / Σ(row + 1), used to compare engines row by row.
n_flagged
How many independent units the analysis used; it sets precision and power.
threshold
The probability above which the model predicts the positive class; 0.5 is rarely the best choice.
final_loss
A neural network that squeezes rows through a narrow layer and rebuilds them; the narrow layer works as a map.
epochs_run
Stopping training when a score on held-back rows has stopped improving for a set number of rounds.
trustworthiness
A 0–1 score for whether rows that look close on a map are really close in the data.

Per group, level or term: emb_check[<dim>], top_row[<rank>], top_error[<rank>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses torch, codesplash; R uses torch, codesplashr.

Default traps between the two languages

  • Same network on LibTorch in double precision on one thread, from the same initial weights (shared Wichmann–Hill stream), with the same Adam arithmetic, batch order and noise draws (normal deviates by inversion: scipy's ndtri vs R's qnorm, ~1e-16). Python's torch and R's torch ship different LibTorch builds, so kernels can differ by an ulp; the map and errors agree to about 1e-12 relative on the fixtures.
Python

The exact script CodeSplash ran for example “Iris map” · 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"},
    ],
})
R

The exact script CodeSplash ran for example “Iris map” · 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")
  )
))

Sources

  • Hinton GE, Salakhutdinov RR (2006). Reducing the dimensionality of data with neural networks. Science 313(5786):504–507.
  • Vincent P, Larochelle H, Bengio Y, Manzagol P-A (2008). Extracting and composing robust features with denoising autoencoders. ICML 2008.
  • Sakurada M, Yairi T (2014). Anomaly detection using autoencoders with nonlinear dimensionality reduction. MLSDA 2014.

From the CodeSplash method registry · discover.autoencoder v1.1.0.