Skip to content

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.

Advanced ~11 min8 steps

What runs in CodeSplash

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

Read first

01

A wide code needs another brake

Read

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

02

The sparsity penalty

Read

Take sigmoid hidden units, so each activation is between 0 and 1. Average unit jj over the rows to get ρ^j\hat\rho_j, and choose a small target rate ρ\rho. 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 ρ\rho and one with ρ^j\hat\rho_j:

Ω=λ∑j[ρlog⁡ρρ^j+(1−ρ)log⁡1−ρ1−ρ^j].\Omega = \lambda \sum_j \left[\rho \log\frac{\rho}{\hat\rho_j} + (1-\rho)\log\frac{1-\rho}{1-\hat\rho_j}\right].

It is zero when a unit fires at exactly the target rate and grows as the unit fires more often.

03

The penalty, unit by unit

Read

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

Python
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())
R
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)))
04

The contractive penalty

Read

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

Ω=λ∥∂h∂x∥F2.\Omega = \lambda \left\lVert \frac{\partial h}{\partial x} \right\rVert_F^2 .

A small value means small input changes barely move the code. For a sigmoid layer h=σ(Wx)h = \sigma(Wx) it has a closed form: each unit's slope hj(1−hj)h_j(1-h_j), 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.

05

Denoising is the cousin

Predict

Predict first

How does a contractive autoencoder relate to the denoising autoencoder from the last lesson?

They resist small input changes in related waysThey have nothing in commonContractive training needs noisy inputs
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.

06

What runs here

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

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.

07

Check: penalties

Checkpoint

Check 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 ∂h/∂x\partial h / \partial x. 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.

08

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