What is DBSCAN Clustering in Machine Learning?
Nov 03, 2026 6 Min Read 4839 Views
(Last Updated)
DBSCAN Clustering (Density-Based Spatial Clustering of Applications with Noise) is an unsupervised algorithm that groups points lying in densely packed regions and labels points in sparse regions as noise.
It requires no preset number of clusters and can recover clusters of arbitrary shape, making it a common alternative to K-Means for irregular, noisy data.
Table of contents
- TL;DR Summary
- What is DBSCAN Clustering?
- Key Parameters
- How DBSCAN Works
- Density Reachability and Connectivity
- DBSCAN Clustering Implementation in Python
- What the -1 Label Means
- Distance Metric and Feature Scaling
- How to Choose eps and min_samples
- DBSCAN vs K-Means vs Hierarchical Clustering
- DBSCAN vs K-Means on Non-Spherical Data
- OPTICS and HDBSCAN
- Time Complexity
- Applications of DBSCAN Clustering
- Limitations of DBSCAN Clustering
- Conclusion
- FAQs
- What is DBSCAN Clustering used for?
- What are core, border and noise points in DBSCAN?
- How do you choose eps and min_samples?
- What does -1 mean in DBSCAN labels?
- Is DBSCAN better than K-Means?
- What is the time complexity of DBSCAN?
- Can DBSCAN handle clusters of different densities?
TL;DR Summary
- DBSCAN Clustering groups points by local density instead of distance to a centroid, determines the number of clusters by itself, and marks sparse points as noise.
- Two parameters control the result:
eps(neighborhood radius) andmin_samples(points required for a dense region). Features should be scaled first. - It copes well with curved clusters and outliers, but it uses one global
eps, so it handles clusters of different density and high-dimensional data poorly.
What is DBSCAN Clustering?
DBSCAN Clustering is a density-based method that defines a cluster as a maximal set of points connected through dense neighborhoods.
A neighborhood is dense when it holds at least min_samples points within a radius of eps, and points that no dense neighborhood reaches are treated as noise.
Key Parameters
eps is the largest distance at which two points count as neighbors. The neighborhood of a point contains every point within eps of it, the point itself included. A value that is too small fragments clusters, and one that is too large merges them.
min_samples (called minPts in the original paper) is the number of points a neighborhood must contain for its center to qualify as a core point. scikit-learn counts the point itself. Higher values demand denser regions and produce more noise. The defaults are eps=0.5 and min_samples=5.
DBSCAN is one of dozens of algorithms a working ML engineer must choose between. HCL GUVI’s Intel & IITM Pravartak Certified AI/ML Course teaches that wider toolkit, from classical machine learning to deep learning and Generative AI, in live classes led by industry experts and Intel engineers, with no prior coding experience required!
How DBSCAN Works
Every point receives one of three roles:
- Core point: at least
min_samplespoints, itself included, lie withineps. - Border point: fewer than
min_samplesneighbors, but withinepsof a core point. - Noise point: neither a core point nor a border point.
The algorithm runs as follows:
- Select an unvisited point and find every point within
epsof it. - If the count is below
min_samples, tentatively mark the point as noise and move on. - Otherwise, start a new cluster containing the point and its neighbors.
- For each neighbor that is also a core point, add that neighbor’s own neighbors to the cluster. Continue until nothing more can be added.
- Pick the next unvisited point and repeat until all points have been visited.
A point first marked as noise can later be claimed as a border point by a cluster that reaches it.
Density Reachability and Connectivity
- Directly density-reachable: point q is directly density-reachable from p if q lies within
epsof p and p is a core point. - Density-reachable: q is density-reachable from p if a chain of points leads from p to q, each directly density-reachable from the one before it.
- Density-connected: p and q are density-connected if some point o exists from which both are density-reachable.
A cluster is a maximal set of density-connected points. A border point cannot extend a chain, so reachability is asymmetric: a core point reaches a border point, but not the reverse.
When a border point lies within eps of core points from two clusters, it joins whichever cluster reaches it first, so its assignment can depend on the row order of the data.
DBSCAN Clustering Implementation in Python
The code below, run with scikit-learn 1.9.1, generates 300 points in four blobs and compares three parameter settings.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score, adjusted_rand_score
X, y_true = make_blobs(n_samples=300, centers=4, cluster_std=0.50, random_state=42)
settings = {"A": (0.2, 5), "B": (0.5, 5), "C": (0.5, 15)}
results = {}
for name, (eps, min_samples) in settings.items():
labels = DBSCAN(eps=eps, min_samples=min_samples).fit_predict(X)
results[name] = labels
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
n_noise = int(np.sum(labels == -1))
sil = silhouette_score(X, labels)
ari = adjusted_rand_score(y_true, labels)
print(f"Case {name}: clusters={n_clusters}, noise={n_noise}, "
f"silhouette={sil:.2f}, ARI={ari:.2f}")
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
for ax, (name, labels) in zip(axes, results.items()):
noise = labels == -1
ax.scatter(X[~noise, 0], X[~noise, 1], c=labels[~noise], cmap="tab10", s=18)
ax.scatter(X[noise, 0], X[noise, 1], c="black", marker="x", s=18)
ax.set_title(f"Case {name}: eps={settings[name][0]}, min_samples={settings[name][1]}")
plt.show()
Output:
Case A: clusters=9, noise=126, silhouette=-0.11, ARI=0.22
Case B: clusters=4, noise=7, silhouette=0.85, ARI=0.97
Case C: clusters=4, noise=33, silhouette=0.71, ARI=0.84
Case A uses an eps too small for this data, so the points split into nine fragments and 126 of 300 are labeled noise.
Case B recovers the four generating groups almost exactly.
Case C keeps the same eps but raises min_samples to 15, which leaves four clusters but moves 33 points into noise.
Adjusted Rand Index (ARI) compares labels with known ground truth, so it applies only to labeled or synthetic data.
The silhouette score above treats noise as one extra group and favors compact, convex clusters, so it is an unreliable judge of DBSCAN on curved shapes. Density-based validation (DBCV) suits unlabeled data better.
What the -1 Label Means
DBSCAN.labels_ holds one integer per point. Values 0, 1, 2 and so on identify clusters, and -1 identifies noise. The value -1 is not a cluster and must be excluded from cluster counts.
The indices of core points are stored in core_sample_indices_, and any labeled point outside that array is a border point. In Case B, 277 points are core, 16 are border, and 7 are noise.
Distance Metric and Feature Scaling
Neighborhoods are measured with the metric parameter, which defaults to Euclidean. Because eps is one distance applied across all features, a feature measured in thousands will dominate one measured in decimals, so standardize features before clustering.
For latitude and longitude, use the haversine metric on coordinates converted to radians, and express eps in radians by dividing kilometers by 6371.0088, the mean Earth radius.
from sklearn.preprocessing import StandardScaler
X_scaled = StandardScaler().fit_transform(X)
# Geographic data: coordinates in degrees, neighborhood radius of 0.5 km
coords = np.radians(latlon_degrees) # columns: latitude, longitude
geo = DBSCAN(eps=0.5 / 6371.0088, min_samples=10,
metric="haversine", algorithm="ball_tree").fit(coords)
How to Choose eps and min_samples
Begin with min_samples. A common heuristic is at least the number of features plus one, and often twice the number of features, which gives 4 for two-dimensional data. Then estimate eps with a k-distance graph:
- Set k equal to
min_samples. - Compute, for every point, the distance to its k-th nearest neighbor. The point itself is returned as its own first neighbor, matching how scikit-learn counts
min_samples. - Sort these distances in ascending order and plot them.
- Read
epsfrom the elbow, where the curve turns sharply upward.
from sklearn.neighbors import NearestNeighbors
min_samples = 5
distances, _ = NearestNeighbors(n_neighbors=min_samples).fit(X).kneighbors(X)
k_distances = np.sort(distances[:, -1])
plt.plot(k_distances)
plt.xlabel("Points sorted by distance")
plt.ylabel("Distance to neighbor 5 (point itself counted)")
plt.title("k-distance graph")
plt.show()
On the blob data, 90% of the points have a distance below about 0.47, after which the curve climbs to a maximum of 1.36. An eps near 0.5 is therefore a sensible choice.
During tuning, one giant cluster means eps is too large, while mostly noise means eps is too small or min_samples too high.
Choosing eps and min_samples is learned by running the algorithm on messy datasets, not by reading about it. HCL GUVI’s Intel & IITM Pravartak Certified AI/ML Course builds that experience through 20+ industry-grade projects and a capstone, with 1:1 doubt sessions with subject matter experts when a result looks wrong!
DBSCAN vs K-Means vs Hierarchical Clustering
| Factor | K-Means | DBSCAN | Hierarchical |
|---|---|---|---|
| Cluster definition | Distance to a centroid | Connected dense regions | Nested merges shown as a dendrogram |
| Number of clusters | Chosen in advance | Found from eps and min_samples | Chosen by cutting the dendrogram |
| Cluster shape | Roughly spherical, similar size | Arbitrary | Depends on the linkage method |
| Outliers | Assigned to a cluster and distort centroids | Labeled as noise | Assigned to a cluster |
| Scalability | Close to linear in the number of points | Near n log n with a spatial index, weaker in high dimensions | Quadratic time and memory or worse |
| Typical use | Customer segmentation, color quantization | Hotspot detection, anomaly detection | Taxonomies, small datasets |
DBSCAN is the stronger choice when the cluster count is unknown, outliers are present, or clusters are curved. K-Means is the stronger choice for large, high-dimensional data with compact clusters of similar size. DBSCAN removes the need to choose k but introduces eps and min_samples in its place.
It also does not handle clusters of different density. A single eps cannot suit a dense cluster and a sparse one at once, so the sparse cluster is either labeled noise or the dense clusters merge. OPTICS and HDBSCAN, covered below, address this.
DBSCAN vs K-Means on Non-Spherical Data
K-Means assigns each point to its nearest centroid, so its cluster boundaries are straight lines between centroids and cannot follow a crescent. The two-moons dataset shows the difference.
from sklearn.cluster import KMeans
from sklearn.datasets import make_moons
Xm, ym = make_moons(n_samples=300, noise=0.06, random_state=42)
km_labels = KMeans(n_clusters=2, n_init=10, random_state=42).fit_predict(Xm)
db_labels = DBSCAN(eps=0.2, min_samples=5).fit_predict(Xm)
print("K-Means ARI:", round(adjusted_rand_score(ym, km_labels), 2))
print("DBSCAN ARI:", round(adjusted_rand_score(ym, db_labels), 2))
K-Means scores an ARI of 0.25, as it cuts across both moons. DBSCAN scores 1.00, recovering both shapes with no noise points.
OPTICS and HDBSCAN
Both algorithms extend DBSCAN to data with varying density, and both are in scikit-learn (OPTICS since version 0.21, HDBSCAN since 1.3).
OPTICS orders points by reachability distance and produces a reachability plot from which clusters at different density levels can be extracted, so it needs no fixed eps.
HDBSCAN builds a hierarchy across all eps values and keeps the clusters that persist the longest. Its main parameter is min_cluster_size, and it labels noise as -1. HDBSCAN is usually the first choice when densities differ, while OPTICS suits inspection through its reachability plot.
from sklearn.cluster import HDBSCAN
labels = HDBSCAN(min_cluster_size=10, copy=True).fit_predict(X)
Time Complexity
The original paper reports an average of O(n log n). DBSCAN issues one neighborhood query per point, and a spatial index such as an R*-tree answers each query in O(log n).
Without an index, or when the index loses its advantage in high dimensions, each query costs O(n) and the total becomes O(n²).
Memory use can approach O(n²) when many points fall inside one another’s neighborhoods, because neighborhoods are stored.
Applications of DBSCAN Clustering
- Anomaly detection: transactions, network flows and sensor readings that fit no dense pattern receive the label -1 and become candidates for review.
- Geospatial hotspots: Huang et al. (2021) clustered about 200 GB of taxi GPS records from Huai’an, China, using DBSCAN+, a parallel DBSCAN variant with Eps of 30 m and MinPts of 3, to locate passenger hotspots at a scale that single-threaded DBSCAN could not handle (Scientific Reports 11, 9420).
- Medical image segmentation: Baselice et al. (2015) applied a modified DBSCAN to per-pixel proton density and relaxation-time estimates, instead of gray-level intensity, to segment and classify brain MR images. On a simulated case study it improved the correct classification rate over a Euclidean-distance approach (IEEE EMBC 2015, pages 2993 to 2996).
Limitations of DBSCAN Clustering
- Parameter sensitivity: small changes in
epscan split or merge clusters. - Varying density: one global
epscannot fit clusters of different density, which is the case HDBSCAN was designed for. - High dimensions: distances lose contrast as dimensions grow, so neighborhoods stop being informative. Reduce dimensionality with PCA or a similar method first.
- No prediction step: DBSCAN has no
predictmethod, so new points require a nearest-core-point rule or a refit.
A point joins a DBSCAN cluster only when enough neighbors support it, and a career in machine learning needs a similar base of connected skills. HCL GUVI’s Intel & IITM Pravartak Certified AI/ML Course builds that base across Python, SQL, machine learning, deep learning and MLOps, with live classes, 20+ projects and placement guidance.
Conclusion
DBSCAN Clustering stands out as a clustering algorithm because it identifies groups of data points based on density and separates noise without forcing every point into a cluster.
It handles irregular shapes better than many traditional methods and offers flexibility for real-world datasets.
With the right approach, DBSCAN becomes a reliable choice for tasks such as anomaly detection and scientific research. Experiment with different parameters, then decide where DBSCAN Clustering delivers the best fit.
FAQs
1. What is DBSCAN Clustering used for?
It finds arbitrarily shaped clusters and outliers, for example, in geospatial analysis, anomaly detection and image segmentation.
2. What are core, border and noise points in DBSCAN?
A core point has at least min_samples points within eps, a border point lies within eps of a core point without being core, and a noise point is neither.
3. How do you choose eps and min_samples?
Set min_samples from the feature count (at least features plus one, often twice the features) and read eps from the elbow of the k-distance graph.
4. What does -1 mean in DBSCAN labels?
It marks noise points that belong to no cluster.
5. Is DBSCAN better than K-Means?
It is better for non-spherical clusters, outliers and an unknown cluster count, while K-Means is better for large datasets with compact, similar-sized clusters.
6. What is the time complexity of DBSCAN?
It averages O(n log n) with a spatial index and degrades to O(n²) without one.
7. Can DBSCAN handle clusters of different densities?
Not well, because it uses a single eps, and HDBSCAN or OPTICS suit this case better.



Did you enjoy this article?