CDiscover · discover.deep_cluster
Deep embedded clustering (DEC and IDEC)
Which groups appear when a neural network reshapes the rows' space to make clusters clearer?
Deep embedded clustering first trains an autoencoder and runs k-means on its codes, then keeps adjusting the encoder and the cluster centers together. Each row gets soft memberships from a Student-t kernel around the centers; a sharpened copy of those memberships becomes the target, so confident assignments pull the space into tighter clusters. DEC drops the decoder for this step; IDEC keeps it and adds the reconstruction error, which stops the space from distorting too far. Training stops when almost no row changes cluster. Lab tier: trained by Adam on torch in both engines from the same initial weights, k-means starts and batch order.
A real result
Example “Iris idec”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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 |
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 |
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Iris idecml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
- Iris dec batchesml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
- Penguins mixed tanhml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass, sex · label: species
- Usarrests k4ml_usarrests · features: Murder, Assault, UrbanPop, Rape · id: state
- Degenerate n2ml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
- Degenerate all naml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
- Degenerate infml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
In the guides
Where it sits in the decision guides
- Clustering (k-means, hierarchical) · DS & ML Decision Guide · Discover — find structure without labels
- Representation learning (autoencoders, contrastive) · DS & ML Decision Guide · Discover — find structure without labels
What you need
- Featuresnumeric / categorical / boolean · 2–500 columns
- Variables that describe each row (numbers are standardized; categories enter as 0/1 columns).
- Known groupscategorical / boolean · 0–1 column
- Optional — compared with the clusters (adjusted Rand index, AMI, NMI); never used to fit.
- Row labelscategorical / numeric · 0–1 column
- Optional names shown on the chart points.
Choices you make
model
- Clusters (k)default 3
Number of cluster centers.
- Objectivedefault idec
DEC fine-tunes the encoder on the cluster target alone; IDEC also keeps rebuilding the rows.
- IDEC (clusters + reconstruction)(default) — Keeps the decoder and adds γ times the cluster loss to the reconstruction error, so the space keeps the rows' local structure.
- DEC (clusters only) — Drops the decoder and trains on the cluster target alone; clusters get tighter, and the space can distort.
- Encoder layers (units)default 16
Units in each encoder layer, input side first; the decoder mirrors them.
- Code sizedefault 2
Coordinates in the learned space where the clusters live (2 draws directly as a map).
- Activationdefault relu
Nonlinearity in the network's hidden layers.
- ReLU(default) — Passes positive signals and zeroes the rest; trains fast and suits most networks.
- tanh — An S-shaped unit with outputs from −1 to 1; a steady choice for small networks on scaled inputs.
- Sigmoid (logistic) — An S-shaped unit with outputs from 0 to 1; trains slowly in deep networks, so keep it for shallow ones.
- Cluster weight (γ)default 0.1
Weight on the cluster loss next to the reconstruction error (the IDEC paper's 0.1).
- Pretraining epochsdefault 200
Passes that train the autoencoder before clustering starts.
- Fine-tuning epochsdefault 100
Upper limit on passes that adjust the encoder and centers together.
- Learning ratedefault 0.005
Adam's step size, for pretraining and fine-tuning.
- Batch sizedefault —
Rows per gradient step; batches follow a seeded shuffle each epoch (the same in Python and R).
Advanced
- Kernel degrees of freedom (α)default 1
Degrees of freedom of the Student-t kernel behind the soft memberships (DEC's 1).
- Target update intervaldefault 5
Epochs between refreshes of the sharpened target memberships.
- Stop when this share of rows changesdefault 0.001
Training stops once fewer rows than this share change cluster between two target refreshes.
- k-means startsdefault 10
k-means++ starts on the pretrained codes; the start with the lowest within-cluster sum of squares sets the centers.
preprocess
- Scale numbersdefault standard
Standardize numbers so each counts equally; turn off only when columns already share one unit.
- Standardize (population SD)(default) — Rescales each number to mean 0 and SD 1 so every column counts equally; the safe choice.
- No scaling — Keeps raw values, so wide-ranging columns dominate; pick it only when columns share one unit.
- Missing valuesdefault drop
Rows with missing values are left out, or filled with the column median (categories get none).
- Leave the row out(default) — Leaves out rows with a missing value; the clean choice when few are missing.
- Fill with the median (categories → none) — Fills numeric gaps with the median and leaves category gaps as no category; keeps every row.
What it reports
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- n_used
- How many independent units the analysis used; it sets precision and power.
- n_noise
- How many independent units the analysis used; it sets precision and power.
- silhouette
- How well each point sits in its cluster compared with the nearest other cluster, from −1 to 1.
- calinski_harabasz
- Between-cluster spread over within-cluster spread. Higher means tighter, better-separated clusters.
- davies_bouldin
- How much each cluster overlaps its most similar neighbor, on average. Lower is better; 0 is the floor.
- objective
- Clustering that keeps adjusting a pretrained encoder and the cluster centers together, so the space itself becomes more clustered.
- k_requested
- Clustering that keeps adjusting a pretrained encoder and the cluster centers together, so the space itself becomes more clustered.
- latent_dim
- A compact set of coordinates from which a model can rebuild data; every point decodes to something, realistic or not.
- pretrain_loss
- Clustering that keeps adjusting a pretrained encoder and the cluster centers together, so the space itself becomes more clustered.
- kmeans_wss
- Clustering that keeps adjusting a pretrained encoder and the cluster centers together, so the space itself becomes more clustered.
- final_kl
- DEC's training target, each row's soft memberships squared and renormalized so confident assignments grow more confident.
- recon_mse
- The share of rows whose final deep cluster differs from the k-means cluster it started in.
- epochs_run
- Clustering that keeps adjusting a pretrained encoder and the cluster centers together, so the space itself becomes more clustered.
- stopped_early
- DEC's training target, each row's soft memberships squared and renormalized so confident assignments grow more confident.
- label_change
- DEC's training target, each row's soft memberships squared and renormalized so confident assignments grow more confident.
- moved_from_kmeans
- The share of rows whose final deep cluster differs from the k-means cluster it started in.
- mean_probability
- A row's degree of belonging to each cluster, summing to 1; DEC uses a Student-t kernel around the centers.
Per group, level or term: size[<cluster>], soft_size[<cluster>], mean[<cluster>,<feature>], ari, ami, nmi
Python and R
Python and R use different algorithms; results agree in substance (relative tolerance 1e-6). Python uses torch; R uses torch.
Default traps between the two languages
- Lab tier. Both engines run the codesplash twin (codesplash.deep.unsupervised.fit_deep_cluster ↔ codesplashr::cs_deep_fit_cluster): the same autoencoder pretraining (fit_autoencoder ↔ cs_deep_fit_autoencoder), k-means++ starts on the codes from the shared Wichmann–Hill stream, Adam written out with torch's arithmetic and the same batch order. Python's and R's torch ship different LibTorch builds, so single kernels can differ by an ulp, which training can amplify; on the fixtures values agree to about 1e-12 relative. A row that sits exactly between two centers could fall on different sides in the two engines; none does on the fixtures.
The exact script CodeSplash ran for example “Iris idec” · 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",
}},
})
The exact script CodeSplash ran for example “Iris idec” · 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"
))
))
Sources
- Xie J, Girshick R, Farhadi A (2016). Unsupervised deep embedding for clustering analysis. ICML 2016, PMLR 48:478–487.
- Guo X, Gao L, Liu X, Yin J (2017). Improved deep embedded clustering with local structure preservation. IJCAI 2017:1753–1759.
- van der Maaten L, Hinton G (2008). Visualizing data using t-SNE. JMLR 9:2579–2605 (the Student-t kernel).
- Arthur D, Vassilvitskii S (2007). k-means++: the advantages of careful seeding. SODA 2007:1027–1035.
From the CodeSplash method registry · discover.deep_cluster v1.0.1.