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.
What runs in CodeSplash
- UCL015Agglomerative hierarchical clustering Runs in CodeSplash
- UCL016DIANA divisive hierarchical clustering Runs in CodeSplash
- UCL017BIRCH Runs in CodeSplash
- UCL018CURE Explained here
- UCL019ROCK Explained here
- UCL020CHAMELEON Explained here
- Hierarchical clustering Verified in Python and R
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
One tree, two directions
ReadA 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.
Linkage decides the tree
ReadFor clusters and , linkageLinkageThe rule hierarchical clustering uses to measure the distance between two groups of rows. is:
- single: the closest pair, ; 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, , 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?
Data
Linkage
Commit your prediction above to see the result
Make your prediction to see the result.
A bridge between two groups
PredictPredict first
Two round groups are joined by a thin trail of points. Which linkage is most likely to merge the two groups early?
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.
Checking a tree
ReadWard clustering on euclidean dissimilarities, cut into 4 clusters (cophenetic correlation 0.70).
- Clusters
- 4
- Mean silhouette
- 0.3370
Plots
View data
| Cluster | Row | PC1 (62%) | PC2 (25%) |
|---|---|---|---|
| 4 | Alabama | 0.9856 | −1.133 |
| 2 | Alaska | 1.950 | −1.073 |
| 2 | Arizona | 1.763 | 0.7460 |
| 1 | Arkansas | −0.1414 | −1.120 |
| 2 | California | 2.524 | 1.543 |
| 2 | Colorado | 1.515 | 0.9876 |
| 1 | Connecticut | −1.359 | 1.089 |
| 1 | Delaware | 0.0477 | 0.3254 |
| 2 | Florida | 3.013 | −0.0392 |
| 4 | Georgia | 1.639 | −1.279 |
| 1 | Hawaii | −0.9127 | 1.570 |
| 3 | Idaho | −1.640 | −0.2110 |
| 2 | Illinois | 1.379 | 0.6818 |
| 1 | Indiana | −0.5055 | 0.1516 |
| 3 | Iowa | −2.254 | 0.1041 |
| 1 | Kansas | −0.7969 | 0.2702 |
| 1 | Kentucky | −0.7509 | −0.9584 |
| 4 | Louisiana | 1.565 | −0.8711 |
| 3 | Maine | −2.397 | −0.3764 |
| 2 | Maryland | 1.763 | −0.4277 |
| 1 | Massachusetts | −0.4862 | 1.474 |
| 2 | Michigan | 2.108 | 0.1554 |
| 3 | Minnesota | −1.693 | 0.6323 |
| 4 | Mississippi | 0.9965 | −2.394 |
| 1 | Missouri | 0.6968 | 0.2634 |
| 3 | Montana | −1.185 | −0.5369 |
| 3 | Nebraska | −1.266 | 0.1940 |
| 2 | Nevada | 2.874 | 0.7756 |
| 3 | New Hampshire | −2.384 | 0.0181 |
| 1 | New Jersey | 0.1816 | 1.450 |
| 2 | New Mexico | 1.980 | −0.1428 |
| 2 | New York | 1.683 | 0.8232 |
| 4 | North Carolina | 1.123 | −2.228 |
| 3 | North Dakota | −2.992 | −0.5991 |
| 1 | Ohio | −0.2260 | 0.7422 |
| 1 | Oklahoma | −0.3118 | 0.2879 |
| 1 | Oregon | 0.0591 | 0.5414 |
| 1 | Pennsylvania | −0.8884 | 0.5711 |
| 1 | Rhode Island | −0.8638 | 1.492 |
| 4 | South Carolina | 1.321 | −1.933 |
| 3 | South Dakota | −1.988 | −0.8233 |
| 4 | Tennessee | 0.9997 | −0.8603 |
| 2 | Texas | 1.355 | 0.4125 |
| 1 | Utah | −0.5506 | 1.472 |
| 3 | Vermont | −2.801 | −1.402 |
| 1 | Virginia | −0.0963 | −0.1997 |
| 1 | Washington | −0.2169 | 0.9701 |
| 3 | West Virginia | −2.109 | −1.425 |
| 3 | Wisconsin | −2.080 | 0.6113 |
| 1 | Wyoming | −0.6294 | −0.3210 |
Merges follow R's hclust convention (negative = row, positive = earlier merge); the last row holds the leaf label only.
View data
| Height | Leaf | Left | Right |
|---|---|---|---|
| 0.2079 | Alabama | −15 | −29 |
| 0.3538 | Alaska | −13 | −32 |
| 0.4331 | Arizona | −14 | −16 |
| 0.4991 | Arkansas | −23 | −49 |
| 0.5408 | California | −20 | −31 |
| 0.5591 | Colorado | −36 | 3 |
| 0.5996 | Connecticut | −37 | −47 |
| 0.6626 | Delaware | −19 | 1 |
| 0.7110 | Florida | −46 | −50 |
| 0.7181 | Georgia | −41 | −48 |
| 0.7465 | Hawaii | −26 | −27 |
| 0.7801 | Idaho | −1 | −18 |
| 0.7860 | Illinois | −35 | −38 |
| 0.7946 | Indiana | −24 | −40 |
| 0.8059 | Iowa | −21 | −30 |
| 0.8158 | Kansas | −12 | 11 |
| 0.8558 | Kentucky | 6 | 13 |
| 0.9523 | Louisiana | −43 | 2 |
| 0.9610 | Maine | −22 | 5 |
| 0.9925 | Maryland | −34 | −45 |
| 1.023 | Massachusetts | −10 | −42 |
| 1.071 | Michigan | −4 | −17 |
| 1.082 | Minnesota | −11 | −44 |
| 1.087 | Mississippi | −7 | −39 |
| 1.102 | Missouri | 12 | 21 |
| 1.172 | Montana | 9 | 22 |
| 1.209 | Nebraska | −5 | −28 |
| 1.220 | Nevada | −33 | 14 |
| 1.273 | New Hampshire | −25 | 7 |
| 1.312 | New Jersey | −3 | 19 |
| 1.330 | New Mexico | 10 | 20 |
| 1.359 | New York | 4 | 8 |
| 1.404 | North Carolina | −6 | 27 |
| 1.555 | North Dakota | 15 | 24 |
| 1.708 | Ohio | −9 | 30 |
| 1.766 | Oklahoma | 16 | 32 |
| 1.830 | Oregon | −8 | 34 |
| 1.956 | Pennsylvania | 17 | 23 |
| 2.226 | Rhode Island | 29 | 38 |
| 2.265 | South Carolina | 18 | 35 |
| 2.742 | South Dakota | 25 | 28 |
| 3.024 | Tennessee | 31 | 36 |
| 3.056 | Texas | −2 | 33 |
| 3.243 | Utah | 37 | 39 |
| 3.532 | Vermont | 40 | 43 |
| 3.772 | Virginia | 26 | 44 |
| 6.527 | Washington | 41 | 45 |
| 7.261 | West Virginia | 42 | 46 |
| 13.653 | Wisconsin | 47 | 48 |
| — | Wyoming | — | — |
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.4683 |
| 1 | 0.4297 |
| 1 | 0.4096 |
| 1 | 0.3996 |
| 1 | 0.3774 |
| 1 | 0.3637 |
| 1 | 0.3374 |
| 1 | 0.3310 |
| 1 | 0.3209 |
| 1 | 0.3180 |
| 1 | 0.2767 |
| 1 | 0.2723 |
| 1 | 0.2587 |
| 1 | 0.2377 |
| 1 | 0.1536 |
| 1 | 0.1244 |
| 1 | 0.0611 |
| 1 | −0.0646 |
| 1 | −0.0847 |
| 2 | 0.4503 |
| 2 | 0.4280 |
| 2 | 0.4194 |
| 2 | 0.4089 |
| 2 | 0.3631 |
| 2 | 0.3174 |
| 2 | 0.3112 |
| 2 | 0.2589 |
| 2 | 0.2462 |
| 2 | 0.1784 |
| 2 | 0.0734 |
| 2 | 0.0545 |
| 3 | 0.5808 |
| 3 | 0.5701 |
| 3 | 0.5617 |
| 3 | 0.5536 |
| 3 | 0.5514 |
| 3 | 0.4921 |
| 3 | 0.4757 |
| 3 | 0.4272 |
| 3 | 0.3389 |
| 3 | 0.2281 |
| 3 | 0.2278 |
| 3 | 0.1120 |
| 4 | 0.5781 |
| 4 | 0.5694 |
| 4 | 0.5091 |
| 4 | 0.4568 |
| 4 | 0.4269 |
| 4 | 0.3752 |
| 4 | 0.3155 |
Clusters
| Cluster | Size | Share | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|
| 1 | 19 | 38.0% | 6.211 | 142.05 | 71.263 | 19.184 |
| 2 | 12 | 24.0% | 10.967 | 264 | 76.500 | 33.608 |
| 3 | 12 | 24.0% | 3.092 | 76 | 52.083 | 11.833 |
| 4 | 7 | 14.0% | 14.671 | 251.29 | 54.286 | 21.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"
))
))
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
| Cluster | Size | Share | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|
| 1 | 19 | 38.0% | 6.211 | 142.05 | 71.263 | 19.184 |
| 2 | 12 | 24.0% | 10.967 | 264 | 76.500 | 33.608 |
| 3 | 12 | 24.0% | 3.092 | 76 | 52.083 | 11.833 |
| 4 | 7 | 14.0% | 14.671 | 251.29 | 54.286 | 21.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.
DIANA: split the widest cluster
ReadDIANADivisive 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 moves to the splinter group while , that is, while it is on average closer to the splinter.
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
View data
| Cluster | Row | PC1 (62%) | PC2 (25%) |
|---|---|---|---|
| 4 | Alabama | 0.9856 | −1.133 |
| 2 | Alaska | 1.950 | −1.073 |
| 2 | Arizona | 1.763 | 0.7460 |
| 1 | Arkansas | −0.1414 | −1.120 |
| 2 | California | 2.524 | 1.543 |
| 2 | Colorado | 1.515 | 0.9876 |
| 1 | Connecticut | −1.359 | 1.089 |
| 1 | Delaware | 0.0477 | 0.3254 |
| 2 | Florida | 3.013 | −0.0392 |
| 4 | Georgia | 1.639 | −1.279 |
| 1 | Hawaii | −0.9127 | 1.570 |
| 3 | Idaho | −1.640 | −0.2110 |
| 2 | Illinois | 1.379 | 0.6818 |
| 1 | Indiana | −0.5055 | 0.1516 |
| 3 | Iowa | −2.254 | 0.1041 |
| 1 | Kansas | −0.7969 | 0.2702 |
| 3 | Kentucky | −0.7509 | −0.9584 |
| 4 | Louisiana | 1.565 | −0.8711 |
| 3 | Maine | −2.397 | −0.3764 |
| 2 | Maryland | 1.763 | −0.4277 |
| 1 | Massachusetts | −0.4862 | 1.474 |
| 2 | Michigan | 2.108 | 0.1554 |
| 3 | Minnesota | −1.693 | 0.6323 |
| 4 | Mississippi | 0.9965 | −2.394 |
| 2 | Missouri | 0.6968 | 0.2634 |
| 3 | Montana | −1.185 | −0.5369 |
| 3 | Nebraska | −1.266 | 0.1940 |
| 2 | Nevada | 2.874 | 0.7756 |
| 3 | New Hampshire | −2.384 | 0.0181 |
| 1 | New Jersey | 0.1816 | 1.450 |
| 2 | New Mexico | 1.980 | −0.1428 |
| 2 | New York | 1.683 | 0.8232 |
| 4 | North Carolina | 1.123 | −2.228 |
| 3 | North Dakota | −2.992 | −0.5991 |
| 1 | Ohio | −0.2260 | 0.7422 |
| 1 | Oklahoma | −0.3118 | 0.2879 |
| 1 | Oregon | 0.0591 | 0.5414 |
| 1 | Pennsylvania | −0.8884 | 0.5711 |
| 1 | Rhode Island | −0.8638 | 1.492 |
| 4 | South Carolina | 1.321 | −1.933 |
| 3 | South Dakota | −1.988 | −0.8233 |
| 4 | Tennessee | 0.9997 | −0.8603 |
| 2 | Texas | 1.355 | 0.4125 |
| 1 | Utah | −0.5506 | 1.472 |
| 3 | Vermont | −2.801 | −1.402 |
| 1 | Virginia | −0.0963 | −0.1997 |
| 1 | Washington | −0.2169 | 0.9701 |
| 3 | West Virginia | −2.109 | −1.425 |
| 3 | Wisconsin | −2.080 | 0.6113 |
| 1 | Wyoming | −0.6294 | −0.3210 |
Divisive tree: a merge's height is the diameter of the cluster that was split there. Merges follow R's hclust convention.
View data
| Height | Leaf | Left | Right |
|---|---|---|---|
| 0.2079 | Alabama | −15 | −29 |
| 0.3538 | Alaska | −13 | −32 |
| 0.4991 | Arizona | −23 | −49 |
| 0.5357 | Arkansas | −14 | −36 |
| 0.5408 | California | −20 | −31 |
| 0.5512 | Colorado | −16 | −38 |
| 0.5996 | Connecticut | −37 | −47 |
| 0.6523 | Delaware | −19 | 1 |
| 0.7047 | Florida | −35 | 4 |
| 0.7110 | Georgia | −46 | −50 |
| 0.7181 | Hawaii | −41 | −48 |
| 0.7591 | Idaho | −12 | −27 |
| 0.7946 | Illinois | −24 | −40 |
| 0.8059 | Indiana | −21 | −30 |
| 0.8493 | Iowa | −1 | −42 |
| 0.8498 | Kansas | 6 | 9 |
| 0.8544 | Kentucky | −43 | 2 |
| 0.8610 | Louisiana | −17 | −26 |
| 0.8680 | Maine | −10 | −18 |
| 1.007 | Maryland | −4 | 10 |
| 1.064 | Massachusetts | −34 | 8 |
| 1.082 | Michigan | −11 | −44 |
| 1.087 | Minnesota | −7 | −39 |
| 1.091 | Mississippi | −22 | 5 |
| 1.097 | Missouri | −45 | 11 |
| 1.143 | Montana | 19 | 15 |
| 1.195 | Nebraska | −33 | 13 |
| 1.209 | Nevada | −5 | −28 |
| 1.223 | New Hampshire | 12 | 3 |
| 1.224 | New Jersey | −3 | 24 |
| 1.413 | New Mexico | −6 | 28 |
| 1.544 | New York | −25 | 17 |
| 1.627 | North Carolina | 14 | 23 |
| 1.662 | North Dakota | 32 | 30 |
| 1.747 | Ohio | 7 | 16 |
| 1.747 | Oklahoma | 25 | 21 |
| 1.819 | Oregon | −8 | 20 |
| 2.080 | Pennsylvania | 22 | 33 |
| 2.116 | Rhode Island | 18 | 29 |
| 2.153 | South Carolina | 37 | 35 |
| 2.361 | South Dakota | 27 | 26 |
| 2.473 | Tennessee | 39 | 36 |
| 2.544 | Texas | −9 | 34 |
| 2.544 | Utah | 31 | 43 |
| 3.120 | Vermont | 40 | 38 |
| 3.324 | Virginia | −2 | 44 |
| 4.445 | Washington | 42 | 45 |
| 4.465 | West Virginia | 41 | 46 |
| 6.138 | Wisconsin | 48 | 47 |
| — | Wyoming | — | — |
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.4731 |
| 1 | 0.4491 |
| 1 | 0.4287 |
| 1 | 0.4157 |
| 1 | 0.4146 |
| 1 | 0.3464 |
| 1 | 0.3285 |
| 1 | 0.3273 |
| 1 | 0.3017 |
| 1 | 0.3016 |
| 1 | 0.3011 |
| 1 | 0.2998 |
| 1 | 0.2849 |
| 1 | 0.2457 |
| 1 | 0.1899 |
| 1 | 0.1247 |
| 1 | −0.1187 |
| 2 | 0.4401 |
| 2 | 0.4177 |
| 2 | 0.4167 |
| 2 | 0.4048 |
| 2 | 0.3651 |
| 2 | 0.3317 |
| 2 | 0.3122 |
| 2 | 0.2696 |
| 2 | 0.2238 |
| 2 | 0.2003 |
| 2 | 0.0736 |
| 2 | 0.0588 |
| 2 | −0.0717 |
| 3 | 0.5438 |
| 3 | 0.5385 |
| 3 | 0.5290 |
| 3 | 0.5260 |
| 3 | 0.5086 |
| 3 | 0.4810 |
| 3 | 0.4788 |
| 3 | 0.3950 |
| 3 | 0.2830 |
| 3 | 0.2615 |
| 3 | 0.1657 |
| 3 | 0.0803 |
| 3 | 0.0638 |
| 4 | 0.5741 |
| 4 | 0.5658 |
| 4 | 0.4988 |
| 4 | 0.4542 |
| 4 | 0.4210 |
| 4 | 0.3701 |
| 4 | 0.2935 |
Clusters
| Cluster | Size | Share | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|
| 1 | 17 | 34.0% | 5.841 | 141.88 | 72.471 | 18.824 |
| 2 | 13 | 26.0% | 10.815 | 257.38 | 76 | 33.192 |
| 3 | 13 | 26.0% | 3.600 | 78.538 | 52.077 | 12.177 |
| 4 | 7 | 14.0% | 14.671 | 251.29 | 54.286 | 21.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"
))
))
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
| Cluster | Size | Share | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|
| 1 | 17 | 34.0% | 5.841 | 141.88 | 72.471 | 18.824 |
| 2 | 13 | 26.0% | 10.815 | 257.38 | 76 | 33.192 |
| 3 | 13 | 26.0% | 3.600 | 78.538 | 52.077 | 12.177 |
| 4 | 7 | 14.0% | 14.671 | 251.29 | 54.286 | 21.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 = 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.
BIRCH: summarize, then cluster
ReadBIRCHBIRCHOne 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 : its count, the vector sum and the sum of squared lengths. The centroid is and the squared radius ; two features merge by adding them.
BIRCH compressed 150 rows into 37 subclusters; Ward clustering of their centers gives 3 clusters.
- Clusters
- 3
- Mean silhouette
- 0.4445
Plots
View data
| Cluster | PC1 (73%) | PC2 (23%) |
|---|---|---|
| 2 | −2.265 | 0.4800 |
| 2 | −2.081 | −0.6741 |
| 2 | −2.364 | −0.3419 |
| 2 | −2.299 | −0.5974 |
| 2 | −2.390 | 0.6468 |
| 2 | −2.076 | 1.489 |
| 2 | −2.444 | 0.0476 |
| 2 | −2.233 | 0.2231 |
| 2 | −2.335 | −1.115 |
| 2 | −2.184 | −0.4690 |
| 2 | −2.166 | 1.044 |
| 2 | −2.326 | 0.1331 |
| 2 | −2.218 | −0.7287 |
| 2 | −2.633 | −0.9615 |
| 2 | −2.199 | 1.860 |
| 2 | −2.262 | 2.686 |
| 2 | −2.208 | 1.484 |
| 2 | −2.190 | 0.4888 |
| 2 | −1.899 | 1.405 |
| 2 | −2.343 | 1.128 |
| 2 | −1.914 | 0.4089 |
| 2 | −2.207 | 0.9241 |
| 2 | −2.774 | 0.4583 |
| 2 | −1.819 | 0.0856 |
| 2 | −2.227 | 0.1373 |
| 2 | −1.952 | −0.6256 |
| 2 | −2.051 | 0.2422 |
| 2 | −2.169 | 0.5271 |
| 2 | −2.140 | 0.3132 |
| 2 | −2.265 | −0.3377 |
| 2 | −2.140 | −0.5045 |
| 2 | −1.832 | 0.4237 |
| 2 | −2.615 | 1.794 |
| 2 | −2.446 | 2.151 |
| 2 | −2.110 | −0.4602 |
| 2 | −2.208 | −0.2061 |
| 2 | −2.045 | 0.6616 |
| 2 | −2.527 | 0.5923 |
| 2 | −2.430 | −0.9042 |
| 2 | −2.170 | 0.2689 |
| 2 | −2.286 | 0.4417 |
| 3 | −1.858 | −2.337 |
| 2 | −2.554 | −0.4791 |
| 2 | −1.964 | 0.4723 |
| 2 | −2.137 | 1.142 |
| 2 | −2.070 | −0.7111 |
| 2 | −2.385 | 1.120 |
| 2 | −2.394 | −0.3862 |
| 2 | −2.229 | 0.9980 |
| 2 | −2.204 | 0.0092 |
| 1 | 1.102 | 0.8630 |
| 1 | 0.7313 | 0.5946 |
| 1 | 1.241 | 0.6163 |
| 3 | 0.4075 | −1.754 |
| 1 | 1.075 | −0.2084 |
| 1 | 0.3887 | −0.5933 |
| 1 | 0.7465 | 0.7730 |
| 3 | −0.4873 | −1.852 |
| 1 | 0.9279 | 0.0322 |
| 1 | 0.0114 | −1.034 |
First 60 of 150 rows.
Leaves are BIRCH subclusters (their centers), not rows. Merges follow R's hclust convention.
View data
| Height | Leaf | Left | Right |
|---|---|---|---|
| 0.3337 | subcluster 1 (15 rows) | −28 | −35 |
| 0.3895 | subcluster 2 (9 rows) | −1 | −5 |
| 0.4962 | subcluster 3 (1 rows) | −13 | −18 |
| 0.5358 | subcluster 4 (1 rows) | −24 | −27 |
| 0.6004 | subcluster 5 (5 rows) | −31 | −36 |
| 0.6038 | subcluster 6 (2 rows) | −12 | −22 |
| 0.6269 | subcluster 7 (16 rows) | −25 | −30 |
| 0.6293 | subcluster 8 (1 rows) | −14 | 3 |
| 0.6409 | subcluster 9 (2 rows) | −20 | −21 |
| 0.6641 | subcluster 10 (3 rows) | −3 | −6 |
| 0.6856 | subcluster 11 (1 rows) | −9 | −15 |
| 0.7210 | subcluster 12 (5 rows) | −17 | 9 |
| 0.8211 | subcluster 13 (6 rows) | −34 | −37 |
| 0.8370 | subcluster 14 (8 rows) | 1 | 4 |
| 0.8994 | subcluster 15 (8 rows) | −2 | 10 |
| 0.9375 | subcluster 16 (4 rows) | −10 | −11 |
| 1.029 | subcluster 17 (5 rows) | −16 | 11 |
| 1.041 | subcluster 18 (4 rows) | −32 | −33 |
| 1.089 | subcluster 19 (1 rows) | −29 | 7 |
| 1.099 | subcluster 20 (4 rows) | −26 | 12 |
| 1.120 | subcluster 21 (1 rows) | −7 | 2 |
| 1.195 | subcluster 22 (6 rows) | 5 | 13 |
| 1.202 | subcluster 23 (3 rows) | −23 | 6 |
| 1.265 | subcluster 24 (4 rows) | −4 | 15 |
| 1.477 | subcluster 25 (7 rows) | 19 | 20 |
| 1.518 | subcluster 26 (1 rows) | −19 | 16 |
| 1.829 | subcluster 27 (3 rows) | 8 | 23 |
| 1.937 | subcluster 28 (6 rows) | 17 | 26 |
| 2.530 | subcluster 29 (1 rows) | 25 | 27 |
| 2.577 | subcluster 30 (4 rows) | 14 | 18 |
| 2.841 | subcluster 31 (4 rows) | 22 | 30 |
| 2.945 | subcluster 32 (1 rows) | −8 | 28 |
| 3.502 | subcluster 33 (2 rows) | 21 | 24 |
| 5.785 | subcluster 34 (2 rows) | 29 | 31 |
| 8.687 | subcluster 35 (1 rows) | 32 | 34 |
| 12.352 | subcluster 36 (2 rows) | 33 | 35 |
| — | subcluster 37 (1 rows) | — | — |
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.5505 |
| 1 | 0.5477 |
| 1 | 0.5442 |
| 1 | 0.5429 |
| 1 | 0.5391 |
| 1 | 0.5391 |
| 1 | 0.5374 |
| 1 | 0.5368 |
| 1 | 0.5312 |
| 1 | 0.5307 |
| 1 | 0.5293 |
| 1 | 0.5270 |
| 1 | 0.5266 |
| 1 | 0.5235 |
| 1 | 0.5182 |
| 1 | 0.5160 |
| 1 | 0.5136 |
| 1 | 0.5112 |
| 1 | 0.4890 |
| 1 | 0.4876 |
| 1 | 0.4855 |
| 1 | 0.4838 |
| 1 | 0.4831 |
| 1 | 0.4766 |
| 1 | 0.4699 |
| 1 | 0.4687 |
| 1 | 0.4572 |
| 1 | 0.4571 |
| 1 | 0.4568 |
| 1 | 0.4565 |
| 1 | 0.4503 |
| 1 | 0.4487 |
| 1 | 0.4463 |
| 1 | 0.4433 |
| 1 | 0.4429 |
| 1 | 0.4360 |
| 1 | 0.4277 |
| 1 | 0.4226 |
| 1 | 0.4142 |
| 1 | 0.4048 |
| 1 | 0.4045 |
| 1 | 0.3972 |
| 1 | 0.3961 |
| 1 | 0.3939 |
| 1 | 0.3938 |
| 1 | 0.3550 |
| 1 | 0.3462 |
| 1 | 0.3411 |
| 1 | 0.3396 |
| 1 | 0.3347 |
| 1 | 0.3330 |
| 1 | 0.3178 |
| 1 | 0.3173 |
| 1 | 0.2842 |
| 1 | 0.2790 |
| 1 | 0.2734 |
| 1 | 0.2719 |
| 1 | 0.2483 |
| 1 | 0.2453 |
| 1 | 0.2272 |
First 60 of 150 rows.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 81 | 54.0% | 6.421 | 2.981 | 5.121 | 1.788 |
| 2 | 49 | 32.7% | 5.016 | 3.451 | 1.465 | 0.2449 |
| 3 | 20 | 13.3% | 5.530 | 2.400 | 3.855 | 1.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"
))
))
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
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 81 | 54.0% | 6.421 | 2.981 | 5.121 | 1.788 |
| 2 | 49 | 32.7% | 5.016 | 3.451 | 1.465 | 0.2449 |
| 3 | 20 | 13.3% | 5.530 | 2.400 | 3.855 | 1.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.
CURE: several shrunk representatives
ReadOne centroid per cluster can't describe a long or bent shape. CURE keeps well-scattered representatives per cluster and pulls each toward the center by a share : . Clusters merge when their closest shrunk representatives are closest.
In the reference's small example, representatives and around center , shrunk with , 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.
ROCK and CHAMELEON: closeness through neighbors
ReadROCK suits categories and baskets. Two rows are neighbors when their similarity passes a threshold , and their link is the number of neighbors they share, . 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 : relative interconnectivity times relative closeness. In the reference's example, and with score 0.128 and 0.405: the closer pair wins. Results hinge on the graph and the first partition.
Where each idea stands in CodeSplash
Read| Entry | In 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.Check your understanding
CheckpointCheck 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
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
: 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 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.
Do it on your own data
In the appUnder 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