Skip to content

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.

Advanced ~15 min9 steps

What runs in CodeSplash

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

Read first

01

Why learn the space?

Read

Classic 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 z=fθ(x)z=f_\theta(x) 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.

02

DEC: sharpen your own guesses

Read

DEC pretrains an autoencoder, starts centers with k-means in its embedding, then trains on soft assignments with Student-t weights, qik∝(1+∥zi−μk∥2/α)−(α+1)/2q_{ik}\propto(1+\lVert z_i-\mu_k\rVert^2/\alpha)^{-(\alpha+1)/2}. It builds a sharper target pik∝qik2/∑iqikp_{ik}\propto q_{ik}^2/\sum_i q_{ik} and minimizes the KL divergence from PP to QQ.

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

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

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

First 60 of 150 rows.

Clusters in the learned space (first two coordinates)Which rows group together, and how well separated are the groups?
View data
CenterClusterCode 1Code 2
false20.41461.218
false20.50081.196
false20.53311.310
false20.54381.269
false20.43281.258
false20.20511.068
false20.52931.228
false20.43141.190
false20.71631.197
false20.47141.277
false20.30311.184
false20.46631.202
false20.56131.260
false20.75981.430
false20.20831.273
false2−0.23541.159
false20.27421.162
false20.39081.161
false20.15861.049
false20.34971.203
false20.29251.071
false20.33391.125
false20.60621.424
false20.30730.9325
false20.41461.131
false20.44681.114
false20.36661.053
false20.37121.176
false20.39641.178
false20.47801.246
false20.46651.207
false20.27941.005
false20.34731.365
false20.22061.343
false20.44671.222
false20.49901.217
false20.32741.170
false20.48261.332
false20.67891.297
false20.40531.172
false20.43421.203
false20.93560.7181
false20.58391.431
false20.31100.9613
false20.25691.052
false20.50751.158
false20.35621.236
false20.53021.331
false20.32921.202
false20.45661.192
false1−2.495−1.086
false1−1.864−0.8205
false1−2.502−1.186
false3−0.5258−1.376
false1−1.804−1.383
false3−0.6215−0.8582
false1−1.904−0.7738
false30.3177−0.5310
false1−1.816−1.107
false3−0.2737−0.7936

First 60 of 153 rows.

Fine-tuning loss by epochIs the network still learning, and which part of its loss moves?
View data
PartLoss per rowEpoch
total0.09431
total0.08242
total0.07553
total0.10404
total0.09685
total0.09046
total0.10777
total0.10118
total0.09579
total0.109410
total0.103811
total0.098912
KL0.09431
KL0.08242
KL0.07553
KL0.10404
KL0.09685
KL0.09046
KL0.10777
KL0.10118
KL0.09579
KL0.109410
KL0.103811
KL0.098912
Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.5392
10.5379
10.5322
10.5285
10.5151
10.5129
10.5088
10.5067
10.5062
10.4897
10.4788
10.4746
10.4720
10.4586
10.4559
10.4495
10.4459
10.4376
10.4366
10.4354
10.4149
10.4113
10.4098
10.4005
10.3921
10.3815
10.3806
10.3772
10.3728
10.3684
10.3626
10.3538
10.3437
10.3076
10.2983
10.2935
10.2162
10.2113
10.2031
10.1593
10.1313
10.1172
10.1171
10.1051
10.0196
10.0094
1−0.0196
1−0.0549
1−0.0796
1−0.0954
1−0.1469
20.7286
20.7276
20.7248
20.7229
20.7228
20.7187
20.7186
20.7156
20.7154

First 60 of 150 rows.

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15134.0%6.7553.0475.4651.961
25033.3%5.0063.4281.4620.2460
34932.7%5.7492.6904.3241.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"
  ))
))
Python

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

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15134.0%6.7553.0475.4651.961
25033.3%5.0063.4281.4620.2460
34932.7%5.7492.6904.3241.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.

03

IDEC and VaDE: keep a tether

Read

IDEC keeps the decoder: L=Lrecon+γ KL(P∥Q)L=L_{recon}+\gamma\,KL(P\Vert Q). Reconstruction anchors the embedding to the data; γ\gamma 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 cc, then z∣cz\mid c, then x∣zx\mid z. The ELBO trains encoder, decoder and mixture together.

04

Ask for three components

Predict

Predict first

You fit VaDE on iris with three mixture components. How many clusters do you get?

Three clustersPossibly fewer: a component can go unused
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.

05

JULE and DeepCluster

Read

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

06

Deep anomaly scores

Read

Deep 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 cc: minimize 1n∑i∥ϕW(xi)−c∥2\frac{1}{n}\sum_i\lVert\phi_W(x_i)-c\rVert^2 plus weight decay; the score is the distance to cc. Its trap is collapse: a network that maps every row to cc 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, E(z)=−log⁡∑kπkN(z;μk,Σk)E(z)=-\log\sum_k\pi_k\mathcal N(z;\mu_k,\Sigma_k). Contaminated training data can become an ordinary component; compare with a plain mixture and with reconstruction error alone.

07

Where each idea stands in CodeSplash

Read
EntryIn 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
Reference · UCL069 · Explained hereJoint Unsupervised Learning (JULE)Couple agglomerative image clustering with convolutional representation learning. It begins with fine groups and uses progressive merges to provide evolving unsupervised training signals. Reference · UCL070 · Needs a data type CodeSplash doesn't load yetDeepClusterTrain visual representations by repeatedly clustering current features and predicting the resulting pseudo-labels.
08

Check your understanding

Checkpoint

Check yourself

DEC trains toward a target PP 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, L=Lrecon+γ KL(P∥Q)L=L_{recon}+\gamma\,KL(P\Vert Q). 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 cc, then z∣cz\mid c, then x∣zx\mid z. Responsibilities for cc 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.

09

Do it on your own data

In the app

Under 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