Sub topic 17
Going further: OPTICS and HDBSCAN
This chapter assumes you have read the DBSCAN chapters. You should know core, border, and noise points, and what eps and min_samples do. You should also be comfortable with scikit-learn's fit and labels_ style and with scaling features before clustering.
DBSCAN has one weakness that the earlier chapters flagged: a single eps describes one density level. OPTICS and HDBSCAN are two answers to that problem. They are standard extensions, and scikit-learn includes both.
The problem: clusters with different densities
Suppose a dataset has two tight clusters and one loose cluster. A small eps fits the tight clusters but marks most of the loose cluster as noise. A large eps captures the loose cluster but may merge the tight ones with their surroundings. No single value works for all three.
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.5, 1.0]:
labels = DBSCAN(eps=eps, min_samples=10).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}: {n_clusters} clusters, {n_noise} noise points")Run it and compare the three lines. Small eps values label many points of the loose cluster as noise. Larger values stop doing that, but the tight clusters then have less margin before they could merge with something nearby.
How the methods relate
OPTICS
OPTICS stands for Ordering Points To Identify the Clustering Structure. It does not produce one clustering directly. It produces an ordering of the points, plus a number for each point called its reachability distance.
Two definitions are needed:
- The core distance of a point is the distance to its
min_samples-th neighbor. A small core distance means the point sits in a dense area. - The reachability distance of a point is how far away it is from the dense region that was explored just before it. A low value means the point is part of a dense area. A high value means the algorithm had to jump across a sparse gap.
OPTICS visits points so that neighbors in dense regions are processed together. If you plot the reachability distances in visiting order, you get a reachability plot. Valleys are clusters, and peaks are the gaps between them. A deep, narrow valley is a tight cluster. A shallow, wide valley is a loose one.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import OPTICS
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,
)
optics = OPTICS(min_samples=10, xi=0.05, min_cluster_size=0.05).fit(X)
reach = optics.reachability_[optics.ordering_].copy()
reach[~np.isfinite(reach)] = np.nan # the first point has infinite reachability
plt.plot(reach)
plt.xlabel("points in OPTICS order")
plt.ylabel("reachability distance")
plt.show()
labels = optics.labels_
print(len(set(labels)) - (1 if -1 in labels else 0), int(np.sum(labels == -1)))OPTICS can turn the plot into labels in two ways:
- The
ximethod, which is the default, looks for steep drops and rises in the reachability plot.xiis the minimum relative steepness that counts as a cluster boundary. It can find clusters of different densities. - The DBSCAN-style cut draws one horizontal line across the plot. Points under the line form clusters, as if you had run DBSCAN with that
eps. Usecluster_optics_dbscanto try several cuts without refitting.
from sklearn.cluster import cluster_optics_dbscan
for eps in [0.3, 0.6, 1.0]:
cut = cluster_optics_dbscan(
reachability=optics.reachability_,
core_distances=optics.core_distances_,
ordering=optics.ordering_,
eps=eps,
)
print(eps, len(set(cut)) - (1 if -1 in cut else 0))HDBSCAN
HDBSCAN is Hierarchical DBSCAN. It removes the eps parameter by considering every density level at once.
The idea in four steps:
- Replace the raw distance with the mutual reachability distance. For two points, this is the largest of three values: their distance, the core distance of the first, and the core distance of the second. It pushes points in sparse areas away from everything else.
- Build a minimum spanning tree over the points using that distance. Removing its longest edges one at a time is equivalent to raising the density threshold, which is what lowering
epsdoes in DBSCAN. - Turn the result into a cluster hierarchy, like a dendrogram. Groups smaller than
min_cluster_sizeare not clusters. They count as points falling out of their parent. - Select clusters from the hierarchy by stability. A cluster is stable if it persists across a wide range of density levels. By default, HDBSCAN picks the set of non-overlapping clusters with the largest total stability. This is the
"eom"(excess of mass) method.
This connects the two halves of the tutorial. HDBSCAN builds a hierarchy as agglomerative clustering does, using a single-linkage-like merge structure on the mutual reachability distance. It then reads flat clusters out of the hierarchy using density instead of a fixed cut height.
import numpy as np
from sklearn.cluster import HDBSCAN
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,
)
hdb = HDBSCAN(min_cluster_size=20).fit(X)
labels = hdb.labels_
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
print(n_clusters, int(np.sum(labels == -1)))
print(hdb.probabilities_[:5])HDBSCAN is available in scikit-learn 1.3 and later. Before that, it was only in the separate hdbscan package.
Parameters
| Parameter | Meaning | Effect of raising it |
|---|---|---|
| `min_cluster_size` | Smallest group that may be called a cluster | Fewer, larger clusters, more noise |
| `min_samples` | Neighbors counted for core distance. Defaults to `min_cluster_size` | More conservative, more points become noise |
| `cluster_selection_epsilon` | Clusters closer than this distance are merged | Fewer small clusters |
| `cluster_selection_method` | `"eom"` or `"leaf"` | `"leaf"` gives many small, fine-grained clusters |
Two practical points follow from the table. First, min_cluster_size is easier to choose than eps because it is a count you can reason about: how many points make a group worth caring about. Second, if you get too much noise, lower min_samples independently of min_cluster_size.
The probabilities_ attribute gives each point a membership strength between 0 and 1. Noise points get 0. Points near the edge of a cluster get low values. This soft information is not available from DBSCAN.
Trade-offs and limits
| Aspect | DBSCAN | OPTICS | HDBSCAN |
|---|---|---|---|
| Varying densities | Poor | Good with `xi` | Good |
| Main parameters | `eps`, `min_samples` | `min_samples`, `xi` | `min_cluster_size` |
| Output | Flat labels | Ordering and flat labels | Flat labels, membership strengths |
| Interpretability | Simple | Reachability plot | Needs some theory |
| Cost | Fast with a spatial index | Usually slower than DBSCAN | Usually slower than DBSCAN |
Common errors:
- Not scaling features. Both methods use distances, so the scaling advice from earlier chapters applies unchanged.
- Treating
xias a distance. It is a relative steepness between 0 and 1, so its useful values differ fromepsvalues. - Expecting HDBSCAN to remove all tuning. It still depends on
min_cluster_sizeandmin_samples, and results can change noticeably when you vary them. - Expecting a
predictmethod. Neither OPTICS nor scikit-learn's HDBSCAN labels new points directly. You must refit, or train a separate classifier on the labels. - Computing a silhouette score including noise. As before, exclude points labeled
-1and make sure at least two clusters were found.
Exercise
A reachability plot from OPTICS shows one deep, narrow valley and one wide, shallow valley, separated by a tall peak. What does this suggest about the data, and why would one DBSCAN run struggle?
Show answer
The data has a tight, dense cluster and a looser, sparser cluster, separated by a gap. A DBSCAN run with an eps small enough for the dense cluster would label much of the sparse cluster as noise. An eps large enough for the sparse cluster would be much bigger than the dense cluster needs, which risks merging it with nearby points. OPTICS or HDBSCAN can recover both clusters.
Exercise
Using the three-blob data from this chapter, you run HDBSCAN with minclustersize=20 and get a large number of points labeled -1. Name two parameter changes you could try, and say what each does.
Show answer
Lower minsamples, which makes core distances smaller, so fewer points count as sparse noise. Lower minclustersize, which lets smaller groups become clusters instead of being discarded. Setting clusterselection_method to "leaf" is another option, since it favors finer clusters.