Sub topic 13
Running DBSCAN in scikit-learn
This chapter assumes you know how core, border, and noise points are defined, and what eps and min_samples control. It also assumes you are comfortable with NumPy and scikit-learn's fit style API. Here you run DBSCAN end to end and read its output.
The workflow
DBSCAN measures distance, so scale first. Then fit, and inspect the labels.
Fitting the model
The example below clusters two interleaved half-moons, a shape that centroid-based methods handle poorly.
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_ # the label -1 marks noise
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
n_noise = int(np.sum(labels == -1))
print(n_clusters, n_noise)Cluster labels are integers starting at 0. The label -1 means noise, so subtract it when you count clusters. DBSCAN has no predict method. Density is defined relative to the training set, so there is no natural way to assign a new point. Use fit_predict when you only need labels.
Estimating eps
Fix min_samples first. A common starting point is twice the number of features, with a minimum of about 4 or 5. Then plot each point's distance to its min_samples-th neighbor, sorted. A good eps lies near the elbow, where distances start to rise sharply.
import numpy as np
import matplotlib.pyplot as plt
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)
X = StandardScaler().fit_transform(X)
min_samples = 5
# The query points are the training points, so each point is its own first neighbor,
# which matches how DBSCAN counts min_samples.
nn = NearestNeighbors(n_neighbors=min_samples).fit(X)
distances, _ = nn.kneighbors(X)
k_dist = np.sort(distances[:, -1])
plt.plot(k_dist)
plt.xlabel("points sorted by distance")
plt.ylabel(f"distance to neighbor number {min_samples}")
plt.show()The elbow is a heuristic and is often fuzzy. Treat it as a first guess and try values on either side.
Reading the fitted model
The fitted object exposes core_sample_indices_. Every clustered point that is not core is a border point.
is_core = np.zeros(len(labels), dtype=bool)
is_core[db.core_sample_indices_] = True
is_noise = labels == -1
is_border = ~is_core & ~is_noise
print(is_core.sum(), is_border.sum(), is_noise.sum())Scoring the result
Silhouette score needs at least two clusters, and noise points should be left out of it. Otherwise the single noise group is scored as if it were a real cluster.
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
X, _ = make_blobs(n_samples=300, centers=3, cluster_std=0.6, random_state=7)
X = StandardScaler().fit_transform(X)
labels = DBSCAN(eps=0.3, min_samples=5).fit_predict(X)
# Silhouette needs at least 2 clusters, and noise points should be excluded.
mask = labels != -1
if len(set(labels[mask])) >= 2:
print(silhouette_score(X[mask], labels[mask]))
else:
print("Fewer than two clusters found; adjust eps or min_samples")Also report the fraction of points marked as noise. A high silhouette score is easy to reach by discarding most of the data.
Common errors
- Unscaled features. One large-valued column dominates the distance, so
epsmeans little. - Everything is noise.
epsis too small ormin_samplestoo large. - One giant cluster.
epsis too large, so separate dense regions merge. - Treating
-1as a cluster. It is a "no cluster" marker.
Exercise
You fit DBSCAN and find that 85% of points have label -1. Name two parameter changes that could fix this, and say which direction each moves.
Show answer
Increase eps, or decrease minsamples. A larger eps lets more points fall within each other's neighborhoods, and a smaller minsamples makes it easier for a point to qualify as core. Both make clusters easier to form. Also check that the features were scaled.