Sub topic 12
Choosing eps and min_samples
DBSCAN needs two numbers, eps and min_samples. Together they define what "dense" means for your data, so the output depends heavily on them. This chapter explains what each parameter controls, how to pick starting values, and how to check the result.
This chapter assumes you know how DBSCAN labels core, border, and noise points. It also assumes you have scaled your features, as covered earlier, and that you can run scikit-learn estimators.
What each parameter controls
eps is a distance. Two points are neighbors if the distance between them is at most eps. The unit is whatever your metric and feature scale produce. An eps of 0.3 means something very different on standardized data than on raw prices in dollars.
min_samples is a count. A point is a core point if at least min_samples points lie within eps of it, including the point itself. This detail matters when you copy advice from papers, because some sources do not count the point itself.
The two parameters work as a pair. They fix a density threshold: at least min_samples points inside a ball of radius eps. Changing one without the other changes that threshold in different ways.
| Change | Effect on the result |
|---|---|
| `eps` too small | Few core points. Most points become noise, and real clusters break into fragments. |
| `eps` too large | Neighborhoods overlap. Separate clusters merge, and noise is absorbed into clusters. |
| `min_samples` too small | Tiny groups and noise specks qualify as clusters. |
| `min_samples` too large | Only large, dense regions survive. Small real clusters become noise. |
Step 1: pick min_samples first
Choose min_samples before eps, because the k-distance method below needs it as input. Use these starting points:
- Start with the default of 5 for low-dimensional data.
- A common rule of thumb is
min_samples >= n_features + 1, and many practitioners use2 * n_features. - Raise it for noisy data or large datasets. A larger value makes the density estimate smoother and filters out small accidental groups.
- Use at least 3. With
min_samplesof 1 every point is a core point, so nothing is ever labeled noise. With 2 the result behaves much like single-linkage clustering.
Domain knowledge beats rules of thumb. If a cluster smaller than 20 points would be meaningless for your application, such as a customer segment too small to act on, set min_samples near 20.
Step 2: estimate eps with the k-distance plot
For each point, compute the distance to its k-th nearest neighbor, with k equal to min_samples. Sort these distances and plot them. Points inside clusters have small k-distances. Noise points have large ones. The curve is flat on the left, then bends upward. The bend, called the elbow, marks roughly where points stop belonging to a dense region. The eps value at the elbow is a good candidate.
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()Because each point is its own first neighbor, n_neighbors=min_samples makes the last column the distance to the point's k-th neighbor under DBSCAN's counting rule. If you used n_neighbors=min_samples + 1, you would overestimate eps slightly.
Step 3: sweep eps and inspect the result
The elbow is a heuristic, and it can be vague. Treat it as the center of a search range. Then run DBSCAN over several nearby values and watch how the cluster count and noise count change.
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)
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(np.sum(labels == -1))
print(f"eps={eps}: clusters={n_clusters}, noise={n_noise}")Read the sweep as follows:
- At very small
eps, expect many noise points and often many small clusters. - At very large
eps, expect a single cluster and almost no noise. - Look for a plateau, a range of
epsover which the cluster count and noise count barely change. A value in the middle of a plateau is more trustworthy than one at an edge, because small changes in the data will not alter the result.
A reasonable result has a noise fraction you can justify, often under about 10 to 20 percent. It also has a cluster count that makes sense for the problem, and the clusters are not dominated by one giant component.
Common errors
- Skipping feature scaling.
epsis one distance applied to all features. If one feature has a range of thousands and another a range of one, the large feature decides every neighborhood and noepsworks well. - Reading the k-distance plot with the wrong k. The k must match
min_samples. If you changemin_sampleslater, redraw the plot. - Expecting one correct answer. Several
epsvalues can give valid but different views: a coarse view with few large clusters, or a fine view with many small ones. - Using one
epsfor clusters of different densities. A single global threshold cannot fit both a tight cluster and a loose one. A value that separates the tight clusters turns the loose cluster into noise. A value that captures the loose cluster merges the tight ones. If the k-distance plot shows several elbows, this is likely your situation, and a method such as HDBSCAN, covered in a later chapter, is a better fit. - Ignoring high dimensions. As the number of features grows, distances between points become similar to each other, so the elbow flattens and
epsbecomes hard to choose. Reduce dimensionality first, or test whether another metric works better. - Duplicate points. Many identical rows inflate local counts. A group of
min_samplesduplicates forms a "cluster" by itself. Deduplicate, or raisemin_samples, if duplicates are not meaningful.
Summary of the procedure
- Scale the features.
- Pick
min_samplesfrom dimensionality and from the smallest group you consider meaningful. - Plot the sorted k-distance curve with k equal to
min_samples, and read a candidateepsat the elbow. - Sweep
epsaround the candidate and record the cluster count and noise fraction. - Choose a value from a stable plateau, then validate it with a metric and by inspecting the clusters.
Exercise
You run DBSCAN with min_samples=5 and eps=0.05 on standardized data and get 40 small clusters and 60 percent noise. What does this suggest, and what do you try next?
Show answer
The eps value is too small, so few points have 5 neighbors within the radius. Real clusters have fragmented and many points fail the core test. Plot the k-distance curve with k=5, read eps near the elbow (probably larger than 0.05), and rerun with several larger values, looking for a plateau in the cluster count and a lower noise fraction.
Exercise
A k-distance plot for your data shows two separate elbows, one at a low distance and one at a high distance. Why is a single eps a problem here, and what are your options?
Show answer
Two elbows usually mean clusters of different densities. A small eps finds the tight clusters but labels the loose one as noise. A large eps captures the loose cluster but merges the tight ones. Options are to accept one density level and treat the other group as noise, to cluster the data in separate passes with different eps values, or to use a method built for varying density such as HDBSCAN or OPTICS.