Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningUnsupervised Learning

Hierarchical and density clustering

P3.C645 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

Hierarchical clustering shows groups at every scale in one tree, and DBSCAN finds groups of any shape and marks the points that belong to none, so neither needs the number of clusters in advance.

Before this: k-means clustering, Features, scaling and data leakage, k-Nearest Neighbors

After this lesson you can

  • Run agglomerative clustering by hand on a handful of points with single, complete, average and Ward linkage, and read the merge heights off a dendrogram
  • Cut a dendrogram at a height or at k clusters, and explain why single linkage chains and complete linkage prefers compact groups
  • Classify points as core, border or noise for a given radius and min_samples, build DBSCAN clusters from them, and choose the radius with a k-distance plot as a heuristic
  • Choose between k-means, Gaussian mixtures, hierarchical clustering and DBSCAN, and score a clustering with the silhouette (no labels) and the adjusted Rand index (with labels)

You have a cloud of points on a page and no labels. How many groups are there? A person may see three, but a program needs a rule. k-means (P3.C1) asks you for the number of groups first, assigns each point to the nearest of k centres, and moves each centre to the mean of its points. That rule gives round groups, and it can cut a curved group in half: on two interleaved half-moons it fails, as P3.C1 shows.

This lesson covers two methods that start from a different idea. Hierarchical clustering does not choose the number of groups at the start. It builds a whole tree of groupings, from every point alone to one big group, and you choose where to cut. DBSCAN defines a group as a crowded region and calls the points in empty regions noise.

Neither method minimizes a single overall loss, the way k-means minimizes the within-cluster sum of squares. Single, complete and average linkage and DBSCAN are procedures with a rule, and Ward only takes the cheapest next merge, one step at a time. The quality of the answer has to be judged afterwards. A later section shows how.

The picture: a dendrogram building up

The widget has made-up points in the plane. Press Step to merge the two closest clusters. The scatter plot shows the current clusters, and the dendrogram below it grows: each U-shaped line joins two clusters at a height equal to the distance at which they merged. The dashed orange line is the cut. Drag its round handle (or focus it and press the arrow keys) to cut the tree at a different height and see which clusters that gives.

Dendrogram building up

Linkage:
02468100246810feature 1feature 2

Every point is its own cluster. Press Step to merge the two closest clusters.

01234merge height

Leaves (bottom) are the points, with the same colour and shape as in the scatter. Solid lines are merges done; dotted lines are merges still to come.

Merges done: 0 of 16
Clusters now: 17
Cut height: 0
Sizes: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1

The points are made up. Clusters are told apart by colour and by marker shape, and a point that is alone is a hollow grey circle. Merge heights use the SciPy convention (for Ward, the square root of twice the increase in within-cluster sum of squares).

Agglomerative clustering on made-up points, one merge at a time. Clusters are shown by colour and by marker shape, and a point still alone is a hollow grey circle. The dendrogram grows to each merge height, and the cut line sets how many merges are done. The DBSCAN tab shows core points (large, filled), border points (small, hollow) and noise (crosses) for a radius ε and a min_samples value.

Things to try:

  • Blobs, any linkage. Press Step 12 times. The three blobs of 5 points are complete, and every merge so far was at a height of at most 1.21.2 (single linkage). The next merge is at 3.563.56, a big jump. Cut in that gap and you get 5 clusters: the three blobs and the two outliers as single points. Cut lower and you split the blobs.
  • Chain between blobs, single versus complete. With single linkage the bridge of close points is absorbed early, so the tree has no tall merge in it: the top merge height is 1.381.38, hardly more than the 1.061.06 before it. Cut at 3 clusters and the groups have 11, 7 and 1 points, so one straggler is peeled off. With complete linkage, the same cut gives groups of 7, 7 and 5 points (the two blobs and the bridge).
  • Two moons. Single linkage cut at 2 clusters gives exactly the two moons (11 points each), although the last merge, at 1.541.54, is only a little taller than the one before it, at 1.441.44, so the tree gives little warning. Switch to complete, average or Ward and the cut at 2 clusters gives groups of 12 and 10 points that mix the two moons.
  • DBSCAN tab. On two moons, set min_samples to 33 and slide ε. At 1.51.5 the two moons are two clusters with no noise. At 1.21.2 they are still two clusters but five points are noise. At 1.01.0 only 7 of the 22 points are still in clusters. Move the probe slider to see, for each point in turn, how many points lie within ε of it (counting itself) and whether it is core, border or noise.

Agglomerative clustering

Agglomerative means “gathering together”. The algorithm is short:

  1. Start with every point as its own cluster, so nn points give nn clusters.
  2. Find the two clusters that are closest, and merge them.
  3. Repeat until one cluster is left. That takes n−1n-1 merges.

The one thing missing is a definition of the distance between two clusters. Points have an obvious distance; clusters need a rule. That rule is the linkage.

Four linkages

For clusters AA and BB, with d(a,b)d(a,b) the distance between two points:

  • Single linkage. The distance of the nearest pair: min⁡a∈A, b∈Bd(a,b)\min_{a\in A,\,b\in B}d(a,b). Two clusters are close if any one point of each is close.
  • Complete linkage. The distance of the farthest pair: max⁡a∈A, b∈Bd(a,b)\max_{a\in A,\,b\in B}d(a,b). Two clusters are close only if every point of one is close to every point of the other.
  • Average linkage. The mean of all the pair distances between the two clusters.
  • Ward linkage. Merge the pair of clusters whose union increases the total within-cluster sum of squares the least. It is the hierarchical cousin of k-means, since that is the quantity k-means minimizes. Ward is defined for Euclidean distances (SciPy says the result is wrong if the distances are not Euclidean).

A worked example you can do by hand

Five made-up points on a line, at positions 0,2,3,6,100, 2, 3, 6, 10. Single and complete linkage will give different trees on the same data, and every step below is a distance you can read off the line.

Single linkage (nearest pair):

  1. The closest pair of points is 22 and 33, distance 11. Merge them at height 11.
  2. The cluster {2,3}\{2,3\} is 22 from the point 00 (nearest pair 00 and 22), 33 from 66, and the point 66 is 44 from 1010. The smallest is 22: merge 00 into it at height 22.
  3. Now {0,2,3}\{0,2,3\} is 33 from the point 66 (nearest pair 33 and 66), and 66 is 44 from 1010. Merge at height 33.
  4. Last, the point 1010 joins {0,2,3,6}\{0,2,3,6\} at height 44 (nearest pair 66 and 1010).

The heights are 1,2,3,41, 2, 3, 4: each merge adds one point to the same growing cluster. This is the chaining effect, and the tree has no gap that says “two groups”.

Complete linkage (farthest pair):

  1. {2,3}\{2,3\} at height 11, as before.
  2. The point 00 is at distance 33 from {2,3}\{2,3\} (farthest pair 00 and 33). The point 66 is 44 from {2,3}\{2,3\} (farthest pair 22 and 66), and 44 from 1010. The smallest is 33: merge 00 into {2,3}\{2,3\} at height 33.
  3. Now {0,2,3}\{0,2,3\} and 66 are 66 apart, but 66 and 1010 are only 44 apart. Merge {6,10}\{6,10\} at height 44.
  4. The two clusters {0,2,3}\{0,2,3\} and {6,10}\{6,10\} are 1010 apart at their farthest pair, so they merge last at height 1010.

The heights are 1,3,4,101, 3, 4, 10, and the last merge is much taller than the rest. Cut just below it and you get two clear groups.

The same points, two linkages, two different 2-cluster answers:

  • Single, cut at height 3.53.5: {0,2,3,6}\{0,2,3,6\} and {10}\{10\}.
  • Complete, cut at height 3.53.5: {0,2,3}\{0,2,3\}, {6}\{6\} and {10}\{10\}. Cut at 2 clusters instead (between 44 and 1010): {0,2,3}\{0,2,3\} and {6,10}\{6,10\}.

Average linkage on the same points merges {2,3}\{2,3\} at 11, the point 00 into it at 2.52.5 (the mean of 22 and 33), then {6,10}\{6,10\} at 44, then the two groups at 38/6=6.33338/6=6.333 (the mean of the six pair distances 6,4,3,10,8,76,4,3,10,8,7). Ward, with the merge increases in sum of squares, gives 0.50.5, 4.1674.167, 88 and 48.13348.133 for the same four merges, which add up to the total sum of squares about the mean, 60.860.8. For two clusters AA and BB, the increase in the within-cluster sum of squares equals nAnBnA+nB∥cA−cB∥2\dfrac{n_An_B}{n_A+n_B}\lVert\mathbf{c}_A-\mathbf{c}_B\rVert^2, where cA\mathbf{c}_A and cB\mathbf{c}_B are the cluster centres. For {0}\{0\} joining {2,3}\{2,3\}: 1⋅23(2.5)2=4.167\tfrac{1\cdot2}{3}(2.5)^2=4.167.

Reading a dendrogram

A dendrogram draws the merge history. The bottom row of leaves is the points. Each U-shaped line is one merge, and its height is the merge distance. For single, complete and average linkage and for Ward, the heights never decrease as the merging goes on, so the tree can be drawn without crossing lines.

  • Cutting at a height. Draw a horizontal line at height hh. Every vertical line it crosses is one cluster. In the example, a cut at 3.53.5 gives the clusters above.
  • Cutting at k clusters. Cut just below the (k−1)(k-1) tallest merges. The cut at 2 clusters is a cut below the last merge only.
  • A tall merge is a signal. If two clusters merge at a height much bigger than the merges before, the data were not close to being one group. Cutting in the long empty gap is a common way to choose kk, but it is a heuristic: some data have no gap.

The same tree gives every cut at once. That is the practical advantage over k-means, where each new kk means a new run, and it is why a dendrogram is useful for exploring data at several scales.

Divisive (top-down) clustering goes the other way: start with one cluster and split it repeatedly. It exists, but it is rarer, and this lesson does not use it.

Cost

A direct implementation of the loop above looks at every pair of clusters at every step: nn steps with about n2n^2 pairs each is O(n3)O(n^3) time, and the pairwise distance matrix needs O(n2)O(n^2) memory. SciPy’s linkage documents O(n2)O(n^2) time for single linkage (a minimum-spanning-tree method) and for complete, average and Ward (a nearest-neighbour-chain method), and O(n2)O(n^2) memory for all of them. Two quadratic costs are why hierarchical clustering is used on thousands of points, not millions. scikit-learn’s AgglomerativeClustering uses SciPy’s routines when no connectivity graph is given.

Using it in code

The code below is shown with the output from a local run (SciPy 1.17 and scikit-learn 1.8). It is not run in the browser because scikit-learn is not available there. The first columns of the SciPy matrix are the two clusters merged (leaves are numbered 00 to 44 in the order of the data, and the new clusters get the next numbers) and the third is the merge height.

import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster
from sklearn.cluster import AgglomerativeClustering

x = np.array([[0.], [2.], [3.], [6.], [10.]])
for method in ["single", "complete"]:
    Z = linkage(x, method=method)
    print(method)
    print(Z[:, [0, 1, 2]])
    print(" 2 clusters:", fcluster(Z, t=2, criterion="maxclust"))
    print(" cut at 3.5:", fcluster(Z, t=3.5, criterion="distance"))
m = AgglomerativeClustering(n_clusters=2, linkage="single").fit(x)
print("sklearn single, 2 clusters:", m.labels_)
m = AgglomerativeClustering(n_clusters=None, distance_threshold=3.5,
                            linkage="complete").fit(x)
print("complete, threshold 3.5:", m.labels_, m.n_clusters_)
single
[[1. 2. 1.]
 [0. 5. 2.]
 [3. 6. 3.]
 [4. 7. 4.]]
 2 clusters: [1 1 1 1 2]
 cut at 3.5: [1 1 1 1 2]
complete
[[ 1.  2.  1.]
 [ 0.  5.  3.]
 [ 3.  4.  4.]
 [ 6.  7. 10.]]
 2 clusters: [1 1 1 2 2]
 cut at 3.5: [1 1 1 2 3]
sklearn single, 2 clusters: [0 0 0 0 1]
complete, threshold 3.5: [0 0 0 2 1] 3

The heights are the ones computed by hand. Row two of the single-linkage matrix reads “merge point 00 with cluster 55 (the cluster made in step one) at height 22”. In scikit-learn, AgglomerativeClustering takes either n_clusters or a distance_threshold (with n_clusters=None), and its default linkage is "ward". The cluster numbers it prints are arbitrary names. For Ward, SciPy reports the height 2 Δ\sqrt{2\,\Delta}, where Δ\Delta is the increase in the sum of squares, and this is also the convention in the widget.

DBSCAN

DBSCAN (density-based spatial clustering of applications with noise) was introduced by Ester, Kriegel, Sander and Xu at KDD 1996. It has two settings:

  • the radius ε\varepsilon (written eps in code), and
  • min_samples, a count.

The ε\varepsilon-neighbourhood of a point is all the points within distance ε\varepsilon of it, counting the point itself (this is scikit-learn’s convention). Then every point is one of three kinds:

  • Core point. Its neighbourhood has at least min_samples points. It sits in a crowded place.
  • Border point. Not core, but within ε\varepsilon of a core point. It sits at the edge of a crowd.
  • Noise point. Neither. It is labelled −1-1 in scikit-learn.

A cluster is a set of core points that can be reached from each other through chains of core points that are within ε\varepsilon of the next one (the cluster is density-connected), together with the border points attached to them. The shape of the cluster does not matter, only that the crowd is connected. That is why DBSCAN can follow a curve.

A worked example

Ten made-up points, with ε=1.5\varepsilon=1.5 and min_samples =4=4:

  • A(0,0)A(0,0), B(1,0)B(1,0), C(0,1)C(0,1), D(1,1)D(1,1): a unit square.
  • E(2.4,0)E(2.4,0): a lone point between two groups.
  • F(3.8,0)F(3.8,0), G(4.8,0)G(4.8,0), H(3.8,1)H(3.8,1), I(4.8,1)I(4.8,1): another unit square.
  • J(2.4,4)J(2.4,4): far from everything.

Count the points within 1.51.5 of each, including itself. In the left square each corner has the other three within 2=1.414\sqrt2=1.414, so AA, CC and DD have 44 and BB has 55 (it also has EE, at distance 1.41.4). EE has itself, BB and FF (both 1.41.4 away): 33. In the right square GG, HH and II have 44 and FF has 55. JJ has only itself: 11.

So the core points are AA, BB, CC, DD, FF, GG, HH, II. EE has 33, which is fewer than 44, so it is not core, but it is within ε\varepsilon of the core points BB and FF: a border point. JJ is noise. The two squares are not density-connected, because the only link between them is EE, and a border point does not pass the connection on. DBSCAN finds two clusters and one noise point.

Now lower min_samples to 33. EE has 33 neighbours and becomes core, so it links the two squares: one cluster of nine points and the noise point JJ. One setting changed the answer from two clusters to one.

Which cluster does EE get when min_samples is 44? It is within ε\varepsilon of core points of both squares, so it could belong to either. scikit-learn gives it to the cluster that reaches it first when the points are processed in order. Shuffling the rows can move EE to the other cluster (a local run with 300 random orders gave each outcome about half the time). Core points and noise points never depend on the order, but border points can.

Two moons

Here is a comparison on 300 points of the two-moons data set (scikit-learn’s make_moons with noise 0.060.06, seed 00). The adjusted Rand index (ARI) compares the clusters with the true moon labels, and the silhouette is described below.

import numpy as np, warnings
warnings.filterwarnings("ignore")
from sklearn.cluster import DBSCAN, KMeans, AgglomerativeClustering
from sklearn.datasets import make_moons
from sklearn.metrics import adjusted_rand_score, silhouette_score

X, y = make_moons(300, noise=0.06, random_state=0)
models = {
    "k-means": KMeans(2, n_init=10, random_state=0),
    "Ward": AgglomerativeClustering(n_clusters=2, linkage="ward"),
    "single": AgglomerativeClustering(n_clusters=2, linkage="single"),
    "DB 0.2": DBSCAN(eps=0.2, min_samples=5),
    "DB 0.1": DBSCAN(eps=0.1, min_samples=5),
    "DB 0.5": DBSCAN(eps=0.5, min_samples=5),
}
print("method  k noise   ARI  silh")
for name, m in models.items():
    lab = m.fit_predict(X)
    k = len(set(lab) - {-1})
    sil = silhouette_score(X, lab) if k > 1 else float("nan")
    print(f"{name:7s}{k:3d}{(lab == -1).sum():5d}"
          f"{adjusted_rand_score(y, lab):6.3f}{sil:6.3f}")
print("true labels: silh", round(silhouette_score(X, y), 3))
method  k noise   ARI  silh
k-means  2    0 0.234 0.488
Ward     2    0 0.297 0.437
single   2    0 1.000 0.327
DB 0.2   2    0 1.000 0.327
DB 0.1  11   15 0.337 0.238
DB 0.5   1    0 0.000   nan
true labels: silh 0.327

(DB 0.2 is DBSCAN with ε=0.2\varepsilon=0.2, and so on; k counts the clusters, not the noise.)

For the ε=0.1\varepsilon=0.1 row, scikit-learn’s silhouette and ARI treat the noise label −1-1 as one more cluster, so those two numbers are only a rough guide.

Three lessons from the table:

  • k-means and Ward cut the moons into round halves and score low on the ARI. Single linkage and DBSCAN with a good ε\varepsilon recover the moons exactly (ARI 1.01.0).
  • ε\varepsilon matters. At 0.10.1 the moons shatter into 1111 clusters and 1515 noise points. At 0.50.5 everything is one cluster (the silhouette is undefined for one cluster).
  • The silhouette prefers the wrong answer. The true moons have a silhouette of 0.3270.327, lower than k-means’ 0.4880.488. The silhouette rewards round, well-separated groups, so it is not a fair judge of curved ones.

Choosing ε: the k-distance plot

A common heuristic: set kk to min_samples, compute for every point the distance to its kk-th nearest point (counting itself as the first), sort these values from smallest to largest and plot them. Points inside crowds have small values, and noise points have large ones. Pick ε\varepsilon near the bend where the curve starts to rise steeply.

For the ten-point example with k=4k=4, the sorted values are 1.40,1.40,1.41×6,1.72,3.841.40, 1.40, 1.41\times6, 1.72, 3.84. The curve is flat at about 1.41.4 and then jumps, so ε=1.5\varepsilon=1.5, just above the flat part, matches the choice used above. This is a heuristic: real curves often have no clean bend, and different bends give different clusterings. It is also common to start with min_samples near twice the number of features (or the default 55) and raise it for noisy data, which is also only a rule of thumb.

Weaknesses

  • One ε for every cluster. If some clusters are dense and others sparse, no single ε\varepsilon fits both. The test below uses three made-up blobs: two tight ones close together and one spread-out one.
  • Many dimensions. Distances become similar in high dimensions (P3.B1), so “within ε\varepsilon” stops separating crowds from empty space.
  • Scale. The radius is one number for all features, so features must be on comparable scales (P3.A11).
  • Border points can depend on the order of the data, as seen above.
import numpy as np, warnings
warnings.filterwarnings("ignore")
from sklearn.cluster import DBSCAN, HDBSCAN
from sklearn.metrics import adjusted_rand_score

rs = np.random.RandomState(0)
X = np.vstack([rs.randn(60, 2) * 0.25,
               rs.randn(60, 2) * 0.25 + [1.6, 0],
               rs.randn(60, 2) * 1.0 + [6, 0]])
y = np.repeat([0, 1, 2], 60)
for eps in (0.15, 0.5, 0.8):
    lab = DBSCAN(eps=eps, min_samples=5).fit_predict(X)
    print(f"DBSCAN eps={eps}: clusters {len(set(lab) - {-1})}, "
          f"noise {(lab == -1).sum()}, ARI {adjusted_rand_score(y, lab):.3f}")
lab = HDBSCAN(min_cluster_size=15).fit_predict(X)
print(f"HDBSCAN: clusters {len(set(lab) - {-1})}, "
      f"noise {(lab == -1).sum()}, ARI {adjusted_rand_score(y, lab):.3f}")
DBSCAN eps=0.15: clusters 3, noise 90, ARI 0.498
DBSCAN eps=0.5: clusters 3, noise 28, ARI 0.869
DBSCAN eps=0.8: clusters 2, noise 7, ARI 0.517
HDBSCAN: clusters 3, noise 7, ARI 0.947

With ε=0.15\varepsilon=0.15, all 60 points of the spread-out blob and 30 of the 120 tight-blob points are noise (90 in all). At ε=0.8\varepsilon=0.8 the two tight blobs merge (two clusters, ARI 0.5170.517). HDBSCAN (hierarchical DBSCAN, available in scikit-learn since version 1.3) runs DBSCAN over many radii and keeps the groups that stay stable, so it does not need a single ε\varepsilon. On this data it finds the three groups and labels 7 points as noise (ARI 0.9470.947). It has its own settings (such as min_cluster_size), it is not guaranteed to work on every data set, and its details are outside this lesson.

Choosing a method

  • k-means (P3.C1). Needs kk. Round, similar-size groups. Every point is assigned, so no noise. Fast, grows with nn roughly linearly per pass.
  • Gaussian mixtures (P3.C2). Needs the number of components. Elliptical groups, soft memberships. Every point is assigned.
  • Hierarchical. Choose kk or a height after the fact, from one tree. Shape depends on the linkage: compact for complete and Ward, flexible but chain-prone for single. Every point is assigned (outliers become singletons or small clusters). Memory and time grow with n2n^2.
  • DBSCAN. No kk, but needs ε\varepsilon and min_samples. Any shape. Labels noise. Struggles with different densities and many dimensions.

No method is best for every data set. Look at the data first (P3.C4 shows how to draw it, and how drawings can mislead).

Judging a clustering

Without labels, you can only measure how well a clustering fits the data’s own geometry. With labels (for testing a method on data where the truth is known), you can compare.

Silhouette (no labels). P3.C1 defines it: for each point, s=(b−a)/max⁡(a,b)s=(b-a)/\max(a,b), where aa is the mean distance to its own cluster and bb the mean distance to the nearest other cluster, so it runs from −1-1 to 11 and a point alone in its cluster scores 00. The score of a clustering is the mean over the points.

On the five points 0,2,3,6,100,2,3,6,10: take the point 66 in the complete-linkage clustering {0,2,3}\{0,2,3\}, {6,10}\{6,10\}. Then a=4a=4 (its distance to 1010) and b=(6+4+3)/3=4.333b=(6+4+3)/3=4.333 (its mean distance to 00, 22 and 33), so s=(4.333−4)/4.333=0.077s=(4.333-4)/4.333=0.077: nearly on the border. The mean silhouette is 0.5270.527 for the complete-linkage clusters and 0.3860.386 for the single-linkage ones {0,2,3,6}\{0,2,3,6\}, {10}\{10\}, so the silhouette prefers the complete-linkage answer here. It was computed with scikit-learn’s silhouette_score. As the moons showed, a high silhouette does not prove that clusters are correct.

Adjusted Rand index (with labels). The Rand index looks at every pair of points and asks whether the two clusterings agree about the pair: both put it together, or both put it apart. The adjusted Rand index (ARI) subtracts what random labels would score, so that 11 means identical clusterings (the names of the clusters do not matter), about 00 means no better than chance, and it can be slightly negative. For example, true groups {1,2,3}\{1,2,3\} and {4,5,6}\{4,5,6\} against found groups {1,2}\{1,2\} and {3,4,5,6}\{3,4,5,6\}: of the 1515 pairs, 44 are together in both and 66 are apart in both, so the Rand index is 10/15=0.66710/15=0.667, while the ARI is 0.3240.324. Labels in real clustering tasks are often not available, and a clustering that disagrees with one labelling can still be a valid grouping of the data.

Depth: three ways to see it

Intuition

Agglomerative clustering is like a map of villages becoming towns becoming regions: the closest houses join first, and the tree records at what distance each join happened. DBSCAN is like finding islands from a map of lit windows at night: crowded areas are islands, and a lone light far from everything is not part of any island. The analogy breaks because villages are joined by roads, while a linkage is only a rule about distances, and because an island has a coastline while DBSCAN’s border points are set by an arbitrary radius.

Math

Linkage between clusters A,BA,B: single min⁡d(a,b)\min d(a,b), complete max⁡d(a,b)\max d(a,b), average 1∣A∣∣B∣∑d(a,b)\frac{1}{|A||B|}\sum d(a,b), Ward Δ(A,B)=∣A∣∣B∣∣A∣+∣B∣∥cA−cB∥2\Delta(A,B)=\frac{|A||B|}{|A|+|B|}\lVert\mathbf{c}_A-\mathbf{c}_B\rVert^2 with SciPy’s height 2Δ\sqrt{2\Delta}. DBSCAN with Nε(x)={x′ : ∥x−x′∥≤ε}N_\varepsilon(\mathbf{x})=\{\mathbf{x}'\,:\,\lVert\mathbf{x}-\mathbf{x}'\rVert\le\varepsilon\} (including x\mathbf{x} itself): x\mathbf{x} is core if ∣Nε(x)∣≥m|N_\varepsilon(\mathbf{x})|\ge m, where mm is min_samples. Two core points are in the same cluster if there is a chain of core points between them in which consecutive points are within ε\varepsilon. A non-core point within ε\varepsilon of a core point is a border point of that core point’s cluster; all other points are noise. Silhouette si=(bi−ai)/max⁡(ai,bi)s_i=(b_i-a_i)/\max(a_i,b_i). ARI =Index−ExpectedMax−Expected=\dfrac{\text{Index}-\text{Expected}}{\text{Max}-\text{Expected}}, where Index is the number of pairs together in both clusterings.

Code

from sklearn.cluster import AgglomerativeClustering, DBSCAN

hier = AgglomerativeClustering(n_clusters=3, linkage="ward")   # needs Euclidean distance
labels = hier.fit_predict(X_scaled)

db = DBSCAN(eps=0.5, min_samples=5).fit(X_scaled)
labels = db.labels_                       # -1 means noise
core = db.core_sample_indices_            # indices of the core points

Scale first (P3.A11): both methods use distances.

Go deeper Why Ward's merge cost has that formula

Let cluster AA have nAn_A points with centre cA\mathbf{c}_A, and BB have nBn_B points with centre cB\mathbf{c}_B. The merged cluster has centre c=(nAcA+nBcB)/(nA+nB)\mathbf{c}=(n_A\mathbf{c}_A+n_B\mathbf{c}_B)/(n_A+n_B). The sum of squares about a centre splits into the sum about each cluster’s own centre plus nA∥cA−c∥2+nB∥cB−c∥2n_A\lVert\mathbf{c}_A-\mathbf{c}\rVert^2+n_B\lVert\mathbf{c}_B-\mathbf{c}\rVert^2. Substituting c\mathbf{c}, the extra part is nAnBnA+nB∥cA−cB∥2\dfrac{n_An_B}{n_A+n_B}\lVert\mathbf{c}_A-\mathbf{c}_B\rVert^2. That is what merging adds, so Ward merges the pair with the smallest extra. It is a greedy rule: each merge is the best single step, and the final clustering need not be the one with the smallest total sum of squares for its number of clusters, which is why k-means can still improve it.

Go deeper Single linkage and the minimum spanning tree

Single-linkage clusters at height hh are exactly the connected pieces of the graph that joins every pair of points at distance at most hh. Because only the nearest links matter, the merge heights are the edge lengths of the minimum spanning tree of the points (the cheapest set of edges that connects all points). This is why single linkage can be computed in O(n2)O(n^2) time, and why it chains: one chain of short edges is enough to connect two crowds. With min_samples =2=2 it is exactly DBSCAN: every point that has a neighbour within ε\varepsilon is core, so the clusters are the connected pieces of the ε\varepsilon-graph, which are the single-linkage clusters at height ε\varepsilon (a point with no neighbour is a singleton there and noise in DBSCAN). Larger min_samples makes DBSCAN less sensitive to thin bridges.

Try it in NumPy

The first cell implements single, complete and average linkage for the five points and prints the merge sequences from the hand example. The second implements DBSCAN on the ten-point example, with min_samples 44 and then 33, and the sorted 4-distances.

Try it: agglomerative clustering from scratch

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The numbers in brackets are positions in the list, so [3][3] is the point 66. The merge heights match the hand calculation. To try Ward, replace the height by the increase in the sum of squares.

Try it: DBSCAN from scratch

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The output shows two clusters (labels 00 and 11, with EE in cluster 00 and JJ as −1-1) for min_samples 44, and a single cluster for min_samples 33. In the loop, a border point is labelled but never added to the stack as a spreading point. Try putting the loop over range(n) in reverse order and see which cluster EE joins.

Common mistakes

Exercises

  1. Three points on a line at 00, 11 and 55. Give the single-linkage and complete-linkage merge heights.
    Show answerThe closest pair is 00 and 11, merged at height 11 in both. The point 55 is 44 from the nearest point of {0,1}\{0,1\} (which is 11), so single linkage merges it at height 44. Its farthest point is 00, at distance 55, so complete linkage merges it at height 55. Single: 1,41, 4. Complete: 1,51, 5.
  2. For the five points 0,2,3,6,100,2,3,6,10, how many clusters does a complete-linkage cut at height 55 give, and which are they?
    Show answerThe merge heights are 1,3,4,101,3,4,10. A cut at 55 is above 11, 33 and 44 and below 1010, so those three merges are done and the last is not. Two clusters: {0,2,3}\{0,2,3\} and {6,10}\{6,10\}.
  3. A DBSCAN run uses ε=1\varepsilon=1 and min_samples =3=3. A point has two other points within distance 11. Is it core?
    Show answerYes. The neighbourhood counts the point itself, so it has 33 points, which meets min_samples =3=3.
  4. In the ten-point example with min_samples 44, what happens to EE if ε\varepsilon is raised to 1.81.8?
    Show answerWith ε=1.8\varepsilon=1.8 the point EE also reaches DD (distance 1.721.72) and HH (distance 1.721.72), so its count rises from 33 to 55 and it becomes a core point. It links the two squares, giving one cluster of nine points; JJ, whose nearest point is 3.313.31 away, stays noise.
  5. Two clusterings of six points give the same groups, but one names them 0,10,1 and the other 1,01,0. What is the adjusted Rand index?
    Show answer11. The index counts pairs of points together or apart, so the names of the clusters do not matter.

Check your understanding

  1. On the five points 0,2,3,6,100,2,3,6,10, what does complete linkage give when the tree is cut into 2 clusters?

  2. Which linkage is most likely to join two blobs through a thin bridge of closely spaced points?

  3. In scikit-learn, a point has 3 points within ε\varepsilon (counting itself), none of them core, and min_samples is 44. What is it?

  4. You run DBSCAN with one ε\varepsilon on data with two tight blobs close together and one very spread-out blob. What typically goes wrong?

  5. For the two-moons data, k-means has a higher silhouette than the true labels. What does that show?

Next: Part 3 ends here. Part 4 starts with P4.1, “From neurons to the perceptron”, the first step towards neural networks. P3.C4 draws data in two dimensions and shows how to misread the clusters in a picture, and P3.C5 uses density to find anomalies.

Key takeaways

  • Agglomerative clustering starts with every point alone and repeatedly merges the two closest clusters. The merge heights form a dendrogram, and cutting it at a height, or at k clusters, gives a flat clustering. Divisive clustering works top-down and is only named here.
  • The linkage defines the distance between clusters. Single uses the nearest pair and chains, complete uses the farthest pair and favours compact groups, average uses the mean of all pairs, and Ward merges the pair that increases the within-cluster sum of squares least (Euclidean only). On the points 0, 2, 3, 6, 10 single and complete give different 2-cluster cuts.
  • A naive implementation needs about n cubed steps, and the matrix of pairwise distances takes n squared memory. SciPy's linkage reaches n squared time for these four methods.
  • DBSCAN has two settings, the radius ε and min_samples. A point with at least min_samples points within ε (counting itself) is a core point; clusters are the density-connected regions of core points; a border point lies within ε of a core point but is not core; the rest is noise, labelled −1 in scikit-learn.
  • DBSCAN finds curved clusters such as two moons and needs no k, but one ε serves every cluster, so very different densities, many dimensions and unscaled features hurt it. The k-distance plot is a heuristic for ε, HDBSCAN relaxes the single-ε limit, and a border point between two clusters can go to either one, depending on the order of the data.
  • Without labels, the silhouette compares each point's distance to its own cluster with its distance to the nearest other cluster, and it favours round, well-separated groups. With labels, the adjusted Rand index counts agreeing pairs, corrected for chance: 1 is perfect and about 0 is random.
Found a mistake? Tell us