Deep clustering and deep anomaly scores: learning the space you cluster in
DEC, IDEC, VaDE, JULE and DeepCluster learn a representation while they cluster; Deep SVDD and DAGMM learn one to score anomalies. How to spot collapse and a network confirming its own guesses.
What runs in CodeSplash
- UCL063Deep Support Vector Data Description (Deep SVDD) Runs in CodeSplash (Experimental)
- UCL064Deep Autoencoding Gaussian Mixture Model (DAGMM) Runs in CodeSplash (Experimental)
- UCL066Deep Embedded Clustering (DEC) Runs in CodeSplash (Experimental)
- UCL067Improved Deep Embedded Clustering (IDEC) Runs in CodeSplash (Experimental)
- UCL068Variational Deep Embedding (VaDE) Runs in CodeSplash (Experimental)
- UCL069Joint Unsupervised Learning (JULE) Explained here
- UCL070DeepCluster Needs a data type CodeSplash doesn't load yet
- Deep embedded clustering (DEC and IDEC) Experimental
- Variational autoencoder (latent map, anomalies and generated rows) Experimental
- Deep SVDD (one-class neural anomaly detection) Experimental
- Deep autoencoding Gaussian mixture (DAGMM) Experimental
You will be able to
- Explain how DEC's sharpened targets work and why self-training can confirm its own mistakes
- Say what IDEC's reconstruction term and VaDE's mixture prior add
- Explain hypersphere collapse in Deep SVDD and the energy score in DAGMM
- Compare a deep result with clustering or scoring the frozen embedding
Why learn the space?
ReadClassic clustering takes the columns as given. If the useful structure is curved or buried in many weak columns, the clusters come out poor. Deep methods learn an embedding and the clusters (or the notion of normal) together.
That freedom is the risk. A network can reshape the data until its own early guesses look convincing. Every method in this lesson needs one comparison: the same clustering or scoring on the frozen pretrained embedding. If joint training doesn't beat it, the extra machinery added nothing.
DEC: sharpen your own guesses
ReadDEC pretrains an autoencoder, starts centers with k-means in its embedding, then trains on soft assignments with Student-t weights, . It builds a sharper target and minimizes the KL divergence from to .
DEC found 3 clusters in 150 rows after 12 fine-tuning epochs (stopped: assignments settled); the mean membership probability is 0.72 and 7.3% of rows moved from the starting k-means clusters.
- Clusters
- 3
- Mean silhouette
- 0.4445
Plots
View data
| Cluster | PC1 (73%) | PC2 (23%) |
|---|---|---|
| 2 | −2.265 | 0.4800 |
| 2 | −2.081 | −0.6741 |
| 2 | −2.364 | −0.3419 |
| 2 | −2.299 | −0.5974 |
| 2 | −2.390 | 0.6468 |
| 2 | −2.076 | 1.489 |
| 2 | −2.444 | 0.0476 |
| 2 | −2.233 | 0.2231 |
| 2 | −2.335 | −1.115 |
| 2 | −2.184 | −0.4690 |
| 2 | −2.166 | 1.044 |
| 2 | −2.326 | 0.1331 |
| 2 | −2.218 | −0.7287 |
| 2 | −2.633 | −0.9615 |
| 2 | −2.199 | 1.860 |
| 2 | −2.262 | 2.686 |
| 2 | −2.208 | 1.484 |
| 2 | −2.190 | 0.4888 |
| 2 | −1.899 | 1.405 |
| 2 | −2.343 | 1.128 |
| 2 | −1.914 | 0.4089 |
| 2 | −2.207 | 0.9241 |
| 2 | −2.774 | 0.4583 |
| 2 | −1.819 | 0.0856 |
| 2 | −2.227 | 0.1373 |
| 2 | −1.952 | −0.6256 |
| 2 | −2.051 | 0.2422 |
| 2 | −2.169 | 0.5271 |
| 2 | −2.140 | 0.3132 |
| 2 | −2.265 | −0.3377 |
| 2 | −2.140 | −0.5045 |
| 2 | −1.832 | 0.4237 |
| 2 | −2.615 | 1.794 |
| 2 | −2.446 | 2.151 |
| 2 | −2.110 | −0.4602 |
| 2 | −2.208 | −0.2061 |
| 2 | −2.045 | 0.6616 |
| 2 | −2.527 | 0.5923 |
| 2 | −2.430 | −0.9042 |
| 2 | −2.170 | 0.2689 |
| 2 | −2.286 | 0.4417 |
| 2 | −1.858 | −2.337 |
| 2 | −2.554 | −0.4791 |
| 2 | −1.964 | 0.4723 |
| 2 | −2.137 | 1.142 |
| 2 | −2.070 | −0.7111 |
| 2 | −2.385 | 1.120 |
| 2 | −2.394 | −0.3862 |
| 2 | −2.229 | 0.9980 |
| 2 | −2.204 | 0.0092 |
| 1 | 1.102 | 0.8630 |
| 1 | 0.7313 | 0.5946 |
| 1 | 1.241 | 0.6163 |
| 3 | 0.4075 | −1.754 |
| 1 | 1.075 | −0.2084 |
| 3 | 0.3887 | −0.5933 |
| 1 | 0.7465 | 0.7730 |
| 3 | −0.4873 | −1.852 |
| 1 | 0.9279 | 0.0322 |
| 3 | 0.0114 | −1.034 |
First 60 of 150 rows.
View data
| Center | Cluster | Code 1 | Code 2 |
|---|---|---|---|
| false | 2 | 0.4146 | 1.218 |
| false | 2 | 0.5008 | 1.196 |
| false | 2 | 0.5331 | 1.310 |
| false | 2 | 0.5438 | 1.269 |
| false | 2 | 0.4328 | 1.258 |
| false | 2 | 0.2051 | 1.068 |
| false | 2 | 0.5293 | 1.228 |
| false | 2 | 0.4314 | 1.190 |
| false | 2 | 0.7163 | 1.197 |
| false | 2 | 0.4714 | 1.277 |
| false | 2 | 0.3031 | 1.184 |
| false | 2 | 0.4663 | 1.202 |
| false | 2 | 0.5613 | 1.260 |
| false | 2 | 0.7598 | 1.430 |
| false | 2 | 0.2083 | 1.273 |
| false | 2 | −0.2354 | 1.159 |
| false | 2 | 0.2742 | 1.162 |
| false | 2 | 0.3908 | 1.161 |
| false | 2 | 0.1586 | 1.049 |
| false | 2 | 0.3497 | 1.203 |
| false | 2 | 0.2925 | 1.071 |
| false | 2 | 0.3339 | 1.125 |
| false | 2 | 0.6062 | 1.424 |
| false | 2 | 0.3073 | 0.9325 |
| false | 2 | 0.4146 | 1.131 |
| false | 2 | 0.4468 | 1.114 |
| false | 2 | 0.3666 | 1.053 |
| false | 2 | 0.3712 | 1.176 |
| false | 2 | 0.3964 | 1.178 |
| false | 2 | 0.4780 | 1.246 |
| false | 2 | 0.4665 | 1.207 |
| false | 2 | 0.2794 | 1.005 |
| false | 2 | 0.3473 | 1.365 |
| false | 2 | 0.2206 | 1.343 |
| false | 2 | 0.4467 | 1.222 |
| false | 2 | 0.4990 | 1.217 |
| false | 2 | 0.3274 | 1.170 |
| false | 2 | 0.4826 | 1.332 |
| false | 2 | 0.6789 | 1.297 |
| false | 2 | 0.4053 | 1.172 |
| false | 2 | 0.4342 | 1.203 |
| false | 2 | 0.9356 | 0.7181 |
| false | 2 | 0.5839 | 1.431 |
| false | 2 | 0.3110 | 0.9613 |
| false | 2 | 0.2569 | 1.052 |
| false | 2 | 0.5075 | 1.158 |
| false | 2 | 0.3562 | 1.236 |
| false | 2 | 0.5302 | 1.331 |
| false | 2 | 0.3292 | 1.202 |
| false | 2 | 0.4566 | 1.192 |
| false | 1 | −2.495 | −1.086 |
| false | 1 | −1.864 | −0.8205 |
| false | 1 | −2.502 | −1.186 |
| false | 3 | −0.5258 | −1.376 |
| false | 1 | −1.804 | −1.383 |
| false | 3 | −0.6215 | −0.8582 |
| false | 1 | −1.904 | −0.7738 |
| false | 3 | 0.3177 | −0.5310 |
| false | 1 | −1.816 | −1.107 |
| false | 3 | −0.2737 | −0.7936 |
First 60 of 153 rows.
View data
| Part | Loss per row | Epoch |
|---|---|---|
| total | 0.0943 | 1 |
| total | 0.0824 | 2 |
| total | 0.0755 | 3 |
| total | 0.1040 | 4 |
| total | 0.0968 | 5 |
| total | 0.0904 | 6 |
| total | 0.1077 | 7 |
| total | 0.1011 | 8 |
| total | 0.0957 | 9 |
| total | 0.1094 | 10 |
| total | 0.1038 | 11 |
| total | 0.0989 | 12 |
| KL | 0.0943 | 1 |
| KL | 0.0824 | 2 |
| KL | 0.0755 | 3 |
| KL | 0.1040 | 4 |
| KL | 0.0968 | 5 |
| KL | 0.0904 | 6 |
| KL | 0.1077 | 7 |
| KL | 0.1011 | 8 |
| KL | 0.0957 | 9 |
| KL | 0.1094 | 10 |
| KL | 0.1038 | 11 |
| KL | 0.0989 | 12 |
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.5392 |
| 1 | 0.5379 |
| 1 | 0.5322 |
| 1 | 0.5285 |
| 1 | 0.5151 |
| 1 | 0.5129 |
| 1 | 0.5088 |
| 1 | 0.5067 |
| 1 | 0.5062 |
| 1 | 0.4897 |
| 1 | 0.4788 |
| 1 | 0.4746 |
| 1 | 0.4720 |
| 1 | 0.4586 |
| 1 | 0.4559 |
| 1 | 0.4495 |
| 1 | 0.4459 |
| 1 | 0.4376 |
| 1 | 0.4366 |
| 1 | 0.4354 |
| 1 | 0.4149 |
| 1 | 0.4113 |
| 1 | 0.4098 |
| 1 | 0.4005 |
| 1 | 0.3921 |
| 1 | 0.3815 |
| 1 | 0.3806 |
| 1 | 0.3772 |
| 1 | 0.3728 |
| 1 | 0.3684 |
| 1 | 0.3626 |
| 1 | 0.3538 |
| 1 | 0.3437 |
| 1 | 0.3076 |
| 1 | 0.2983 |
| 1 | 0.2935 |
| 1 | 0.2162 |
| 1 | 0.2113 |
| 1 | 0.2031 |
| 1 | 0.1593 |
| 1 | 0.1313 |
| 1 | 0.1172 |
| 1 | 0.1171 |
| 1 | 0.1051 |
| 1 | 0.0196 |
| 1 | 0.0094 |
| 1 | −0.0196 |
| 1 | −0.0549 |
| 1 | −0.0796 |
| 1 | −0.0954 |
| 1 | −0.1469 |
| 2 | 0.7286 |
| 2 | 0.7276 |
| 2 | 0.7248 |
| 2 | 0.7229 |
| 2 | 0.7228 |
| 2 | 0.7187 |
| 2 | 0.7186 |
| 2 | 0.7156 |
| 2 | 0.7154 |
First 60 of 150 rows.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 51 | 34.0% | 6.755 | 3.047 | 5.465 | 1.961 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
| 3 | 49 | 32.7% | 5.749 | 2.690 | 4.324 | 1.380 |
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 ffc77849ffd597ff
# 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_dec_batches/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 <- "dec"
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(80),
epochs = as.integer(30),
update_interval = as.integer(3),
tol = 0.001,
lr = 0.005,
batch_size = 32,
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 = "dec",
hidden_layers = c(8),
latent_dim = 2,
activation = "relu",
gamma = 0.1,
alpha = 1,
pretrain_epochs = 80,
epochs = 30,
update_interval = 3,
tol = 0.001,
learning_rate = 0.005,
batch_size = 32,
n_init = 10,
scale = "standard",
missing = "drop"
))
))
DEC found 3 clusters in 150 rows after 12 fine-tuning epochs (stopped: assignments settled); the mean membership probability is 0.72 and 7.3% of rows moved from the starting k-means clusters.
- Clusters
- 3
- Mean silhouette
- 0.4445
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 | 51 | 34.0% | 6.755 | 3.047 | 5.465 | 1.961 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
| 3 | 49 | 32.7% | 5.749 | 2.690 | 4.324 | 1.380 |
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 ffc77849ffd597ff
# 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_dec_batches/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 = "dec"
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=80,
epochs=30,
update_interval=3,
tol=0.001,
lr=0.005,
batch_size=32,
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": "dec",
"hidden_layers": [8],
"latent_dim": 2,
"activation": "relu",
"gamma": 0.1,
"alpha": 1,
"pretrain_epochs": 80,
"epochs": 30,
"update_interval": 3,
"tol": 0.001,
"learning_rate": 0.005,
"batch_size": 32,
"n_init": 10,
"scale": "standard",
"missing": "drop",
}},
})
Training moved 7.3% of rows away from their k-means start. Self-training rewards confidence, not correctness: wrong early assignments can be locked in. And DEC drops the decoder, so the embedding is free to distort.
IDEC and VaDE: keep a tether
ReadIDEC keeps the decoder: . Reconstruction anchors the embedding to the data; sets the balance, too large and it acts like DEC, too small and clusters barely move. Track both parts of the loss.
VaDEVaDEA variational autoencoder whose prior is a learned mixture of Gaussians, so the same model maps, generates and clusters rows. is a variational autoencoder whose prior is a Gaussian mixture: draw a component , then , then . The ELBO trains encoder, decoder and mixture together.
Ask for three components
PredictPredict first
You fit VaDE on iris with three mixture components. How many clusters do you get?
Reveal
Possibly fewer. Here 2 of 3 components ended up holding rows. Inactive components and posterior collapse are common in VaDE; a good ELBO doesn't promise clusters that match human categories.
JULE and DeepCluster
ReadJULE alternates agglomerative merging with representation learning: merge clusters in the current feature space, then train the network so samples in a cluster are closer to each other than to nearby samples outside it. An early bad merge shapes the features that decide later merges.
DeepCluster trains an image backbone at scale: run k-means on its features, use the cluster ids as pseudo-labels, train a classifier head on them, repeat. Its goal is the representation, not the clusters, so evaluate it with frozen linear probes or nearest-neighbor retrieval on held-out labels. Watch for collapse onto a few clusters.
Deep anomaly scores
ReadDeep SVDDDeep SVDDA network trained to map typical rows close to one fixed center; a row's squared distance to it is its anomaly score. maps normal rows close to a center : minimize plus weight decay; the score is the distance to . Its trap is collapse: a network that maps every row to gets zero loss. The original design forbids bias terms for that reason, so a falling loss alone isn't progress. Here the representation kept 6.4% of its starting spread.
DAGMMDAGMMAn autoencoder and a Gaussian mixture trained together; a row's anomaly score is its energy under the mixture. feeds an autoencoder's latent code and reconstruction error to a Gaussian mixture and scores rows by energy, . Contaminated training data can become an ordinary component; compare with a plain mixture and with reconstruction error alone.
Where each idea stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| Deep SVDD (UCL063) | Runs in CodeSplash (Experimental): Deep SVDD |
| DAGMM (UCL064) | Runs in CodeSplash (Experimental): Deep autoencoding Gaussian mixture (DAGMM) |
| DEC (UCL066) | Runs in CodeSplash (Experimental): Deep embedded clustering, objective DEC |
| IDEC (UCL067) | Runs in CodeSplash (Experimental): Deep embedded clustering, objective IDEC |
| VaDE (UCL068) | Runs as an option of Variational autoencoder: Prior mixture |
| JULE (UCL069) | Explained here |
| DeepCluster (UCL070) | Needs a data type CodeSplash doesn't load yet: it trains an image backbone at scale |
Check your understanding
CheckpointCheck yourself
DEC trains toward a target built by squaring and renormalizing its own soft assignments. What's the risk?
Show the answer
Answer: b
The target comes from the model's own guesses. Compare with k-means on the frozen pretrained embedding to see whether training helped.
Check yourself
What does DEC give up by dropping the decoder during clustering?
Show the answer
Answer: a
Without reconstruction, nothing stops the encoder from warping space to make clusters look tight. IDEC adds the decoder back.
Check yourself
In IDEC, . What happens with a very large γ?
Show the answer
Answer: b
γ balances faithfulness against cluster sharpness. Track both loss parts, and reconstruction error by subgroup.
Check yourself
Does IDEC's reconstruction term guarantee that meaningful neighborhoods survive?
Show the answer
Answer: b
Reconstruction discourages distortion; it doesn't forbid it. Compare with DEC and frozen-embedding clustering under matched encoders.
Check yourself
What makes VaDE a clustering method rather than a plain VAE?
Show the answer
Answer: a
VaDE generates , then , then . Responsibilities for give soft cluster memberships.
Check yourself
A VaDE fit has a strong ELBO but one component holds no rows. What's going on?
Show the answer
Answer: b
Check component usage, responsibilities and stability across seeds, not only the bound.
Check yourself
Why is an early mistake costly in JULE?
Show the answer
Answer: b
Clustering and representation feed each other. Evaluate several initializations and compare with the same merging on fixed features.
Check yourself
JULE's loss compares pairs in the same cluster with nearby samples outside it. Can you swap in a different sampling rule and still call it JULE?
Show the answer
Answer: b
Change them and you've built a different method. Say so when you report it.
Check yourself
How should you judge DeepCluster?
Show the answer
Answer: b
DeepCluster's product is a representation. Pseudo-label accuracy isn't measured during unlabeled training, so evaluate the features separately.
Check yourself
What failure must DeepCluster training guard against?
Show the answer
Answer: a
If one cluster takes everything, predicting it is easy and teaches nothing. Monitor cluster sizes and reassign empty clusters.
Check yourself
A Deep SVDD training loss falls close to zero. Is that good news?
Show the answer
Answer: b
A constant map has zero loss and no power to separate anomalies. Watch the representation's spread and held-out ranking, not only the loss.
Check yourself
What should you compare Deep SVDD against?
Show the answer
Answer: b
Deep scores earn their cost only if they rank held-out anomalies better than simpler detectors.
Check yourself
How does DAGMM score a row?
Show the answer
Answer: b
High energy means the row falls where the mixture puts little density.
Check yourself
The training data contain a cluster of bad rows. What can DAGMM do with them?
Show the answer
Answer: a
A mixture fits whatever density is there. Clean the training data where you can, inspect each component and compare with a standalone mixture.
Do it on your own data
In the appUnder Find segments, open Deep embedded clustering and compare its labels with k-means on the same rows; under Spot anomalies, run Deep SVDD or DAGMM next to Isolation Forest. These are Experimental: check the training curves and the spread warnings before you trust a score.
Concepts in this lesson