Learning path: Find Structure Without Labels: Clustering, PCA and Recommenders · Step 3 of 6
Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
Two more ways to find groups: agglomerative clustering builds a family tree of merges (the dendrogram), and DBSCAN grows clusters from crowds and leaves loners out as noise. Shown on eight homes, 2,600 customers and two moons.
What you will learn
- Read a dendrogram and cut it into clusters
- Compare ward, complete, average and single linkage
- Find odd-shaped clusters and noise with DBSCAN
- Tune eps and see what too small and too big do
Before you start
- K-Means Clustering
- Choosing k: Elbow and Silhouette
K-means is quick, but it needs k up front and it likes round, blob-shaped groups. Here are two more ways to find groups. Hierarchical clustering builds a family tree. DBSCAN looks for crowds.
A family tree for data points
Remember the eight homes A to H from the pizza shops? At the start, every home is its own little family. Then we keep merging the two closest families:
- A and C are close, and so are E and F. Both pairs merge at a distance of 1.
- Then B and D, then H, then G, then A-C with B-D. All small steps, from 1.41 to 2.55.
- At the very end the two big families merge, at 15.31. That's a huge jump.
Merging from the bottom up like this is called agglomerative clustering, and the tree of merges is a dendrogram.
Build and read the tree
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage, dendrogram
from sklearn.cluster import (
AgglomerativeClustering, DBSCAN, KMeans)
from sklearn.datasets import make_moons
homes = pd.DataFrame({"home": list("ABCDEFGH"),
"x": [1, 2, 1, 3, 7, 8, 7, 9],
"y": [2, 1, 3, 2, 6, 6, 8, 7]})
Z = linkage(homes[["x", "y"]], method="ward")
print(Z.round(2))
[[ 0. 2. 1. 2. ]
[ 4. 5. 1. 2. ]
[ 1. 3. 1.41 2. ]
[ 7. 9. 2.08 3. ]
[ 6. 11. 2.38 4. ]
[ 8. 10. 2.55 4. ]
[12. 13. 15.31 8. ]]
One row per merge. The first row says: merge point 0 and point 2 (A and C) at a distance of 1, and the new family has 2 members. New families get the next numbers (8, 9, 10 ...), so row 4 merges H (7) with family 9 (E and F). The last row joins everything at 15.31.
dendrogram(Z, labels=list("ABCDEFGH"))
plt.axhline(8, color="red", linestyle="--")
plt.ylabel("merge distance")
plt.show()

Cut where the vertical lines are longest. The cut at 8 crosses two lines, which gives two families: A B C D and E F G H. The same answer k-means gave us.
Linkage: how far apart are two families?
To merge "the closest" families, we must say how to measure the distance between two groups. That choice is the linkage:
| Linkage | Distance between two families |
|---|---|
| single | The closest pair of points. One close pair is enough. |
| complete | The farthest pair. Every pair must be close. |
| average | The average over all pairs. |
| ward | Merge the families that add the least spread (inertia), so groups stay tight. The default in scikit-learn. |
Let's try all four on our 2,600 customers (visit score and spending rank), with four clusters each. The file is called Instagram visits clustering.csv here; it holds the same data as customers.csv.
df = pd.read_csv("Instagram visits clustering.csv")
X = df.iloc[:, 1:]
for link in ["ward", "complete", "average", "single"]:
model = AgglomerativeClustering(
n_clusters=4, linkage=link)
labels = model.fit_predict(X)
print(link.ljust(8), np.bincount(labels))
ward [1104 500 597 399]
complete [994 396 610 600]
average [1083 517 402 598]
single [2597 1 1 1]
Ward, complete and average all give four sensible groups. Single gives 2,597 customers in one group and then 1, 1 and 1. It only needs one close pair, so it chains everyone together. Not much help to a marketing team.
DBSCAN: crowds at a fair
Now the second idea. Picture a fair where people bunch up around the busy stalls.
- If at least 5 people are within your arm's reach (counting you), you're part of a crowd. Arm's reach is eps, and 5 is min_samples.
- If nobody is near you, you're a loner. DBSCAN calls that noise and gives it the label
-1. - A crowd grows from neighbour to neighbour, so it can have any shape, even a curve.
Notice we never said how many crowds there are. No k is needed, and loners are simply left out.
Two moons and twelve loners
Here's a shape k-means doesn't like: two moons, plus 12 random points as loners.
M, _ = make_moons(n_samples=300, noise=0.06,
random_state=42)
rng = np.random.default_rng(42)
loners = rng.uniform([-1.5, -1], [2.5, 1.5],
size=(12, 2))
M = np.vstack([M, loners])
print(M.shape)
(312, 2)
First k-means with k = 2, because we can see two moons:
km = KMeans(n_clusters=2, n_init=10,
random_state=42)
km_labels = km.fit_predict(M)
print(np.bincount(km_labels))
[154 158]
Then DBSCAN with eps 0.2 and min_samples 5:
db = DBSCAN(eps=0.2, min_samples=5)
db_labels = db.fit_predict(M)
print("clusters:", len(set(db_labels) - {-1}))
print("noise :", (db_labels == -1).sum())
clusters: 2
noise : 7
No k anywhere. DBSCAN found two clusters on its own and marked 7 points as noise. Let's compare the pictures:
fig, ax = plt.subplots(1, 2, figsize=(9, 3.2))
ax[0].scatter(M[:, 0], M[:, 1], c=km_labels)
ax[0].set_title("K-means, k = 2")
noise = db_labels == -1
ax[1].scatter(M[~noise, 0], M[~noise, 1],
c=db_labels[~noise])
ax[1].scatter(M[noise, 0], M[noise, 1],
c="red", marker="x")
ax[1].set_title("DBSCAN, red x = noise")
plt.show()

K-means cuts the space in half, so each colour owns a piece of both moons. DBSCAN follows the shape: one colour per moon, and the red crosses are the noise points.
eps: how far is "near"?
DBSCAN has its own knob. Same min_samples=5, four values of eps:
for eps in [0.05, 0.1, 0.2, 0.5]:
model = DBSCAN(eps=eps, min_samples=5)
labels = model.fit_predict(M)
n = len(set(labels) - {-1})
print(eps, "->", n, "clusters,",
(labels == -1).sum(), "noise")
0.05 -> 7 clusters, 271 noise
0.1 -> 15 clusters, 36 noise
0.2 -> 2 clusters, 7 noise
0.5 -> 1 clusters, 2 noise
- eps too small (0.05): almost everyone is a loner, 271 noise points.
- eps right (0.2): two moons, 7 noise points.
- eps too big (0.5): both moons melt into one cluster.
Our moon coordinates are all on a similar scale. On real data with mixed units, scale the columns first, because eps is a distance (see Feature Scaling).
Common mistakes
- Using single linkage by default. It chains points together; on our customers it gave 2,597, 1, 1, 1.
- Forcing k-means onto curved shapes. It always cuts with straight borders.
- Picking eps without trying a few values. Too small and everything is noise, too big and everything merges.
- Throwing the noise away without a look. The
-1rows are often the most interesting ones.
Quick recap
| Method | Key idea | Knob | Our result |
|---|---|---|---|
| Agglomerative | Merge the closest families, bottom up | linkage, where to cut | Two families: ABCD, EFGH |
| Linkage | What "closest" means | ward (default) | Single chains to 2,597 |
| DBSCAN | Grow clusters from crowds, loners are noise | eps, min_samples | 2 moons, 7 noise at eps 0.2 |
Try it yourself
Run DBSCAN on the moons with min_samples=10. Which eps gives you two moons now, and how many noise points?
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Choosing k for K-Means: the Elbow Method and the Silhouette Score
Next →Dimensionality Reduction with PCA: 13 Columns Down to 2
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
K-Means Clustering: Find Groups in Data With No Labels
How k-means finds groups without labels: the assign-update loop worked by hand on eight homes, then KMeans on 2,600 customers, bad random starts, k-means++ and why you scale first.
Choosing k for K-Means: the Elbow Method and the Silhouette Score
K-means always returns exactly k groups, even when k is wrong. Use the elbow plot and the silhouette score to pick k for 2,600 customers, then describe each group in plain words.
Dimensionality Reduction with PCA: 13 Columns Down to 2
PCA squeezes many columns into a few new ones and keeps most of the information. Reduce 178 wines from 13 columns to 2, see why scaling comes first, pick the number of components and use PCA in a pipeline.
Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
Which items are bought together? Work out support, confidence and lift by hand on eight baskets, then let Apriori in mlxtend find 240 rules in 14,963 real grocery baskets.