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.
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 (single linkage). The next merge is at , 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 , hardly more than the 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 , is only a little taller than the one before it, at , 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 and slide ε. At the two moons are two clusters with no noise. At they are still two clusters but five points are noise. At 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:
- Start with every point as its own cluster, so points give clusters.
- Find the two clusters that are closest, and merge them.
- Repeat until one cluster is left. That takes 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 and , with the distance between two points:
- Single linkage. The distance of the nearest pair: . Two clusters are close if any one point of each is close.
- Complete linkage. The distance of the farthest pair: . 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 . 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):
- The closest pair of points is and , distance . Merge them at height .
- The cluster is from the point (nearest pair and ), from , and the point is from . The smallest is : merge into it at height .
- Now is from the point (nearest pair and ), and is from . Merge at height .
- Last, the point joins at height (nearest pair and ).
The heights are : 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):
- at height , as before.
- The point is at distance from (farthest pair and ). The point is from (farthest pair and ), and from . The smallest is : merge into at height .
- Now and are apart, but and are only apart. Merge at height .
- The two clusters and are apart at their farthest pair, so they merge last at height .
The heights are , 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 : and .
- Complete, cut at height : , and . Cut at 2 clusters instead (between and ): and .
Average linkage on the same points merges at , the point into it at (the mean of and ), then at , then the two groups at (the mean of the six pair distances ). Ward, with the merge increases in sum of squares, gives , , and for the same four merges, which add up to the total sum of squares about the mean, . For two clusters and , the increase in the within-cluster sum of squares equals , where and are the cluster centres. For joining : .
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 . Every vertical line it crosses is one cluster. In the example, a cut at gives the clusters above.
- Cutting at k clusters. Cut just below the 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 , 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 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: steps with about pairs each is time, and the pairwise distance matrix needs memory. SciPy’s linkage documents time for single linkage (a minimum-spanning-tree method) and for complete, average and Ward (a nearest-neighbour-chain method), and 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 to 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 with cluster (the cluster made in step one) at height ”. 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 , where 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 (written
epsin code), and - min_samples, a count.
The -neighbourhood of a point is all the points within distance 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 of a core point. It sits at the edge of a crowd.
- Noise point. Neither. It is labelled 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 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 and min_samples :
- , , , : a unit square.
- : a lone point between two groups.
- , , , : another unit square.
- : far from everything.
Count the points within of each, including itself. In the left square each corner has the other three within , so , and have and has (it also has , at distance ). has itself, and (both away): . In the right square , and have and has . has only itself: .
So the core points are , , , , , , , . has , which is fewer than , so it is not core, but it is within of the core points and : a border point. is noise. The two squares are not density-connected, because the only link between them is , and a border point does not pass the connection on. DBSCAN finds two clusters and one noise point.
Now lower min_samples to . has neighbours and becomes core, so it links the two squares: one cluster of nine points and the noise point . One setting changed the answer from two clusters to one.
Which cluster does get when min_samples is ? It is within 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 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 , seed ). 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 , and so on; k counts the clusters, not the noise.)
For the row, scikit-learn’s silhouette and ARI treat the noise label 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 recover the moons exactly (ARI ).
- matters. At the moons shatter into clusters and noise points. At everything is one cluster (the silhouette is undefined for one cluster).
- The silhouette prefers the wrong answer. The true moons have a silhouette of , lower than k-means’ . 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 to min_samples, compute for every point the distance to its -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 near the bend where the curve starts to rise steeply.
For the ten-point example with , the sorted values are . The curve is flat at about and then jumps, so , 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 ) 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 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 ” 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 , all 60 points of the spread-out blob and 30 of the 120 tight-blob points are noise (90 in all). At the two tight blobs merge (two clusters, ARI ). 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 . On this data it finds the three groups and labels 7 points as noise (ARI ). 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 . Round, similar-size groups. Every point is assigned, so no noise. Fast, grows with roughly linearly per pass.
- Gaussian mixtures (P3.C2). Needs the number of components. Elliptical groups, soft memberships. Every point is assigned.
- Hierarchical. Choose 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 .
- DBSCAN. No , but needs 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, , where is the mean distance to its own cluster and the mean distance to the nearest other cluster, so it runs from to and a point alone in its cluster scores . The score of a clustering is the mean over the points.
On the five points : take the point in the complete-linkage clustering , . Then (its distance to ) and (its mean distance to , and ), so : nearly on the border. The mean silhouette is for the complete-linkage clusters and for the single-linkage ones , , 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 means identical clusterings (the names of the clusters do not matter), about means no better than chance, and it can be slightly negative. For example, true groups and against found groups and : of the pairs, are together in both and are apart in both, so the Rand index is , while the ARI is . 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 : single , complete , average , Ward with SciPy’s height . DBSCAN with (including itself): is core if , where 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 . A non-core point within of a core point is a border point of that core point’s cluster; all other points are noise. Silhouette . ARI , 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 pointsScale first (P3.A11): both methods use distances.
Go deeper Why Ward's merge cost has that formula
Let cluster have points with centre , and have points with centre . The merged cluster has centre . The sum of squares about a centre splits into the sum about each cluster’s own centre plus . Substituting , the extra part is . 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 are exactly the connected pieces of the graph that joins every pair of points at distance at most . 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 time, and why it chains: one chain of short edges is enough to connect two crowds. With min_samples it is exactly DBSCAN: every point that has a neighbour within is core, so the clusters are the connected pieces of the -graph, which are the single-linkage clusters at height (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 and then , and the sorted 4-distances.
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 is the point . The merge heights match the hand calculation. To try Ward, replace the height by the increase in the sum of squares.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The output shows two clusters (labels and , with in cluster and as ) for min_samples , and a single cluster for min_samples . 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 joins.
Common mistakes
Exercises
- Three points on a line at , and . Give the single-linkage and complete-linkage merge heights.
Show answer
The closest pair is and , merged at height in both. The point is from the nearest point of (which is ), so single linkage merges it at height . Its farthest point is , at distance , so complete linkage merges it at height . Single: . Complete: . - For the five points , how many clusters does a complete-linkage cut at height give, and which are they?
Show answer
The merge heights are . A cut at is above , and and below , so those three merges are done and the last is not. Two clusters: and . - A DBSCAN run uses and min_samples . A point has two other points within distance . Is it core?
Show answer
Yes. The neighbourhood counts the point itself, so it has points, which meets min_samples . - In the ten-point example with min_samples , what happens to if is raised to ?
Show answer
With the point also reaches (distance ) and (distance ), so its count rises from to and it becomes a core point. It links the two squares, giving one cluster of nine points; , whose nearest point is away, stays noise. - Two clusterings of six points give the same groups, but one names them and the other . What is the adjusted Rand index?
Show answer
. The index counts pairs of points together or apart, so the names of the clusters do not matter.
Check your understanding
On the five points , what does complete linkage give when the tree is cut into 2 clusters?
Complete linkage merges at , the point at , and at , and the final merge happens at , so cutting below it leaves and . The split with alone is what single linkage gives, because single linkage keeps adding the nearest point to one growing cluster. The other two splits separate points that merged early.
Which linkage is most likely to join two blobs through a thin bridge of closely spaced points?
Single linkage links two clusters if any one pair of their points is close, so a chain of near points connects them. Complete linkage needs all pairs to be close, so a bridge does not help it. Ward looks at the cluster centres and sizes, not at the nearest pair, so it is much less prone to chaining. A bridge can matter a great deal to single linkage even if it has only a few points.
In scikit-learn, a point has 3 points within (counting itself), none of them core, and min_samples is . What is it?
It has fewer than min_samples points in its neighbourhood, so it is not core, and none of its neighbours is core, so it is not a border point either. Points that are neither are noise and get the label . DBSCAN does not create one-point clusters for them.
You run DBSCAN with one on data with two tight blobs close together and one very spread-out blob. What typically goes wrong?
One radius has to serve every cluster. A radius small enough to separate the tight blobs is too small for the sparse blob, whose points then lack neighbours, while a radius large enough for the sparse blob joins the tight ones. DBSCAN does not need the number of clusters and is not limited to round shapes, and it does not shatter a sparse blob into many clusters when the radius is large.
For the two-moons data, k-means has a higher silhouette than the true labels. What does that show?
The silhouette is a distance-based score that rewards compact groups, and half-moons are not compact. It is still useful for comparing clusterings of similar shapes. The true labels are the moons, and k-means cut them across, so it did not find them. The DBSCAN run that matched the truth had a good , and the silhouette itself is not broken.
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.