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.
What runs in CodeSplash
- Hierarchical clustering Verified in Python and R
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
A tree instead of a number
ReadHierarchical 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 before fitting. You cut the tree afterwards, at a height or at a chosen number of clusters, and you can compare cuts without refitting.
Make a guess
PredictPredict 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?
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.
Cut the tree
ExploreAExplorable · 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.
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.
Four linkages
Read| Linkage | Distance between groups | Tends to give |
|---|---|---|
| Ward | Increase in within-cluster variance | Compact groups of similar size |
| Average | Mean of all pairs | A balance, with moderate chaining |
| Complete | Farthest pair | Tight groups of similar diameter |
| Single | Closest pair | Long 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.
Is the tree faithful?
ReadThe 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.
Read the card
In the appWard 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",
}},
})
Ward on US arrests, cut at = 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.
Check your understanding
CheckpointCheck 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.
Do it on your own data
In the appUnder Find segments, choose Hierarchical clustering. Pick a linkage and whether to cut by number of clusters or by height.
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])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.
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