Skip to content

Hierarchies from Ward to CHAMELEON: merging, splitting and summarizing

Agglomerative linkages, DIANA's splits and BIRCH's summaries all build a tree of clusters. CURE, ROCK and CHAMELEON change what "close" means for whole clusters. What each one assumes, and how to check a tree.

Advanced ~15 min11 steps

What runs in CodeSplash

You will be able to

  • Write the four common linkages and say which shapes each favors
  • Explain why every hierarchical method is greedy and what that costs
  • Read a BIRCH clustering feature and say what compression can erase
  • Describe how CURE, ROCK and CHAMELEON measure closeness between clusters

Read first

01

One tree, two directions

Read

A hierarchy nests clusters inside clusters. Agglomerative methods start from single rows and merge the closest pair again and again; divisive methods start from everything and split. Cutting the tree at some height gives a partition.

Both directions are greedy: a merge or split, once made, is never undone, so an early mistake shapes everything below it. And the tree depends on one choice above all: how to measure the distance between two clusters, not two rows.

02

Linkage decides the tree

Read

For clusters AA and BB, linkageLinkageThe rule hierarchical clustering uses to measure the distance between two groups of rows. is:

  • single: the closest pair, min⁡i∈A,j∈Bdij\min_{i\in A,j\in B} d_{ij}; follows curved shapes but chains through bridges;
  • complete: the farthest pair; compact clusters of small diameter;
  • average: the mean over all pairs;
  • Ward: the smallest rise in within-cluster squared error, Δ=∣A∣∣B∣∣A∣+∣B∣∥xˉA−xˉB∥2\Delta=\frac{|A||B|}{|A|+|B|}\lVert\bar x_A-\bar x_B\rVert^2, which only means "variance" with Euclidean distances.

These give different trees, not noisy estimates of one true tree.

AExplorable · Cut a dendrogram

How do you choose clusters from a tree of merges?

Draw a horizontal line at this height across the tree. How many clusters does it cut into?

16
How sure?

Data

Linkage

0.12
36
cut

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

03

A bridge between two groups

Predict

Predict first

Two round groups are joined by a thin trail of points. Which linkage is most likely to merge the two groups early?

Single linkageComplete linkageWard
Reveal

Single linkage. It only needs one close pair, and the trail supplies a chain of them. Complete linkage and Ward weigh the whole clusters and keep the groups apart longer.

04

Checking a tree

Read
Hierarchical clusteringRecorded · Python and R agreeRecorded 2026-11-25 · 48 values compared
R

Ward clustering on euclidean dissimilarities, cut into 4 clusters (cophenetic correlation 0.70).

Clusters
4
Mean silhouette
0.3370

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
ClusterRowPC1 (62%)PC2 (25%)
4Alabama0.9856−1.133
2Alaska1.950−1.073
2Arizona1.7630.7460
1Arkansas−0.1414−1.120
2California2.5241.543
2Colorado1.5150.9876
1Connecticut−1.3591.089
1Delaware0.04770.3254
2Florida3.013−0.0392
4Georgia1.639−1.279
1Hawaii−0.91271.570
3Idaho−1.640−0.2110
2Illinois1.3790.6818
1Indiana−0.50550.1516
3Iowa−2.2540.1041
1Kansas−0.79690.2702
1Kentucky−0.7509−0.9584
4Louisiana1.565−0.8711
3Maine−2.397−0.3764
2Maryland1.763−0.4277
1Massachusetts−0.48621.474
2Michigan2.1080.1554
3Minnesota−1.6930.6323
4Mississippi0.9965−2.394
1Missouri0.69680.2634
3Montana−1.185−0.5369
3Nebraska−1.2660.1940
2Nevada2.8740.7756
3New Hampshire−2.3840.0181
1New Jersey0.18161.450
2New Mexico1.980−0.1428
2New York1.6830.8232
4North Carolina1.123−2.228
3North Dakota−2.992−0.5991
1Ohio−0.22600.7422
1Oklahoma−0.31180.2879
1Oregon0.05910.5414
1Pennsylvania−0.88840.5711
1Rhode Island−0.86381.492
4South Carolina1.321−1.933
3South Dakota−1.988−0.8233
4Tennessee0.9997−0.8603
2Texas1.3550.4125
1Utah−0.55061.472
3Vermont−2.801−1.402
1Virginia−0.0963−0.1997
1Washington−0.21690.9701
3West Virginia−2.109−1.425
3Wisconsin−2.0800.6113
1Wyoming−0.6294−0.3210
DendrogramHow do rows merge into clusters, and where should the tree be cut?

Merges follow R's hclust convention (negative = row, positive = earlier merge); the last row holds the leaf label only.

View data
HeightLeafLeftRight
0.2079Alabama−15−29
0.3538Alaska−13−32
0.4331Arizona−14−16
0.4991Arkansas−23−49
0.5408California−20−31
0.5591Colorado−363
0.5996Connecticut−37−47
0.6626Delaware−191
0.7110Florida−46−50
0.7181Georgia−41−48
0.7465Hawaii−26−27
0.7801Idaho−1−18
0.7860Illinois−35−38
0.7946Indiana−24−40
0.8059Iowa−21−30
0.8158Kansas−1211
0.8558Kentucky613
0.9523Louisiana−432
0.9610Maine−225
0.9925Maryland−34−45
1.023Massachusetts−10−42
1.071Michigan−4−17
1.082Minnesota−11−44
1.087Mississippi−7−39
1.102Missouri1221
1.172Montana922
1.209Nebraska−5−28
1.220Nevada−3314
1.273New Hampshire−257
1.312New Jersey−319
1.330New Mexico1020
1.359New York48
1.404North Carolina−627
1.555North Dakota1524
1.708Ohio−930
1.766Oklahoma1632
1.830Oregon−834
1.956Pennsylvania1723
2.226Rhode Island2938
2.265South Carolina1835
2.742South Dakota2528
3.024Tennessee3136
3.056Texas−233
3.243Utah3739
3.532Vermont4043
3.772Virginia2644
6.527Washington4145
7.261West Virginia4246
13.653Wisconsin4748
—Wyoming——
Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.4683
10.4297
10.4096
10.3996
10.3774
10.3637
10.3374
10.3310
10.3209
10.3180
10.2767
10.2723
10.2587
10.2377
10.1536
10.1244
10.0611
1−0.0646
1−0.0847
20.4503
20.4280
20.4194
20.4089
20.3631
20.3174
20.3112
20.2589
20.2462
20.1784
20.0734
20.0545
30.5808
30.5701
30.5617
30.5536
30.5514
30.4921
30.4757
30.4272
30.3389
30.2281
30.2278
30.1120
40.5781
40.5694
40.5091
40.4568
40.4269
40.3752
40.3155

Clusters

ClusterSizeShareMurderAssaultUrbanPopRape
11938.0%6.211142.0571.26319.184
21224.0%10.96726476.50033.608
31224.0%3.0927652.08311.833
4714.0%14.671251.2954.28621.686
The exact R script · R R version 4.5.1 (2025-06-13)
# Hierarchical clustering
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.hierarchical 1.1.0 · spec e1102c6213753e0b
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
FEATURES <- c("Murder", "Assault", "UrbanPop", "Rape")
LABEL <- NULL  # known groups (external validation only)
ROW_ID <- "state"  # row labels for charts
SEED <- 42
KINDS <- list(
  Murder = "numeric",
  Assault = "numeric",
  UrbanPop = "numeric",
  Rape = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.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.hierarchical/usarrests_ward/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL

# %% Clustering
if (length(rows) > 10000) stop("Hierarchical clustering keeps every pairwise dissimilarity; use it on at most 10,000 rows.")
LINKAGE <- "ward"
DISTANCE <- "auto"
if (DISTANCE == "auto") DISTANCE <- if (any(unlist(KINDS[FEATURES]) != "numeric")) "gower" else "euclidean"
d <- if (DISTANCE == "gower") {
  stats::as.dist(cs_ml_gower(frame, FEATURES, KINDS))
} else {
  stats::dist(X, method = if (DISTANCE == "manhattan") "manhattan" else "euclidean")
}
D <- as.matrix(d)
dimnames(D) <- NULL
hc <- stats::hclust(d, method = if (LINKAGE == "ward") "ward.D2" else LINKAGE)
if (4 > nrow(D)) cs_error("CS_E_TOO_FEW_ROWS", what = "Cutting the tree into 4 clusters", min = 4, n = nrow(D))
raw <- stats::cutree(hc, k = 4) - 1L
raw <- unname(raw)
values$cophenetic <- stats::cor(as.vector(stats::cophenetic(hc)), as.vector(d))
values$linkage_label <- switch(LINKAGE, ward = "Ward", complete = "Complete-linkage", average = "Average-linkage", single = "Single-linkage")
heights <- rev(hc$height)
for (i in seq_len(min(20L, length(heights)))) values[[sprintf("height[%d]", i)]] <- heights[i]
if (length(rows) <= 2000) {
  leaf <- if (!is.null(ROW_ID)) as.character(frame[[ROW_ID]]) else as.character(rows + 1L)
  charts[[length(charts) + 1L]] <- cs_chart(
    "dendrogram", "dendrogram", "Dendrogram",
    list(merge_left = cs_col("Left", c(hc$merge[, 1], NA), "numeric"),
         merge_right = cs_col("Right", c(hc$merge[, 2], NA), "numeric"),
         height = cs_col("Height", c(hc$height, NA), "numeric"),
         label = cs_col("Leaf", leaf, "categorical")),
    controls = list(k = length(unique(raw))),
    note = "Merges follow R's hclust convention (negative = row, positive = earlier merge); the last row holds the leaf label only."
  )
}
summary <- sprintf("%s clustering on %s dissimilarities, cut into %d clusters (cophenetic correlation %.2f).",
                   values$linkage_label, DISTANCE, length(unique(raw)), values$cophenetic)

# %% 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 = "Hierarchical clustering",
  engine = cs_engine_info("stats", "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(
    direction = "agglomerative",
    compress = "none",
    threshold = 0.5,
    branching = 50,
    linkage = "ward",
    distance = "auto",
    cut = "k",
    k = 4,
    height = 1,
    scale = "standard",
    missing = "drop"
  ))
))
Python

Ward clustering on euclidean dissimilarities, cut into 4 clusters (cophenetic correlation 0.70).

Clusters
4
Mean silhouette
0.3370

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

Clusters

ClusterSizeShareMurderAssaultUrbanPopRape
11938.0%6.211142.0571.26319.184
21224.0%10.96726476.50033.608
31224.0%3.0927652.08311.833
4714.0%14.671251.2954.28621.686
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Hierarchical clustering
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.hierarchical 1.1.0 · spec e1102c6213753e0b
# Dataset: ml_usarrests (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 scipy.cluster.hierarchy import cophenet, fcluster, linkage
from scipy.spatial.distance import pdist, squareform

# %% Data
FEATURES = ["Murder", "Assault", "UrbanPop", "Rape"]
LABEL = None  # known groups (external validation only)
ROW_ID = "state"  # row labels for charts
SEED = 42
KINDS = {
    "Murder": "numeric",
    "Assault": "numeric",
    "UrbanPop": "numeric",
    "Rape": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.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.hierarchical/usarrests_ward/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None

# %% Clustering
if len(rows) > 10000:
    raise ValueError("Hierarchical clustering keeps every pairwise dissimilarity; use it on at most 10,000 rows.")
LINKAGE = "ward"
DISTANCE = "auto"
if DISTANCE == "auto":
    DISTANCE = "gower" if any(KINDS[f] != "numeric" for f in FEATURES) else "euclidean"
if DISTANCE == "gower":
    D = csc.gower(frame, FEATURES, KINDS)
    condensed = squareform(D, checks=False)
else:
    condensed = pdist(X, metric="cityblock" if DISTANCE == "manhattan" else "euclidean")
    D = squareform(condensed)
Z = linkage(condensed, method=LINKAGE)  # Ward here = R's "ward.D2"
if 4 > X.shape[0]:  # scipy would quietly cut into fewer clusters; R stops (same rule in both now)
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="Cutting the tree into 4 clusters", min=4, n=int(X.shape[0]))
raw = fcluster(Z, 4, criterion="maxclust").astype(np.int64)
values["cophenetic"] = float(cophenet(Z, condensed)[0])
values["linkage_label"] = {"ward": "Ward", "complete": "Complete-linkage", "average": "Average-linkage", "single": "Single-linkage"}[LINKAGE]
heights = Z[::-1, 2]
for i, h in enumerate(heights[:20], start=1):
    values[f"height[{i}]"] = float(h)
if len(rows) <= 2000:
    merge = csc.merge_r(Z)
    leaf = [str(v) for v in frame[ROW_ID].astype("object").to_numpy()] if ROW_ID else [str(r + 1) for r in rows]
    pad = [None]
    charts.append(cs.chart(
        "dendrogram", "dendrogram", "Dendrogram",
        {
            "merge_left": cs.col("Left", [int(v) for v in merge[:, 0]] + pad, "numeric"),
            "merge_right": cs.col("Right", [int(v) for v in merge[:, 1]] + pad, "numeric"),
            "height": cs.col("Height", list(Z[:, 2]) + pad, "numeric"),
            "label": cs.col("Leaf", leaf, "categorical"),
        },
        controls={"k": int(len(set(raw.tolist())))},
        note="Merges follow R's hclust convention (negative = row, positive = earlier merge); the last row holds the leaf label only.",
    ))
summary = (
    f"{values['linkage_label']} clustering on {DISTANCE} dissimilarities, cut into {len(set(raw.tolist()))} clusters "
    f"(cophenetic correlation {values['cophenetic']:.2f})."
)

# %% 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": "Hierarchical clustering",
    "engine": cs.engine_info("scipy", "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": {
        "direction": "agglomerative",
        "compress": "none",
        "threshold": 0.5,
        "branching": 50,
        "linkage": "ward",
        "distance": "auto",
        "cut": "k",
        "k": 4,
        "height": 1,
        "scale": "standard",
        "missing": "drop",
    }},
})

The cophenetic correlationCophenetic correlationThe correlation between original distances and the heights at which pairs of rows join in a dendrogram. compares the heights at which pairs of rows first meet in the tree with their original distances; here it is 0.698. A high value says the tree is a faithful summary of the distances, not that the clusters are real.

A large jump in merge height is a hint at a natural cut, but it is exploratory, not a test. Bootstrap the rows and see whether the same branches come back.

05

DIANA: split the widest cluster

Read

DIANADivisive analysis (DIANA)Builds the tree top-down: split the widest cluster by peeling off the rows least like the rest, until every row stands alone. picks the cluster with the largest diameter and starts a splinter group from its most dissimilar row. A row ii moves to the splinter group while Δi=dˉ(i,rest)−dˉ(i,splinter)>0\Delta_i=\bar d(i,\text{rest})-\bar d(i,\text{splinter})>0, that is, while it is on average closer to the splinter.

Hierarchical clusteringRecorded · Python and R agreeRecorded 2026-11-25 · 49 values compared
R

Divisive clustering (DIANA) on euclidean dissimilarities, cut into 4 clusters (divisive coefficient 0.85, cophenetic correlation 0.70).

Clusters
4
Mean silhouette
0.3318

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
ClusterRowPC1 (62%)PC2 (25%)
4Alabama0.9856−1.133
2Alaska1.950−1.073
2Arizona1.7630.7460
1Arkansas−0.1414−1.120
2California2.5241.543
2Colorado1.5150.9876
1Connecticut−1.3591.089
1Delaware0.04770.3254
2Florida3.013−0.0392
4Georgia1.639−1.279
1Hawaii−0.91271.570
3Idaho−1.640−0.2110
2Illinois1.3790.6818
1Indiana−0.50550.1516
3Iowa−2.2540.1041
1Kansas−0.79690.2702
3Kentucky−0.7509−0.9584
4Louisiana1.565−0.8711
3Maine−2.397−0.3764
2Maryland1.763−0.4277
1Massachusetts−0.48621.474
2Michigan2.1080.1554
3Minnesota−1.6930.6323
4Mississippi0.9965−2.394
2Missouri0.69680.2634
3Montana−1.185−0.5369
3Nebraska−1.2660.1940
2Nevada2.8740.7756
3New Hampshire−2.3840.0181
1New Jersey0.18161.450
2New Mexico1.980−0.1428
2New York1.6830.8232
4North Carolina1.123−2.228
3North Dakota−2.992−0.5991
1Ohio−0.22600.7422
1Oklahoma−0.31180.2879
1Oregon0.05910.5414
1Pennsylvania−0.88840.5711
1Rhode Island−0.86381.492
4South Carolina1.321−1.933
3South Dakota−1.988−0.8233
4Tennessee0.9997−0.8603
2Texas1.3550.4125
1Utah−0.55061.472
3Vermont−2.801−1.402
1Virginia−0.0963−0.1997
1Washington−0.21690.9701
3West Virginia−2.109−1.425
3Wisconsin−2.0800.6113
1Wyoming−0.6294−0.3210
DendrogramHow do rows merge into clusters, and where should the tree be cut?

Divisive tree: a merge's height is the diameter of the cluster that was split there. Merges follow R's hclust convention.

View data
HeightLeafLeftRight
0.2079Alabama−15−29
0.3538Alaska−13−32
0.4991Arizona−23−49
0.5357Arkansas−14−36
0.5408California−20−31
0.5512Colorado−16−38
0.5996Connecticut−37−47
0.6523Delaware−191
0.7047Florida−354
0.7110Georgia−46−50
0.7181Hawaii−41−48
0.7591Idaho−12−27
0.7946Illinois−24−40
0.8059Indiana−21−30
0.8493Iowa−1−42
0.8498Kansas69
0.8544Kentucky−432
0.8610Louisiana−17−26
0.8680Maine−10−18
1.007Maryland−410
1.064Massachusetts−348
1.082Michigan−11−44
1.087Minnesota−7−39
1.091Mississippi−225
1.097Missouri−4511
1.143Montana1915
1.195Nebraska−3313
1.209Nevada−5−28
1.223New Hampshire123
1.224New Jersey−324
1.413New Mexico−628
1.544New York−2517
1.627North Carolina1423
1.662North Dakota3230
1.747Ohio716
1.747Oklahoma2521
1.819Oregon−820
2.080Pennsylvania2233
2.116Rhode Island1829
2.153South Carolina3735
2.361South Dakota2726
2.473Tennessee3936
2.544Texas−934
2.544Utah3143
3.120Vermont4038
3.324Virginia−244
4.445Washington4245
4.465West Virginia4146
6.138Wisconsin4847
—Wyoming——
Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.4731
10.4491
10.4287
10.4157
10.4146
10.3464
10.3285
10.3273
10.3017
10.3016
10.3011
10.2998
10.2849
10.2457
10.1899
10.1247
1−0.1187
20.4401
20.4177
20.4167
20.4048
20.3651
20.3317
20.3122
20.2696
20.2238
20.2003
20.0736
20.0588
2−0.0717
30.5438
30.5385
30.5290
30.5260
30.5086
30.4810
30.4788
30.3950
30.2830
30.2615
30.1657
30.0803
30.0638
40.5741
40.5658
40.4988
40.4542
40.4210
40.3701
40.2935

Clusters

ClusterSizeShareMurderAssaultUrbanPopRape
11734.0%5.841141.8872.47118.824
21326.0%10.815257.387633.192
31326.0%3.60078.53852.07712.177
4714.0%14.671251.2954.28621.686
The exact R script · R R version 4.5.1 (2025-06-13)
# Hierarchical clustering
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.hierarchical 1.1.0 · spec 2adbc488c95ce1ba
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
FEATURES <- c("Murder", "Assault", "UrbanPop", "Rape")
LABEL <- NULL  # known groups (external validation only)
ROW_ID <- "state"  # row labels for charts
SEED <- 42
KINDS <- list(
  Murder = "numeric",
  Assault = "numeric",
  UrbanPop = "numeric",
  Rape = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.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.hierarchical/usarrests_divisive/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL

# %% Clustering
DISTANCE <- "auto"
if (DISTANCE == "auto") DISTANCE <- if (any(unlist(KINDS[FEATURES]) != "numeric")) "gower" else "euclidean"
# Divisive analysis (DIANA): split the widest cluster by the splinter rule until every row stands alone
# (twin: diana in codesplash.ml.cluster_partition; matches cluster::diana's heights and divisive coefficient)
if (length(rows) > 5000) stop("Divisive clustering keeps every pairwise dissimilarity; use it on at most 5,000 rows.")
D <- if (DISTANCE == "gower") cs_ml_gower(frame, FEATURES, KINDS) else as.matrix(stats::dist(X, method = if (DISTANCE == "manhattan") "manhattan" else "euclidean"))
dimnames(D) <- NULL
splits <- cs_cp_diana(D)
if (4 > length(rows)) stop(sprintf("k = %d needs at least %d rows; %d are usable.", 4, 4, length(rows)))
raw <- cs_cp_diana_cut(length(rows), splits, k = 4)
cc <- cs_cp_diana_cophenetic(D, splits)
values$cophenetic <- cc$cophenetic
values$divisive_coefficient <- cc$dc
values$linkage_label <- "Divisive (DIANA)"
for (i in seq_len(min(20L, length(splits)))) values[[sprintf("height[%d]", i)]] <- splits[[i]]$height
if (length(rows) <= 2000) {
  mg <- cs_cp_diana_merge(length(rows), splits)
  leaf <- if (!is.null(ROW_ID)) as.character(frame[[ROW_ID]]) else as.character(rows + 1L)
  charts[[length(charts) + 1L]] <- cs_chart(
    "dendrogram", "dendrogram", "Dendrogram",
    list(merge_left = cs_col("Left", c(mg$merge[, 1], NA), "numeric"),
         merge_right = cs_col("Right", c(mg$merge[, 2], NA), "numeric"),
         height = cs_col("Height", c(mg$heights, NA), "numeric"),
         label = cs_col("Leaf", leaf, "categorical")),
    controls = list(k = length(unique(raw))),
    note = "Divisive tree: a merge's height is the diameter of the cluster that was split there. Merges follow R's hclust convention."
  )
}
summary <- sprintf("Divisive clustering (DIANA) on %s dissimilarities, cut into %d clusters (divisive coefficient %.2f, cophenetic correlation %.2f).",
                   DISTANCE, length(unique(raw)), values$divisive_coefficient, values$cophenetic)

# %% 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 = "Hierarchical clustering",
  engine = cs_engine_info("stats", "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(
    direction = "divisive",
    compress = "none",
    threshold = 0.5,
    branching = 50,
    linkage = "ward",
    distance = "auto",
    cut = "k",
    k = 4,
    height = 1,
    scale = "standard",
    missing = "drop"
  ))
))
Python

Divisive clustering (DIANA) on euclidean dissimilarities, cut into 4 clusters (divisive coefficient 0.85, cophenetic correlation 0.70).

Clusters
4
Mean silhouette
0.3318

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

Clusters

ClusterSizeShareMurderAssaultUrbanPopRape
11734.0%5.841141.8872.47118.824
21326.0%10.815257.387633.192
31326.0%3.60078.53852.07712.177
4714.0%14.671251.2954.28621.686
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Hierarchical clustering
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.hierarchical 1.1.0 · spec 2adbc488c95ce1ba
# Dataset: ml_usarrests (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 scipy.cluster.hierarchy import cophenet, fcluster, linkage
from scipy.spatial.distance import pdist, squareform
from codesplash.ml import cluster_partition as cpart

# %% Data
FEATURES = ["Murder", "Assault", "UrbanPop", "Rape"]
LABEL = None  # known groups (external validation only)
ROW_ID = "state"  # row labels for charts
SEED = 42
KINDS = {
    "Murder": "numeric",
    "Assault": "numeric",
    "UrbanPop": "numeric",
    "Rape": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.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.hierarchical/usarrests_divisive/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None

# %% Clustering
DISTANCE = "auto"
if DISTANCE == "auto":
    DISTANCE = "gower" if any(KINDS[f] != "numeric" for f in FEATURES) else "euclidean"
# Divisive analysis (DIANA): split the widest cluster by the splinter rule until every row stands alone
# (twin: cs_cp_diana; matches cluster::diana's heights and divisive coefficient)
if len(rows) > 5000:
    raise ValueError("Divisive clustering keeps every pairwise dissimilarity; use it on at most 5,000 rows.")
if DISTANCE == "gower":
    D = csc.gower(frame, FEATURES, KINDS)
else:
    D = squareform(pdist(X, metric="cityblock" if DISTANCE == "manhattan" else "euclidean"))
splits = cpart.diana(D)
if 4 > len(rows):
    raise ValueError(f"k = 4 needs at least 4 rows; {len(rows)} are usable.")
raw = cpart.diana_cut(len(rows), splits, k=4)
values["cophenetic"], values["divisive_coefficient"] = cpart.diana_cophenetic(D, splits)
values["linkage_label"] = "Divisive (DIANA)"
for i, sp in enumerate(splits[:20], start=1):
    values[f"height[{i}]"] = float(sp[0])
if len(rows) <= 2000:
    merge, mh = cpart.diana_merge(len(rows), splits)
    leaf = [str(v) for v in frame[ROW_ID].astype("object").to_numpy()] if ROW_ID else [str(r + 1) for r in rows]
    pad = [None]
    charts.append(cs.chart(
        "dendrogram", "dendrogram", "Dendrogram",
        {
            "merge_left": cs.col("Left", [int(v) for v in merge[:, 0]] + pad, "numeric"),
            "merge_right": cs.col("Right", [int(v) for v in merge[:, 1]] + pad, "numeric"),
            "height": cs.col("Height", list(mh) + pad, "numeric"),
            "label": cs.col("Leaf", leaf, "categorical"),
        },
        controls={"k": int(len(set(raw.tolist())))},
        note="Divisive tree: a merge's height is the diameter of the cluster that was split there. Merges follow R's hclust convention.",
    ))
summary = (
    f"Divisive clustering (DIANA) on {DISTANCE} dissimilarities, cut into {len(set(raw.tolist()))} clusters "
    f"(divisive coefficient {values['divisive_coefficient']:.2f}, cophenetic correlation {values['cophenetic']:.2f})."
)

# %% 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": "Hierarchical clustering",
    "engine": cs.engine_info("scipy", "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": {
        "direction": "divisive",
        "compress": "none",
        "threshold": 0.5,
        "branching": 50,
        "linkage": "ward",
        "distance": "auto",
        "cut": "k",
        "k": 4,
        "height": 1,
        "scale": "standard",
        "missing": "drop",
    }},
})

The divisive coefficient here is 0.851; values near 1 mean strong splits, but the coefficient grows with the number of rows. Running k-means with kk = 2 again and again is a different algorithm, so don't call it DIANA. Name the columns that drive a split before naming its children.

06

BIRCH: summarize, then cluster

Read

BIRCHBIRCHOne pass over the rows builds a tree of tight subclusters (count, sum, sum of squares); clustering then runs on their centers. streams the rows into a tree of tight subclusters. Each subcluster keeps only a clustering feature (N,LS,SS)(N, LS, SS): its count, the vector sum and the sum of squared lengths. The centroid is LS/NLS/N and the squared radius SS/N−∥LS/N∥2SS/N-\lVert LS/N\rVert^2; two features merge by adding them.

Hierarchical clusteringRecorded · Python and R agreeRecorded 2026-11-25 · 48 values compared
R

BIRCH compressed 150 rows into 37 subclusters; Ward clustering of their centers gives 3 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
3−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
10.3887−0.5933
10.74650.7730
3−0.4873−1.852
10.92790.0322
10.0114−1.034

First 60 of 150 rows.

Dendrogram of BIRCH subclustersHow do rows merge into clusters, and where should the tree be cut?

Leaves are BIRCH subclusters (their centers), not rows. Merges follow R's hclust convention.

View data
HeightLeafLeftRight
0.3337subcluster 1 (15 rows)−28−35
0.3895subcluster 2 (9 rows)−1−5
0.4962subcluster 3 (1 rows)−13−18
0.5358subcluster 4 (1 rows)−24−27
0.6004subcluster 5 (5 rows)−31−36
0.6038subcluster 6 (2 rows)−12−22
0.6269subcluster 7 (16 rows)−25−30
0.6293subcluster 8 (1 rows)−143
0.6409subcluster 9 (2 rows)−20−21
0.6641subcluster 10 (3 rows)−3−6
0.6856subcluster 11 (1 rows)−9−15
0.7210subcluster 12 (5 rows)−179
0.8211subcluster 13 (6 rows)−34−37
0.8370subcluster 14 (8 rows)14
0.8994subcluster 15 (8 rows)−210
0.9375subcluster 16 (4 rows)−10−11
1.029subcluster 17 (5 rows)−1611
1.041subcluster 18 (4 rows)−32−33
1.089subcluster 19 (1 rows)−297
1.099subcluster 20 (4 rows)−2612
1.120subcluster 21 (1 rows)−72
1.195subcluster 22 (6 rows)513
1.202subcluster 23 (3 rows)−236
1.265subcluster 24 (4 rows)−415
1.477subcluster 25 (7 rows)1920
1.518subcluster 26 (1 rows)−1916
1.829subcluster 27 (3 rows)823
1.937subcluster 28 (6 rows)1726
2.530subcluster 29 (1 rows)2527
2.577subcluster 30 (4 rows)1418
2.841subcluster 31 (4 rows)2230
2.945subcluster 32 (1 rows)−828
3.502subcluster 33 (2 rows)2124
5.785subcluster 34 (2 rows)2931
8.687subcluster 35 (1 rows)3234
12.352subcluster 36 (2 rows)3335
—subcluster 37 (1 rows)——
Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.5505
10.5477
10.5442
10.5429
10.5391
10.5391
10.5374
10.5368
10.5312
10.5307
10.5293
10.5270
10.5266
10.5235
10.5182
10.5160
10.5136
10.5112
10.4890
10.4876
10.4855
10.4838
10.4831
10.4766
10.4699
10.4687
10.4572
10.4571
10.4568
10.4565
10.4503
10.4487
10.4463
10.4433
10.4429
10.4360
10.4277
10.4226
10.4142
10.4048
10.4045
10.3972
10.3961
10.3939
10.3938
10.3550
10.3462
10.3411
10.3396
10.3347
10.3330
10.3178
10.3173
10.2842
10.2790
10.2734
10.2719
10.2483
10.2453
10.2272

First 60 of 150 rows.

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
18154.0%6.4212.9815.1211.788
24932.7%5.0163.4511.4650.2449
32013.3%5.5302.4003.8551.155
The exact R script · R R version 4.5.1 (2025-06-13)
# Hierarchical clustering
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.hierarchical 1.1.0 · spec 6d81cedea4df0810
# 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)

# %% 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.hierarchical/iris_birch_ward/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL

# %% Clustering
DISTANCE <- "auto"
if (DISTANCE == "auto") DISTANCE <- if (any(unlist(KINDS[FEATURES]) != "numeric")) "gower" else "euclidean"
# BIRCH: one pass builds a clustering-feature tree of small subclusters, then the chosen linkage clusters the
# subcluster centers and every row takes the cluster of its nearest center (twin: birch, scikit-learn's rules)
if (DISTANCE != "euclidean" && "auto" != "auto") cs_error("CS_E_INVALID_OPTION", option = "Dissimilarity", allowed = "Euclidean (or automatic) with BIRCH compression", value = DISTANCE)
DISTANCE <- "euclidean"
LINKAGE <- "ward"
bt <- cs_cp_birch(X, 0.4, 10)
cents <- bt$centroids
m_sub <- nrow(cents)
if (m_sub > 10000) stop(sprintf("BIRCH left %s subclusters; raise the threshold so at most 10,000 remain.", format(m_sub, big.mark = ",")))
if (m_sub < 2) stop("BIRCH merged every row into one subcluster; lower the threshold.")
d <- stats::dist(cents)
hc <- stats::hclust(d, method = if (LINKAGE == "ward") "ward.D2" else LINKAGE)
if (3 > m_sub) stop(sprintf("BIRCH made only %d subclusters, fewer than k = %d; lower the threshold.", m_sub, 3))
sub_lab <- unname(stats::cutree(hc, k = 3)) - 1L
nearest <- cs_cp_assign_nearest(X, cents)
raw <- sub_lab[nearest + 1L]
values$n_subclusters <- m_sub
values$compression <- length(rows) / m_sub
values$cophenetic <- if (m_sub > 2) stats::cor(as.vector(stats::cophenetic(hc)), as.vector(d)) else NaN
values$linkage_label <- switch(LINKAGE, ward = "Ward", complete = "Complete-linkage", average = "Average-linkage", single = "Single-linkage")
heights <- rev(hc$height)
for (i in seq_len(min(20L, length(heights)))) values[[sprintf("height[%d]", i)]] <- heights[i]
if (m_sub <= 2000) {
  leaf <- sprintf("subcluster %d (%d rows)", seq_len(m_sub), as.integer(bt$counts))
  charts[[length(charts) + 1L]] <- cs_chart(
    "dendrogram", "dendrogram", "Dendrogram of BIRCH subclusters",
    list(merge_left = cs_col("Left", c(hc$merge[, 1], NA), "numeric"),
         merge_right = cs_col("Right", c(hc$merge[, 2], NA), "numeric"),
         height = cs_col("Height", c(hc$height, NA), "numeric"),
         label = cs_col("Leaf", leaf, "categorical")),
    controls = list(k = length(unique(sub_lab))),
    note = "Leaves are BIRCH subclusters (their centers), not rows. Merges follow R's hclust convention."
  )
}
summary <- sprintf("BIRCH compressed %s rows into %s subclusters; %s clustering of their centers gives %d clusters.",
                   format(length(rows), big.mark = ","), format(m_sub, big.mark = ","), values$linkage_label, length(unique(raw)))

# %% 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 = "Hierarchical clustering",
  engine = cs_engine_info("stats", "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(
    direction = "agglomerative",
    compress = "birch",
    threshold = 0.4,
    branching = 10,
    linkage = "ward",
    distance = "auto",
    cut = "k",
    k = 3,
    height = 1,
    scale = "standard",
    missing = "drop"
  ))
))
Python

BIRCH compressed 150 rows into 37 subclusters; Ward clustering of their centers gives 3 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
18154.0%6.4212.9815.1211.788
24932.7%5.0163.4511.4650.2449
32013.3%5.5302.4003.8551.155
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Hierarchical clustering
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.hierarchical 1.1.0 · spec 6d81cedea4df0810
# 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 scipy.cluster.hierarchy import cophenet, fcluster, linkage
from scipy.spatial.distance import pdist, squareform
from codesplash.ml import cluster_partition as cpart

# %% 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.hierarchical/iris_birch_ward/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None

# %% Clustering
DISTANCE = "auto"
if DISTANCE == "auto":
    DISTANCE = "gower" if any(KINDS[f] != "numeric" for f in FEATURES) else "euclidean"
# BIRCH: one pass builds a clustering-feature tree of small subclusters, then the chosen linkage clusters the
# subcluster centers and every row takes the cluster of its nearest center (twin: cs_cp_birch; scikit-learn's rules)
if DISTANCE != "euclidean" and "auto" != "auto":
    cs.cs_error("CS_E_INVALID_OPTION", option="Dissimilarity", allowed="Euclidean (or automatic) with BIRCH compression", value=DISTANCE)
DISTANCE = "euclidean"
LINKAGE = "ward"
cents, counts = cpart.birch(X, 0.4, 10)
m_sub = len(cents)
if m_sub > 10000:
    raise ValueError(f"BIRCH left {m_sub:,} subclusters; raise the threshold so at most 10,000 remain.")
if m_sub < 2:
    raise ValueError("BIRCH merged every row into one subcluster; lower the threshold.")
condensed = pdist(cents, metric="euclidean")
Z = linkage(condensed, method=LINKAGE)  # Ward here = R's "ward.D2"
if 3 > m_sub:
    raise ValueError(f"BIRCH made only {m_sub} subclusters, fewer than k = 3; lower the threshold.")
sub_lab = fcluster(Z, 3, criterion="maxclust").astype(np.int64)
nearest = cpart.assign_nearest(X, cents)
raw = sub_lab[nearest]
values["n_subclusters"] = int(m_sub)
values["compression"] = float(len(rows) / m_sub)
values["cophenetic"] = float(cophenet(Z, condensed)[0]) if m_sub > 2 else float("nan")
values["linkage_label"] = {"ward": "Ward", "complete": "Complete-linkage", "average": "Average-linkage", "single": "Single-linkage"}[LINKAGE]
heights = Z[::-1, 2]
for i, h in enumerate(heights[:20], start=1):
    values[f"height[{i}]"] = float(h)
if m_sub <= 2000:
    merge = csc.merge_r(Z)
    leaf = [f"subcluster {i + 1} ({int(c)} rows)" for i, c in enumerate(counts)]
    pad = [None]
    charts.append(cs.chart(
        "dendrogram", "dendrogram", "Dendrogram of BIRCH subclusters",
        {
            "merge_left": cs.col("Left", [int(v) for v in merge[:, 0]] + pad, "numeric"),
            "merge_right": cs.col("Right", [int(v) for v in merge[:, 1]] + pad, "numeric"),
            "height": cs.col("Height", list(Z[:, 2]) + pad, "numeric"),
            "label": cs.col("Leaf", leaf, "categorical"),
        },
        controls={"k": int(len(set(sub_lab.tolist())))},
        note="Leaves are BIRCH subclusters (their centers), not rows. Merges follow R's hclust convention.",
    ))
summary = (
    f"BIRCH compressed {len(rows):,} rows into {m_sub:,} subclusters; {values['linkage_label']} clustering of their centers "
    f"gives {len(set(raw.tolist()))} 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": "Hierarchical clustering",
    "engine": cs.engine_info("scipy", "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": {
        "direction": "agglomerative",
        "compress": "birch",
        "threshold": 0.4,
        "branching": 10,
        "linkage": "ward",
        "distance": "auto",
        "cut": "k",
        "k": 3,
        "height": 1,
        "scale": "standard",
        "missing": "drop",
    }},
})

Here 150 rows became 37 subclusters before Ward ran. The summaries assume Euclidean numbers, and the threshold and row order shape them: a rare group can vanish inside one subcluster. Report the compression and check the final cost on all rows.

07

CURE: several shrunk representatives

Read

One centroid per cluster can't describe a long or bent shape. CURE keeps cc well-scattered representatives per cluster and pulls each toward the center by a share α\alpha: r′=(1−α)r+αμr'=(1-\alpha)r+\alpha\mu. Clusters merge when their closest shrunk representatives are closest.

In the reference's small example, representatives (0,0)(0,0) and (4,2)(4,2) around center (2,1)(2,1), shrunk with α=0.3\alpha=0.3, move to (0.600, 0.300) and (3.40, 1.70). Shrinking tempers extreme representatives; it doesn't make the method immune to every kind of contamination. Full CURE also samples, which can miss small groups.

08

ROCK and CHAMELEON: closeness through neighbors

Read

ROCK suits categories and baskets. Two rows are neighbors when their similarity passes a threshold θ\theta, and their link is the number of neighbors they share, L(i,j)=∣N(i)∩N(j)∣L(i,j)=\lvert N(i)\cap N(j)\rvert. Clusters merge by links, normalized for size. Very common items create hubs, and a link count is neither a probability nor a significance level.

CHAMELEON builds a nearest-neighbor graph, cuts it into small pieces, then merges pieces scoring high on RI⋅RCβRI\cdot RC^{\beta}: relative interconnectivity times relative closeness. In the reference's example, RI=(0.8,0.5)RI=(0.8,0.5) and RC=(0.4,0.9)RC=(0.4,0.9) with β=2\beta=2 score 0.128 and 0.405: the closer pair wins. Results hinge on the graph and the first partition.

09

Where each idea stands in CodeSplash

Read
EntryIn CodeSplash
Agglomerative (UCL015)Runs in CodeSplash: Hierarchical clustering, four linkages
DIANA (UCL016)Runs as an option of Hierarchical clustering: Direction Divisive (DIANA)
BIRCH (UCL017)Runs as an option of Hierarchical clustering: Compress first with BIRCH
CURE (UCL018)Explained here
ROCK (UCL019)Explained here
CHAMELEON (UCL020)Explained here

The reference's CURE, ROCK and CHAMELEON programs show one component each (shrinking, link counts, a merge score), not a full fit. For curved or uneven-density groups in the app, try single linkage, HDBSCAN or spectral clustering.

Reference · UCL018 · Explained hereCURERepresent each cluster with several well-scattered points shrunk toward its centroid, allowing hierarchical clustering to capture shapes more flexibly than one centroid while reducing influence of extreme… Reference · UCL019 · Explained hereROCKCluster categorical or set-like records using shared-neighbor links rather than only raw pairwise similarity. Objects may be linked strongly when they have many common neighbors even if their direct similarity is modest. Reference · UCL020 · Explained hereCHAMELEONCluster a nearest-neighbor graph using both interconnectivity and closeness relative to each candidate cluster's internal structure. It targets groups whose size, density, or shape differs.
10

Check your understanding

Checkpoint

Check yourself

You build a Gower dissimilarity for mixed columns. Which linkage loses its usual meaning?

Show the answer

Answer: c

Ward's merge cost is a change in squared error around means, which needs Euclidean geometry. Average and complete linkage only compare dissimilarities.

Check yourself

A tree has a high cophenetic correlation. What does that tell you?

Show the answer

Answer: a

Cophenetic correlation measures how faithfully the tree summarizes distances. Whether the clusters are real needs stability or a test.

Check yourself

DIANA's first split puts two similar rows on different sides. What happens later in the tree?

Show the answer

Answer: b

Divisive and agglomerative methods are both greedy: an early decision constrains all its descendants.

Check yourself

A colleague splits the data with 2-means, then splits each half with 2-means again, and calls it DIANA. Is that right?

Show the answer

Answer: b

Recursive k-means is a divisive method, but not DIANA. Label the algorithm you ran.

Check yourself

What does a BIRCH clustering feature store for a subcluster?

Show the answer

Answer: b

(N,LS,SS)(N, LS, SS) are additive, so subclusters can grow and merge without revisiting rows. That's what lets BIRCH handle large data in one pass.

Check yourself

What can BIRCH's compression step lose?

Show the answer

Answer: a

Once rows are summarized, the final clustering only sees subclusters. Check sensitivity to the radius threshold and to row order, and report the compression.

Check yourself

Why does CURE keep several representatives per cluster instead of one centroid?

Show the answer

Answer: b

Several scattered representatives trace a cluster's shape; shrinking them toward the center tempers the extreme ones.

Check yourself

In CURE, what happens as the shrinkage share α moves from 0 toward 1?

Show the answer

Answer: b

r′=(1−α)r+αμr'=(1-\alpha)r+\alpha\mu: at α = 1 every representative sits on the centroid. Small α keeps the shape; larger α resists stray points.

Check yourself

In ROCK, what is the link between two shopping baskets?

Show the answer

Answer: b

Links count shared neighbors, so two baskets can be linked through many similar baskets even if they share few items directly. A link count is not a probability.

Check yourself

You lower ROCK's similarity threshold θ. What changes?

Show the answer

Answer: a

θ sets which rows are neighbors, and links are built from neighbors. Check how stable the clusters are across thresholds.

Check yourself

CHAMELEON compares two candidate merges with RI⋅RCβRI\cdot RC^{\beta} and β = 2. What does raising β do?

Show the answer

Answer: b

β is the exponent on relative closeness, so a larger β lets a close pair win even with weaker interconnectivity.

Check yourself

Two analysts run CHAMELEON on the same data and get different clusters. What is the likeliest reason?

Show the answer

Answer: b

CHAMELEON's merges only see the graph and the initial pieces, so those choices drive the result. Report them and test stability across neighbor counts.

11

Do it on your own data

In the app

Under Find segments, open Hierarchical clustering. Compare two Linkage choices on the same rows, try Direction: Divisive (DIANA), and turn on Compress first for tables too large to cluster row by row.

Concepts in this lesson