DBSCAN (Density-Based Spatial Clustering of Applications with Noise) groups points that are packed closely together and marks isolated points as noise. It finds clusters of any shape and does not need the number of clusters in advance.
What You Will Learn
- Core, border and noise points
- eps and min_samples
- DBSCAN vs K-Means on curved clusters
- Choosing eps with a k-distance plot
- When to use DBSCAN
Prerequisites
How It Works
| Point type | Rule |
|---|---|
| Core | Has at least min_samples points within distance eps |
| Border | Within eps of a core point but not core itself |
| Noise (label −1) | Neither core nor border |
Clusters grow by connecting core points that are within eps of each other.
DBSCAN vs K-Means
import numpy as np
from sklearn.datasets import make_moons
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import DBSCAN, KMeans
from sklearn.metrics import adjusted_rand_score
X, y = make_moons(300, noise=0.06, random_state=0) # two interleaving half-moons
X = StandardScaler().fit_transform(X)
db = DBSCAN(eps=0.3, min_samples=5).fit(X)
labels = db.labels_
print(set(labels), np.bincount(labels[labels >= 0]), (labels == -1).sum())
km = KMeans(n_clusters=2, n_init=10, random_state=0).fit(X)
print(round(adjusted_rand_score(y, labels), 3), round(adjusted_rand_score(y, km.labels_), 3))
{np.int64(0), np.int64(1), np.int64(-1)}
[150 149] 1
0.993 0.47
Explanation: DBSCAN finds both moons (150 and 149 points) and marks 1 point as noise. The adjusted Rand index (1 = perfect match with the true groups) is 0.993 for DBSCAN but only 0.47 for K-Means, which can only draw straight boundaries between round clusters. (NumPy 2 shows labels as np.int64(…); NumPy 1.x prints just {0, 1, -1}.)
Choosing eps
from sklearn.neighbors import NearestNeighbors
import matplotlib.pyplot as plt
dist, _ = NearestNeighbors(n_neighbors=5).fit(X).kneighbors(X)
plt.plot(np.sort(dist[:, -1])); plt.ylabel("distance to 5th neighbour"); plt.show()
Explanation: Sort each point’s distance to its k-th neighbour (k = min_samples). The “elbow” where the curve bends sharply upward is a good eps. Always scale features first, because eps is a distance.
| K-Means | DBSCAN | Hierarchical | |
|---|---|---|---|
| Number of clusters | Must choose k | Found automatically | Choose by cutting the dendrogram |
| Cluster shape | Round, similar size | Any shape | Depends on linkage |
| Outliers | Forced into clusters | Labelled noise | Forced into clusters |
| Weakness | Non-spherical data | Varying densities, high dimensions | Slow on big data |
Use Cases
- Geographic hotspots (GPS points of deliveries or crimes)
- Anomaly detection – the noise points
- Image segmentation
- Customer groups with irregular shapes
sklearn.cluster.HDBSCAN, scikit-learn 1.3+), which removes the need to pick eps.Series
ML fundamentals series: What is ML · Types of ML · Train/Test Split · Overfitting & Bias-Variance · Regularization · Confusion Matrix · ROC & AUC · Cross-Validation · Ensembles · DBSCAN
Interview Questions
Q: What are eps and min_samples?
eps is the neighbourhood radius; min_samples is how many points are needed within it to form a core point.
Q: Advantages of DBSCAN over K-Means?
No need to choose k, finds arbitrary shapes and identifies outliers as noise.
Practice Exercises
- Try eps = 0.1 and 0.6 and explain the results.
- Run DBSCAN on latitude/longitude data with the haversine metric.
Summary
DBSCAN clusters by density, finds any shape and labels outliers as −1. Scale features and pick eps from a k-distance plot.
Next: Hierarchical Clustering · PCA
Machine Learning Tutorials, Courses and Certifications