Skip to content

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.

Verified in Python and R Python and R agree to 10 decimals

A real result

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

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

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

Clusters
4
Mean silhouette
0.3370

Plots

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

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

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

Clusters

ClusterSizeShareMurderAssaultUrbanPopRape
11938.0%6.211142.0571.26319.184
21224.0%10.96726476.50033.608
31224.0%3.0927652.08311.833
4714.0%14.671251.2954.28621.686
Python

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

Clusters
4
Mean silhouette
0.3370

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

Clusters

ClusterSizeShareMurderAssaultUrbanPopRape
11938.0%6.211142.0571.26319.184
21224.0%10.96726476.50033.608
31224.0%3.0927652.08311.833
4714.0%14.671251.2954.28621.686

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

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

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.