TExcelTAD
Home › Machine Learning › DBSCAN & Choosing Clusters

DBSCAN & Choosing Clusters

K-means needs you to pick the number of clusters and assumes round blobs. DBSCAN (Density-Based Spatial Clustering of Applications with Noise) takes a different approach: a cluster is a region where points are densely packed, separated from other clusters by sparse regions. It finds the number of clusters by itself, handles odd shapes, and labels isolated points as noise.

How DBSCAN works

Two parameters:

  • eps: the radius of a point's neighbourhood,
  • min_samples: how many points (including itself) must be within eps for a point to be a core point.

Then:

  1. Core points that are within eps of each other belong to the same cluster.
  2. Non-core points within eps of a core point join that cluster (border points).
  3. Everything else is noise, labelled -1.

Curved shapes: DBSCAN vs k-means

python · try it yourself
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.cluster import DBSCAN, KMeans

X, _ = make_moons(n_samples=300, noise=0.06, random_state=0)

km_labels = KMeans(n_clusters=2, n_init=10, random_state=0).fit_predict(X)
db_labels = DBSCAN(eps=0.2, min_samples=5).fit_predict(X)

fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].scatter(X[:, 0], X[:, 1], c=km_labels, cmap="coolwarm", s=10)
axes[0].set_title("k-means (k=2)")
axes[1].scatter(X[:, 0], X[:, 1], c=db_labels, cmap="coolwarm", s=10)
axes[1].set_title("DBSCAN")
plt.show()
print("DBSCAN found clusters:", sorted(set(db_labels.tolist())))
DBSCAN found clusters: [0, 1]

K-means cuts the moons with a straight line because it only knows "closest centre". DBSCAN follows the dense curved bands.

Noise points

DBSCAN doesn't force every point into a cluster. Here we add a few random outliers:

python · try it yourself
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import DBSCAN

X, _ = make_blobs(n_samples=150, centers=[[0, 0], [5, 5]], cluster_std=0.6, random_state=2)
rng = np.random.default_rng(0)
outliers = rng.uniform(-3, 8, size=(8, 2))
X_all = np.vstack([X, outliers])

labels = DBSCAN(eps=0.7, min_samples=5).fit_predict(X_all)
print("clusters:", sorted(set(labels.tolist()) - {-1}))
print("noise points:", int((labels == -1).sum()))
print("labels of the 8 added outliers:", labels[-8:])
clusters: [0, 1]
noise points: 11
labels of the 8 added outliers: [-1 -1 -1  1 -1 -1 -1 -1]

Some added points happen to land inside a blob and get absorbed; the truly isolated ones are labelled -1. This makes DBSCAN handy for anomaly detection.

Choosing eps

eps matters a lot. Too small: almost everything is noise. Too large: clusters merge. Try a few values:

python · try it yourself
from sklearn.datasets import make_moons
from sklearn.cluster import DBSCAN

X, _ = make_moons(n_samples=300, noise=0.06, random_state=0)
for eps in [0.05, 0.1, 0.2, 0.5, 1.0]:
    labels = DBSCAN(eps=eps, min_samples=5).fit_predict(X)
    n_clusters = len(set(labels) - {-1})
    print(f"eps={eps:<4}  clusters={n_clusters}  noise={int((labels == -1).sum())}")
eps=0.05  clusters=10  noise=243
eps=0.1   clusters=11  noise=15
eps=0.2   clusters=2  noise=0
eps=0.5   clusters=1  noise=0
eps=1.0   clusters=1  noise=0

A common heuristic: compute each point's distance to its min_samples-th nearest neighbour, sort those distances and look for the "knee" where they suddenly rise. Also remember to scale features first.

The silhouette score

How do you judge a clustering without labels? The silhouette score compares, for every point, the average distance to its own cluster (a) with the average distance to the nearest other cluster (b): (b - a) / max(a, b). It ranges from −1 to 1; higher means tighter, better-separated clusters. It's a good way to choose k for k-means:

python · try it yourself
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

X, _ = make_blobs(n_samples=400, centers=5, cluster_std=1.0, random_state=10)
for k in range(2, 9):
    labels = KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(X)
    print(f"k={k}: silhouette = {silhouette_score(X, labels):.3f}")
k=2: silhouette = 0.583
k=3: silhouette = 0.613
k=4: silhouette = 0.697
k=5: silhouette = 0.775
k=6: silhouette = 0.694
k=7: silhouette = 0.598
k=8: silhouette = 0.523

Unlike inertia, the silhouette score doesn't automatically improve with more clusters, so you can simply pick the k with the highest score.

Which clustering algorithm?

Algorithm Needs k? Cluster shapes Handles noise Scales to big data
K-means yes round, similar size no very well
Hierarchical (agglomerative) yes (or a cut height) depends on linkage no poorly (n² memory)
DBSCAN no (needs eps) any shape yes well
Gaussian mixture (GaussianMixture) yes elliptical, soft assignments no well

Test yourself

What label does DBSCAN give to noise points?

  1. 0
  2. -1
  3. None
  4. The nearest cluster

Which data would DBSCAN handle better than k-means?

  1. Three round, equal-sized blobs
  2. Two interleaving crescent shapes
  3. Data with no structure
  4. Points on a perfect grid

What does a silhouette score close to 1 indicate?

  1. Points are far from their own cluster
  2. Clusters are tight and well separated
  3. There is only one cluster
  4. The data is noisy