Sub topic 13
Running DBSCAN in scikit-learn
This chapter assumes you know how DBSCAN defines core, border, and noise points. It also assumes you know what eps and min_samples mean, and that you have used scikit-learn's fit and fit_predict methods. Here you will run DBSCAN, read its outputs, and avoid the usual mistakes.
The estimator and its parameters
sklearn.cluster.DBSCAN follows the usual estimator pattern, with a few differences.
| Parameter | Default | What it controls |
|---|---|---|
| `eps` | 0.5 | Neighborhood radius. A point's neighbors are the points within this distance, including the point itself. |
| `min_samples` | 5 | Neighbors needed, counting the point itself, for a point to be a core point. |
| `metric` | `"euclidean"` | Distance function. Also accepts `"precomputed"` for a distance matrix. |
| `algorithm` | `"auto"` | Neighbor search method: `ball_tree`, `kd_tree`, or `brute`. |
| `n_jobs` | `None` | Parallel workers for the neighbor search. |
After fitting, three attributes matter most:
labels_holds one integer per sample. Clusters are numbered from 0, and noise is-1.core_sample_indices_holds the indices of the core points.components_holds the coordinates of the core points.
The default eps=0.5 has no meaning independent of your data's units. Never rely on it.
A first run
The code below scales the features, fits DBSCAN, and separates the three point types. Border points are the points that are neither core nor noise.
import numpy as np
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_moons
from sklearn.preprocessing import StandardScaler
X, _ = make_moons(n_samples=300, noise=0.05, random_state=0)
X = StandardScaler().fit_transform(X)
db = DBSCAN(eps=0.3, min_samples=5).fit(X)
labels = db.labels_
core_mask = np.zeros(len(X), dtype=bool)
core_mask[db.core_sample_indices_] = True
noise_mask = labels == -1
border_mask = ~core_mask & ~noise_mask
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
print("clusters:", n_clusters)
print("core:", int(core_mask.sum()))
print("border:", int(border_mask.sum()))
print("noise:", int(noise_mask.sum()))The expression len(set(labels)) - (1 if -1 in labels else 0) matters. The label -1 is not a cluster, so you must subtract it before reporting a cluster count.
Why scaling comes first
eps is one radius applied to every feature at once. If one feature ranges from 0 to 100000 and another from 0 to 1, the large feature decides every neighbor test. After StandardScaler, each feature has unit variance, so one eps is meaningful across all of them.
Scale only when the features are comparable in importance. For geographic coordinates, scaling latitude and longitude separately distorts real distances. Use a metric that matches the geometry instead, as shown below.
Sensitivity to eps
Small changes in eps can change the result a lot. Sweeping a few values is a quick sanity check.
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_moons
from sklearn.preprocessing import StandardScaler
X, _ = make_moons(n_samples=300, noise=0.05, random_state=0)
X = StandardScaler().fit_transform(X)
for eps in [0.1, 0.2, 0.3, 0.5, 1.0]:
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((labels == -1).sum())
print(f"eps={eps}: clusters={n_clusters}, noise={n_noise}")Expect two patterns. Very small eps fragments the data into many tiny clusters and labels most points as noise. Very large eps merges everything into one cluster. A good value sits between these extremes, where the cluster count is stable across a range of eps values.
Other metrics
Pass any metric supported by sklearn.metrics.pairwise_distances. For latitude and longitude, use haversine, which expects radians and returns distances in radians. Convert a physical radius by dividing by Earth's radius, about 6371 km.
import numpy as np
from sklearn.cluster import DBSCAN
# Latitude and longitude in degrees: three points near Paris, two near Tokyo.
coords_deg = np.array([
[48.8566, 2.3522],
[48.8606, 2.3376],
[48.8530, 2.3499],
[35.6762, 139.6503],
[35.6895, 139.6917],
])
coords_rad = np.radians(coords_deg)
eps_km = 5.0
db = DBSCAN(
eps=eps_km / 6371.0,
min_samples=2,
metric="haversine",
algorithm="ball_tree",
).fit(coords_rad)
print(db.labels_)The ball_tree algorithm supports haversine. You can also compute a full distance matrix yourself and use metric="precomputed". That option works for custom dissimilarities, but the matrix needs memory proportional to n squared.
There is no predict method
DBSCAN has fit and fit_predict but no predict. The algorithm defines clusters over the whole dataset, so a new point has no stored model to be assigned by. A common workaround assigns a new point to the cluster of its nearest core point, provided that core point is within eps. Otherwise the new point is noise.
import numpy as np
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_moons
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import StandardScaler
X, _ = make_moons(n_samples=300, noise=0.05, random_state=0)
scaler = StandardScaler().fit(X)
X_scaled = scaler.transform(X)
db = DBSCAN(eps=0.3, min_samples=5).fit(X_scaled)
core_labels = db.labels_[db.core_sample_indices_]
X_new, _ = make_moons(n_samples=20, noise=0.05, random_state=1)
X_new_scaled = scaler.transform(X_new)
nn = NearestNeighbors(n_neighbors=1).fit(db.components_)
dist, idx = nn.kneighbors(X_new_scaled)
new_labels = np.where(dist[:, 0] <= db.eps, core_labels[idx[:, 0]], -1)
print(new_labels)Use scaler.transform on new data, not fit_transform. Refitting the scaler would put new points in a different coordinate system from the model.
Scale and memory
A neighbor search with a tree index costs roughly O(n log n) in low dimensions. In high dimensions, trees lose their advantage and the cost approaches O(n²). The memory cost is a bigger concern. scikit-learn's implementation stores each point's full neighbor list. If eps is large or the data is dense, those lists can grow toward n² entries and exhaust memory, even when the final clustering is simple. If memory spikes, lower eps, subsample, or consider HDBSCAN, which later chapters mention.
Common errors
- Forgetting to scale. Distances are dominated by the largest-range feature.
- Counting
-1as a cluster. Subtract it from the cluster count. - Treating
min_samplesas excluding the point. scikit-learn counts the point itself. - Passing
epsin the wrong units. Withhaversine,epsis in radians, not kilometers. - Scoring noise. Metrics such as the silhouette score expect real clusters. Exclude the
-1points, and check that at least two clusters remain before calling the metric. - Expecting a
predictmethod. Use the nearest-core-point approach above.
Exercise
A DBSCAN run on scaled data returns labels that contain 0, 1, 2, and -1. How many clusters did it find, and how would you list the border points?
Show answer
It found three clusters, because -1 marks noise and is not a cluster. Border points are in a cluster (label not equal to -1) but are not core points. Build a boolean mask from db.core_sample_indices_, then select (labels != -1) & ~core_mask.
Exercise
You fit DBSCAN with metric="haversine" on latitude and longitude in degrees and eps=5, hoping for a 5 km radius. Everything lands in one cluster. What went wrong, and how do you fix it?
Show answer
Haversine expects coordinates in radians and returns distances in radians, so eps=5 is a huge radius that covers the whole globe. Convert the coordinates with np.radians and set eps=5 / 6371, which is 5 km divided by Earth's radius in km.