Hierarchical and Density-Based Clustering
Hierarchical clustering builds a sequence of nested groups, while density-based methods connect observations according to local neighborhood rules and can leave some unassigned. They offer alternatives to the compact nearest-center groups favored by k-means. They still require choices about distance, scale, and which groups to report. A returned cluster count reflects those choices as well as the data.
Linkage and the shape of a hierarchy
Agglomerative clustering starts with one cluster per observation and repeatedly merges two clusters. Linkage defines how to compare a pair of clusters; the pointwise distance, feature scaling, optional connectivity restrictions, and the stopping or cutting rule also affect the result. With two groups \(A=\{0,1\}\) and \(B=\{3,4\}\), the cross-group distances are 3, 4, 2, and 3. Single linkage uses 2, complete uses 4, and average uses 3.
| Linkage | Distance between clusters | Tendency |
|---|---|---|
| Single | the closest pair of points | connects groups through short paths |
| Complete | the farthest pair of points | favors bounded-diameter groups |
| Average | the mean over all cross pairs | uses all cross-pair distances |
| Ward | increase in within-cluster sum of squares | favors small increases in squared error |
from sklearn.cluster import AgglomerativeClustering, KMeans
from sklearn.datasets import make_moons
from sklearn.metrics import adjusted_rand_score
X, y = make_moons(n_samples=1000, noise=0.06, random_state=0)
for link in ("ward", "complete", "average", "single"):
lab = AgglomerativeClustering(n_clusters=2, linkage=link).fit_predict(X)
print(f"{link:9s} ARI {adjusted_rand_score(y, lab):.4f}")
print(f"{'k-means':9s} ARI "
f"{adjusted_rand_score(y, KMeans(2, n_init=10, random_state=0).fit_predict(X)):.4f}")
# ward ARI 0.3452
# complete ARI 0.3666
# average ARI 0.4457
# single ARI 1.0000
# k-means ARI 0.2533
For these two crescents, single linkage agrees with the generating labels at ARI 1.0000. ARI compares pairwise cluster membership while accounting for chance agreement and does not require matching numeric cluster IDs. Short within-crescent links connect each crescent before the final cross-crescent merge. Ward gives 0.3452 and k-means 0.2533. Their preference for compact groups is poorly matched to this sample, but these two ARIs do not measure how closely the two fitted partitions agree with each other.
Ward chooses the merge with the smallest increase in within-cluster sum of squared distances: \(\Delta(A,B)=\frac{n_A n_B}{n_A+n_B}\|\bar x_A-\bar x_B\|^2\). The counts \(n_A,n_B\) and means \(\bar x_A,\bar x_B\) describe the two groups. This is the same sum-of-squares criterion used by k-means, but Ward makes irreversible greedy merges instead of reassigning points among centers. It need not reproduce a k-means partition. Ward requires Euclidean geometry in these implementations.
What single linkage costs
Single linkageโs short-hop connectivity can join groups through a thin bridge. The next experiment adds twelve observations between two Gaussian clouds and compares the result with single linkage before the bridge is added.
import numpy as np
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import adjusted_rand_score
rng = np.random.default_rng(0)
a = rng.normal([0, 0], 0.5, size=(300, 2))
b = rng.normal([6, 0], 0.5, size=(300, 2))
bridge = np.column_stack([np.linspace(1.2, 4.8, 12), # twelve points
rng.normal(0, 0.05, 12)])
X = np.vstack([a, b, bridge])
y = np.r_[np.zeros(300), np.ones(300), np.full(12, -1)]
real = y >= 0
base_labels = AgglomerativeClustering(n_clusters=2, linkage="single").fit_predict(X[real])
print(f"single without bridge ARI {adjusted_rand_score(y[real], base_labels):.4f}")
for link in ("single", "average", "complete", "ward"):
lab = AgglomerativeClustering(n_clusters=2, linkage=link).fit_predict(X)
print(f"{link:9s} ARI on the real clusters {adjusted_rand_score(y[real], lab[real]):.4f}"
f" sizes {np.bincount(lab)}")
# single without bridge ARI 1.0000
# single ARI on the real clusters 0.0000 sizes [611 1]
# average ARI on the real clusters 1.0000 sizes [306 306]
# complete ARI on the real clusters 1.0000 sizes [311 301]
# ward ARI on the real clusters 1.0000 sizes [310 302]
Single linkage has ARI 1.0 before the bridge. After adding it, the two-cluster cut has sizes 611 and 1, with displayed ARI 0.0000 on the 600 original observations. Average, complete, and Ward retain ARI 1.0 on those observations, but their full cluster sizes differ because they assign bridge points differently. This score excludes the bridge; it does not say that every assignment is unchanged.
This effect is called chaining. At a distance threshold, single-linkage clusters correspond to connected components of the graph joining pairs within that distance. A path can join distant regions even if most cross-region pairs are far apart. Whether one added observation is sufficient depends on the gap and threshold; this experiment uses twelve.
Complete linkage bases a merge on the farthest cross pair, so one short bridging pair alone cannot trigger a low-height merge of two extended groups. It favors bounded-diameter groups but does not mathematically prohibit non-convex arrangements of observations. Average linkage uses every cross pair. These criteria produce different compromises; no linkage is guaranteed to recover every connected shape or to resist every kind of noise.
The dendrogram
A fully built merge tree records all successive merges. Cutting at different heights gives nested partitions, so groups at a lower cut are contained in groups at a higher cut. Equal merge heights can make a horizontal cut skip some cluster counts. A library fit stopped early may not contain the full tree. The next block uses the bridge dataset from the preceding block; run the body examples in order.
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster
Z = linkage(X, method="ward") # the merge tree, computed once
print(f"{'cut height':>11} {'clusters':>9}")
for h in (2, 5, 10, 20, 40):
print(f"{h:11.1f} {len(np.unique(fcluster(Z, h, criterion='distance'))):9d}")
print("last four merge heights:", np.round(Z[-4:, 2], 3))
# cut height clusters
# 2.0 25
# 5.0 11
# 10.0 3
# 20.0 2
# 40.0 2
# last four merge heights: [ 8.807 9.155 12.027 103.541]
The last four Ward merge heights are about 8.807, 9.155, 12.027, and 103.541. After the merge near 12.027 and before the final merge near 103.541, there are two groups. This explains why cuts at both 20 and 40 give two. The five cut counts alone would not identify the location or width of that gap, which is why the code also prints the actual merge heights.
SciPyโs Ward height is \(\sqrt{2\Delta}\), not the raw sum-of-squares increase. For two singleton points at 0 and 2, the merge increases squared error by 2 and has height 2. Heights depend on scaling, linkage, and, for Ward, group sizes. A large gap can guide inspection of a cut, but is not an independent test that the resulting groups are natural populations.
Density-based clustering
For unweighted DBSCAN, an observation is a core point when its epsilon-radius neighborhood contains at least min_samples observations, including itself. Connected core points form groups. A non-core point within epsilon of a core point can join as a border point; other points receive label โ1, or noise. Border points do not propagate connectivity the way core points do, and a border point adjacent to two groups can be assigned differently when input order changes.
For points 0, 0.1, 0.2, and 0.4 on a line, epsilon 0.15 and min_samples=3 make 0.1 a core point: its neighborhood contains the first three observations. Points 0 and 0.2 are border points, and 0.4 is noise. Thus low local neighbor count does not automatically mean noise. The returned number of groups, including possibly zero, follows these rules and parameter settings.
import numpy as np
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_moons
from sklearn.metrics import adjusted_rand_score
X, y = make_moons(n_samples=1000, noise=0.06, random_state=0)
for eps in (0.05, 0.10, 0.15, 0.20, 0.30, 0.50):
lab = DBSCAN(eps=eps, min_samples=5).fit_predict(X)
n_clusters = len(set(lab)) - (1 if -1 in lab else 0)
print(f"eps {eps:4.2f} clusters {n_clusters:3d} noise {np.mean(lab == -1):.3f}"
f" ARI {adjusted_rand_score(y, lab):.4f}")
# eps 0.05 clusters 13 noise 0.116 ARI 0.1683
# eps 0.10 clusters 2 noise 0.002 ARI 0.9960
# eps 0.15 clusters 2 noise 0.000 ARI 1.0000
# eps 0.20 clusters 2 noise 0.000 ARI 1.0000
# eps 0.30 clusters 1 noise 0.000 ARI 0.0000
# eps 0.50 clusters 1 noise 0.000 ARI 0.0000
At epsilon 0.15 and 0.20, DBSCAN matches both crescents with no noise labels, although no parameter directly requests two groups. At 0.05 it returns thirteen clusters and rejects 11.6% of observations; at 0.30 it returns one cluster. The ARI is computed on every row and treats all โ1 labels as one predicted group. That is an evaluation convention, not a claim that rejected points form a coherent cluster.
Of the radii tested, 0.10 through 0.20 perform well on these labels. The sweep does not locate every successful radius. Epsilon is measured in the units of the chosen distance, and min_samples changes which points can connect groups.
DBSCAN provides a rejection category as part of its clustering rule. Its clusters partition the assigned subset, while noise rows remain outside those clusters. Treating all noise as one additional label yields a partition for bookkeeping, but does not make it a meaningful group. Downstream use should specify how rejected observations are handled and report their fraction.
Different density scales
import numpy as np
from sklearn.cluster import DBSCAN, HDBSCAN
from sklearn.metrics import adjusted_rand_score
rng = np.random.default_rng(0)
X = np.vstack([rng.normal([0, 0], 0.12, size=(700, 2)), # tight
rng.normal([2.0, 0], 0.45, size=(700, 2)), # medium
rng.normal([6.0, 0], 1.30, size=(700, 2))]) # diffuse
y = np.r_[np.zeros(700), np.ones(700), 2 * np.ones(700)]
print(f"{'eps':>6} {'clusters':>9} {'noise':>7} {'ARI':>8}")
for eps in (0.15, 0.25, 0.40, 0.70, 1.00, 1.50):
lab = DBSCAN(eps=eps, min_samples=10).fit_predict(X)
n = len(set(lab)) - (1 if -1 in lab else 0)
print(f"{eps:6.2f} {n:9d} {np.mean(lab == -1):7.3f} {adjusted_rand_score(y, lab):8.4f}")
for mcs in (20, 50):
lab = HDBSCAN(min_cluster_size=mcs, min_samples=10, copy=True).fit_predict(X)
n = len(set(lab)) - (1 if -1 in lab else 0)
print(f"HDBSCAN mcs={mcs:3d} clusters {n:2d} noise {np.mean(lab == -1):.3f}"
f" ARI {adjusted_rand_score(y, lab):.4f}")
print(" retained by generating group:", np.round([np.mean(lab[y == j] >= 0) for j in range(3)], 3))
# eps clusters noise ARI
# 0.15 4 0.375 0.8399
# 0.25 6 0.177 0.8161
# 0.40 4 0.050 0.9092
# 0.70 1 0.007 0.0002
# 1.00 1 0.001 0.0000
# 1.50 1 0.000 0.0000
# HDBSCAN mcs= 20 clusters 3 noise 0.071 ARI 0.9036
# retained by generating group: [1. 0.993 0.794]
# HDBSCAN mcs= 50 clusters 3 noise 0.071 ARI 0.9036
# retained by generating group: [1. 0.993 0.794]
These generating groups have standard deviations 0.12, 0.45, and 1.30. The six tested DBSCAN radii yield 4, 6, 4, 1, 1, and 1 groups. Small radii reject or fragment sparse regions, while larger radii connect groups through intervening observations. This sweep does not prove that no radius can return three groups. Different densities can make a global radius difficult to choose, but sufficiently separated unequal-density groups can still be recovered by DBSCAN.
HDBSCAN forms a hierarchy using mutual-reachability distance: for the default scaling, it takes the maximum of the two pointsโ core distances and their ordinary distance. A core distance is the neighbor radius associated with min_samples. The hierarchy is condensed using min_cluster_size, and the default excess-of-mass selection favors stable groups using membership and persistence across density levels. It is not simply choosing the widest interval on the epsilon axis. Both parameters matter. The code fixes min_samples=10 while changing the minimum cluster size; leaving it unset in scikit-learn would change it with that size.
Both HDBSCAN settings return three groups, reject 7.1% of rows, and give ARI 0.9036. Retention is about 100%, 99.3%, and 79.4% in the tight, medium, and diffuse generating groups. The count is right while many diffuse-group observations are excluded. DBSCAN at epsilon 0.40 has four groups and slightly higher all-row ARI, 0.9092. Count, pairwise agreement, and retention answer different questions. Report them together; reporting ARI only on retained rows would also need the retained fraction and an explanation of which rows were excluded.
References
- Ester, M., Kriegel, H.-P., Sander, J., & Xu, X. (1996). A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise. KDD.
- Campello, R. J. G. B., Moulavi, D., & Sander, J. (2013). Density-Based Clustering Based on Hierarchical Density Estimates. PAKDD.
- scikit-learn documentation. sklearn.cluster.HDBSCAN
- SciPy documentation. scipy.cluster.hierarchy.linkage
- Tibshirani, Walther, and Hastie (2001). Estimating the number of clusters in a data set via the gap statistic
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
