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.
A real result
Example “Iris map”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
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 |
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 |
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.
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"},
],
})
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.