Sub topic 14
Where DBSCAN struggles
This chapter assumes you can run DBSCAN in scikit-learn. It also assumes you know the core, border and noise definitions, and that you have used the k-distance plot to pick eps. Here we look at the data and settings where those tools stop working, and at how to recognize each failure.
One density setting for the whole dataset
DBSCAN uses a single eps and a single min_samples everywhere. A point is core if at least min_samples points, itself included, lie within eps of it. That rule describes one density level. If your clusters sit at different densities, no single setting fits them all.
The following code builds two tight blobs and one diffuse blob, then sweeps eps.
import numpy as np
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_blobs
X, _ = make_blobs(
n_samples=[200, 200, 200],
centers=[[0, 0], [6, 0], [3, 6]],
cluster_std=[0.3, 0.3, 1.5],
random_state=0,
)
for eps in [0.2, 0.4, 0.8, 1.5]:
labels = DBSCAN(eps=eps, min_samples=5).fit_predict(X)
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
n_noise = int(np.sum(labels == -1))
print(f"eps={eps}: clusters={n_clusters}, noise={n_noise}")Expect a trade-off. With a small eps, the tight blobs form clusters, but most of the diffuse blob is labeled noise. With a large eps, the diffuse blob becomes a cluster, but the neighborhoods of its outer points start to reach the other blobs. Clusters can then merge. No value in the sweep recovers all three groups cleanly, and the k-distance plot shows several elbows instead of one.
Chaining through bridges
DBSCAN joins two dense regions if a chain of core points links them. This works like single linkage in hierarchical clustering. A thin line of points between two clusters, such as measurement noise or a road between two towns, can fuse them into one cluster. Raising min_samples helps, because a sparse bridge then has too few neighbors to produce core points. Raising it also turns more genuine low-density points into noise.
Border points depend on data order
Core points and noise points are fully determined by eps, min_samples and the data. Border points are not always determined. A border point that lies within eps of core points from two different clusters is assigned to whichever cluster reaches it first. In scikit-learn, that depends on the order of the rows. Shuffling the input can move a few border points between clusters, but it does not change which points are core or noise.
import numpy as np
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=300, centers=3, cluster_std=1.2, random_state=1)
base = DBSCAN(eps=0.6, min_samples=5).fit(X)
core_mask = np.zeros(len(X), dtype=bool)
core_mask[base.core_sample_indices_] = True
rng = np.random.default_rng(0)
perm = rng.permutation(len(X))
shuffled = DBSCAN(eps=0.6, min_samples=5).fit(X[perm])
shuffled_core = np.zeros(len(X), dtype=bool)
shuffled_core[shuffled.core_sample_indices_] = True
# Map the shuffled results back to the original row order.
core_back = np.zeros(len(X), dtype=bool)
core_back[perm] = shuffled_core
noise_back = np.zeros(len(X), dtype=bool)
noise_back[perm] = shuffled.labels_ == -1
print("same core points:", np.array_equal(core_mask, core_back))
print("same noise points:", np.array_equal(base.labels_ == -1, noise_back))Both checks should print True. Only the cluster labels of ambiguous border points can differ. This rarely matters in practice. It does matter if you compare runs exactly, or if you treat each border point's assignment as meaningful.
High-dimensional data
DBSCAN depends on a distance threshold, so it inherits the weakness of distance in many dimensions. As the number of features grows, distances between random points concentrate. The nearest and farthest neighbors end up at nearly the same distance, and "within eps" stops separating dense from sparse. This code measures the effect.
import numpy as np
from scipy.spatial.distance import pdist
rng = np.random.default_rng(0)
for d in [2, 10, 100, 1000]:
X = rng.random((300, d))
dist = pdist(X)
print(f"d={d}: min/max distance ratio = {dist.min() / dist.max():.2f}")The ratio rises toward 1 as d grows. Once every pair of points is about equally far apart, the k-distance plot has no elbow. Any eps makes either every point noise or every point part of one cluster. Reduce dimensionality first, for example with PCA, or choose a metric that suits the data, such as cosine distance for text vectors. Even then, check that the k-distance curve shows a clear bend.
Sensitivity to eps and scaling
Small changes in eps can change the result sharply. Near a threshold, an increase of a few percent can merge two clusters or turn a cluster's fringe into noise. Features on different scales also distort the eps ball, so a feature measured in thousands dominates the distance. Standardize features first, as covered in the scaling chapter. Also check how stable your clustering is across a small range of eps values, instead of trusting one setting.
Cost and memory
With a spatial index (a k-d tree or ball tree), neighborhood queries in low dimensions are fast, and DBSCAN is roughly O(n log n). The index loses its advantage as dimensionality grows, and the cost moves toward O(n²). Memory can also be a problem. scikit-learn stores the neighborhood of every point. A large eps on a large dataset can make those neighborhoods hold a large share of all n² pairs. If you hit memory errors, reduce eps, subsample the data, or use a precomputed sparse neighbor graph.
No predict for new points
DBSCAN has fit and fit_predict, but no predict. A new point has no stored cluster centroid, and adding it could in principle change which points are core. To label new data, you can assign each new point to the cluster of its nearest core point if that core point is within eps, and mark it noise otherwise. Treat this as an approximation.
Diagnosing a bad result
Summary of failure modes
| Problem | Cause | Typical remedy |
|---|---|---|
| Varying density | One global `eps` | OPTICS or HDBSCAN |
| Chaining | Core points connect through a sparse bridge | Raise `min_samples`, lower `eps` |
| Border point flips | Order-dependent assignment | Accept it, or ignore border assignments |
| High dimensions | Distances concentrate | PCA, a better metric |
| Sensitivity to `eps` | Hard density threshold | Sweep `eps` and check stability |
| Memory use | Stored neighborhoods | Subsample, lower `eps`, sparse graph |
| No `predict` | No cluster model | Nearest-core-point assignment |
Exercise
A dataset has one tight cluster and one sparse cluster. With eps=0.3, DBSCAN labels most of the sparse cluster as noise. With eps=1.0, it finds the sparse cluster but merges the tight cluster with a nearby one. Why does no eps fix this, and what would you try next?
Show answer
DBSCAN applies one eps and one min_samples to every region, so it can represent only one density level. An eps small enough to separate the tight clusters is too small to connect the sparse cluster, and an eps large enough for the sparse cluster joins nearby dense ones. Use a method that handles varying density, such as OPTICS or HDBSCAN. You can also cluster the regions separately or rescale the data if the density differences come from the feature scales.
Exercise
You shuffle the rows of a dataset and rerun DBSCAN with the same eps and min_samples. A handful of points change cluster. Which kinds of points can change, and which cannot?
Show answer
Only border points that lie within eps of core points from two different clusters can change, because they join whichever cluster reaches them first. Core points and noise points are fixed by eps, min_samples and the data, so they do not change.