Lesson 2 of 9
Density-Based Spatial Clustering (DBSCAN) & HDBSCAN for Arbitrary Geometries
DBSCAN (Density-Based Spatial Clustering of Applications with Noise) groups points based on local density reachability rather than distance to a central centroid. It defines clusters as dense regions separated by areas of low density, controlled by two parameters: `eps` (neighborhood radius) and `min_samples` (minimum points required to form a dense core). DBSCAN automatically discovers clusters of arbitrary non-linear shapes and marks peripheral noise as anomalies (label = -1).
DBSCAN on Non-Spherical Concentric Manifolds vs K-Means
import numpy as np
import pandas as pd
from sklearn.datasets import make_moons
from sklearn.cluster import DBSCAN, KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import adjusted_rand_score
# Generate non-linear interlocking half-moons
np.random.seed(42)
X_raw, y_true = make_moons(n_samples=500, noise=0.08, random_state=42)
X = StandardScaler().fit_transform(X_raw)
# 1. K-MEANS (Fails to capture non-linear geometry)
kmeans = KMeans(n_clusters=2, random_state=42)
kmeans_labels = kmeans.fit_predict(X)
# 2. DBSCAN (Captures arbitrary density-connected shapes)
dbscan = DBSCAN(eps=0.3, min_samples=5)
dbscan_labels = dbscan.fit_predict(X)
# Identify core samples vs noise
n_clusters = len(set(dbscan_labels)) - (1 if -1 in dbscan_labels else 0)
n_noise = np.sum(dbscan_labels == -1)
# Evaluate against true cluster structure via Adjusted Rand Index (ARI)
ari_kmeans = adjusted_rand_score(y_true, kmeans_labels)
ari_dbscan = adjusted_rand_score(y_true, dbscan_labels)
print("=== CLUSTERING ARBITRARY GEOMETRIES BENCHMARK ===")
print(f"K-Means Adjusted Rand Index : {ari_kmeans:.4f} (Fails: splits moons along straight line)")
print(f"DBSCAN Adjusted Rand Index : {ari_dbscan:.4f} (Perfect recovery of true manifold!)")
print(f"DBSCAN Clusters Identified : {n_clusters}")
print(f"Outlier Noise Points Flagged: {n_noise} (label = -1)")Pro Tip: The K-Distance Graph Heuristic for Tuning `eps`
Never guess `eps`. Plot the K-Distance Graph: For every point, compute the distance to its k-th nearest neighbor (`k = min_samples`). Sort distances in ascending order and plot the curve. The optimal `eps` is the 'knee' or 'elbow' where distance accelerates sharply.
MlDBSCANClustering Visual Representation
Hands-On Challenge: HDBSCAN Hierarchical Density Clustering
Use `sklearn.cluster.HDBSCAN` on a dataset with varying density clusters. Observe how HDBSCAN automatically extracts stable clusters across variable density thresholds without requiring a fixed `eps` parameter.
Quick Quiz & Key Concept Checks
Common Pitfall: Default `eps=0.5` on Unscaled Features
DBSCAN's default `eps=0.5` is arbitrary. If your features have unscaled ranges spanning 100 to 10,000, a neighborhood radius of 0.5 will find zero neighbors, marking 100% of the dataset as noise points (-1). Always standardize data before DBSCAN.