Skip to content

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.

Experimental Python and R use different algorithms; results agree in substance Seeded Also called DEC, IDEC, deep embedded clustering…

A real result

Example “Iris idec”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

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

Clusters
3
Mean silhouette
0.3993

Plots

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

First 60 of 150 rows.

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

First 60 of 153 rows.

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

First 60 of 90 rows.

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

First 60 of 150 rows.

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15436.0%5.0063.3441.5960.3037
25335.3%6.7403.0405.4361.940
34328.7%5.7912.7194.4051.412
Python

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

Clusters
3
Mean silhouette
0.3993

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

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15436.0%5.0063.3441.5960.3037
25335.3%6.7403.0405.4361.940
34328.7%5.7912.7194.4051.412

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

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",
    }},
})
R

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.