Skip to content

Deep clustering: DEC, IDEC and a mixture-prior VAE

Let a neural network shape the space it clusters in. DEC and IDEC refine an autoencoder around k centers; VaDE gives a VAE a mixture prior. How each trains, and why tight clusters in a learned space aren't proof.

Applied ~12 min9 steps

What runs in CodeSplash

You will be able to

  • Explain how DEC builds and sharpens its own training target
  • Tell DEC from IDEC and say what the reconstruction term protects against
  • Read a VaDE clustering and the importance-weighted bound

Read first

01

Cluster in a space you learn

Read

k-means and Gaussian mixtures cluster rows in the space you give them. Deep embedded clusteringDeep embedded clusteringClustering that keeps adjusting a pretrained encoder and the cluster centers together, so the space itself becomes more clustered. also learns the space: it keeps adjusting an encoder so the clusters in its codes get clearer. Both methods here are Experimental.

02

How DEC trains

Read
  1. Train an autoencoder and take its codes.
  2. Run k-means on the codes to place k centers.
  3. Give each row soft membershipsSoft membershipA row's degree of belonging to each cluster, summing to 1; DEC uses a Student-t kernel around the centers. from a Student-t kernel around the centers.
  4. Square and renormalize those memberships into a sharpened targetSharpened target distributionDEC's training target, each row's soft memberships squared and renormalized so confident assignments grow more confident., then train the encoder and centers toward it.
  5. Refresh the target every few epochs; stop when almost no row changes cluster.

The target is built from the model's own guesses, so confident rows pull the space tighter around their centers.

Deep embedded clustering (DEC and IDEC)Recorded · Python and R agreeRecorded 2026-11-25 · 39 values compared
R

IDEC found 3 clusters in 150 rows after 30 fine-tuning epochs (stopped: assignments settled); the mean membership probability is 0.66 and 8.0% of rows moved from the starting k-means clusters.

Clusters
3
Mean silhouette
0.3993

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
ClusterPC1 (73%)PC2 (23%)
1−2.2650.4800
1−2.081−0.6741
1−2.364−0.3419
1−2.299−0.5974
1−2.3900.6468
1−2.0761.489
1−2.4440.0476
1−2.2330.2231
1−2.335−1.115
1−2.184−0.4690
1−2.1661.044
1−2.3260.1331
1−2.218−0.7287
1−2.633−0.9615
1−2.1991.860
1−2.2622.686
1−2.2081.484
1−2.1900.4888
1−1.8991.405
1−2.3431.128
1−1.9140.4089
1−2.2070.9241
1−2.7740.4583
1−1.8190.0856
1−2.2270.1373
1−1.952−0.6256
1−2.0510.2422
1−2.1690.5271
1−2.1400.3132
1−2.265−0.3377
1−2.140−0.5045
1−1.8320.4237
1−2.6151.794
1−2.4462.151
1−2.110−0.4602
1−2.208−0.2061
1−2.0450.6616
1−2.5270.5923
1−2.430−0.9042
1−2.1700.2689
1−2.2860.4417
1−1.858−2.337
1−2.554−0.4791
1−1.9640.4723
1−2.1371.142
1−2.070−0.7111
1−2.3851.120
1−2.394−0.3862
1−2.2290.9980
1−2.2040.0092
21.1020.8630
20.73130.5946
21.2410.6163
30.4075−1.754
21.075−0.2084
30.3887−0.5933
20.74650.7730
1−0.4873−1.852
20.92790.0322
30.0114−1.034

First 60 of 150 rows.

Clusters in the learned space (first two coordinates)Which rows group together, and how well separated are the groups?
View data
CenterClusterCode 1Code 2
false1−0.02630.9294
false10.71660.8719
false10.54851.002
false10.73620.9276
false1−0.08380.9420
false1−0.67000.9079
false10.33640.9566
false10.13210.9268
false11.1520.8101
false10.55880.9830
false1−0.41020.9176
false10.23310.9369
false10.82300.8983
false11.1610.9618
false1−0.86241.083
false1−1.3111.107
false1−0.62720.9733
false1−0.05670.8886
false1−0.70060.8951
false1−0.37970.9304
false1−0.11340.8395
false1−0.30910.8633
false10.18351.063
false10.07680.7584
false10.20040.8866
false10.63790.8262
false10.06060.8286
false1−0.09320.8991
false10.03110.9167
false10.51590.9519
false10.59050.9157
false1−0.15230.7915
false1−0.66551.104
false1−0.92371.130
false10.52830.9426
false10.39160.9787
false1−0.23920.8923
false10.00250.9962
false11.0470.8824
false10.07620.9134
false10.01020.9189
false11.7670.4897
false10.71641.043
false1−0.11350.7463
false1−0.44680.8372
false10.75200.8310
false1−0.36600.9419
false10.59360.9989
false1−0.36030.9180
false10.25640.9443
false2−2.658−0.9546
false2−1.905−0.6354
false2−2.556−1.041
false30.0456−0.7241
false2−1.741−1.132
false3−0.5398−0.4468
false2−1.909−0.5864
false10.9314−0.1152
false2−1.850−0.9166
false30.0142−0.2851

First 60 of 153 rows.

Fine-tuning loss by epochIs the network still learning, and which part of its loss moves?
View data
PartLoss per rowEpoch
total0.09901
total0.09712
total0.09513
total0.09354
total0.09155
total0.09116
total0.08967
total0.08798
total0.08649
total0.084910
total0.084311
total0.082812
total0.081413
total0.080114
total0.078915
total0.078416
total0.077117
total0.076018
total0.074919
total0.073820
total0.073421
total0.072422
total0.071423
total0.070424
total0.069525
total0.069226
total0.068427
total0.067628
total0.066829
total0.066130
KL0.09611
KL0.09352
KL0.09223
KL0.09074
KL0.08925
KL0.09886
KL0.09767
KL0.09668
KL0.09559
KL0.094410
KL0.100211
KL0.098712
KL0.097313
KL0.096214
KL0.095315
KL0.101616
KL0.100417
KL0.099318
KL0.098119
KL0.096920
KL0.102621
KL0.101222
KL0.099923
KL0.098924
KL0.097925
KL0.103426
KL0.102027
KL0.100528
KL0.099129
KL0.097930

First 60 of 90 rows.

Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.6727
10.6726
10.6722
10.6668
10.6666
10.6654
10.6654
10.6643
10.6593
10.6563
10.6551
10.6455
10.6453
10.6448
10.6412
10.6314
10.6275
10.6260
10.6249
10.6214
10.6212
10.6155
10.6138
10.6099
10.6043
10.6025
10.6001
10.5960
10.5896
10.5871
10.5864
10.5845
10.5837
10.5818
10.5814
10.5576
10.5451
10.5450
10.5345
10.5301
10.5270
10.5240
10.5216
10.5212
10.5109
10.4926
10.4819
10.4681
10.4016
10.1161
1−0.3795
1−0.3909
1−0.4055
1−0.4138
20.5106
20.5104
20.5028
20.5025
20.4868
20.4845

First 60 of 150 rows.

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15436.0%5.0063.3441.5960.3037
25335.3%6.7403.0405.4361.940
34328.7%5.7912.7194.4051.412
The exact R script · R R version 4.5.1 (2025-06-13)
# Deep embedded clustering (DEC and IDEC)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.deep_cluster 1.0.1 · spec 4582a03932e3fc6c
# 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)
# Checked before the shared preparation: +/-Inf stops with CS_E_NOT_FINITE, too few usable rows with CS_E_TOO_FEW_ROWS.
pre_ <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = c("sepal_length", "sepal_width", "petal_length", "petal_width")))
cs_check_finite_columns(pre_, c("sepal_length", "sepal_width", "petal_length", "petal_width"))
usable_ <- if ("drop" == "drop") nrow(stats::na.omit(pre_)) else nrow(pre_)
if (usable_ < max(3L, 3 + 1L)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("%d clusters", 3), min = max(3L, 3 + 1L), n = usable_)

# %% Data
FEATURES <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
LABEL <- "species"  # known groups (external validation only)
ROW_ID <- NULL  # row labels for charts
SEED <- 42
KINDS <- list(
  sepal_length = "numeric",
  sepal_width = "numeric",
  petal_length = "numeric",
  petal_width = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = unique(c(FEATURES, LABEL, ROW_ID))))
n_input <- nrow(df)
prep <- cs_ml_cluster_prepare(df, FEATURES, KINDS, LEVELS, missing = "drop", scale = "standard")
X <- prep$X; rows <- prep$rows; names_ <- prep$names; frame <- prep$frame
warnings <- list()
if (length(rows) < n_input) {
  warnings <- c(warnings, sprintf("%d of %d rows were left out because a feature was missing.", n_input - length(rows), n_input))
}
if (length(rows) < 3) stop("Clustering needs at least three rows with every feature present.")
truth <- if (!is.null(LABEL)) as.character(frame[[LABEL]]) else NULL
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.deep_cluster/iris_idec/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL

# %% Clustering
K <- as.integer(3)
if (K >= length(rows)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("%d clusters", K), min = K + 1L, n = length(rows))
OBJECTIVE <- "idec"
LATENT <- as.integer(2)
# Pretrain an autoencoder, start the centers with k-means on its codes, then fine-tune on the
# sharpened soft assignments (DEC) or on them plus the reconstruction (IDEC); torch for R, float64, one thread.
fit <- cs_deep_fit_cluster(
  X, as.integer(unlist(c(8))), LATENT, K,
  objective = OBJECTIVE,
  activation = "relu",
  alpha = 1,
  gamma = 0.1,
  pretrain_epochs = as.integer(100),
  epochs = as.integer(40),
  update_interval = as.integer(5),
  tol = 0.001,
  lr = 0.005,
  batch_size = NULL,
  n_init = as.integer(10),
  seed = SEED
)
q <- fit$q
if (any(!is.finite(q))) cs_error("CS_E_NO_CONVERGENCE", what = "Deep embedded clustering")
raw <- as.integer(fit$labels)
canon <- cs_ml_canonical(raw)
canon_of <- integer(0)
for (j in seq_len(K)) {
  members <- which(raw == j - 1L)
  if (length(members)) {
    canon_of[as.character(j)] <- canon[members[1]]
    extra[[sprintf("membership_%d", canon[members[1]])]] <- q[, j]  # soft membership in canonical cluster ids
  }
}
extra$probability <- apply(q, 1, max)
hist <- fit$history
values$objective <- switch(OBJECTIVE, dec = "DEC", idec = "IDEC")
values$k_requested <- K
values$latent_dim <- LATENT
values$pretrain_loss <- fit$pretrain_loss
values$kmeans_wss <- fit$kmeans_wss
values$final_kl <- if (length(hist)) hist[[length(hist)]]$kl else NaN
values$recon_mse <- fit$recon_mse
values$epochs_run <- fit$epochs_run
values$stopped_early <- isTRUE(fit$stopped)
values$label_change <- fit$label_change
values$moved_from_kmeans <- mean(raw != fit$kmeans_labels)
values$mean_probability <- mean(apply(q, 1, max))
for (j in names(canon_of)) values[[sprintf("soft_size[%d]", canon_of[[j]])]] <- sum(q[, as.integer(j)])
if (K - length(canon_of) > 0L) {
  warnings <- c(warnings, sprintf("%d of the %d centers ended with no rows; the clustering has %d clusters.", K - length(canon_of), K, length(canon_of)))
}
Z <- fit$embedding
if (LATENT >= 2L) {
  show_ <- cs_ml_even_sample(length(rows)) + 1L  # 0-based picks (the Python twin's) as R rows
  cent_ <- as.integer(names(canon_of))[order(canon_of)]
  ids_ <- sort(as.integer(canon_of))
  charts[[length(charts) + 1L]] <- cs_chart(
    "latent", "cluster-scatter", "Clusters in the learned space (first two coordinates)",
    list(
      x = cs_col("Code 1", c(Z[show_, 1], fit$centers[cent_, 1]), "numeric"),
      y = cs_col("Code 2", c(Z[show_, 2], fit$centers[cent_, 2]), "numeric"),
      cluster = cs_col("Cluster", c(as.character(canon[show_]), as.character(canon_of[as.character(cent_)])), "categorical", levels = as.character(ids_)),
      centroid = cs_col("Center", c(rep(FALSE, length(show_)), rep(TRUE, length(cent_))), "boolean")
    ),
    note = if (length(show_) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(show_), big.mark = ","), format(length(rows), big.mark = ","))
  )
}
if (length(hist)) {
  parts_ <- c(total = "loss", KL = "kl")
  if (OBJECTIVE == "idec") parts_ <- c(parts_, reconstruction = "recon")
  ep_ <- vapply(hist, function(h) as.numeric(h$epoch), numeric(1))
  charts[[length(charts) + 1L]] <- cs_chart("training", "training-components", "Fine-tuning loss by epoch", list(
    x = cs_col("Epoch", rep(ep_, length(parts_)), "numeric"),
    value = cs_col("Loss per row", unlist(lapply(parts_, function(key) vapply(hist, function(h) as.numeric(h[[key]]), numeric(1))), use.names = FALSE), "numeric"),
    component = cs_col("Part", rep(names(parts_), each = length(hist)), "categorical", levels = names(parts_))
  ))
}
summary <- paste0(
  sprintf("%s found %d cluster%s in %s rows after %d fine-tuning epoch%s", values$objective, length(canon_of), if (length(canon_of) != 1L) "s" else "",
          format(length(rows), big.mark = ","), fit$epochs_run, if (fit$epochs_run != 1L) "s" else ""),
  if (isTRUE(fit$stopped)) " (stopped: assignments settled)" else "",
  sprintf("; the mean membership probability is %.2f and %.1f%% of rows moved from the starting k-means clusters.", values$mean_probability, 100 * values$moved_from_kmeans)
)

# %% Canonical labels and validation
labels <- cs_ml_canonical(raw)
ids <- sort(unique(labels[labels != -1]))
k <- length(ids)
values$k <- k
values$n_noise <- sum(labels == -1)
if (!is.null(centers)) {
  cid <- if (is.null(center_ids)) seq_len(nrow(centers)) - 1L else center_ids
  raw_of <- vapply(ids, function(c) raw[which(labels == c)[1]], numeric(1))
  centers <- centers[match(raw_of, cid), , drop = FALSE]
  for (i in seq_along(ids)) for (j in seq_along(names_)) {
    values[[sprintf("center[%d,%s]", ids[i], names_[j])]] <- centers[i, j]
  }
}
sz <- cs_ml_cluster_sizes(labels)
for (c in names(sz)) values[[sprintf("size[%s]", c)]] <- sz[[c]]
check <- cs_ml_cluster_validation(X, labels, truth, D = D, cap = 3000, seed = SEED)
widths <- check$.widths
check$.widths <- NULL
values <- c(values, check)
profile_rows <- list()
for (c in ids) {
  member <- labels == c
  row <- list(cluster = c, size = sum(member), share = mean(member))
  for (f in FEATURES) {
    if (identical(KINDS[[f]], "numeric")) {
      m <- mean(suppressWarnings(as.numeric(frame[[f]]))[member], na.rm = TRUE)
      row[[f]] <- m
      values[[sprintf("mean[%d,%s]", c, f)]] <- m
    } else {
      v <- as.character(frame[[f]])[member]
      v <- v[!is.na(v)]
      top <- if (length(v)) sort(table(v), decreasing = TRUE) else NULL
      row[[f]] <- if (length(top)) sprintf("%s (%.0f%%)", names(top)[1], 100 * top[[1]] / sum(member)) else ""
    }
  }
  profile_rows[[length(profile_rows) + 1L]] <- row
}
tables <- c(list(list(
  key = "clusters", title = "Clusters",
  columns = c(list(list(key = "cluster", label = "Cluster", type = "integer"),
                   list(key = "size", label = "Size", type = "integer"),
                   list(key = "share", label = "Share", type = "percent")),
              lapply(FEATURES, function(f) list(key = f, label = f, type = if (identical(KINDS[[f]], "numeric")) "number" else "string"))),
  rows = profile_rows
)), tables)

# %% Labels file and charts
path <- do.call(cs_ml_write_labels, c(list(out, rows, labels), extra))
name_of <- function(c) as.character(c)  # noise stays "-1" (drawn gray, listed last)
pr <- cs_ml_project2(X, centers, names_)
show <- cs_ml_even_sample(length(rows))
xs <- pr$P[show + 1L, 1]; ys <- pr$P[show + 1L, 2]
cl <- name_of(labels[show + 1L])
cent <- rep(FALSE, length(show))
lab <- if (!is.null(ROW_ID)) as.character(frame[[ROW_ID]])[show + 1L] else NULL
if (!is.null(pr$C)) {
  xs <- c(xs, pr$C[, 1]); ys <- c(ys, pr$C[, 2])
  cl <- c(cl, name_of(ids)); cent <- c(cent, rep(TRUE, length(ids)))
  if (!is.null(lab)) lab <- c(lab, sprintf("center %d", ids))
}
level_names <- c(as.character(ids), if (values$n_noise > 0) "-1")
charts <- c(list(cs_chart(
  "clusters", "cluster-scatter", "Clusters",
  list(x = cs_col(pr$labels[1], xs, "numeric"), y = cs_col(pr$labels[2], ys, "numeric"),
       cluster = cs_col("Cluster", cl, "categorical", levels = level_names),
       centroid = if (!is.null(pr$C)) cs_col("Center", cent, "boolean"),
       label = if (!is.null(lab)) cs_col("Row", lab, "categorical")),
  note = if (length(show) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(show), big.mark = ","), format(length(rows), big.mark = ","))
)), charts)
if (!is.nan(values$silhouette)) {
  wl <- labels[widths$pick + 1L]
  o <- order(wl, -widths$width)
  charts[[length(charts) + 1L]] <- cs_chart(
    "silhouette", "silhouette-plot", "Silhouette widths",
    list(cluster = cs_col("Cluster", as.character(wl[o]), "categorical", levels = as.character(ids)),
         width = cs_col("Silhouette width", widths$width[o], "numeric")),
    note = if (length(widths$pick) == sum(labels != -1)) NULL else sprintf("%s rows sampled for the silhouette.", format(length(widths$pick), big.mark = ","))
  )
}

# %% Result
if (is.null(summary)) {
  summary <- sprintf("%d cluster%s in %s rows", k, if (k != 1) "s" else "", format(length(rows), big.mark = ","))
  if (values$n_noise > 0) summary <- paste0(summary, sprintf(" (%s noise points)", format(values$n_noise, big.mark = ",")))
  if (!is.nan(values$silhouette)) summary <- paste0(summary, sprintf("; mean silhouette %.2f", values$silhouette))
  summary <- paste0(summary, ".")
}
cs_publish(list(
  title = "Deep embedded clustering (DEC and IDEC)",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = list(list(key = "k", label = "Clusters", value = k, format = "integer"),
                    list(key = "silhouette", label = "Mean silhouette", value = values$silhouette)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = path, format = "parquet")),
  model = list(kind = "clusterer", features = I(names_), params = list(
    k = 3,
    objective = "idec",
    hidden_layers = c(8),
    latent_dim = 2,
    activation = "relu",
    gamma = 0.1,
    alpha = 1,
    pretrain_epochs = 100,
    epochs = 40,
    update_interval = 5,
    tol = 0.001,
    learning_rate = 0.005,
    batch_size = NULL,
    n_init = 10,
    scale = "standard",
    missing = "drop"
  ))
))
Python

IDEC found 3 clusters in 150 rows after 30 fine-tuning epochs (stopped: assignments settled); the mean membership probability is 0.66 and 8.0% of rows moved from the starting k-means clusters.

Clusters
3
Mean silhouette
0.3993

To keep this page light, the plots are shown once, under the R tab.

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15436.0%5.0063.3441.5960.3037
25335.3%6.7403.0405.4361.940
34328.7%5.7912.7194.4051.412
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Deep embedded clustering (DEC and IDEC)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.deep_cluster 1.0.1 · spec 4582a03932e3fc6c
# 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 numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.stats.rng import Rng
from codesplash.deep import unsupervised as du  # twin of codesplashr::cs_deep_fit_cluster (shared initial weights, Adam written out)

# Checked before the shared preparation: ±Inf stops with CS_E_NOT_FINITE, too few usable rows with CS_E_TOO_FEW_ROWS.
_pre = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=["sepal_length", "sepal_width", "petal_length", "petal_width"])
cs.check_finite_columns(_pre, ["sepal_length", "sepal_width", "petal_length", "petal_width"])
_usable = len(_pre.dropna()) if "drop" == "drop" else len(_pre)
if _usable < max(3, 3 + 1):
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="%d clusters" % 3, min=max(3, 3 + 1), n=_usable)

# %% Data
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
LABEL = "species"  # known groups (external validation only)
ROW_ID = None  # row labels for charts
SEED = 42
KINDS = {
    "sepal_length": "numeric",
    "sepal_width": "numeric",
    "petal_length": "numeric",
    "petal_width": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=list(dict.fromkeys(FEATURES + [c for c in (LABEL, ROW_ID) if c])))
n_input = len(df)
X, rows, names, frame = csc.prepare(df, FEATURES, KINDS, LEVELS, missing="drop", scale="standard")
warnings = []
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a feature was missing.")
if len(rows) < 3:
    raise ValueError("Clustering needs at least three rows with every feature present.")
truth = frame[LABEL].astype("object").to_numpy() if LABEL else None
out = csml.out_dir("target/academy-parity/run-8142/discover.deep_cluster/iris_idec/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None

# %% Clustering
K = 3
if K >= len(rows):
    cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"{K} clusters", min=K + 1, n=len(rows))
OBJECTIVE = "idec"
LATENT = 2
# Pretrain an autoencoder, start the centers with k-means on its codes, then fine-tune on the
# sharpened soft assignments (DEC) or on them plus the reconstruction (IDEC); PyTorch, float64, one thread.
fit = du.fit_deep_cluster(
    X, [int(u) for u in [8]], LATENT, K,
    objective=OBJECTIVE,
    activation="relu",
    alpha=1,
    gamma=0.1,
    pretrain_epochs=100,
    epochs=40,
    update_interval=5,
    tol=0.001,
    lr=0.005,
    batch_size=None,
    n_init=10,
    seed=SEED,
)
q = fit["q"]
if not np.all(np.isfinite(q)):
    cs.cs_error("CS_E_NO_CONVERGENCE", what="Deep embedded clustering")
raw = fit["labels"].astype(np.int64)
canon = csc.canonical(raw)
canon_of = {}
for j in range(K):
    members = np.flatnonzero(raw == j)
    if len(members):
        canon_of[j] = int(canon[members[0]])
        extra[f"membership_{canon_of[j]}"] = q[:, j]  # soft membership in canonical cluster ids
extra["probability"] = q.max(axis=1)
hist = fit["history"]
values["objective"] = {"dec": "DEC", "idec": "IDEC"}[OBJECTIVE]
values["k_requested"] = K
values["latent_dim"] = LATENT
values["pretrain_loss"] = float(fit["pretrain_loss"])
values["kmeans_wss"] = float(fit["kmeans_wss"])
values["final_kl"] = float(hist[-1]["kl"]) if hist else float("nan")
values["recon_mse"] = float(fit["recon_mse"])
values["epochs_run"] = int(fit["epochs_run"])
values["stopped_early"] = bool(fit["stopped"])
values["label_change"] = float(fit["label_change"])
values["moved_from_kmeans"] = float(np.mean(raw != fit["kmeans_labels"]))
values["mean_probability"] = float(np.mean(q.max(axis=1)))
for j, c in canon_of.items():
    values[f"soft_size[{c}]"] = float(q[:, j].sum())
if K - len(canon_of):
    warnings.append(f"{K - len(canon_of)} of the {K} centers ended with no rows; the clustering has {len(canon_of)} clusters.")
Z = fit["embedding"]
if LATENT >= 2:
    show_ = csc.even_sample(len(rows))
    ids_ = sorted(canon_of.values())
    cent_ = [j for j in sorted(canon_of, key=lambda j: canon_of[j])]
    charts.append(cs.chart(
        "latent", "cluster-scatter", "Clusters in the learned space (first two coordinates)",
        {
            "x": cs.col("Code 1", list(Z[show_, 0]) + [float(fit["centers"][j, 0]) for j in cent_], "numeric"),
            "y": cs.col("Code 2", list(Z[show_, 1]) + [float(fit["centers"][j, 1]) for j in cent_], "numeric"),
            "cluster": cs.col("Cluster", [str(c) for c in canon[show_]] + [str(canon_of[j]) for j in cent_], "categorical", levels=[str(c) for c in ids_]),
            "centroid": cs.col("Center", [False] * len(show_) + [True] * len(cent_), "boolean"),
        },
        note=None if len(show_) == len(rows) else f"{len(show_):,} of {len(rows):,} rows shown.",
    ))
if hist:
    _parts = [("total", "loss"), ("KL", "kl")] + ([("reconstruction", "recon")] if OBJECTIVE == "idec" else [])
    _ep = [h["epoch"] for h in hist]
    charts.append(cs.chart("training", "training-components", "Fine-tuning loss by epoch", {
        "x": cs.col("Epoch", _ep * len(_parts), "numeric"),
        "value": cs.col("Loss per row", [float(h[key]) for _, key in _parts for h in hist], "numeric"),
        "component": cs.col("Part", [name for name, _ in _parts for _ in hist], "categorical", levels=[name for name, _ in _parts]),
    }))
summary = (
    f"{values['objective']} found {len(canon_of)} cluster{'s' if len(canon_of) != 1 else ''} in {len(rows):,} rows after "
    f"{int(fit['epochs_run'])} fine-tuning epoch{'s' if fit['epochs_run'] != 1 else ''}"
    + (" (stopped: assignments settled)" if fit["stopped"] else "")
    + f"; the mean membership probability is {values['mean_probability']:.2f} and {values['moved_from_kmeans']:.1%} of rows moved from the starting k-means clusters."
)

# %% Canonical labels and validation
labels = csc.canonical(raw)
ids = [int(c) for c in sorted(set(labels.tolist())) if c != -1]
k = len(ids)
values["k"] = k
values["n_noise"] = int(np.sum(labels == -1))
if centers is not None:
    # reorder centers to canonical ids: the raw id of each canonical cluster
    raw_of = {c: raw[np.flatnonzero(labels == c)[0]] for c in ids}
    pos = {int(r): i for i, r in enumerate(center_ids if center_ids is not None else range(len(centers)))}
    centers = np.array([centers[pos[int(raw_of[c])]] for c in ids])
    for c, row in zip(ids, centers):
        for name, v in zip(names, row):
            values[f"center[{c},{name}]"] = float(v)
for c, m in csc.sizes(labels).items():
    values[f"size[{c}]"] = m
check = csc.validation(X, labels, truth, D=D, cap=3000, seed=SEED)
widths, picked = check.pop("_widths")
values.update(check)
# per-cluster means of numeric features in their own units (interpretation)
profile_rows = []
for c in ids:
    member = labels == c
    row = {"cluster": c, "size": int(member.sum()), "share": float(member.mean())}
    for f in FEATURES:
        if KINDS[f] == "numeric":
            m = float(np.nanmean(pd.to_numeric(frame[f], errors="coerce").to_numpy(dtype=np.float64)[member]))
            row[f] = m
            values[f"mean[{c},{f}]"] = m
        else:
            top = pd.Series(frame[f].astype("object").to_numpy()[member]).dropna().astype(str).value_counts()
            row[f] = f"{top.index[0]} ({top.iloc[0] / member.sum():.0%})" if len(top) else ""
    profile_rows.append(row)
tables.insert(0, {
    "key": "clusters",
    "title": "Clusters",
    "columns": [
        {"key": "cluster", "label": "Cluster", "type": "integer"},
        {"key": "size", "label": "Size", "type": "integer"},
        {"key": "share", "label": "Share", "type": "percent"},
    ]
    + [{"key": f, "label": f, "type": "number" if KINDS[f] == "numeric" else "string"} for f in FEATURES],
    "rows": profile_rows,
})

# %% Labels file and charts
path = csc.write_labels(out, rows, labels, **extra)
name_of = lambda c: str(c)  # noqa: E731  — noise stays "-1" (drawn gray, listed last)
P, C, axes = csc.project2(X, centers, names)
show = csc.even_sample(len(rows))
point_labels = [str(v) for v in frame[ROW_ID].astype("object").to_numpy()[show]] if ROW_ID else None
xs, ys = list(P[show, 0]), list(P[show, 1])
cl = [name_of(c) for c in labels[show]]
cent = [False] * len(show)
lab = point_labels
if C is not None:
    xs += list(C[:, 0])
    ys += list(C[:, 1])
    cl += [name_of(c) for c in ids]
    cent += [True] * len(ids)
    lab = None if lab is None else lab + [f"center {c}" for c in ids]
level_names = [str(c) for c in ids] + (["-1"] if values["n_noise"] else [])
charts.insert(0, cs.chart(
    "clusters", "cluster-scatter", "Clusters",
    {
        "x": cs.col(axes[0], xs, "numeric"),
        "y": cs.col(axes[1], ys, "numeric"),
        "cluster": cs.col("Cluster", cl, "categorical", levels=level_names),
        "centroid": cs.col("Center", cent, "boolean") if C is not None else None,
        "label": cs.col("Row", lab, "categorical") if lab is not None else None,
    },
    note=None if len(show) == len(rows) else f"{len(show):,} of {len(rows):,} rows shown.",
))
if not np.isnan(values["silhouette"]):
    wl = labels[picked]
    order = np.lexsort((-widths, wl))
    charts.append(cs.chart(
        "silhouette", "silhouette-plot", "Silhouette widths",
        {"cluster": cs.col("Cluster", [str(c) for c in wl[order]], "categorical", levels=[str(c) for c in ids]),
         "width": cs.col("Silhouette width", list(widths[order]), "numeric")},
        note=None if len(picked) == int(np.sum(labels != -1)) else f"{len(picked):,} rows sampled for the silhouette.",
    ))

# %% Result
if summary is None:
    summary = f"{k} cluster{'s' if k != 1 else ''} in {len(rows):,} rows"
    if values["n_noise"]:
        summary += f" ({values['n_noise']:,} noise points)"
    if not np.isnan(values["silhouette"]):
        summary += f"; mean silhouette {values['silhouette']:.2f}"
    summary += "."
cs.publish({
    "title": "Deep embedded clustering (DEC and IDEC)",
    "engine": cs.engine_info("torch", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "k", "label": "Clusters", "value": k, "format": "integer"},
        {"key": "silhouette", "label": "Mean silhouette", "value": values["silhouette"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": path, "format": "parquet"}],
    "model": {"kind": "clusterer", "features": names, "params": {
        "k": 3,
        "objective": "idec",
        "hidden_layers": [8],
        "latent_dim": 2,
        "activation": "relu",
        "gamma": 0.1,
        "alpha": 1,
        "pretrain_epochs": 100,
        "epochs": 40,
        "update_interval": 5,
        "tol": 0.001,
        "learning_rate": 0.005,
        "batch_size": None,
        "n_init": 10,
        "scale": "standard",
        "missing": "drop",
    }},
})

On iris, IDEC settles into 3 clusters after 30 fine-tuning epochs, with a mean membership probability of 0.66. Against the species it scores an adjusted Rand index of 0.60.

03

DEC or IDEC?

Predict

Predict first

One version trains on the cluster target alone; the other also keeps rebuilding the rows. Which is more likely to bend the space into clusters that aren't in the data?

DECIDECThey behave the same
Reveal

DEC. With nothing tying the codes to the rows, the encoder is free to distort the space to make the target easy. IDEC keeps the decoder and adds the reconstruction error, so the codes must still describe the rows. On iris with DEC, 7.3% of rows moved away from their starting k-means cluster.

04

Two views of the clusters

Read
Cluster mapWhich rows group together, and how well separated are the groups?
View data
PC1PC2clustercenter
−1.546−0.33201false
−1.8711.2191false
−2.5161.2281false
−1.458−0.16501false
−3.1080.52601false
−1.3441.3991false
−2.7980.14501false
−1.1240.59401false
−2.1190.60101false
−1.7740.99201false
−1.3510.51201false
−1.5350.05901false
−2.1820.25001false
−2.6840.41201false
−2.3910.22401false
−2.567−0.07101false
−1.2930.75401false
−2.4570.45001false
−2.475−0.38901false
−0.7180−0.25101false
−3.4690.47201false
−2.1930.55301false
−2.0730.06801false
−1.6550.18501false
−2.2310.69301false
−1.1840.67701false
−3.5500.31001false
−1.5050.27101false
−2.0431.7511false
−1.7200.98801false
−2.3230.23701false
−1.497−0.04401false
−1.953−0.94001false
−2.852−0.33001false
−1.8240.22401false
−2.3860.67601false
−2.285−0.27201false
−1.1640.57801false
−1.820−0.16401false
−2.3900.63801false
−1.9511.0421false
−2.2580.52501false
−1.135−0.33501false
−2.5140.52001false
−1.5690.64101false
−2.9760.37501false
−2.7121.2501false
−2.3910.78901false
−1.3740.39701false
−2.527−0.45301false
−2.5170.50001false
−2.673−0.15101false
−1.9550.75501false
−1.3680.12701false
−1.3250.73601false
−1.1570.60401false
−3.0621.0491false
−1.413−0.44601false
−1.7440.58501false
−0.6700−0.41201false

First 60 of 519 rows.

The result card draws the clusters twice: in the original features (the first two principal components) and in the learned code. Groups that look crisp only in the learned code deserve suspicion. The silhouette is computed in the original features for that reason.

05

A VAE that clusters: VaDE

Read

A plain VAE's prior is one standard normal, so its space has no built-in groups. VaDEVaDEA variational autoencoder whose prior is a learned mixture of Gaussians, so the same model maps, generates and clusters rows. replaces the prior with a mixture of K Gaussians learned with the networks. Each row's cluster is the component most likely to have produced its code, and generated rows draw a component first.

Variational autoencoder (latent map, anomalies and generated rows)Recorded · Python and R agreeRecorded 2026-11-25 · 49 values compared
R

A variational autoencoder mapped 150 rows into 2 latent coordinates (2 in use); the mean squared reconstruction error is 0.154 per standardized column and the mean KL is 1.06 nats; 8 rows with a loss of at least 3.24 are flagged as anomalies. 150 rows generated from the prior differ from the data by a mean KS distance of 0.125. The mixture prior's 3 components hold 2 clusters of rows.

Mean reconstruction error
0.1545
Mean KL (nats per row)
1.060
Active latent dimensions
2
Trustworthiness (k = 10)
0.9758
Anomalies
8

Plots

Latent means by mixture component (component means marked)Which rows group together, and how well separated are the groups?
View data
Component meanComponentLatent 1 (μ)Latent 2 (μ)
false21.2091.167
false21.2550.8371
false21.2980.9618
false21.2960.8686
false21.2101.208
false21.0851.355
false21.2671.047
false21.2201.090
false21.3470.7337
false21.2620.9096
false21.1461.289
false21.2331.057
false21.2920.8480
false21.4020.8266
false21.1011.483
false21.0181.590
false21.1261.395
false21.1981.159
false21.0691.334
false21.1561.304
false21.1351.100
false21.1581.250
false21.2821.197
false21.1280.9619
false21.1981.024
false21.2040.8165
false21.1811.057
false21.1861.166
false21.2031.120
false21.2630.9292
false21.2500.8752
false21.1251.092
false21.1201.448
false21.0871.519
false21.2460.8946
false21.2641.003
false21.1641.213
false21.2271.200
false21.3550.8076
false21.2061.099
false21.2211.160
false21.1620.1799
false21.3350.9257
false21.1451.092
false21.1011.259
false21.2560.8101
false21.1541.297
false21.3000.9399
false21.1571.280
false21.2371.042
false1−0.6808−0.3430
false1−0.5544−0.3459
false1−0.6960−0.4233
false1−0.1850−0.7979
false1−0.5467−0.5576
false1−0.3479−0.5572
false1−0.5927−0.3249
false10.1240−0.6021
false1−0.5526−0.4878
false1−0.1628−0.5936

First 60 of 152 rows.

Per-row loss (reconstruction + β·KL) distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyPer-row loss
false1.195
false1.935
false1.521
false1.780
false1.249
false2.179
false1.369
false1.178
false2.656
false1.678
false1.598
false1.214
false2.005
false2.638
false3.121
true5.327
false2.163
false1.194
false2.282
false1.636
false1.469
false1.443
false1.576
false1.436
false1.261
false1.945
false1.216
false1.236
false1.256
false1.484
false1.651
false1.493
false2.882
true3.634
false1.634
false1.462
false1.554
false1.298
false2.342
false1.201
false1.189
true5.689
false1.851
false1.396
false1.748
false1.935
false1.638
false1.582
false1.506
false1.267
false1.758
false1.285
false1.243
false1.979
false0.8198
false1.066
false1.483
false2.923
false1.095
false1.755

First 60 of 150 rows.

Training loss and its parts by epochIs the network still learning, and which part of its loss moves?
View data
PartLoss per rowEpoch
total5.0131
total5.4022
total4.8613
total4.5114
total4.3975
total4.0706
total4.0207
total3.6158
total3.4679
total3.24810
total3.10611
total3.23412
total3.25813
total2.77214
total3.22715
total2.83216
total2.63717
total2.43018
total2.74719
total2.59020
total2.37921
total2.44222
total2.49623
total2.36424
total2.35825
total2.26226
total2.24627
total2.31728
total2.33029
total2.22730
total2.25831
total2.16732
total2.30233
total2.15334
total2.15535
total2.14036
total2.25537
total2.15438
total2.16139
total2.08440
total2.21441
total2.13642
total2.09543
total2.12944
total2.20945
total2.14746
total2.05147
total2.06948
total2.16449
total2.13850
total2.23351
total2.22752
total2.19453
total2.04254
total2.14755
total2.23856
total2.09957
total2.09858
total2.00259
total2.25060

First 60 of 600 rows.

sepal_length: data vs rows generated from the priorDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcesepal_length
0.2222real4.360
0.0556real4.480
0.2222real4.600
0.1111real4.720
0.2778real4.840
0.8889real4.960
0.5000real5.080
0.2222real5.200
0.0556real5.320
0.3333real5.440
0.7222real5.560
0.4444real5.680
0.3889real5.800
0.1667real5.920
0.6667real6.040
0.2222real6.160
0.5000real6.280
0.3889real6.400
0.2778real6.520
0.1111real6.640
0.6111real6.760
0.2222real6.880
0.0556real7
0.0556real7.120
0.2222real7.240
0.0556real7.360
0real7.480
0.0556real7.600
0.2222real7.720
0.0556real7.840
0synthetic4.360
0synthetic4.480
0.2222synthetic4.600
0.3333synthetic4.720
0.3889synthetic4.840
0.9444synthetic4.960
0.6111synthetic5.080
0.3889synthetic5.200
0.1111synthetic5.320
0.0556synthetic5.440
0.1111synthetic5.560
0.1667synthetic5.680
0.6111synthetic5.800
0.3889synthetic5.920
0.4444synthetic6.040
0.6667synthetic6.160
0.5556synthetic6.280
0.4444synthetic6.400
0.3889synthetic6.520
0.5000synthetic6.640
0.5556synthetic6.760
0.2778synthetic6.880
0.1667synthetic7
0synthetic7.120
0synthetic7.240
0synthetic7.360
0synthetic7.480
0synthetic7.600
0synthetic7.720
0synthetic7.840

Assumptions

  • Latent dimensions in use — 2 of 2 latent dimensions vary across rows (variance of μ > 0.01).

Rows the model finds least typical

RankRowPer-row losssepal_lengthsepal_widthpetal_lengthpetal_width
1425.6894.5002.3001.3000.3000
21325.4267.9003.8006.4002
3165.3275.7004.4001.5000.4000
41185.1227.7003.8006.7002.200
51194.3307.7002.6006.9002.300
6613.958523.5001
7343.6345.5004.2001.4000.2000
81233.2447.7002.8006.7002
91103.2247.2003.6006.1002.500
10153.1215.80041.2000.2000
11582.9234.9002.4003.3001
12942.89252.3003.3001
13332.8825.2004.1001.5000.1000
141072.7154.9002.5004.5001.700
151362.6927.70036.1002.300
1692.6564.4002.9001.4000.2000
17142.6384.30031.1000.1000
18992.6345.1002.50031.100
19632.59162.20041
201062.5817.60036.6002.100

Latent dimensions

DimensionMean KL (nats)Variance of μActive
10.32520.7428yes
20.09850.6258yes

Mixture prior components

ComponentRowsPrior weightMean 1Mean 2
11000.4957−0.5351−0.5602
2500.33731.1761.058
The exact R script · R R version 4.5.1 (2025-06-13)
# Variational autoencoder (latent map, anomalies and generated rows)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.vae 1.2.0 · spec a366cea2bf985d25
# 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_fit_vae: torch VAE with shared initial weights (twin of codesplash.deep.generative)

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE <- "median"
SCALE <- "standard"
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = c("sepal_length", "sepal_width", "petal_length", "petal_width"))), c("sepal_length", "sepal_width", "petal_length", "petal_width"))
# 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.vae/iris_vade/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]]

# %% Variational autoencoder (torch for R, float64, one thread): encoder -> (mu, log sigma^2) -> z = mu + sigma * eps -> decoder
HIDDEN <- as.integer(unlist(c(8)))
LATENT <- as.integer(2)
BETA <- 1
N_SAMPLES <- as.integer(150)
PRIOR <- "mixture"  # N(0, I), or a learned Gaussian mixture (VaDE)
IWAE <- as.integer(0)
if (PRIOR == "mixture" && length(rows) <= 3) {
  cs_error("CS_E_TOO_FEW_ROWS", what = "A 3-component mixture prior", min = 3 + 1, n = length(rows))
}
fit <- if (PRIOR == "mixture") {
  cs_deep_fit_vade(
    X, HIDDEN, LATENT, as.integer(3),
    activation = "tanh",
    beta = BETA,
    epochs = as.integer(200),
    lr = 0.01,
    batch_size = NULL,
    weight_decay = 0,
    n_samples = N_SAMPLES,
    pretrain_epochs = as.integer(100),
    seed = 42
  )
} else {
  cs_deep_fit_vae(
    X, HIDDEN, LATENT,
    activation = "tanh",
    beta = BETA,
    epochs = as.integer(200),
    lr = 0.01,
    batch_size = NULL,
    weight_decay = 0,
    n_samples = N_SAMPLES,
    seed = 42
  )
}
if (any(!is.finite(fit$score))) cs_error("CS_E_NO_CONVERGENCE", what = "Variational autoencoder training")
Z <- fit$embedding  # posterior means mu (n x LATENT)
scores <- fit$score  # squared reconstruction error at z = mu plus beta x KL, per row
errors <- fit$error  # mean squared reconstruction error per standardized column

# %% Anomalies by the per-row loss
RULE <- "share"
flagged <- cs_ml_flag(scores, RULE, 0.05, 10)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-scores, rows)  # largest loss 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 <- if (k_eval >= 1L) cs_ml_trustworthiness(X[sample, , drop = FALSE], Z[sample, , drop = FALSE], k_eval) else NaN  # undefined with fewer than 3 rows

# %% Mixture prior: each row's component at z = mu (canonical ids 1..k by size)
clusters <- NULL
if (PRIOR == "mixture") {
  clusters <- cs_ml_canonical(fit$cluster)
  comp_of <- integer(0)
  for (j in seq_along(fit$pi)) {
    members <- which(fit$cluster == j - 1L)
    if (length(members)) comp_of[as.character(j)] <- clusters[members[1]]
  }
}

# %% Importance-weighted bound on log p(x) (and the ELBO from the same draws)
bound <- if (IWAE > 0L) cs_deep_iwae_bound(X, fit, LATENT, "tanh", IWAE, 42) else NULL

# %% Generated rows: decode prior draws back to the columns' units
gen_cols <- if (N_SAMPLES > 0L) cs_deep_decode_design(fitted, fit$samples) else list()
NUMERIC <- Filter(function(f) identical(design$kinds[[f]], "numeric"), FEATURES)
sample_ks <- list()
if (N_SAMPLES > 0L) for (f in NUMERIC) sample_ks[[f]] <- cs_deep_ks(suppressWarnings(as.numeric(df[[f]])), gen_cols[[f]])

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.vae/iris_vade/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"))
labels_df <- data.frame(row = as.integer(rows), score = scores, anomaly = flags)
if (!is.null(clusters)) labels_df$cluster <- as.integer(clusters)
nanoparquet::write_parquet(labels_df, file.path(out, "labels.parquet"))
hist <- data.frame(
  epoch = vapply(fit$history, function(h) as.numeric(h$epoch), numeric(1)),
  loss = vapply(fit$history, function(h) h$loss, numeric(1)),
  reconstruction = vapply(fit$history, function(h) h$recon, numeric(1)),
  kl = vapply(fit$history, function(h) h$kl, numeric(1))
)
nanoparquet::write_parquet(hist, file.path(out, "history.parquet"))
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")
)
if (N_SAMPLES > 0L) {
  nanoparquet::write_parquet(as.data.frame(gen_cols[FEATURES], check.names = FALSE), file.path(out, "samples.parquet"))
  artifacts[[length(artifacts) + 1L]] <- list(key = "samples", path = file.path(out, "samples.parquet"), format = "parquet",
                                              title = "Rows generated from the prior")
}

# %% Result
active <- as.integer(fit$active)
values <- list(
  n = length(rows), n_features = ncol(X), latent_dim = LATENT, recon_mse = mean(errors), kl = mean(fit$kl_row),
  elbo_loss = mean(scores), active_dims = active, error_check = cs_ml_checksum(scores, rows), n_flagged = sum(flags),
  threshold = threshold, final_loss = hist$loss[nrow(hist)], epochs_run = fit$epochs_run, trustworthiness = trust,
  n_samples = N_SAMPLES, sample_ks_mean = if (length(sample_ks)) mean(unlist(sample_ks)) else NaN
)
for (j in seq_len(LATENT)) {
  values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(Z[, j], rows)
  values[[sprintf("kl_dim[%d]", j)]] <- fit$kl_dim[j]
}
for (f in names(sample_ks)) values[[sprintf("sample_ks[%s]", f)]] <- sample_ks[[f]]
if (!is.null(clusters)) {
  values$components <- length(fit$pi)
  values$n_clusters <- length(comp_of)
  for (j in names(comp_of)) {
    values[[sprintf("pi[%d]", comp_of[[j]])]] <- fit$pi[as.integer(j)]
    values[[sprintf("cluster_size[%d]", comp_of[[j]])]] <- sum(clusters == comp_of[[j]])
  }
}
if (!is.null(bound)) {
  values$iwae_samples <- IWAE
  values$iwae_bound <- mean(bound$iwae)
  values$elbo_estimate <- mean(bound$elbo)
  values$iwae_gap <- values$iwae_bound - values$elbo_estimate
}
for (rank in seq_len(min(10L, length(ord)))) {
  values[[sprintf("top_row[%d]", rank)]] <- rows[ord[rank]]
  values[[sprintf("top_score[%d]", rank)]] <- scores[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, score = scores[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
})
dim_rows <- lapply(seq_len(LATENT), function(j) list(dim = j, kl = fit$kl_dim[j], var_mu = fit$mu_var[j], active = fit$mu_var[j] > 0.01))
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 && !is.null(clusters)) {
  cent_ <- as.integer(names(comp_of))[order(comp_of)]
  charts[[length(charts) + 1L]] <- cs_chart("latent", "cluster-scatter", "Latent means by mixture component (component means marked)", list(
    x = cs_col("Latent 1 (μ)", c(Z[pick, 1], fit$mu_c[cent_, 1]), "numeric"),
    y = cs_col("Latent 2 (μ)", c(Z[pick, 2], fit$mu_c[cent_, 2]), "numeric"),
    cluster = cs_col("Component", c(as.character(clusters[pick]), as.character(comp_of[as.character(cent_)])), "categorical",
                     levels = as.character(sort(as.integer(comp_of)))),
    centroid = cs_col("Component mean", c(rep(FALSE, length(pick)), rep(TRUE, length(cent_))), "boolean")
  ), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ",")))
} else if (LATENT >= 2L) {
  charts[[length(charts) + 1L]] <- cs_chart("latent", "latent-prior", "Latent means against the N(0, I) prior", list(
    x = cs_col("Latent 1 (μ)", Z[pick, 1], "numeric"),
    y = cs_col("Latent 2 (μ)", Z[pick, 2], "numeric"),
    group = 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", "Per-row loss (reconstruction + β·KL) distribution", list(
  score = cs_col("Per-row loss", scores, "numeric"),
  anomaly = cs_col("Anomaly", flags, "boolean")
), controls = list(threshold = threshold))
ne <- nrow(hist)
charts[[length(charts) + 1L]] <- cs_chart("training", "training-components", "Training loss and its parts by epoch", list(
  x = cs_col("Epoch", rep(hist$epoch, 3), "numeric"),
  value = cs_col("Loss per row", c(hist$loss, hist$reconstruction, hist$kl), "numeric"),
  component = cs_col("Part", rep(c("total", "reconstruction", "KL"), each = ne), "categorical", levels = c("total", "reconstruction", "KL"))
))
if (length(sample_ks)) {
  f0 <- NUMERIC[1]
  d <- cs_synth_density_rows(suppressWarnings(as.numeric(df[[f0]])), as.numeric(gen_cols[[f0]]))
  if (!is.null(d)) {
    charts[[length(charts) + 1L]] <- cs_chart("samples", "density-compare", sprintf("%s: data vs rows generated from the prior", f0), list(
      x = cs_col(f0, d$x, "numeric"), density = cs_col("Density", d$density, "numeric"),
      source = cs_col("Source", d$source, "categorical", levels = c("real", "synthetic"))))
  }
}
assumptions <- list(list(
  key = "active_units", label = "Latent dimensions in use",
  status = if (active == LATENT) "pass" else if (active == 0L) "fail" else "warn",
  detail = paste0(sprintf("%d of %d latent dimension%s vary across rows (variance of μ > 0.01)", active, LATENT, if (LATENT != 1L) "s" else ""),
                  if (active == LATENT) "." else "; the rest collapsed onto the prior and carry no information about the rows.")
))
if (active < LATENT) {
  warnings <- c(warnings, sprintf("Posterior collapse: %d latent dimension%s carry no information (KL ≈ 0). Lower β, shrink the bottleneck, or train longer.",
                                  LATENT - active, if (LATENT - active != 1L) "s" else ""))
}
summary <- sprintf("A variational autoencoder mapped %d rows into %d latent coordinate%s (%d in use); the mean squared reconstruction error is %s per standardized column and the mean KL is %s nats; %d rows with a loss of at least %s are flagged as anomalies.",
                   length(rows), LATENT, if (LATENT != 1L) "s" else "", active, format(signif(mean(errors), 3)), format(signif(mean(fit$kl_row), 3)),
                   sum(flags), format(signif(threshold, 3)))
if (length(sample_ks)) summary <- paste0(summary, sprintf(" %d rows generated from the prior differ from the data by a mean KS distance of %.3f.", N_SAMPLES, values$sample_ks_mean))
if (!is.null(clusters)) summary <- paste0(summary, sprintf(" The mixture prior's %d components hold %d cluster%s of rows.", length(fit$pi), length(comp_of), if (length(comp_of) != 1L) "s" else ""))
if (!is.null(bound)) summary <- paste0(summary, sprintf(" The importance-weighted bound with %d draws is %s nats per row (%s above the ELBO estimate).", IWAE,
                                                       format(signif(values$iwae_bound, 4)), format(signif(values$iwae_gap, 3))))
extra_stats <- list()
if (!is.null(bound)) extra_stats[[1]] <- list(key = "iwae_bound", label = sprintf("Log-likelihood bound (IWAE, %d draws)", IWAE), value = values$iwae_bound)
extra_tables <- list()
if (!is.null(clusters)) {
  ordj <- as.integer(names(comp_of))[order(comp_of)]
  extra_tables[[1]] <- list(
    key = "components", title = "Mixture prior components",
    columns = c(list(list(key = "cluster", label = "Component", type = "integer"), list(key = "size", label = "Rows", type = "integer"),
                     list(key = "weight", label = "Prior weight", type = "number")),
                lapply(seq_len(LATENT), function(d) list(key = sprintf("mu_%d", d), label = sprintf("Mean %d", d), type = "number"))),
    rows = lapply(ordj, function(j) {
      cc <- comp_of[[as.character(j)]]
      r <- list(cluster = cc, size = sum(clusters == cc), weight = fit$pi[j])
      for (d in seq_len(LATENT)) r[[sprintf("mu_%d", d)]] <- fit$mu_c[j, d]
      r
    })
  )
}
cs_publish(list(
  title = "Variational autoencoder (latent map, anomalies and generated rows)",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = c(list(
    list(key = "recon_mse", label = "Mean reconstruction error", value = mean(errors)),
    list(key = "kl", label = "Mean KL (nats per row)", value = mean(fit$kl_row)),
    list(key = "active_dims", label = "Active latent dimensions", value = active, format = "integer"),
    list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = trust),
    list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer")
  ), extra_stats),
  tables = c(list(
    list(
      key = "top", title = "Rows the model finds least typical",
      columns = c(list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
                       list(key = "score", label = "Per-row loss", type = "number")),
                  lapply(FEATURES, function(f) list(key = f, label = f))),
      rows = table_rows
    ),
    list(
      key = "latent", title = "Latent dimensions",
      columns = list(list(key = "dim", label = "Dimension", type = "integer"), list(key = "kl", label = "Mean KL (nats)", type = "number"),
                     list(key = "var_mu", label = "Variance of μ", type = "number"), list(key = "active", label = "Active", type = "boolean")),
      rows = dim_rows
    )
  ), extra_tables),
  charts = charts,
  assumptions = assumptions,
  values = values,
  warnings = warnings,
  artifacts = artifacts
))
Python

A variational autoencoder mapped 150 rows into 2 latent coordinates (2 in use); the mean squared reconstruction error is 0.154 per standardized column and the mean KL is 1.06 nats; 8 rows with a loss of at least 3.24 are flagged as anomalies. 150 rows generated from the prior differ from the data by a mean KS distance of 0.125. The mixture prior's 3 components hold 2 clusters of rows.

Mean reconstruction error
0.1545
Mean KL (nats per row)
1.060
Active latent dimensions
2
Trustworthiness (k = 10)
0.9758
Anomalies
8

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Latent dimensions in use — 2 of 2 latent dimensions vary across rows (variance of μ > 0.01).

Rows the model finds least typical

RankRowPer-row losssepal_lengthsepal_widthpetal_lengthpetal_width
1425.6894.5002.3001.3000.3000
21325.4267.9003.8006.4002
3165.3275.7004.4001.5000.4000
41185.1227.7003.8006.7002.200
51194.3307.7002.6006.9002.300
6613.958523.5001
7343.6345.5004.2001.4000.2000
81233.2447.7002.8006.7002
91103.2247.2003.6006.1002.500
10153.1215.80041.2000.2000
11582.9234.9002.4003.3001
12942.89252.3003.3001
13332.8825.2004.1001.5000.1000
141072.7154.9002.5004.5001.700
151362.6927.70036.1002.300
1692.6564.4002.9001.4000.2000
17142.6384.30031.1000.1000
18992.6345.1002.50031.100
19632.59162.20041
201062.5817.60036.6002.100

Latent dimensions

DimensionMean KL (nats)Variance of μActive
10.32520.7428yes
20.09850.6258yes

Mixture prior components

ComponentRowsPrior weightMean 1Mean 2
11000.4957−0.5351−0.5602
2500.33731.1761.058
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Variational autoencoder (latent map, anomalies and generated rows)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.vae 1.2.0 · spec a366cea2bf985d25
# 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 generative as gen  # twin of codesplashr::cs_deep_fit_vae (shared initial weights, Adam written out)
from codesplash.deep import unsupervised as du  # VaDE prior and the importance-weighted bound (twin of codesplashr::cs_deep_fit_vade)
from codesplash.ml import anomaly as csanom
from codesplash.ml import embed as csembed
from codesplash.synth import common as sy

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE = "median"
SCALE = "standard"
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=["sepal_length", "sepal_width", "petal_length", "petal_width"]), ["sepal_length", "sepal_width", "petal_length", "petal_width"])
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.vae/iris_vade/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]

# %% Variational autoencoder (PyTorch, float64, one thread): encoder → (μ, log σ²) → z = μ + σ·ε → decoder
HIDDEN = [int(u) for u in [8]]
LATENT = 2
BETA = 1
N_SAMPLES = 150
PRIOR = "mixture"  # N(0, I), or a learned Gaussian mixture (VaDE)
IWAE = 0
if PRIOR == "mixture" and len(rows) <= 3:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="A 3-component mixture prior", min=3 + 1, n=len(rows))
if PRIOR == "mixture":
    fit = du.fit_vade(
        X, HIDDEN, LATENT, 3,
        activation="tanh",
        beta=BETA,
        epochs=200,
        lr=0.01,
        batch_size=None,
        weight_decay=0,
        n_samples=N_SAMPLES,
        pretrain_epochs=100,
        seed=42,
    )
else:
    fit = gen.fit_vae(
        X, HIDDEN, LATENT,
        activation="tanh",
        beta=BETA,
        epochs=200,
        lr=0.01,
        batch_size=None,
        weight_decay=0,
        n_samples=N_SAMPLES,
        seed=42,
    )
if not np.all(np.isfinite(fit["score"])):
    cs.cs_error("CS_E_NO_CONVERGENCE", what="Variational autoencoder training")
Z = fit["embedding"]  # posterior means μ (n × LATENT)
scores = fit["score"]  # squared reconstruction error at z = μ plus β × KL, per row
errors = fit["error"]  # mean squared reconstruction error per standardized column

# %% Anomalies by the per-row loss
RULE = "share"
flags, threshold = csanom.flag(scores, RULE, 0.05, 10)
order = np.lexsort((rows, -scores))  # largest loss 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) if k_eval >= 1 else float("nan")  # undefined with fewer than 3 rows

# %% Mixture prior: each row's component at z = μ (canonical ids 1…k by size)
clusters = None
if PRIOR == "mixture":
    from codesplash.ml import cluster as csc

    clusters = csc.canonical(fit["cluster"])
    comp_of = {}
    for j in range(len(fit["pi"])):
        members = np.flatnonzero(fit["cluster"] == j)
        if len(members):
            comp_of[j] = int(clusters[members[0]])

# %% Importance-weighted bound on log p(x) (and the ELBO from the same draws)
bound = du.iwae_bound(X, fit, LATENT, "tanh", IWAE, 42) if IWAE > 0 else None

# %% Generated rows: decode prior draws back to the columns' units
gen_cols = gen.decode_design(fitted, fit["samples"]) if N_SAMPLES > 0 else {}
NUMERIC = [f for f in FEATURES if design.kinds[f] == "numeric"]
sample_ks = {}
for f in NUMERIC if N_SAMPLES > 0 else []:
    real = pd.to_numeric(df[f], errors="coerce").to_numpy(dtype=np.float64)
    sample_ks[f] = gen.ks_distance(real, gen_cols[f])

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.vae/iris_vade/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": scores, "anomaly": flags, **({"cluster": clusters} if clusters is not None else {})}).to_parquet(
    os.path.join(out, "labels.parquet"), index=False
)
history = pd.DataFrame({
    "epoch": [h["epoch"] for h in fit["history"]],
    "loss": [h["loss"] for h in fit["history"]],
    "reconstruction": [h["recon"] for h in fit["history"]],
    "kl": [h["kl"] for h in fit["history"]],
})
history.to_parquet(os.path.join(out, "history.parquet"), index=False)
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 N_SAMPLES > 0:
    pd.DataFrame({f: gen_cols[f] for f in FEATURES}).to_parquet(os.path.join(out, "samples.parquet"), index=False)
    artifacts.append({"key": "samples", "path": os.path.join(out, "samples.parquet"), "format": "parquet", "title": "Rows generated from the prior"})

# %% Result
active = int(fit["active"])
values = {
    "n": len(rows),
    "n_features": int(X.shape[1]),
    "latent_dim": LATENT,
    "recon_mse": float(np.mean(errors)),
    "kl": float(np.mean(fit["kl_row"])),
    "elbo_loss": float(np.mean(scores)),
    "active_dims": active,
    "error_check": csembed.checksum(scores, rows),
    "n_flagged": int(flags.sum()),
    "threshold": float(threshold),
    "final_loss": float(fit["history"][-1]["loss"]),
    "epochs_run": int(fit["epochs_run"]),
    "trustworthiness": trust,
    "n_samples": N_SAMPLES,
    "sample_ks_mean": float(np.mean(list(sample_ks.values()))) if sample_ks else float("nan"),
}
for j in range(LATENT):
    values[f"emb_check[{j + 1}]"] = csembed.checksum(Z[:, j], rows)
    values[f"kl_dim[{j + 1}]"] = float(fit["kl_dim"][j])
for f, v in sample_ks.items():
    values[f"sample_ks[{f}]"] = v
if clusters is not None:
    values["components"] = int(len(fit["pi"]))
    values["n_clusters"] = len(comp_of)
    for j, c in comp_of.items():
        values[f"pi[{c}]"] = float(fit["pi"][j])
        values[f"cluster_size[{c}]"] = int(np.sum(clusters == c))
if bound is not None:
    values["iwae_samples"] = IWAE
    values["iwae_bound"] = float(np.mean(bound["iwae"]))
    values["elbo_estimate"] = float(np.mean(bound["elbo"]))
    values["iwae_gap"] = values["iwae_bound"] - values["elbo_estimate"]
for rank, i in enumerate(order[:10], start=1):
    values[f"top_row[{rank}]"] = int(rows[i])
    values[f"top_score[{rank}]"] = float(scores[i])
table_rows = []
for rank, i in enumerate(order[:20], start=1):
    r = {"rank": rank, "row": int(rows[i]) + 1, "score": float(scores[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)
dim_rows = [{"dim": j + 1, "kl": float(fit["kl_dim"][j]), "var_mu": float(fit["mu_var"][j]), "active": bool(fit["mu_var"][j] > 0.01)} for j in range(LATENT)]
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 and clusters is not None:
    _cent = sorted(comp_of, key=lambda j: comp_of[j])
    charts.append(cs.chart("latent", "cluster-scatter", "Latent means by mixture component (component means marked)", {
        "x": cs.col("Latent 1 (μ)", list(Z[pick, 0]) + [float(fit["mu_c"][j, 0]) for j in _cent], "numeric"),
        "y": cs.col("Latent 2 (μ)", list(Z[pick, 1]) + [float(fit["mu_c"][j, 1]) for j in _cent], "numeric"),
        "cluster": cs.col("Component", [str(c) for c in clusters[pick]] + [str(comp_of[j]) for j in _cent], "categorical",
                          levels=[str(c) for c in sorted(comp_of.values())]),
        "centroid": cs.col("Component mean", [False] * len(pick) + [True] * len(_cent), "boolean"),
    }, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown."))
elif LATENT >= 2:
    charts.append(cs.chart("latent", "latent-prior", "Latent means against the N(0, I) prior", {
        "x": cs.col("Latent 1 (μ)", Z[pick, 0], "numeric"),
        "y": cs.col("Latent 2 (μ)", Z[pick, 1], "numeric"),
        "group": 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", "Per-row loss (reconstruction + β·KL) distribution", {
    "score": cs.col("Per-row loss", scores, "numeric"),
    "anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold)}))
ep = [h["epoch"] for h in fit["history"]]
charts.append(cs.chart("training", "training-components", "Training loss and its parts by epoch", {
    "x": cs.col("Epoch", ep * 3, "numeric"),
    "value": cs.col("Loss per row", [h["loss"] for h in fit["history"]] + [h["recon"] for h in fit["history"]] + [h["kl"] for h in fit["history"]], "numeric"),
    "component": cs.col("Part", ["total"] * len(ep) + ["reconstruction"] * len(ep) + ["KL"] * len(ep), "categorical", levels=["total", "reconstruction", "KL"]),
}))
if sample_ks:
    f0 = NUMERIC[0]
    xs, dens, src = sy.density_rows(pd.to_numeric(df[f0], errors="coerce").to_numpy(dtype=np.float64), np.asarray(gen_cols[f0], dtype=np.float64))
    if xs:
        charts.append(cs.chart("samples", "density-compare", f"{f0}: data vs rows generated from the prior", {
            "x": cs.col(f0, xs, "numeric"),
            "density": cs.col("Density", dens, "numeric"),
            "source": cs.col("Source", src, "categorical", levels=["real", "synthetic"]),
        }))
assumptions = [{
    "key": "active_units",
    "label": "Latent dimensions in use",
    "status": "pass" if active == LATENT else ("fail" if active == 0 else "warn"),
    "detail": f"{active} of {LATENT} latent dimension{'s' if LATENT != 1 else ''} vary across rows (variance of μ > 0.01)"
              + ("." if active == LATENT else "; the rest collapsed onto the prior and carry no information about the rows."),
}]
if active < LATENT:
    warnings.append(f"Posterior collapse: {LATENT - active} latent dimension{'s' if LATENT - active != 1 else ''} carry no information (KL ≈ 0). Lower β, shrink the bottleneck, or train longer.")
summary = (
    f"A variational autoencoder mapped {len(rows)} rows into {LATENT} latent coordinate{'s' if LATENT != 1 else ''} "
    f"({active} in use); the mean squared reconstruction error is {np.mean(errors):.3g} per standardized column and the mean KL is "
    f"{np.mean(fit['kl_row']):.3g} nats; {int(flags.sum())} rows with a loss of at least {threshold:.3g} are flagged as anomalies."
)
if sample_ks:
    summary += f" {N_SAMPLES} rows generated from the prior differ from the data by a mean KS distance of {values['sample_ks_mean']:.3f}."
if clusters is not None:
    summary += f" The mixture prior's {len(fit['pi'])} components hold {len(comp_of)} cluster{'s' if len(comp_of) != 1 else ''} of rows."
if bound is not None:
    summary += f" The importance-weighted bound with {IWAE} draws is {values['iwae_bound']:.4g} nats per row ({values['iwae_gap']:.3g} above the ELBO estimate)."
extra_stats = []
if bound is not None:
    extra_stats.append({"key": "iwae_bound", "label": f"Log-likelihood bound (IWAE, {IWAE} draws)", "value": values["iwae_bound"]})
extra_tables = []
if clusters is not None:
    extra_tables.append({
        "key": "components",
        "title": "Mixture prior components",
        "columns": [{"key": "cluster", "label": "Component", "type": "integer"}, {"key": "size", "label": "Rows", "type": "integer"},
                    {"key": "weight", "label": "Prior weight", "type": "number"}]
                   + [{"key": f"mu_{d + 1}", "label": f"Mean {d + 1}", "type": "number"} for d in range(LATENT)],
        "rows": [{"cluster": comp_of[j], "size": int(np.sum(clusters == comp_of[j])), "weight": float(fit["pi"][j]),
                  **{f"mu_{d + 1}": float(fit["mu_c"][j, d]) for d in range(LATENT)}} for j in sorted(comp_of, key=lambda j: comp_of[j])],
    })
cs.publish({
    "title": "Variational autoencoder (latent map, anomalies and generated rows)",
    "engine": cs.engine_info("torch", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "recon_mse", "label": "Mean reconstruction error", "value": float(np.mean(errors))},
        {"key": "kl", "label": "Mean KL (nats per row)", "value": float(np.mean(fit["kl_row"]))},
        {"key": "active_dims", "label": "Active latent dimensions", "value": active, "format": "integer"},
        {"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": trust},
        {"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
    ] + extra_stats,
    "tables": [
        {
            "key": "top",
            "title": "Rows the model finds least typical",
            "columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
                        {"key": "score", "label": "Per-row loss", "type": "number"}] + [{"key": f, "label": f} for f in FEATURES],
            "rows": table_rows,
        },
        {
            "key": "latent",
            "title": "Latent dimensions",
            "columns": [{"key": "dim", "label": "Dimension", "type": "integer"}, {"key": "kl", "label": "Mean KL (nats)", "type": "number"},
                        {"key": "var_mu", "label": "Variance of μ", "type": "number"}, {"key": "active", "label": "Active", "type": "boolean"}],
            "rows": dim_rows,
        },
    ] + extra_tables,
    "charts": charts,
    "assumptions": assumptions,
    "values": values,
    "warnings": warnings,
    "artifacts": artifacts,
})

With three components on iris, the mixture prior holds 2 clusters of rows.

06

How tight is the ELBO?

Reflect

A VAE's loss is a bound on the log-likelihood, not the log-likelihood itself. The importance-weighted boundImportance-weighted boundA tighter lower bound on a row's log-likelihood than the ELBO, from averaging importance weights over several latent draws. averages over several latent draws per row and is never looser. On the diabetes data with 50 draws it is −9.442 nats per row, 0.066 above the ELBO estimate from the same draws. A large gap means the encoder's distributions fit the true posterior poorly.

07

Check your understanding

Checkpoint

Check yourself

Where does DEC's training target come from?

Show the answer

Answer: b

DEC is self-training: the target sharpens the current memberships, so confident rows pull the space tighter.

Check yourself

When does fine-tuning stop before the epoch limit?

Show the answer

Answer: a

The run reports whether it stopped early and the last share of rows that changed cluster.

Check yourself

Why might you prefer IDEC to DEC?

Show the answer

Answer: b

Both pretrain an autoencoder. IDEC keeps its decoder during fine-tuning and weights the cluster loss by γ.

Check yourself

The importance-weighted bound sits well above the ELBO estimate. What does that tell you?

Show the answer

Answer: b

The bound tightens as draws increase; the gap measures how much the single-draw ELBO undersells the model's likelihood.

08

Recap

Recap
  • DEC and IDEC start from k-means on an autoencoder's codes, then train toward a sharpened version of their own memberships.
  • IDEC keeps the reconstruction term, which stops the learned space from distorting freely.
  • VaDE gives a VAE a mixture prior, so one model maps, generates and clusters rows.
  • The importance-weighted bound shows how loose the ELBO is; deep clusters still need a stability check.
09

Do it on your own data

In the app

Under Find segments, open the Deep learning group and run Deep embedded clustering with IDEC. Then run a Gaussian mixture with the same k and compare the profiles.

Concepts in this lesson