Sparse and contractive autoencoders: penalties instead of a bottleneck
Two ways to keep a wide autoencoder from copying its input. A sparsity penalty keeps hidden units mostly quiet; a contractive penalty keeps the code steady when the input wobbles.
What runs in CodeSplash
- DNN033Sparse autoencoder Partly runs in CodeSplash
- DNN034Contractive autoencoder Partly runs in CodeSplash
- Autoencoder (neural map and reconstruction anomalies) Verified in Python and R
You will be able to
- Compute a KL sparsity penalty from average hidden activations
- Explain what the contractive penalty measures and why it resists small input changes
- Say what CodeSplash's autoencoder offers today and what it doesn't
A wide code needs another brake
ReadThe last lesson's autoencoder was kept honest by a narrow bottleneck. Sometimes you want a wide code instead, with more hidden units than columns, so that each unit can specialize. Then something else has to stop the network from copying its input.
Two classic brakes add a penalty to the rebuild loss:
- a sparse autoencoderSparse autoencoderAn autoencoder penalized when hidden units fire too often on average, so each unit responds to fewer rows. penalizes hidden units that are active too often;
- a contractive autoencoderContractive autoencoderAn autoencoder penalized by how much its code moves when the input moves a little (the encoder's squared Jacobian norm). penalizes a code that moves a lot when the input moves a little.
Both trade some rebuild accuracy for a code with a property you asked for.
The sparsity penalty
ReadTake sigmoid hidden units, so each activation is between 0 and 1. Average unit over the rows to get , and choose a small target rate . The penalty is the KL divergenceKullback–Leibler divergenceHow many extra nats it costs to describe draws from one distribution with a code built for another; 0 when they match. between two coin flips, one with heads rate and one with :
It is zero when a unit fires at exactly the target rate and grows as the unit fires more often.
The penalty, unit by unit
ReadIn the reference's example three units average activations near the target, well above it, and a little above it. The first unit sits on the target, so its KL term is zero up to rounding; the other two cost 0.368 and 0.037. Weighted and summed, the penalty is 0.081.
import numpy as np
H = np.array([[.1, .5, .2], [.05, .4, .3], [.15, .6, .1]]) # rows x hidden units
rho = .1
mean = np.clip(H.mean(0), 1e-8, 1 - 1e-8)
kl = rho * np.log(rho / mean) + (1 - rho) * np.log((1 - rho) / (1 - mean))
print(kl, .2 * kl.sum())H <- matrix(c(.1, .5, .2, .05, .4, .3, .15, .6, .1), ncol = 3, byrow = TRUE)
rho <- .1
m <- pmin(pmax(colMeans(H), 1e-8), 1 - 1e-8)
kl <- rho * log(rho / m) + (1 - rho) * log((1 - rho) / (1 - m))
print(c(kl, .2 * sum(kl)))The contractive penalty
ReadThe contractive penalty is the squared Frobenius norm of the encoder's JacobianJacobianFor a function with several outputs, the table of every output's derivative with respect to every input., the matrix of how each code coordinate changes with each input column:
A small value means small input changes barely move the code. For a sigmoid layer it has a closed form: each unit's slope , squared, times the squared length of its weight row. The reference's example gets 0.0349, and checks the closed form against the full Jacobian.
Denoising is the cousin
PredictPredict first
How does a contractive autoencoder relate to the denoising autoencoder from the last lesson?
Reveal
They're related. Denoising makes the rebuild resist small random changes to the input; contraction makes the code resist small changes directly. With tiny Gaussian noise, denoising behaves much like a contractive penalty on the whole autoencoder. Neither needs labels.
What runs here
ReadAn autoencoder compressed 150 rows into 2 coordinates; 8 rows with reconstruction errors ≥ 0.141 are flagged as anomalies.
- Mean reconstruction error
- 0.0395
- Trustworthiness (k = 10)
- 0.9779
- Anomalies
- 8
- Threshold
- 0.1414
Plots
View data
| species | Coordinate 1 | Coordinate 2 |
|---|---|---|
| setosa | 0.8994 | 0.5535 |
| setosa | 0.9614 | 0.1290 |
| setosa | 1.041 | 0.3232 |
| setosa | 1.050 | 0.2386 |
| setosa | 0.9346 | 0.6399 |
| setosa | 0.6920 | 0.8300 |
| setosa | 1.031 | 0.4823 |
| setosa | 0.9246 | 0.4699 |
| setosa | 1.111 | 0.0860 |
| setosa | 0.9879 | 0.2291 |
| setosa | 0.7797 | 0.7039 |
| setosa | 0.9827 | 0.4750 |
| setosa | 1.028 | 0.1515 |
| setosa | 1.208 | 0.2006 |
| setosa | 0.6507 | 0.9397 |
| setosa | 0.5948 | 1.188 |
| setosa | 0.7307 | 0.8459 |
| setosa | 0.8656 | 0.5412 |
| setosa | 0.6110 | 0.7550 |
| setosa | 0.8558 | 0.7800 |
| setosa | 0.7610 | 0.4417 |
| setosa | 0.8218 | 0.6900 |
| setosa | 1.102 | 0.6698 |
| setosa | 0.7623 | 0.3291 |
| setosa | 0.9534 | 0.4590 |
| setosa | 0.9081 | 0.1166 |
| setosa | 0.8447 | 0.4406 |
| setosa | 0.8541 | 0.5451 |
| setosa | 0.8632 | 0.4625 |
| setosa | 1.011 | 0.3136 |
| setosa | 0.9764 | 0.2207 |
| setosa | 0.7121 | 0.4197 |
| setosa | 0.8799 | 1.009 |
| setosa | 0.7451 | 1.082 |
| setosa | 0.9538 | 0.2157 |
| setosa | 0.9510 | 0.3041 |
| setosa | 0.7609 | 0.5356 |
| setosa | 1.002 | 0.6513 |
| setosa | 1.126 | 0.1742 |
| setosa | 0.8896 | 0.4647 |
| setosa | 0.9103 | 0.5495 |
| setosa | 1.024 | −0.4486 |
| setosa | 1.132 | 0.3436 |
| setosa | 0.7735 | 0.4957 |
| setosa | 0.7826 | 0.7464 |
| setosa | 0.9591 | 0.1226 |
| setosa | 0.8804 | 0.7830 |
| setosa | 1.062 | 0.3270 |
| setosa | 0.8172 | 0.7070 |
| setosa | 0.9332 | 0.3872 |
| versicolor | −0.5769 | −0.0873 |
| versicolor | −0.3555 | −0.0717 |
| versicolor | −0.5746 | −0.1889 |
| versicolor | 0.1318 | −0.7268 |
| versicolor | −0.3387 | −0.4084 |
| versicolor | −0.0251 | −0.3516 |
| versicolor | −0.3847 | −0.0073 |
| versicolor | 0.4388 | −0.5574 |
| versicolor | −0.3375 | −0.3061 |
| versicolor | 0.1561 | −0.4038 |
First 60 of 150 rows.
View data
| Anomaly | Reconstruction error |
|---|---|
| false | 0.0038 |
| false | 0.0104 |
| false | 0.0023 |
| false | 0.0084 |
| false | 0.0011 |
| false | 0.0008 |
| false | 0.0356 |
| false | 0.0021 |
| false | 0.0171 |
| false | 0.0120 |
| false | 0.0198 |
| false | 0.0095 |
| false | 0.0075 |
| false | 0.0252 |
| false | 0.0704 |
| false | 0.0247 |
| false | 0.0087 |
| false | 0.0031 |
| false | 0.0458 |
| false | 0.0058 |
| false | 0.0481 |
| false | 0.0086 |
| false | 0.0391 |
| false | 0.0086 |
| false | 0.0269 |
| false | 0.0186 |
| false | 0.0055 |
| false | 0.0109 |
| false | 0.0189 |
| false | 0.0081 |
| false | 0.0023 |
| false | 0.0369 |
| false | 0.0286 |
| false | 0.0141 |
| false | 0.0046 |
| false | 0.0149 |
| false | 0.0715 |
| false | 0.0061 |
| false | 0.0213 |
| false | 0.0072 |
| false | 0.0037 |
| false | 0.0231 |
| false | 0.0375 |
| false | 0.0341 |
| false | 0.0227 |
| false | 0.0039 |
| false | 0.0076 |
| false | 0.0108 |
| false | 0.0090 |
| false | 0.0046 |
| true | 0.1810 |
| false | 0.0220 |
| false | 0.1093 |
| false | 0.0026 |
| false | 0.0536 |
| false | 0.0116 |
| false | 0.0037 |
| false | 0.0193 |
| false | 0.1183 |
| false | 0.0575 |
First 60 of 150 rows.
View data
| Epoch | Reconstruction loss | Set |
|---|---|---|
| 1 | 0.9193 | train |
| 2 | 0.8359 | train |
| 3 | 0.7698 | train |
| 4 | 0.7086 | train |
| 5 | 0.6472 | train |
| 6 | 0.5876 | train |
| 7 | 0.5328 | train |
| 8 | 0.4868 | train |
| 9 | 0.4519 | train |
| 10 | 0.4259 | train |
| 11 | 0.4032 | train |
| 12 | 0.3784 | train |
| 13 | 0.3499 | train |
| 14 | 0.3198 | train |
| 15 | 0.2915 | train |
| 16 | 0.2671 | train |
| 17 | 0.2466 | train |
| 18 | 0.2291 | train |
| 19 | 0.2146 | train |
| 20 | 0.2032 | train |
| 21 | 0.1949 | train |
| 22 | 0.1884 | train |
| 23 | 0.1821 | train |
| 24 | 0.1752 | train |
| 25 | 0.1676 | train |
| 26 | 0.1593 | train |
| 27 | 0.1502 | train |
| 28 | 0.1402 | train |
| 29 | 0.1297 | train |
| 30 | 0.1196 | train |
| 31 | 0.1108 | train |
| 32 | 0.1036 | train |
| 33 | 0.0981 | train |
| 34 | 0.0943 | train |
| 35 | 0.0919 | train |
| 36 | 0.0907 | train |
| 37 | 0.0900 | train |
| 38 | 0.0890 | train |
| 39 | 0.0872 | train |
| 40 | 0.0848 | train |
| 41 | 0.0821 | train |
| 42 | 0.0798 | train |
| 43 | 0.0780 | train |
| 44 | 0.0766 | train |
| 45 | 0.0754 | train |
| 46 | 0.0743 | train |
| 47 | 0.0734 | train |
| 48 | 0.0725 | train |
| 49 | 0.0713 | train |
| 50 | 0.0699 | train |
| 51 | 0.0683 | train |
| 52 | 0.0669 | train |
| 53 | 0.0656 | train |
| 54 | 0.0644 | train |
| 55 | 0.0632 | train |
| 56 | 0.0624 | train |
| 57 | 0.0619 | train |
| 58 | 0.0616 | train |
| 59 | 0.0613 | train |
| 60 | 0.0609 | train |
First 60 of 200 rows.
Rows reconstructed worst
| Rank | Row | Reconstruction error | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 115 | 0.2760 | 5.800 | 2.800 | 5.100 | 2.400 |
| 2 | 107 | 0.2472 | 4.900 | 2.500 | 4.500 | 1.700 |
| 3 | 101 | 0.2335 | 6.300 | 3.300 | 6 | 2.500 |
| 4 | 51 | 0.1810 | 7 | 3.200 | 4.700 | 1.400 |
| 5 | 137 | 0.1731 | 6.300 | 3.400 | 5.600 | 2.400 |
| 6 | 149 | 0.1554 | 6.200 | 3.400 | 5.400 | 2.300 |
| 7 | 122 | 0.1531 | 5.600 | 2.800 | 4.900 | 2 |
| 8 | 77 | 0.1414 | 6.800 | 2.800 | 4.800 | 1.400 |
| 9 | 63 | 0.1393 | 6 | 2.200 | 4 | 1 |
| 10 | 130 | 0.1242 | 7.200 | 3 | 5.800 | 1.600 |
| 11 | 59 | 0.1183 | 6.600 | 2.900 | 4.600 | 1.300 |
| 12 | 66 | 0.1139 | 6.700 | 3.100 | 4.400 | 1.400 |
| 13 | 145 | 0.1111 | 6.700 | 3.300 | 5.700 | 2.500 |
| 14 | 53 | 0.1093 | 6.900 | 3.100 | 4.900 | 1.500 |
| 15 | 88 | 0.1092 | 6.300 | 2.300 | 4.400 | 1.300 |
| 16 | 114 | 0.0994 | 5.700 | 2.500 | 5 | 2 |
| 17 | 116 | 0.0945 | 6.400 | 3.200 | 5.300 | 2.300 |
| 18 | 76 | 0.0935 | 6.600 | 3 | 4.400 | 1.400 |
| 19 | 132 | 0.0892 | 7.900 | 3.800 | 6.400 | 2 |
| 20 | 85 | 0.0855 | 5.400 | 3 | 4.500 | 1.500 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Autoencoder (neural map and reconstruction anomalies)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.autoencoder 1.1.0 · spec b20a603fe1151222
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_deep_*: torch networks with shared initial weights (twin of codesplash.deep)
# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE <- "median"
SCALE <- "standard"
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/discover.autoencoder/iris_map/out-r")
FEATURES <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
sepal_length = "numeric",
sepal_width = "numeric",
petal_length = "numeric",
petal_width = "numeric"
),
levels = list(
),
impute = IMPUTE,
scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df)) # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
LABEL <- "species"
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = LABEL))[[LABEL]]
# %% Autoencoder (torch for R, float64, one thread): encoder -> linear bottleneck -> mirrored decoder
HIDDEN <- as.integer(unlist(c(8)))
LATENT <- as.integer(2)
fit <- cs_deep_fit_autoencoder(
X, HIDDEN, LATENT,
activation = "tanh",
epochs = as.integer(200),
lr = 0.02,
batch_size = NULL,
weight_decay = 0,
noise = 0,
seed = 42
)
Z <- fit$embedding # n x LATENT bottleneck coordinates
errors <- fit$error # mean squared reconstruction error per row (standardized features)
# %% Anomalies by reconstruction error
RULE <- "share"
flagged <- cs_ml_flag(errors, RULE, 0.05, 1)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-errors, rows) # largest error first, ties by row
# %% Neighborhood preservation of the map (same rows in both engines)
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(10L, length(sample) - 2L)
trust <- cs_ml_trustworthiness(X[sample, , drop = FALSE], Z[sample, , drop = FALSE], k_eval)
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.autoencoder/iris_map/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(LATENT)) emb[[paste0("dim_", j)]] <- Z[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
nanoparquet::write_parquet(data.frame(row = as.integer(rows), score = errors, anomaly = flags), file.path(out, "labels.parquet"))
nanoparquet::write_parquet(cs_deep_history_frame(fit$history), file.path(out, "history.parquet"))
# %% Result
history <- cs_deep_history_frame(fit$history)
values <- list(
n = length(rows), n_features = ncol(X), latent_dim = LATENT, recon_mse = mean(errors),
error_check = cs_ml_checksum(errors, rows), n_flagged = sum(flags), threshold = threshold,
final_loss = history$loss[nrow(history)], epochs_run = fit$epochs_run, trustworthiness = trust
)
for (j in seq_len(LATENT)) values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(Z[, j], rows)
for (rank in seq_len(min(10L, length(ord)))) {
values[[sprintf("top_row[%d]", rank)]] <- rows[ord[rank]]
values[[sprintf("top_error[%d]", rank)]] <- errors[ord[rank]]
}
top <- utils::head(ord, 20L)
table_rows <- lapply(seq_along(top), function(rank) {
i <- top[rank]
r <- list(rank = rank, row = rows[i] + 1L, error = errors[i])
for (f in FEATURES) {
v <- df[[f]][rows[i] + 1L]
r[[f]] <- if (is.na(v)) NULL else if (is.numeric(v)) v else as.character(v)
}
r
})
pick <- cs_ml_sample_rows(length(rows), 5000)
groups <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
g <- df[[LABEL]][rows[pick] + 1L]
ifelse(is.na(g), "(missing)", as.character(g))
}
charts <- list()
if (LATENT >= 2L) {
charts[[length(charts) + 1L]] <- cs_chart("map", "cluster-scatter", "Autoencoder map (bottleneck coordinates 1 and 2)", list(
x = cs_col("Coordinate 1", Z[pick, 1], "numeric"),
y = cs_col("Coordinate 2", Z[pick, 2], "numeric"),
cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ",")))
}
charts[[length(charts) + 1L]] <- cs_chart("errors", "anomaly-scores", "Reconstruction error distribution", list(
score = cs_col("Reconstruction error", errors, "numeric"),
anomaly = cs_col("Anomaly", flags, "boolean")
), controls = list(threshold = threshold))
charts[[length(charts) + 1L]] <- cs_chart("training", "learning-curve", "Training loss by epoch", list(
n = cs_col("Epoch", history$epoch, "numeric"),
score = cs_col("Reconstruction loss", history$loss, "numeric"),
set = cs_col("Set", rep("train", nrow(history)), "categorical")
))
cs_publish(list(
title = "Autoencoder (neural map and reconstruction anomalies)",
engine = cs_engine_info("torch", "nanoparquet"),
n = length(rows),
summary = sprintf("An autoencoder compressed %d rows into %d coordinate%s; %d rows with reconstruction errors ≥ %s are flagged as anomalies.",
length(rows), LATENT, if (LATENT != 1L) "s" else "", sum(flags), format(signif(threshold, 3))),
statistics = list(
list(key = "recon_mse", label = "Mean reconstruction error", value = mean(errors)),
list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = trust),
list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer"),
list(key = "threshold", label = "Threshold", value = threshold)
),
tables = list(list(
key = "top", title = "Rows reconstructed worst",
columns = c(list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
list(key = "error", label = "Reconstruction error", type = "number")),
lapply(FEATURES, function(f) list(key = f, label = f))),
rows = table_rows
)),
charts = charts,
values = values,
warnings = warnings,
artifacts = list(
list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"),
list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"),
list(key = "history", path = file.path(out, "history.parquet"), format = "parquet")
)
))
An autoencoder compressed 150 rows into 2 coordinates; 8 rows with reconstruction errors ≥ 0.141 are flagged as anomalies.
- Mean reconstruction error
- 0.0395
- Trustworthiness (k = 10)
- 0.9779
- Anomalies
- 8
- Threshold
- 0.1414
To keep this page light, the plots are shown once, under the R tab.
Rows reconstructed worst
| Rank | Row | Reconstruction error | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 115 | 0.2760 | 5.800 | 2.800 | 5.100 | 2.400 |
| 2 | 107 | 0.2472 | 4.900 | 2.500 | 4.500 | 1.700 |
| 3 | 101 | 0.2335 | 6.300 | 3.300 | 6 | 2.500 |
| 4 | 51 | 0.1810 | 7 | 3.200 | 4.700 | 1.400 |
| 5 | 137 | 0.1731 | 6.300 | 3.400 | 5.600 | 2.400 |
| 6 | 149 | 0.1554 | 6.200 | 3.400 | 5.400 | 2.300 |
| 7 | 122 | 0.1531 | 5.600 | 2.800 | 4.900 | 2 |
| 8 | 77 | 0.1414 | 6.800 | 2.800 | 4.800 | 1.400 |
| 9 | 63 | 0.1393 | 6 | 2.200 | 4 | 1 |
| 10 | 130 | 0.1242 | 7.200 | 3 | 5.800 | 1.600 |
| 11 | 59 | 0.1183 | 6.600 | 2.900 | 4.600 | 1.300 |
| 12 | 66 | 0.1139 | 6.700 | 3.100 | 4.400 | 1.400 |
| 13 | 145 | 0.1111 | 6.700 | 3.300 | 5.700 | 2.500 |
| 14 | 53 | 0.1093 | 6.900 | 3.100 | 4.900 | 1.500 |
| 15 | 88 | 0.1092 | 6.300 | 2.300 | 4.400 | 1.300 |
| 16 | 114 | 0.0994 | 5.700 | 2.500 | 5 | 2 |
| 17 | 116 | 0.0945 | 6.400 | 3.200 | 5.300 | 2.300 |
| 18 | 76 | 0.0935 | 6.600 | 3 | 4.400 | 1.400 |
| 19 | 132 | 0.0892 | 7.900 | 3.800 | 6.400 | 2 |
| 20 | 85 | 0.0855 | 5.400 | 3 | 4.500 | 1.500 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Autoencoder (neural map and reconstruction anomalies)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.autoencoder 1.1.0 · spec b20a603fe1151222
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.deep import core as deep # twin of codesplashr::cs_deep_* (shared initial weights, Adam written out)
from codesplash.ml import anomaly as csanom
from codesplash.ml import embed as csembed
# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE = "median"
SCALE = "standard"
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-8142/discover.autoencoder/iris_map/out-python",
)
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"sepal_length": "numeric",
"sepal_width": "numeric",
"petal_length": "numeric",
"petal_width": "numeric",
},
levels={
},
impute=IMPUTE,
scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df) # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
LABEL = "species"
if LABEL:
df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=[LABEL])[LABEL]
# %% Autoencoder (PyTorch, float64, one thread): encoder → linear bottleneck → mirrored decoder
HIDDEN = [int(u) for u in [8]]
LATENT = 2
fit = deep.fit_autoencoder(
X, HIDDEN, LATENT,
activation="tanh",
epochs=200,
lr=0.02,
batch_size=None,
weight_decay=0,
noise=0,
seed=42,
)
Z = fit["embedding"] # n × LATENT bottleneck coordinates
errors = fit["error"] # mean squared reconstruction error per row (standardized features)
# %% Anomalies by reconstruction error
RULE = "share"
flags, threshold = csanom.flag(errors, RULE, 0.05, 1)
order = np.lexsort((rows, -errors)) # largest error first, ties by row
# %% Neighborhood preservation of the map (same rows in both engines)
sample = csembed.sample_rows(len(rows))
k_eval = min(10, len(sample) - 2)
trust = csembed.trustworthiness(X[sample], Z[sample], k_eval)
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.autoencoder/iris_map/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64), **{f"dim_{j + 1}": Z[:, j] for j in range(LATENT)}})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
pd.DataFrame({"row": rows.astype(np.int64), "score": errors, "anomaly": flags}).to_parquet(os.path.join(out, "labels.parquet"), index=False)
deep.history_frame(fit["history"]).to_parquet(os.path.join(out, "history.parquet"), index=False)
# %% Result
values = {
"n": len(rows),
"n_features": int(X.shape[1]),
"latent_dim": LATENT,
"recon_mse": float(np.mean(errors)),
"error_check": csembed.checksum(errors, rows),
"n_flagged": int(flags.sum()),
"threshold": float(threshold),
"final_loss": float(fit["history"][-1]["loss"]),
"epochs_run": int(fit["epochs_run"]),
"trustworthiness": trust,
}
for j in range(LATENT):
values[f"emb_check[{j + 1}]"] = csembed.checksum(Z[:, j], rows)
for rank, i in enumerate(order[:10], start=1):
values[f"top_row[{rank}]"] = int(rows[i])
values[f"top_error[{rank}]"] = float(errors[i])
top = order[:20]
table_rows = []
for rank, i in enumerate(top, start=1):
r = {"rank": rank, "row": int(rows[i]) + 1, "error": float(errors[i])}
for f in FEATURES:
v = df[f].iloc[rows[i]]
r[f] = None if pd.isna(v) else (v if isinstance(v, (int, float)) else str(v)) # None, NaN, pd.NA, NaT
table_rows.append(r)
pick = csembed.sample_rows(len(rows), 5000)
groups = [("All rows" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = []
if LATENT >= 2:
charts.append(cs.chart("map", "cluster-scatter", "Autoencoder map (bottleneck coordinates 1 and 2)", {
"x": cs.col("Coordinate 1", Z[pick, 0], "numeric"),
"y": cs.col("Coordinate 2", Z[pick, 1], "numeric"),
"cluster": cs.col(LABEL or "Group", groups, "categorical"),
}, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown."))
charts.append(cs.chart("errors", "anomaly-scores", "Reconstruction error distribution", {
"score": cs.col("Reconstruction error", errors, "numeric"),
"anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold)}))
charts.append(cs.chart("training", "learning-curve", "Training loss by epoch", {
"n": cs.col("Epoch", [h["epoch"] for h in fit["history"]], "numeric"),
"score": cs.col("Reconstruction loss", [h["loss"] for h in fit["history"]], "numeric"),
"set": cs.col("Set", ["train"] * len(fit["history"]), "categorical"),
}))
cs.publish({
"title": "Autoencoder (neural map and reconstruction anomalies)",
"engine": cs.engine_info("torch", "numpy", "pandas"),
"n": len(rows),
"summary": f"An autoencoder compressed {len(rows)} rows into {LATENT} coordinate{'s' if LATENT != 1 else ''}; {int(flags.sum())} rows with reconstruction errors ≥ {threshold:.3g} are flagged as anomalies.",
"statistics": [
{"key": "recon_mse", "label": "Mean reconstruction error", "value": float(np.mean(errors))},
{"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": trust},
{"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
{"key": "threshold", "label": "Threshold", "value": float(threshold)},
],
"tables": [{
"key": "top",
"title": "Rows reconstructed worst",
"columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
{"key": "error", "label": "Reconstruction error", "type": "number"}] + [{"key": f, "label": f} for f in FEATURES],
"rows": table_rows,
}],
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [
{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"},
{"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet"},
],
})
If you need a wide code today, use input noise: it gives most of the contractive effect. Whatever penalty you add, check it the same way as before. Compare held-out rebuild error and downstream use with PCA, and pick the penalty weight on validation rows.
Check: penalties
CheckpointCheck yourself
A hidden unit's average activation equals the sparsity target exactly. What does it add to the KL sparsity penalty?
Show the answer
Answer: a
The KL divergence between two identical coin flips is zero. Units that fire more often than the target pay; at the target they pay nothing.
Check yourself
Why add a sparsity penalty to an autoencoder with more hidden units than inputs?
Show the answer
Answer: b
Without a bottleneck, a wide network can copy. Keeping units mostly quiet forces each to respond to a narrower pattern. Activations get small on average, not exactly zero.
Check yourself
What does the contractive penalty measure?
Show the answer
Answer: c
It is the squared Frobenius norm of . A small value means nearby inputs get nearby codes.
Check yourself
You want CodeSplash's autoencoder to give codes that don't jump around for tiny input changes. What's the closest option it has today?
Show the answer
Answer: a
There is no contractive option yet. Denoising with small noise has a similar effect: the model learns to ignore small input changes.
Recap
Recap- With a wide code, a penalty replaces the bottleneck as the brake on copying.
- The sparsity penalty is a sum of KL terms between each unit's average activation and a small target.
- The contractive penalty is the squared Jacobian norm of the encoder: codes resist small input changes.
- CodeSplash runs plain and denoising autoencoders; these two penalties are explained here.
Concepts in this lesson