Skip to content

Hierarchical clustering and reading a dendrogram

Build a tree of merges instead of fixing k in advance, cut it where you need to, and see how the linkage changes the tree.

Applied ~11 min9 steps

What runs in CodeSplash

You will be able to

  • Read merge heights on a dendrogram and cut it into clusters
  • Choose between Ward, average, complete and single linkage
  • Interpret the cophenetic correlation

Read first

01

A tree instead of a number

Read

Hierarchical clustering starts with every row alone and repeatedly merges the two closest groups, until only one remains. The record of those merges is a dendrogramDendrogramA tree of successive merges, where the height of each join shows how far apart the two groups were..

The height of each join shows how far apart the two groups were when they merged. A long vertical stretch with no joins means the groups below it are well separated.

You don't choose kk before fitting. You cut the tree afterwards, at a height or at a chosen number of clusters, and you can compare cuts without refitting.

02

Make a guess

Predict

Predict first

Two tight groups are joined by a thin chain of points. Which linkageLinkageThe rule hierarchical clustering uses to measure the distance between two groups of rows. is more likely to treat them as one long cluster?

WardSingleBoth the same
Reveal

Single linkage. It measures the distance between groups by their closest pair, so a chain of neighboring points bridges the gap. Ward merges to minimize the increase in within-cluster variance and tends to give compact groups of similar size.

03

Cut the tree

Explore

AExplorable · Cut a dendrogram

How do you choose clusters from a tree of merges?

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

16
How sure?

Data

Linkage

0.12
36
cut

Commit your prediction above to see the result

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

Make your prediction to see the result.

On three round clusters, drag the cut to recover them exactly. Then try the chain data and compare Ward with Single. Turn on the break-it toggle to see a chain collapse the clusters.

04

Four linkages

Read
LinkageDistance between groupsTends to give
WardIncrease in within-cluster varianceCompact groups of similar size
AverageMean of all pairsA balance, with moderate chaining
CompleteFarthest pairTight groups of similar diameter
SingleClosest pairLong chains; can find odd shapes

Ward is the default, and its variance reasoning assumes Euclidean distances. If your data has categories and you use GowerGower distanceA distance for mixed tables that scales each column to 0–1, compares it, and averages over the columns. distance, prefer average or complete linkage.

05

Is the tree faithful?

Read

The cophenetic correlationCophenetic correlationThe correlation between original distances and the heights at which pairs of rows join in a dendrogram. compares original distances between rows with the height at which they first join in the tree. Near 1 means the tree preserves the distances well.

On iris with average linkage it's 0.854. On chick weights with single linkage it's only 0.387, so that tree says little about the original distances.

It measures the tree, not the clusters. A faithful tree doesn't guarantee that any cut gives useful groups.

06

Read the card

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

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

Clusters
4
Mean silhouette
0.3370

Plots

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

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

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

Clusters

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

# %% Setup
library(codesplashr)

# %% Data
FEATURES <- c("Murder", "Assault", "UrbanPop", "Rape")
LABEL <- NULL  # known groups (external validation only)
ROW_ID <- "state"  # row labels for charts
SEED <- 42
KINDS <- list(
  Murder = "numeric",
  Assault = "numeric",
  UrbanPop = "numeric",
  Rape = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.parquet", col_select = unique(c(FEATURES, LABEL, ROW_ID))))
n_input <- nrow(df)
prep <- cs_ml_cluster_prepare(df, FEATURES, KINDS, LEVELS, missing = "drop", scale = "standard")
X <- prep$X; rows <- prep$rows; names_ <- prep$names; frame <- prep$frame
warnings <- list()
if (length(rows) < n_input) {
  warnings <- c(warnings, sprintf("%d of %d rows were left out because a feature was missing.", n_input - length(rows), n_input))
}
if (length(rows) < 3) stop("Clustering needs at least three rows with every feature present.")
truth <- if (!is.null(LABEL)) as.character(frame[[LABEL]]) else NULL
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.hierarchical/usarrests_ward/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL

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

# %% Canonical labels and validation
labels <- cs_ml_canonical(raw)
ids <- sort(unique(labels[labels != -1]))
k <- length(ids)
values$k <- k
values$n_noise <- sum(labels == -1)
if (!is.null(centers)) {
  cid <- if (is.null(center_ids)) seq_len(nrow(centers)) - 1L else center_ids
  raw_of <- vapply(ids, function(c) raw[which(labels == c)[1]], numeric(1))
  centers <- centers[match(raw_of, cid), , drop = FALSE]
  for (i in seq_along(ids)) for (j in seq_along(names_)) {
    values[[sprintf("center[%d,%s]", ids[i], names_[j])]] <- centers[i, j]
  }
}
sz <- cs_ml_cluster_sizes(labels)
for (c in names(sz)) values[[sprintf("size[%s]", c)]] <- sz[[c]]
check <- cs_ml_cluster_validation(X, labels, truth, D = D, cap = 3000, seed = SEED)
widths <- check$.widths
check$.widths <- NULL
values <- c(values, check)
profile_rows <- list()
for (c in ids) {
  member <- labels == c
  row <- list(cluster = c, size = sum(member), share = mean(member))
  for (f in FEATURES) {
    if (identical(KINDS[[f]], "numeric")) {
      m <- mean(suppressWarnings(as.numeric(frame[[f]]))[member], na.rm = TRUE)
      row[[f]] <- m
      values[[sprintf("mean[%d,%s]", c, f)]] <- m
    } else {
      v <- as.character(frame[[f]])[member]
      v <- v[!is.na(v)]
      top <- if (length(v)) sort(table(v), decreasing = TRUE) else NULL
      row[[f]] <- if (length(top)) sprintf("%s (%.0f%%)", names(top)[1], 100 * top[[1]] / sum(member)) else ""
    }
  }
  profile_rows[[length(profile_rows) + 1L]] <- row
}
tables <- c(list(list(
  key = "clusters", title = "Clusters",
  columns = c(list(list(key = "cluster", label = "Cluster", type = "integer"),
                   list(key = "size", label = "Size", type = "integer"),
                   list(key = "share", label = "Share", type = "percent")),
              lapply(FEATURES, function(f) list(key = f, label = f, type = if (identical(KINDS[[f]], "numeric")) "number" else "string"))),
  rows = profile_rows
)), tables)

# %% Labels file and charts
path <- do.call(cs_ml_write_labels, c(list(out, rows, labels), extra))
name_of <- function(c) as.character(c)  # noise stays "-1" (drawn gray, listed last)
pr <- cs_ml_project2(X, centers, names_)
show <- cs_ml_even_sample(length(rows))
xs <- pr$P[show + 1L, 1]; ys <- pr$P[show + 1L, 2]
cl <- name_of(labels[show + 1L])
cent <- rep(FALSE, length(show))
lab <- if (!is.null(ROW_ID)) as.character(frame[[ROW_ID]])[show + 1L] else NULL
if (!is.null(pr$C)) {
  xs <- c(xs, pr$C[, 1]); ys <- c(ys, pr$C[, 2])
  cl <- c(cl, name_of(ids)); cent <- c(cent, rep(TRUE, length(ids)))
  if (!is.null(lab)) lab <- c(lab, sprintf("center %d", ids))
}
level_names <- c(as.character(ids), if (values$n_noise > 0) "-1")
charts <- c(list(cs_chart(
  "clusters", "cluster-scatter", "Clusters",
  list(x = cs_col(pr$labels[1], xs, "numeric"), y = cs_col(pr$labels[2], ys, "numeric"),
       cluster = cs_col("Cluster", cl, "categorical", levels = level_names),
       centroid = if (!is.null(pr$C)) cs_col("Center", cent, "boolean"),
       label = if (!is.null(lab)) cs_col("Row", lab, "categorical")),
  note = if (length(show) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(show), big.mark = ","), format(length(rows), big.mark = ","))
)), charts)
if (!is.nan(values$silhouette)) {
  wl <- labels[widths$pick + 1L]
  o <- order(wl, -widths$width)
  charts[[length(charts) + 1L]] <- cs_chart(
    "silhouette", "silhouette-plot", "Silhouette widths",
    list(cluster = cs_col("Cluster", as.character(wl[o]), "categorical", levels = as.character(ids)),
         width = cs_col("Silhouette width", widths$width[o], "numeric")),
    note = if (length(widths$pick) == sum(labels != -1)) NULL else sprintf("%s rows sampled for the silhouette.", format(length(widths$pick), big.mark = ","))
  )
}

# %% Result
if (is.null(summary)) {
  summary <- sprintf("%d cluster%s in %s rows", k, if (k != 1) "s" else "", format(length(rows), big.mark = ","))
  if (values$n_noise > 0) summary <- paste0(summary, sprintf(" (%s noise points)", format(values$n_noise, big.mark = ",")))
  if (!is.nan(values$silhouette)) summary <- paste0(summary, sprintf("; mean silhouette %.2f", values$silhouette))
  summary <- paste0(summary, ".")
}
cs_publish(list(
  title = "Hierarchical clustering",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = list(list(key = "k", label = "Clusters", value = k, format = "integer"),
                    list(key = "silhouette", label = "Mean silhouette", value = values$silhouette)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = path, format = "parquet")),
  model = list(kind = "clusterer", features = I(names_), params = list(
    direction = "agglomerative",
    compress = "none",
    threshold = 0.5,
    branching = 50,
    linkage = "ward",
    distance = "auto",
    cut = "k",
    k = 4,
    height = 1,
    scale = "standard",
    missing = "drop"
  ))
))
Python

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

Clusters
4
Mean silhouette
0.3370

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

Clusters

ClusterSizeShareMurderAssaultUrbanPopRape
11938.0%6.211142.0571.26319.184
21224.0%10.96726476.50033.608
31224.0%3.0927652.08311.833
4714.0%14.671251.2954.28621.686
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Hierarchical clustering
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.hierarchical 1.1.0 · spec e1102c6213753e0b
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.stats.rng import Rng
from scipy.cluster.hierarchy import cophenet, fcluster, linkage
from scipy.spatial.distance import pdist, squareform

# %% Data
FEATURES = ["Murder", "Assault", "UrbanPop", "Rape"]
LABEL = None  # known groups (external validation only)
ROW_ID = "state"  # row labels for charts
SEED = 42
KINDS = {
    "Murder": "numeric",
    "Assault": "numeric",
    "UrbanPop": "numeric",
    "Rape": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=list(dict.fromkeys(FEATURES + [c for c in (LABEL, ROW_ID) if c])))
n_input = len(df)
X, rows, names, frame = csc.prepare(df, FEATURES, KINDS, LEVELS, missing="drop", scale="standard")
warnings = []
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a feature was missing.")
if len(rows) < 3:
    raise ValueError("Clustering needs at least three rows with every feature present.")
truth = frame[LABEL].astype("object").to_numpy() if LABEL else None
out = csml.out_dir("target/academy-parity/run-8142/discover.hierarchical/usarrests_ward/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None

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

# %% Canonical labels and validation
labels = csc.canonical(raw)
ids = [int(c) for c in sorted(set(labels.tolist())) if c != -1]
k = len(ids)
values["k"] = k
values["n_noise"] = int(np.sum(labels == -1))
if centers is not None:
    # reorder centers to canonical ids: the raw id of each canonical cluster
    raw_of = {c: raw[np.flatnonzero(labels == c)[0]] for c in ids}
    pos = {int(r): i for i, r in enumerate(center_ids if center_ids is not None else range(len(centers)))}
    centers = np.array([centers[pos[int(raw_of[c])]] for c in ids])
    for c, row in zip(ids, centers):
        for name, v in zip(names, row):
            values[f"center[{c},{name}]"] = float(v)
for c, m in csc.sizes(labels).items():
    values[f"size[{c}]"] = m
check = csc.validation(X, labels, truth, D=D, cap=3000, seed=SEED)
widths, picked = check.pop("_widths")
values.update(check)
# per-cluster means of numeric features in their own units (interpretation)
profile_rows = []
for c in ids:
    member = labels == c
    row = {"cluster": c, "size": int(member.sum()), "share": float(member.mean())}
    for f in FEATURES:
        if KINDS[f] == "numeric":
            m = float(np.nanmean(pd.to_numeric(frame[f], errors="coerce").to_numpy(dtype=np.float64)[member]))
            row[f] = m
            values[f"mean[{c},{f}]"] = m
        else:
            top = pd.Series(frame[f].astype("object").to_numpy()[member]).dropna().astype(str).value_counts()
            row[f] = f"{top.index[0]} ({top.iloc[0] / member.sum():.0%})" if len(top) else ""
    profile_rows.append(row)
tables.insert(0, {
    "key": "clusters",
    "title": "Clusters",
    "columns": [
        {"key": "cluster", "label": "Cluster", "type": "integer"},
        {"key": "size", "label": "Size", "type": "integer"},
        {"key": "share", "label": "Share", "type": "percent"},
    ]
    + [{"key": f, "label": f, "type": "number" if KINDS[f] == "numeric" else "string"} for f in FEATURES],
    "rows": profile_rows,
})

# %% Labels file and charts
path = csc.write_labels(out, rows, labels, **extra)
name_of = lambda c: str(c)  # noqa: E731  — noise stays "-1" (drawn gray, listed last)
P, C, axes = csc.project2(X, centers, names)
show = csc.even_sample(len(rows))
point_labels = [str(v) for v in frame[ROW_ID].astype("object").to_numpy()[show]] if ROW_ID else None
xs, ys = list(P[show, 0]), list(P[show, 1])
cl = [name_of(c) for c in labels[show]]
cent = [False] * len(show)
lab = point_labels
if C is not None:
    xs += list(C[:, 0])
    ys += list(C[:, 1])
    cl += [name_of(c) for c in ids]
    cent += [True] * len(ids)
    lab = None if lab is None else lab + [f"center {c}" for c in ids]
level_names = [str(c) for c in ids] + (["-1"] if values["n_noise"] else [])
charts.insert(0, cs.chart(
    "clusters", "cluster-scatter", "Clusters",
    {
        "x": cs.col(axes[0], xs, "numeric"),
        "y": cs.col(axes[1], ys, "numeric"),
        "cluster": cs.col("Cluster", cl, "categorical", levels=level_names),
        "centroid": cs.col("Center", cent, "boolean") if C is not None else None,
        "label": cs.col("Row", lab, "categorical") if lab is not None else None,
    },
    note=None if len(show) == len(rows) else f"{len(show):,} of {len(rows):,} rows shown.",
))
if not np.isnan(values["silhouette"]):
    wl = labels[picked]
    order = np.lexsort((-widths, wl))
    charts.append(cs.chart(
        "silhouette", "silhouette-plot", "Silhouette widths",
        {"cluster": cs.col("Cluster", [str(c) for c in wl[order]], "categorical", levels=[str(c) for c in ids]),
         "width": cs.col("Silhouette width", list(widths[order]), "numeric")},
        note=None if len(picked) == int(np.sum(labels != -1)) else f"{len(picked):,} rows sampled for the silhouette.",
    ))

# %% Result
if summary is None:
    summary = f"{k} cluster{'s' if k != 1 else ''} in {len(rows):,} rows"
    if values["n_noise"]:
        summary += f" ({values['n_noise']:,} noise points)"
    if not np.isnan(values["silhouette"]):
        summary += f"; mean silhouette {values['silhouette']:.2f}"
    summary += "."
cs.publish({
    "title": "Hierarchical clustering",
    "engine": cs.engine_info("scipy", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "k", "label": "Clusters", "value": k, "format": "integer"},
        {"key": "silhouette", "label": "Mean silhouette", "value": values["silhouette"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": path, "format": "parquet"}],
    "model": {"kind": "clusterer", "features": names, "params": {
        "direction": "agglomerative",
        "compress": "none",
        "threshold": 0.5,
        "branching": 50,
        "linkage": "ward",
        "distance": "auto",
        "cut": "k",
        "k": 4,
        "height": 1,
        "scale": "standard",
        "missing": "drop",
    }},
})

Ward on US arrests, cut at kk = 4: silhouette 0.337 and cophenetic correlation 0.698.

With only 50 rows, you can read every state on the tree. That's a real strength of this method on small data. With many thousands of rows, the distance matrix gets expensive and the leaves become unreadable.

07

Check your understanding

Checkpoint

Check yourself

On a dendrogram, what does the height where two branches join tell you?

Show the answer

Answer: a

Height is merge distance. Left-to-right order is partly arbitrary, so don't read closeness from how near two leaves appear along the axis, only from where they join.

Check yourself

What does changing the cut height require?

Show the answer

Answer: a

The tree records every merge. That makes it cheap to compare 3, 4 or 5 clusters from one fit.

Check yourself

Hierarchical merges can't be undone. What follows from that?

Show the answer

Answer: a

Greedy merging is deterministic and doesn't reconsider. k-means can move a row between clusters later, while a tree never revisits a merge.

08

Do it on your own data

In the app

Under Find segments, choose Hierarchical clustering. Pick a linkage and whether to cut by number of clusters or by height.

Python
import pandas as pd
from scipy.cluster.hierarchy import cophenet, fcluster, linkage
from scipy.spatial.distance import pdist
from sklearn.preprocessing import StandardScaler

df = pd.read_csv("usarrests.csv")
X = StandardScaler().fit_transform(df[["Murder", "Assault", "UrbanPop", "Rape"]])
Z = linkage(X, method="ward")
print(cophenet(Z, pdist(X))[0])
print(fcluster(Z, t=4, criterion="maxclust")[:10])
R
df <- read.csv("usarrests.csv")
X <- scale(df[, c("Murder", "Assault", "UrbanPop", "Rape")])
d <- dist(X)
hc <- hclust(d, method = "ward.D2")
cor(cophenetic(hc), d)
head(cutree(hc, k = 4), 10)

In R, ward.D2 is the one that matches Ward's criterion on unsquared distances. The older ward.D needs squared distances, which is a common trap.

09

Recap

Recap
  • A dendrogram records every merge, and height is the distance at merge.
  • Linkage changes the shape of what you find; single linkage chains.
  • Cophenetic correlation says how faithful the tree is, not how useful a cut will be.

Concepts in this lesson