DBSCAN: Density-Based Clustering
GPS points of taxi pick-ups form dense clusters at stations and along busy streets, with scattered points everywhere else. k-means would force every stray point into a cluster and cut the curved streets into round pieces. DBSCAN (Density-Based Spatial Clustering of Applications with Noise, Ester and colleagues, 1996) defines a cluster as a region where points are densely packed, follows such regions in any shape, finds the number of clusters by itself, and labels isolated points as noise. The Machine Learning course introduces it; here you trace it point by point and implement it.
Definitions
Two parameters: a radius (eps) and a count minPts (scikit-learn: min_samples). The -neighbourhood of a point is every point within distance , the point itself included. Then:
- a core point has at least
minPtspoints in its -neighbourhood; - a border point is not core but lies in the neighbourhood of a core point;
- a noise point is neither.
A cluster is a maximal set of core points that can reach each other through chains of neighbouring core points, plus the border points attached to them. The algorithm visits each point once: when it meets an unvisited core point, it starts a new cluster and grows it by a breadth-first search through core points' neighbourhoods. A border point within reach of two clusters joins whichever reaches it first.
Step through it
Sixteen points: two dense groups and some strays, , minPts . Core points are drawn large, border points hollow, noise as crosses; each frame shows one visited point's -circle:
The same points through scikit-learn's DBSCAN:
import numpy as np
from sklearn.cluster import DBSCAN
points = np.array([[10, 10], [14, 12], [12, 17], [18, 15], [15, 8], [24, 12],
[60, 60], [64, 64], [61, 69], [68, 63], [66, 56], [72, 68], [57, 66],
[40, 40], [85, 20], [30, 80]])
db = DBSCAN(eps=8, min_samples=3).fit(points)
core = np.zeros(len(points), bool); core[db.core_sample_indices_] = True
for i, (p, lab) in enumerate(zip(points.tolist(), db.labels_)):
kind = "core" if core[i] else ("border" if lab >= 0 else "noise")
print(f"point {i:2d} {str(p):9s} cluster {lab:2d} {kind}")point 0 [10, 10] cluster 0 core
point 1 [14, 12] cluster 0 core
point 2 [12, 17] cluster 0 core
point 3 [18, 15] cluster 0 core
point 4 [15, 8] cluster 0 core
point 5 [24, 12] cluster 0 border
point 6 [60, 60] cluster 1 core
point 7 [64, 64] cluster 1 core
point 8 [61, 69] cluster 1 core
point 9 [68, 63] cluster 1 core
point 10 [66, 56] cluster 1 core
point 11 [72, 68] cluster 1 border
point 12 [57, 66] cluster 1 core
point 13 [40, 40] cluster -1 noise
point 14 [85, 20] cluster -1 noise
point 15 [30, 80] cluster -1 noise
Point 5 at has only one other point within 8, at distance ; with itself that makes 2, fewer than 3, so it is not core, but it is in a core point's neighbourhood and joins as a border point. The three strays are noise (label ). Nobody told the algorithm there were two clusters.
From scratch on two moons
The moons data with three added outliers. k-means with is compared too, using the adjusted Rand index (ARI) against the true moons:
import numpy as np
from sklearn.datasets import make_moons
from sklearn.cluster import DBSCAN, KMeans
from sklearn.metrics import adjusted_rand_score
X, moon = make_moons(n_samples=200, noise=0.06, random_state=0)
X = np.vstack([X, [[-1.0, 1.4], [2.2, -0.8], [0.5, 1.6]]]) # three outliers
def dbscan(X, eps, min_pts):
D = np.sqrt(((X[:, None] - X[None]) ** 2).sum(axis=2))
neighbours = [np.flatnonzero(row <= eps) for row in D] # includes the point itself
core = np.array([len(nb) >= min_pts for nb in neighbours])
labels = np.full(len(X), -1) # -1 = noise
cluster = 0
for i in range(len(X)):
if labels[i] != -1 or not core[i]:
continue
labels[i] = cluster
queue = list(neighbours[i])
while queue: # grow the cluster through core points
j = queue.pop()
if labels[j] == -1:
labels[j] = cluster
if core[j]:
queue.extend(neighbours[j])
cluster += 1
return labels, core
labels, core = dbscan(X, eps=0.2, min_pts=5)
sk = DBSCAN(eps=0.2, min_samples=5).fit(X)
print("clusters:", labels.max() + 1, " noise points:", int(np.sum(labels == -1)), " core points:", int(core.sum()))
print("same core points as sklearn:", bool(np.all(core[sk.core_sample_indices_]) and core.sum() == len(sk.core_sample_indices_)))
print("same noise points as sklearn:", bool(np.all((labels == -1) == (sk.labels_ == -1))))
print("outliers' labels:", labels[-3:].tolist())
km = KMeans(n_clusters=2, n_init=10, random_state=0).fit(X)
print("agreement with the true moons (ARI): DBSCAN", round(adjusted_rand_score(moon, labels[:200]), 3),
" k-means", round(adjusted_rand_score(moon, km.labels_[:200]), 3))clusters: 2 noise points: 3 core points: 197
same core points as sklearn: True
same noise points as sklearn: True
outliers' labels: [-1, -1, -1]
agreement with the true moons (ARI): DBSCAN 1.0 k-means 0.256
DBSCAN recovers both moons exactly (ARI 1.0) and flags exactly the three added outliers as noise, matching scikit-learn's core and noise points. k-means, which can only draw a straight boundary between two centroids, cuts across the moons (ARI 0.256).
Choosing eps
A practical rule: compute each point's distance to its minPts-th nearest neighbour, sort these distances, and look for the "knee" where they shoot up; points beyond it are in sparse regions. Then compare a few values:
import numpy as np
from sklearn.datasets import make_moons
from sklearn.neighbors import NearestNeighbors
from sklearn.cluster import DBSCAN
X, _ = make_moons(n_samples=200, noise=0.06, random_state=0)
X = np.vstack([X, [[-1.0, 1.4], [2.2, -0.8], [0.5, 1.6]]])
k = 5
dist, _ = NearestNeighbors(n_neighbors=k).fit(X).kneighbors(X) # the point itself is the first neighbour
kdist = np.sort(dist[:, -1])
print("sorted distance to the 5th neighbour (itself counted), every 25th point:", kdist[::25].round(3))
print("the largest five:", kdist[-5:].round(3))
for eps in [0.05, 0.1, 0.2, 0.4, 0.8]:
lab = DBSCAN(eps=eps, min_samples=k).fit(X).labels_
print(f"eps {eps:4.2f}: clusters {lab.max() + 1}, noise {np.sum(lab == -1):3d}")sorted distance to the 5th neighbour (itself counted), every 25th point: [0.057 0.079 0.089 0.097 0.105 0.113 0.124 0.145 0.646]
the largest five: [0.218 0.273 0.646 0.709 0.729]
eps 0.05: clusters 0, noise 203
eps 0.10: clusters 18, noise 58
eps 0.20: clusters 2, noise 3
eps 0.40: clusters 1, noise 3
eps 0.80: clusters 1, noise 0
The 5-th neighbour distance is below 0.15 for almost every point and jumps to above 0.6 for the three outliers: any between about 0.2 and 0.27 separates dense from sparse. Too small an shatters the moons into 18 fragments (or everything is noise); too large merges the moons () and then swallows the outliers (). A common starting point for minPts is twice the number of features.
Strengths, weaknesses, when to use it
| Strengths | Weaknesses |
|---|---|
| clusters of any shape | one for the whole data: clusters of very different density cannot all be found |
| finds the number of clusters | sensitive to ; needs scaled features |
| labels outliers as noise | struggles in high dimensions (distances concentrate) |
| deterministic for core and noise points | border points between clusters depend on visiting order |
Use DBSCAN for spatial data, for irregular clusters with noise, and as an outlier detector. HDBSCAN (sklearn.cluster.HDBSCAN) runs DBSCAN over all values at once and keeps the most stable clusters, which handles varying densities and removes the need to choose .
Pitfalls
- Forgetting that the point counts itself.
min_samples=5means the point plus 4 neighbours, in scikit-learn and in the viz above. - Raw coordinates in different units. Latitude and longitude degrees are not equal distances; project them or use the haversine metric.
- Treating noise as a cluster. Label is "no cluster"; metrics like silhouette count it as one unless you drop it.
Practice
- Keeping
min_samples=3, how large must be before the point in the step-through example stops being noise, and what does it become?
Answer
Its nearest core point is at ; every other point is farther than 30. With it lies in that core point's neighbourhood, but it has only one neighbour besides itself, so it becomes a border point of cluster 1, not a core point. A radius more than three times the one that describes the clusters well is a sign that the point really is an outlier.
- Why can DBSCAN's border points depend on the order of the data, while core and noise points do not?
Answer
Core status depends only on neighbour counts, and noise means "no core point within ", both order-free. A border point within reach of core points of two clusters is assigned to whichever cluster's search reaches it first, which depends on the visiting order.
Test yourself
When is a point a core point in DBSCAN?
- When it is the centroid of a cluster
- When at least
minPtspoints, itself included, lie within distance - When it has no neighbours
- When it is on a cluster's edge
What does DBSCAN do with an isolated point far from every cluster?
- Assigns it to the nearest cluster
- Labels it noise ()
- Makes it its own cluster
- Removes it from the data
Which situation suits DBSCAN better than k-means?
- Five round, equal-size clusters
- Curved clusters with scattered outliers
- Data with 500 features
- You must have exactly 4 clusters