CDiscover · discover.hierarchical
Hierarchical clustering
How do rows merge into ever larger groups, and where should the tree be cut?
Agglomerative clustering (Ward, complete, average or single linkage) on Euclidean, Manhattan or Gower dissimilarities, cut into k clusters or at a height. Python (scipy) and R (hclust) build the same merge sequence; the dendrogram, the cophenetic correlation and the cut clusters are reported. Two variants: divisive analysis (DIANA, top-down splits by the splinter rule) and BIRCH compression, which summarizes the rows in one pass into small subclusters so Ward and the other linkages run on large data.
A real result
Example “Usarrests ward”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Ward 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 |
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 |
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Usarrests wardml_usarrests · features: Murder, Assault, UrbanPop, Rape · id: state
- Regress k above rowsml_usarrests · features: Murder, Assault, UrbanPop, Rape · id: state
- Iris average heightml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
- Penguins gower completeml_penguins · features: bill_len, bill_dep, island, sex · label: species
- Chick single manhattanml_chickweight · features: weight, Time
- Usarrests divisiveml_usarrests · features: Murder, Assault, UrbanPop, Rape · id: state
- Penguins divisive gower heightml_penguins · features: bill_len, bill_dep, island, sex · label: species
- Iris birch wardml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
In the guides
Where it sits in the decision guides
- Clustering (k-means, hierarchical) · DS & ML Decision Guide · Discover — find structure without labels
What you need
- Featuresnumeric / categorical / boolean · 1–200 columns
- Variables that define similarity.
- Known groupscategorical / boolean · 0–1 column
- Optional — compared with the clusters (adjusted Rand index, AMI, NMI); never used to fit.
- Row labelscategorical / numeric · 0–1 column
- Optional names for the dendrogram leaves and chart points.
Choices you make
model
- Directiondefault agglomerative
Build the tree bottom-up by merging (agglomerative) or top-down by splitting (divisive, DIANA).
- Agglomerative (merge upward)(default) — Starts from single rows and merges the closest clusters by the chosen linkage; the usual choice.
- Divisive (DIANA, split downward) — Starts from all rows and splits the widest cluster, peeling off the rows least like the rest; good at the top-level split.
- Compress firstdefault none
BIRCH summarizes the rows into small subclusters in one pass, then clusters their centers; use it past about 10,000 rows.
- No (every row)(default) — Clusters every row directly; exact, up to 10,000 rows.
- BIRCH subclusters (large data) — Builds a clustering-feature tree of tight subclusters (Euclidean), clusters their centers, and gives each row its nearest center's cluster.
- Subcluster radiusdefault 0.5
Largest radius a BIRCH subcluster may reach on the scaled design; smaller means more, tighter subclusters.
- Linkagedefault ward
How the distance between clusters is measured. Ward makes compact groups; single linkage can chain.
- Ward (minimum variance; R ward.D2)(default) — Merges the pair that adds the least within-cluster variance; gives compact, similar-sized clusters, so it's the usual choice.
- Complete — Measures clusters by their farthest pair; gives compact clusters but is sensitive to outliers.
- Average (UPGMA) — Measures clusters by the mean of all pairs; a balance between single and complete.
- Single — Measures clusters by their closest pair; can follow long curved shapes, but tends to chain.
- Dissimilaritydefault auto
Dissimilarity between rows: Gower handles mixed types; Euclidean and Manhattan suit numbers.
- Automatic (Gower when there are categories, else Euclidean)(default) — Uses Gower when any column is categorical and Euclidean otherwise; the usual choice.
- Euclidean on the scaled design — Straight-line distance on scaled numbers; the standard for numeric data, but sensitive to outliers.
- Manhattan on the scaled design — Sums absolute differences on scaled numbers; less sensitive to outliers than Euclidean.
- Gower (mixed types) — Averages a per-column difference across numbers and categories; pick it for mixed data.
- Cut the treedefault k
Cut the tree into a chosen number of clusters, or at a chosen height.
- Into k clusters(default) — Cuts the tree into the number of clusters you set; pick it when you know how many groups you want.
- At a height — Cuts the tree at the distance you set; pick it when a merge distance has real meaning.
- Clusters (k)default 3
Number of clusters when cutting into k.
- Cut heightdefault 1
Merge height at which the tree is cut, when cutting at a height.
Advanced
- Branching factordefault 50
Most subclusters a node of the BIRCH tree holds before it splits.
preprocess
- Scale numbersdefault standard
Standardize numbers so each counts equally in distances; turn off only when columns already share one unit.
- Standardize (population SD)(default) — Rescales each number to mean 0 and SD 1 so every column counts equally in distances; the safe choice.
- No scaling — Keeps raw values, so wide-ranging columns dominate distances; pick it only when columns share one unit.
- Missing valuesdefault drop
Rows with missing values are left out, or filled with the column median (categories get none).
- Leave the row out(default) — Leaves out rows with a missing value; the clean choice when few are missing.
- Fill with the median (categories → none) — Fills numeric gaps with the median and leaves category gaps as no category; keeps every row, at some cost to the shape.
What it reports
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- n_used
- How many independent units the analysis used; it sets precision and power.
- n_noise
- How many independent units the analysis used; it sets precision and power.
- cophenetic
- The correlation between original distances and the heights at which pairs of rows join in a dendrogram.
- silhouette
- How well each point sits in its cluster compared with the nearest other cluster, from −1 to 1.
- calinski_harabasz
- Between-cluster spread over within-cluster spread. Higher means tighter, better-separated clusters.
- davies_bouldin
- How much each cluster overlaps its most similar neighbor, on average. Lower is better; 0 is the floor.
- linkage_label
- How distances between clusters were measured when merging, e.g. Ward, average or single linkage.
Per group, level or term: size[<cluster>], height[<i>] (the i-th highest merge), mean[<cluster>,<feature>], ari, ami, nmi, divisive_coefficient, n_subclusters, compression
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses scipy; R uses stats.
Default traps between the two languages
- Divisive (DIANA) and the BIRCH tree are written-out twins (codesplash.ml.cluster_partition ↔ codesplashr ml_cluster_partition.R): DIANA reproduces cluster::diana's split heights and divisive coefficient, and the BIRCH tree uses scikit-learn's insertion and split rules (same subclusters as sklearn.cluster.Birch).
- scipy.cluster.hierarchy.linkage and stats::hclust apply the same Lance–Williams updates (Ward = ward.D2), so merge heights agree; exactly tied dissimilarities may merge in a different order.
- cophenetic (≤ 1e-4): with many exactly tied Gower dissimilarities (categorical features) the two libraries merge tied pairs in a different order, which moves a few cophenetic distances; heights and the cut clusters still agree.
The exact script CodeSplash ran for example “Usarrests ward” · 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 exact script CodeSplash ran for example “Usarrests ward” · 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"
))
))
Sources
- Kaufman L, Rousseeuw PJ (1990). Finding Groups in Data. Wiley, ch. 6 (DIANA).
- Zhang T, Ramakrishnan R, Livny M (1996). BIRCH: an efficient data clustering method for very large databases. SIGMOD '96, 103–114.
- Ward JH (1963). Hierarchical grouping to optimize an objective function. JASA 58:236–244.
- Murtagh F, Legendre P (2014). Ward's hierarchical agglomerative clustering method. J Classif 31:274–295.
From the CodeSplash method registry · discover.hierarchical v1.1.0.