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.
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
Cluster in a space you learn
Readk-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.
How DEC trains
Read- Train an autoencoder and take its codes.
- Run k-means on the codes to place k centers.
- 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.
- 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.
- 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.
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
View data
| Cluster | PC1 (73%) | PC2 (23%) |
|---|---|---|
| 1 | −2.265 | 0.4800 |
| 1 | −2.081 | −0.6741 |
| 1 | −2.364 | −0.3419 |
| 1 | −2.299 | −0.5974 |
| 1 | −2.390 | 0.6468 |
| 1 | −2.076 | 1.489 |
| 1 | −2.444 | 0.0476 |
| 1 | −2.233 | 0.2231 |
| 1 | −2.335 | −1.115 |
| 1 | −2.184 | −0.4690 |
| 1 | −2.166 | 1.044 |
| 1 | −2.326 | 0.1331 |
| 1 | −2.218 | −0.7287 |
| 1 | −2.633 | −0.9615 |
| 1 | −2.199 | 1.860 |
| 1 | −2.262 | 2.686 |
| 1 | −2.208 | 1.484 |
| 1 | −2.190 | 0.4888 |
| 1 | −1.899 | 1.405 |
| 1 | −2.343 | 1.128 |
| 1 | −1.914 | 0.4089 |
| 1 | −2.207 | 0.9241 |
| 1 | −2.774 | 0.4583 |
| 1 | −1.819 | 0.0856 |
| 1 | −2.227 | 0.1373 |
| 1 | −1.952 | −0.6256 |
| 1 | −2.051 | 0.2422 |
| 1 | −2.169 | 0.5271 |
| 1 | −2.140 | 0.3132 |
| 1 | −2.265 | −0.3377 |
| 1 | −2.140 | −0.5045 |
| 1 | −1.832 | 0.4237 |
| 1 | −2.615 | 1.794 |
| 1 | −2.446 | 2.151 |
| 1 | −2.110 | −0.4602 |
| 1 | −2.208 | −0.2061 |
| 1 | −2.045 | 0.6616 |
| 1 | −2.527 | 0.5923 |
| 1 | −2.430 | −0.9042 |
| 1 | −2.170 | 0.2689 |
| 1 | −2.286 | 0.4417 |
| 1 | −1.858 | −2.337 |
| 1 | −2.554 | −0.4791 |
| 1 | −1.964 | 0.4723 |
| 1 | −2.137 | 1.142 |
| 1 | −2.070 | −0.7111 |
| 1 | −2.385 | 1.120 |
| 1 | −2.394 | −0.3862 |
| 1 | −2.229 | 0.9980 |
| 1 | −2.204 | 0.0092 |
| 2 | 1.102 | 0.8630 |
| 2 | 0.7313 | 0.5946 |
| 2 | 1.241 | 0.6163 |
| 3 | 0.4075 | −1.754 |
| 2 | 1.075 | −0.2084 |
| 3 | 0.3887 | −0.5933 |
| 2 | 0.7465 | 0.7730 |
| 1 | −0.4873 | −1.852 |
| 2 | 0.9279 | 0.0322 |
| 3 | 0.0114 | −1.034 |
First 60 of 150 rows.
View data
| Center | Cluster | Code 1 | Code 2 |
|---|---|---|---|
| false | 1 | −0.0263 | 0.9294 |
| false | 1 | 0.7166 | 0.8719 |
| false | 1 | 0.5485 | 1.002 |
| false | 1 | 0.7362 | 0.9276 |
| false | 1 | −0.0838 | 0.9420 |
| false | 1 | −0.6700 | 0.9079 |
| false | 1 | 0.3364 | 0.9566 |
| false | 1 | 0.1321 | 0.9268 |
| false | 1 | 1.152 | 0.8101 |
| false | 1 | 0.5588 | 0.9830 |
| false | 1 | −0.4102 | 0.9176 |
| false | 1 | 0.2331 | 0.9369 |
| false | 1 | 0.8230 | 0.8983 |
| false | 1 | 1.161 | 0.9618 |
| false | 1 | −0.8624 | 1.083 |
| false | 1 | −1.311 | 1.107 |
| false | 1 | −0.6272 | 0.9733 |
| false | 1 | −0.0567 | 0.8886 |
| false | 1 | −0.7006 | 0.8951 |
| false | 1 | −0.3797 | 0.9304 |
| false | 1 | −0.1134 | 0.8395 |
| false | 1 | −0.3091 | 0.8633 |
| false | 1 | 0.1835 | 1.063 |
| false | 1 | 0.0768 | 0.7584 |
| false | 1 | 0.2004 | 0.8866 |
| false | 1 | 0.6379 | 0.8262 |
| false | 1 | 0.0606 | 0.8286 |
| false | 1 | −0.0932 | 0.8991 |
| false | 1 | 0.0311 | 0.9167 |
| false | 1 | 0.5159 | 0.9519 |
| false | 1 | 0.5905 | 0.9157 |
| false | 1 | −0.1523 | 0.7915 |
| false | 1 | −0.6655 | 1.104 |
| false | 1 | −0.9237 | 1.130 |
| false | 1 | 0.5283 | 0.9426 |
| false | 1 | 0.3916 | 0.9787 |
| false | 1 | −0.2392 | 0.8923 |
| false | 1 | 0.0025 | 0.9962 |
| false | 1 | 1.047 | 0.8824 |
| false | 1 | 0.0762 | 0.9134 |
| false | 1 | 0.0102 | 0.9189 |
| false | 1 | 1.767 | 0.4897 |
| false | 1 | 0.7164 | 1.043 |
| false | 1 | −0.1135 | 0.7463 |
| false | 1 | −0.4468 | 0.8372 |
| false | 1 | 0.7520 | 0.8310 |
| false | 1 | −0.3660 | 0.9419 |
| false | 1 | 0.5936 | 0.9989 |
| false | 1 | −0.3603 | 0.9180 |
| false | 1 | 0.2564 | 0.9443 |
| false | 2 | −2.658 | −0.9546 |
| false | 2 | −1.905 | −0.6354 |
| false | 2 | −2.556 | −1.041 |
| false | 3 | 0.0456 | −0.7241 |
| false | 2 | −1.741 | −1.132 |
| false | 3 | −0.5398 | −0.4468 |
| false | 2 | −1.909 | −0.5864 |
| false | 1 | 0.9314 | −0.1152 |
| false | 2 | −1.850 | −0.9166 |
| false | 3 | 0.0142 | −0.2851 |
First 60 of 153 rows.
View data
| Part | Loss per row | Epoch |
|---|---|---|
| total | 0.0990 | 1 |
| total | 0.0971 | 2 |
| total | 0.0951 | 3 |
| total | 0.0935 | 4 |
| total | 0.0915 | 5 |
| total | 0.0911 | 6 |
| total | 0.0896 | 7 |
| total | 0.0879 | 8 |
| total | 0.0864 | 9 |
| total | 0.0849 | 10 |
| total | 0.0843 | 11 |
| total | 0.0828 | 12 |
| total | 0.0814 | 13 |
| total | 0.0801 | 14 |
| total | 0.0789 | 15 |
| total | 0.0784 | 16 |
| total | 0.0771 | 17 |
| total | 0.0760 | 18 |
| total | 0.0749 | 19 |
| total | 0.0738 | 20 |
| total | 0.0734 | 21 |
| total | 0.0724 | 22 |
| total | 0.0714 | 23 |
| total | 0.0704 | 24 |
| total | 0.0695 | 25 |
| total | 0.0692 | 26 |
| total | 0.0684 | 27 |
| total | 0.0676 | 28 |
| total | 0.0668 | 29 |
| total | 0.0661 | 30 |
| KL | 0.0961 | 1 |
| KL | 0.0935 | 2 |
| KL | 0.0922 | 3 |
| KL | 0.0907 | 4 |
| KL | 0.0892 | 5 |
| KL | 0.0988 | 6 |
| KL | 0.0976 | 7 |
| KL | 0.0966 | 8 |
| KL | 0.0955 | 9 |
| KL | 0.0944 | 10 |
| KL | 0.1002 | 11 |
| KL | 0.0987 | 12 |
| KL | 0.0973 | 13 |
| KL | 0.0962 | 14 |
| KL | 0.0953 | 15 |
| KL | 0.1016 | 16 |
| KL | 0.1004 | 17 |
| KL | 0.0993 | 18 |
| KL | 0.0981 | 19 |
| KL | 0.0969 | 20 |
| KL | 0.1026 | 21 |
| KL | 0.1012 | 22 |
| KL | 0.0999 | 23 |
| KL | 0.0989 | 24 |
| KL | 0.0979 | 25 |
| KL | 0.1034 | 26 |
| KL | 0.1020 | 27 |
| KL | 0.1005 | 28 |
| KL | 0.0991 | 29 |
| KL | 0.0979 | 30 |
First 60 of 90 rows.
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.6727 |
| 1 | 0.6726 |
| 1 | 0.6722 |
| 1 | 0.6668 |
| 1 | 0.6666 |
| 1 | 0.6654 |
| 1 | 0.6654 |
| 1 | 0.6643 |
| 1 | 0.6593 |
| 1 | 0.6563 |
| 1 | 0.6551 |
| 1 | 0.6455 |
| 1 | 0.6453 |
| 1 | 0.6448 |
| 1 | 0.6412 |
| 1 | 0.6314 |
| 1 | 0.6275 |
| 1 | 0.6260 |
| 1 | 0.6249 |
| 1 | 0.6214 |
| 1 | 0.6212 |
| 1 | 0.6155 |
| 1 | 0.6138 |
| 1 | 0.6099 |
| 1 | 0.6043 |
| 1 | 0.6025 |
| 1 | 0.6001 |
| 1 | 0.5960 |
| 1 | 0.5896 |
| 1 | 0.5871 |
| 1 | 0.5864 |
| 1 | 0.5845 |
| 1 | 0.5837 |
| 1 | 0.5818 |
| 1 | 0.5814 |
| 1 | 0.5576 |
| 1 | 0.5451 |
| 1 | 0.5450 |
| 1 | 0.5345 |
| 1 | 0.5301 |
| 1 | 0.5270 |
| 1 | 0.5240 |
| 1 | 0.5216 |
| 1 | 0.5212 |
| 1 | 0.5109 |
| 1 | 0.4926 |
| 1 | 0.4819 |
| 1 | 0.4681 |
| 1 | 0.4016 |
| 1 | 0.1161 |
| 1 | −0.3795 |
| 1 | −0.3909 |
| 1 | −0.4055 |
| 1 | −0.4138 |
| 2 | 0.5106 |
| 2 | 0.5104 |
| 2 | 0.5028 |
| 2 | 0.5025 |
| 2 | 0.4868 |
| 2 | 0.4845 |
First 60 of 150 rows.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 54 | 36.0% | 5.006 | 3.344 | 1.596 | 0.3037 |
| 2 | 53 | 35.3% | 6.740 | 3.040 | 5.436 | 1.940 |
| 3 | 43 | 28.7% | 5.791 | 2.719 | 4.405 | 1.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"
))
))
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
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 54 | 36.0% | 5.006 | 3.344 | 1.596 | 0.3037 |
| 2 | 53 | 35.3% | 6.740 | 3.040 | 5.436 | 1.940 |
| 3 | 43 | 28.7% | 5.791 | 2.719 | 4.405 | 1.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.
DEC or IDEC?
PredictPredict 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?
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.
Two views of the clusters
ReadView data
| PC1 | PC2 | cluster | center |
|---|---|---|---|
| −1.546 | −0.3320 | 1 | false |
| −1.871 | 1.219 | 1 | false |
| −2.516 | 1.228 | 1 | false |
| −1.458 | −0.1650 | 1 | false |
| −3.108 | 0.5260 | 1 | false |
| −1.344 | 1.399 | 1 | false |
| −2.798 | 0.1450 | 1 | false |
| −1.124 | 0.5940 | 1 | false |
| −2.119 | 0.6010 | 1 | false |
| −1.774 | 0.9920 | 1 | false |
| −1.351 | 0.5120 | 1 | false |
| −1.535 | 0.0590 | 1 | false |
| −2.182 | 0.2500 | 1 | false |
| −2.684 | 0.4120 | 1 | false |
| −2.391 | 0.2240 | 1 | false |
| −2.567 | −0.0710 | 1 | false |
| −1.293 | 0.7540 | 1 | false |
| −2.457 | 0.4500 | 1 | false |
| −2.475 | −0.3890 | 1 | false |
| −0.7180 | −0.2510 | 1 | false |
| −3.469 | 0.4720 | 1 | false |
| −2.193 | 0.5530 | 1 | false |
| −2.073 | 0.0680 | 1 | false |
| −1.655 | 0.1850 | 1 | false |
| −2.231 | 0.6930 | 1 | false |
| −1.184 | 0.6770 | 1 | false |
| −3.550 | 0.3100 | 1 | false |
| −1.505 | 0.2710 | 1 | false |
| −2.043 | 1.751 | 1 | false |
| −1.720 | 0.9880 | 1 | false |
| −2.323 | 0.2370 | 1 | false |
| −1.497 | −0.0440 | 1 | false |
| −1.953 | −0.9400 | 1 | false |
| −2.852 | −0.3300 | 1 | false |
| −1.824 | 0.2240 | 1 | false |
| −2.386 | 0.6760 | 1 | false |
| −2.285 | −0.2720 | 1 | false |
| −1.164 | 0.5780 | 1 | false |
| −1.820 | −0.1640 | 1 | false |
| −2.390 | 0.6380 | 1 | false |
| −1.951 | 1.042 | 1 | false |
| −2.258 | 0.5250 | 1 | false |
| −1.135 | −0.3350 | 1 | false |
| −2.514 | 0.5200 | 1 | false |
| −1.569 | 0.6410 | 1 | false |
| −2.976 | 0.3750 | 1 | false |
| −2.712 | 1.250 | 1 | false |
| −2.391 | 0.7890 | 1 | false |
| −1.374 | 0.3970 | 1 | false |
| −2.527 | −0.4530 | 1 | false |
| −2.517 | 0.5000 | 1 | false |
| −2.673 | −0.1510 | 1 | false |
| −1.955 | 0.7550 | 1 | false |
| −1.368 | 0.1270 | 1 | false |
| −1.325 | 0.7360 | 1 | false |
| −1.157 | 0.6040 | 1 | false |
| −3.062 | 1.049 | 1 | false |
| −1.413 | −0.4460 | 1 | false |
| −1.744 | 0.5850 | 1 | false |
| −0.6700 | −0.4120 | 1 | false |
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.
A VAE that clusters: VaDE
ReadA 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.
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
View data
| Component mean | Component | Latent 1 (μ) | Latent 2 (μ) |
|---|---|---|---|
| false | 2 | 1.209 | 1.167 |
| false | 2 | 1.255 | 0.8371 |
| false | 2 | 1.298 | 0.9618 |
| false | 2 | 1.296 | 0.8686 |
| false | 2 | 1.210 | 1.208 |
| false | 2 | 1.085 | 1.355 |
| false | 2 | 1.267 | 1.047 |
| false | 2 | 1.220 | 1.090 |
| false | 2 | 1.347 | 0.7337 |
| false | 2 | 1.262 | 0.9096 |
| false | 2 | 1.146 | 1.289 |
| false | 2 | 1.233 | 1.057 |
| false | 2 | 1.292 | 0.8480 |
| false | 2 | 1.402 | 0.8266 |
| false | 2 | 1.101 | 1.483 |
| false | 2 | 1.018 | 1.590 |
| false | 2 | 1.126 | 1.395 |
| false | 2 | 1.198 | 1.159 |
| false | 2 | 1.069 | 1.334 |
| false | 2 | 1.156 | 1.304 |
| false | 2 | 1.135 | 1.100 |
| false | 2 | 1.158 | 1.250 |
| false | 2 | 1.282 | 1.197 |
| false | 2 | 1.128 | 0.9619 |
| false | 2 | 1.198 | 1.024 |
| false | 2 | 1.204 | 0.8165 |
| false | 2 | 1.181 | 1.057 |
| false | 2 | 1.186 | 1.166 |
| false | 2 | 1.203 | 1.120 |
| false | 2 | 1.263 | 0.9292 |
| false | 2 | 1.250 | 0.8752 |
| false | 2 | 1.125 | 1.092 |
| false | 2 | 1.120 | 1.448 |
| false | 2 | 1.087 | 1.519 |
| false | 2 | 1.246 | 0.8946 |
| false | 2 | 1.264 | 1.003 |
| false | 2 | 1.164 | 1.213 |
| false | 2 | 1.227 | 1.200 |
| false | 2 | 1.355 | 0.8076 |
| false | 2 | 1.206 | 1.099 |
| false | 2 | 1.221 | 1.160 |
| false | 2 | 1.162 | 0.1799 |
| false | 2 | 1.335 | 0.9257 |
| false | 2 | 1.145 | 1.092 |
| false | 2 | 1.101 | 1.259 |
| false | 2 | 1.256 | 0.8101 |
| false | 2 | 1.154 | 1.297 |
| false | 2 | 1.300 | 0.9399 |
| false | 2 | 1.157 | 1.280 |
| false | 2 | 1.237 | 1.042 |
| false | 1 | −0.6808 | −0.3430 |
| false | 1 | −0.5544 | −0.3459 |
| false | 1 | −0.6960 | −0.4233 |
| false | 1 | −0.1850 | −0.7979 |
| false | 1 | −0.5467 | −0.5576 |
| false | 1 | −0.3479 | −0.5572 |
| false | 1 | −0.5927 | −0.3249 |
| false | 1 | 0.1240 | −0.6021 |
| false | 1 | −0.5526 | −0.4878 |
| false | 1 | −0.1628 | −0.5936 |
First 60 of 152 rows.
View data
| Anomaly | Per-row loss |
|---|---|
| false | 1.195 |
| false | 1.935 |
| false | 1.521 |
| false | 1.780 |
| false | 1.249 |
| false | 2.179 |
| false | 1.369 |
| false | 1.178 |
| false | 2.656 |
| false | 1.678 |
| false | 1.598 |
| false | 1.214 |
| false | 2.005 |
| false | 2.638 |
| false | 3.121 |
| true | 5.327 |
| false | 2.163 |
| false | 1.194 |
| false | 2.282 |
| false | 1.636 |
| false | 1.469 |
| false | 1.443 |
| false | 1.576 |
| false | 1.436 |
| false | 1.261 |
| false | 1.945 |
| false | 1.216 |
| false | 1.236 |
| false | 1.256 |
| false | 1.484 |
| false | 1.651 |
| false | 1.493 |
| false | 2.882 |
| true | 3.634 |
| false | 1.634 |
| false | 1.462 |
| false | 1.554 |
| false | 1.298 |
| false | 2.342 |
| false | 1.201 |
| false | 1.189 |
| true | 5.689 |
| false | 1.851 |
| false | 1.396 |
| false | 1.748 |
| false | 1.935 |
| false | 1.638 |
| false | 1.582 |
| false | 1.506 |
| false | 1.267 |
| false | 1.758 |
| false | 1.285 |
| false | 1.243 |
| false | 1.979 |
| false | 0.8198 |
| false | 1.066 |
| false | 1.483 |
| false | 2.923 |
| false | 1.095 |
| false | 1.755 |
First 60 of 150 rows.
View data
| Part | Loss per row | Epoch |
|---|---|---|
| total | 5.013 | 1 |
| total | 5.402 | 2 |
| total | 4.861 | 3 |
| total | 4.511 | 4 |
| total | 4.397 | 5 |
| total | 4.070 | 6 |
| total | 4.020 | 7 |
| total | 3.615 | 8 |
| total | 3.467 | 9 |
| total | 3.248 | 10 |
| total | 3.106 | 11 |
| total | 3.234 | 12 |
| total | 3.258 | 13 |
| total | 2.772 | 14 |
| total | 3.227 | 15 |
| total | 2.832 | 16 |
| total | 2.637 | 17 |
| total | 2.430 | 18 |
| total | 2.747 | 19 |
| total | 2.590 | 20 |
| total | 2.379 | 21 |
| total | 2.442 | 22 |
| total | 2.496 | 23 |
| total | 2.364 | 24 |
| total | 2.358 | 25 |
| total | 2.262 | 26 |
| total | 2.246 | 27 |
| total | 2.317 | 28 |
| total | 2.330 | 29 |
| total | 2.227 | 30 |
| total | 2.258 | 31 |
| total | 2.167 | 32 |
| total | 2.302 | 33 |
| total | 2.153 | 34 |
| total | 2.155 | 35 |
| total | 2.140 | 36 |
| total | 2.255 | 37 |
| total | 2.154 | 38 |
| total | 2.161 | 39 |
| total | 2.084 | 40 |
| total | 2.214 | 41 |
| total | 2.136 | 42 |
| total | 2.095 | 43 |
| total | 2.129 | 44 |
| total | 2.209 | 45 |
| total | 2.147 | 46 |
| total | 2.051 | 47 |
| total | 2.069 | 48 |
| total | 2.164 | 49 |
| total | 2.138 | 50 |
| total | 2.233 | 51 |
| total | 2.227 | 52 |
| total | 2.194 | 53 |
| total | 2.042 | 54 |
| total | 2.147 | 55 |
| total | 2.238 | 56 |
| total | 2.099 | 57 |
| total | 2.098 | 58 |
| total | 2.002 | 59 |
| total | 2.250 | 60 |
First 60 of 600 rows.
View data
| Density | Source | sepal_length |
|---|---|---|
| 0.2222 | real | 4.360 |
| 0.0556 | real | 4.480 |
| 0.2222 | real | 4.600 |
| 0.1111 | real | 4.720 |
| 0.2778 | real | 4.840 |
| 0.8889 | real | 4.960 |
| 0.5000 | real | 5.080 |
| 0.2222 | real | 5.200 |
| 0.0556 | real | 5.320 |
| 0.3333 | real | 5.440 |
| 0.7222 | real | 5.560 |
| 0.4444 | real | 5.680 |
| 0.3889 | real | 5.800 |
| 0.1667 | real | 5.920 |
| 0.6667 | real | 6.040 |
| 0.2222 | real | 6.160 |
| 0.5000 | real | 6.280 |
| 0.3889 | real | 6.400 |
| 0.2778 | real | 6.520 |
| 0.1111 | real | 6.640 |
| 0.6111 | real | 6.760 |
| 0.2222 | real | 6.880 |
| 0.0556 | real | 7 |
| 0.0556 | real | 7.120 |
| 0.2222 | real | 7.240 |
| 0.0556 | real | 7.360 |
| 0 | real | 7.480 |
| 0.0556 | real | 7.600 |
| 0.2222 | real | 7.720 |
| 0.0556 | real | 7.840 |
| 0 | synthetic | 4.360 |
| 0 | synthetic | 4.480 |
| 0.2222 | synthetic | 4.600 |
| 0.3333 | synthetic | 4.720 |
| 0.3889 | synthetic | 4.840 |
| 0.9444 | synthetic | 4.960 |
| 0.6111 | synthetic | 5.080 |
| 0.3889 | synthetic | 5.200 |
| 0.1111 | synthetic | 5.320 |
| 0.0556 | synthetic | 5.440 |
| 0.1111 | synthetic | 5.560 |
| 0.1667 | synthetic | 5.680 |
| 0.6111 | synthetic | 5.800 |
| 0.3889 | synthetic | 5.920 |
| 0.4444 | synthetic | 6.040 |
| 0.6667 | synthetic | 6.160 |
| 0.5556 | synthetic | 6.280 |
| 0.4444 | synthetic | 6.400 |
| 0.3889 | synthetic | 6.520 |
| 0.5000 | synthetic | 6.640 |
| 0.5556 | synthetic | 6.760 |
| 0.2778 | synthetic | 6.880 |
| 0.1667 | synthetic | 7 |
| 0 | synthetic | 7.120 |
| 0 | synthetic | 7.240 |
| 0 | synthetic | 7.360 |
| 0 | synthetic | 7.480 |
| 0 | synthetic | 7.600 |
| 0 | synthetic | 7.720 |
| 0 | synthetic | 7.840 |
Assumptions
- Latent dimensions in use — 2 of 2 latent dimensions vary across rows (variance of μ > 0.01).
Rows the model finds least typical
| Rank | Row | Per-row loss | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 42 | 5.689 | 4.500 | 2.300 | 1.300 | 0.3000 |
| 2 | 132 | 5.426 | 7.900 | 3.800 | 6.400 | 2 |
| 3 | 16 | 5.327 | 5.700 | 4.400 | 1.500 | 0.4000 |
| 4 | 118 | 5.122 | 7.700 | 3.800 | 6.700 | 2.200 |
| 5 | 119 | 4.330 | 7.700 | 2.600 | 6.900 | 2.300 |
| 6 | 61 | 3.958 | 5 | 2 | 3.500 | 1 |
| 7 | 34 | 3.634 | 5.500 | 4.200 | 1.400 | 0.2000 |
| 8 | 123 | 3.244 | 7.700 | 2.800 | 6.700 | 2 |
| 9 | 110 | 3.224 | 7.200 | 3.600 | 6.100 | 2.500 |
| 10 | 15 | 3.121 | 5.800 | 4 | 1.200 | 0.2000 |
| 11 | 58 | 2.923 | 4.900 | 2.400 | 3.300 | 1 |
| 12 | 94 | 2.892 | 5 | 2.300 | 3.300 | 1 |
| 13 | 33 | 2.882 | 5.200 | 4.100 | 1.500 | 0.1000 |
| 14 | 107 | 2.715 | 4.900 | 2.500 | 4.500 | 1.700 |
| 15 | 136 | 2.692 | 7.700 | 3 | 6.100 | 2.300 |
| 16 | 9 | 2.656 | 4.400 | 2.900 | 1.400 | 0.2000 |
| 17 | 14 | 2.638 | 4.300 | 3 | 1.100 | 0.1000 |
| 18 | 99 | 2.634 | 5.100 | 2.500 | 3 | 1.100 |
| 19 | 63 | 2.591 | 6 | 2.200 | 4 | 1 |
| 20 | 106 | 2.581 | 7.600 | 3 | 6.600 | 2.100 |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 0.3252 | 0.7428 | yes |
| 2 | 0.0985 | 0.6258 | yes |
Mixture prior components
| Component | Rows | Prior weight | Mean 1 | Mean 2 |
|---|---|---|---|---|
| 1 | 100 | 0.4957 | −0.5351 | −0.5602 |
| 2 | 50 | 0.3373 | 1.176 | 1.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
))
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
| Rank | Row | Per-row loss | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 42 | 5.689 | 4.500 | 2.300 | 1.300 | 0.3000 |
| 2 | 132 | 5.426 | 7.900 | 3.800 | 6.400 | 2 |
| 3 | 16 | 5.327 | 5.700 | 4.400 | 1.500 | 0.4000 |
| 4 | 118 | 5.122 | 7.700 | 3.800 | 6.700 | 2.200 |
| 5 | 119 | 4.330 | 7.700 | 2.600 | 6.900 | 2.300 |
| 6 | 61 | 3.958 | 5 | 2 | 3.500 | 1 |
| 7 | 34 | 3.634 | 5.500 | 4.200 | 1.400 | 0.2000 |
| 8 | 123 | 3.244 | 7.700 | 2.800 | 6.700 | 2 |
| 9 | 110 | 3.224 | 7.200 | 3.600 | 6.100 | 2.500 |
| 10 | 15 | 3.121 | 5.800 | 4 | 1.200 | 0.2000 |
| 11 | 58 | 2.923 | 4.900 | 2.400 | 3.300 | 1 |
| 12 | 94 | 2.892 | 5 | 2.300 | 3.300 | 1 |
| 13 | 33 | 2.882 | 5.200 | 4.100 | 1.500 | 0.1000 |
| 14 | 107 | 2.715 | 4.900 | 2.500 | 4.500 | 1.700 |
| 15 | 136 | 2.692 | 7.700 | 3 | 6.100 | 2.300 |
| 16 | 9 | 2.656 | 4.400 | 2.900 | 1.400 | 0.2000 |
| 17 | 14 | 2.638 | 4.300 | 3 | 1.100 | 0.1000 |
| 18 | 99 | 2.634 | 5.100 | 2.500 | 3 | 1.100 |
| 19 | 63 | 2.591 | 6 | 2.200 | 4 | 1 |
| 20 | 106 | 2.581 | 7.600 | 3 | 6.600 | 2.100 |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 0.3252 | 0.7428 | yes |
| 2 | 0.0985 | 0.6258 | yes |
Mixture prior components
| Component | Rows | Prior weight | Mean 1 | Mean 2 |
|---|---|---|---|---|
| 1 | 100 | 0.4957 | −0.5351 | −0.5602 |
| 2 | 50 | 0.3373 | 1.176 | 1.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.
How tight is the ELBO?
ReflectA 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.
Check your understanding
CheckpointCheck 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.
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.
Do it on your own data
In the appUnder 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