K-means needs you to pick the number of clusters in advance and assumes clusters are round blobs of similar size. Real groups are often curved, uneven, or surrounded by outliers. This lesson covers two clustering methods that work differently. DBSCAN finds clusters as dense regions of points and labels isolated points as noise. Hierarchical clustering builds a family tree of merges, so you can choose how many clusters you want after seeing the structure.
In this lesson you will learn
- How DBSCAN uses
epsandmin_samples - Core points, border points and noise
- Why DBSCAN handles curved clusters that K-means cannot
- Agglomerative (bottom-up) hierarchical clustering
- Reading a merge history and cutting it into clusters
This lesson follows K-Means Clustering.
DBSCAN vs K-Means
import numpy as np
from sklearn.cluster import DBSCAN, KMeans
from sklearn.datasets import make_moons
# Two interlocking half-moons plus a few random outliers
X, y = make_moons(n_samples=200, noise=0.06, random_state=1)
rng = np.random.default_rng(1)
X = np.vstack([X, rng.uniform(-1.5, 2.5, size=(6, 2))])
km = KMeans(n_clusters=2, n_init=10, random_state=1).fit(X)
db = DBSCAN(eps=0.2, min_samples=5).fit(X)
def agreement(labels):
"""Share of the 200 moon points whose cluster matches their true moon."""
l = labels[:200]
return max(np.mean(l == y), np.mean(l == 1 - y))
print(f"K-means: clusters={len(set(km.labels_))}, moon agreement={agreement(km.labels_):.2f}")
n_clusters = len(set(db.labels_)) - (1 if -1 in db.labels_ else 0)
print(f"DBSCAN : clusters={n_clusters}, noise points={np.sum(db.labels_ == -1)}, "
f"moon agreement={agreement(db.labels_):.2f}")
Output
K-means: clusters=2, moon agreement=0.75
DBSCAN : clusters=2, noise points=5, moon agreement=1.00
- The data is two interlocking half-moons plus six random outliers.
- K-means splits the space with a straight boundary between two centres, so it cuts across both moons and matches the true groups only 75% of the time. It also forces every outlier into a cluster.
- DBSCAN treats a point as a core point if at least
min_samplespoints lie within distanceepsof it. Clusters grow by connecting nearby core points, so they can follow any shape. - Points near a cluster but not dense enough themselves are border points; points far from everything are noise, labelled
-1. Five of the six outliers were recognised as noise (one happened to land near a moon). - DBSCAN found the number of clusters, 2, by itself and matched the moons perfectly.
Hierarchical Clustering
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster
from sklearn.cluster import AgglomerativeClustering
# Monthly spending (thousand taka) on food and entertainment for 8 students
students = ["Ali", "Bina", "Chayan", "Dipa", "Esha", "Farid", "Gita", "Hasan"]
X = np.array([[8, 1], [9, 2], [8, 2], [3, 6], [4, 7], [3, 7], [12, 9], [13, 8]])
Z = linkage(X, method="ward") # bottom-up merge history
print("Merge steps (cluster a, cluster b, distance, new size):")
for a, b, d, size in Z[:4]:
print(f" {int(a):2d} + {int(b):2d} at distance {d:5.2f} -> size {int(size)}")
for k in [2, 3]:
labels = fcluster(Z, t=k, criterion="maxclust")
groups = {}
for name, lab in zip(students, labels):
groups.setdefault(lab, []).append(name)
print(f"{k} clusters:", sorted(groups.values()))
agg = AgglomerativeClustering(n_clusters=3, linkage="ward").fit(X)
print("scikit-learn labels:", agg.labels_)
Output
Merge steps (cluster a, cluster b, distance, new size):
0 + 2 at distance 1.00 -> size 2
3 + 5 at distance 1.00 -> size 2
1 + 8 at distance 1.29 -> size 3
4 + 9 at distance 1.29 -> size 3
2 clusters: [['Ali', 'Bina', 'Chayan', 'Dipa', 'Esha', 'Farid'], ['Gita', 'Hasan']]
3 clusters: [['Ali', 'Bina', 'Chayan'], ['Dipa', 'Esha', 'Farid'], ['Gita', 'Hasan']]
scikit-learn labels: [2 2 2 1 1 1 0 0]
- Agglomerative clustering starts with every student as a cluster of one and repeatedly merges the two closest clusters until only one remains.
linkagereturns the merge history. Each row joins two clusters (numbers 0–7 are the original students, 8 and above are clusters created by earlier merges) at a certain distance. Ali and Chayan merge first because their spending is almost identical.- Ward linkage merges the pair that increases the total within-cluster variance the least, giving compact clusters. Other options are single, complete and average linkage.
fclustercuts the tree to get a chosen number of clusters. Two clusters separates the high spenders, Gita and Hasan; three clusters also splits food-heavy from entertainment-heavy spenders.- Drawing the history as a dendrogram (
scipy.cluster.hierarchy.dendrogram) shows long vertical gaps where a cut gives well-separated clusters.
Choosing a Clustering Method
| K-means | DBSCAN | Hierarchical | |
|---|---|---|---|
| Number of clusters | Must be given | Found automatically | Chosen after building the tree |
| Cluster shape | Round, similar size | Any shape | Depends on linkage |
| Outliers | Forced into clusters | Labelled as noise | Forced into clusters |
| Main settings | k | eps, min_samples | Linkage, cut level |
| Large data | Very fast | Fast with indexing | Slow (memory grows with n2) |
Common Mistakes
- Not scaling features; all three methods depend on distances.
- Picking
epsblindly: too small makes everything noise, too large merges all clusters. Plot each point’s distance to its k-th nearest neighbour and look for the “elbow”. - Using DBSCAN when clusters have very different densities; one
epscannot suit them all. Try HDBSCAN. - Running hierarchical clustering on hundreds of thousands of rows, which needs too much memory.
Practice Exercises
Exercise 1. Run DBSCAN on the moons data with eps values 0.05, 0.2 and 0.6, and print the number of clusters and noise points for each.
Show answer
for eps in [0.05, 0.2, 0.6]:
labels = DBSCAN(eps=eps, min_samples=5).fit_predict(X)
k = len(set(labels)) - (1 if -1 in labels else 0)
print(eps, k, (labels == -1).sum())
A tiny eps marks most points as noise; a large eps merges the two moons into one cluster.
Exercise 2. Which method would you use to find unusual credit card transactions among normal ones, and why?
Show answer
DBSCAN, because it labels points in sparse regions as noise. Those noise points are candidate anomalies, whereas K-means and hierarchical clustering would place them inside some cluster.
Frequently Asked Questions
What is HDBSCAN?
A newer version of DBSCAN that builds a hierarchy of density levels and picks the most stable clusters, so it handles clusters of different densities and needs no eps. Scikit-learn includes it as sklearn.cluster.HDBSCAN.
How do I evaluate clusters without labels?
Use internal measures such as the silhouette score, which compares how close each point is to its own cluster versus the nearest other cluster, and check whether the clusters make sense to someone who knows the data.
Summary
- DBSCAN grows clusters from dense regions and labels outliers as noise.
- It finds the number of clusters itself and handles any shape.
- Hierarchical clustering records every merge; cut the tree at the level you need.
- Scale features and choose the method that matches your data’s shape and size.
Next: Handling Imbalanced Data.
