Sub topic 16
Choosing a method for your data
This chapter assumes you can run AgglomerativeClustering and DBSCAN in scikit-learn. It also assumes you know what linkage, eps, and min_samples mean, and that you have scaled features before. The goal is a repeatable way to pick between the two methods, and to know when neither fits.
Start from what you believe about the data
Both methods use distances, but they assume different things about what a cluster is. Ward and complete linkage favor compact, roughly round groups. Single linkage and DBSCAN follow chains of nearby points, so they can recover elongated or curved shapes. The shape you expect is the strongest single input to the decision.
Four other facts about your problem narrow the choice:
- Do you know the number of clusters? Agglomerative clustering needs
n_clustersor a distance threshold. DBSCAN needs neither, but it needseps. - Do you expect outliers? DBSCAN labels them
-1. Agglomerative clustering assigns every point to some cluster, so outliers either distort clusters or become tiny clusters of their own. - Do you need the hierarchy itself? A dendrogram shows structure at several scales. DBSCAN gives one flat result at one density.
- How many points do you have? Standard agglomerative clustering stores a pairwise distance structure. Memory grows with the square of the sample count, and run time grows at least that fast. DBSCAN with a spatial index is usually cheaper on large, low-dimensional data.
A decision flow
Treat the flow as a starting point. You still confirm the choice by running the methods and comparing results.
Side-by-side comparison
| Question | Agglomerative (Ward, complete, average) | Single linkage | DBSCAN |
|---|---|---|---|
| Cluster shape | Compact, roughly convex | Elongated, chained | Arbitrary |
| Number of clusters | Chosen by you (cut level) | Chosen by you | Found from `eps` and `min_samples` |
| Outliers | Forced into clusters | Often isolated as singletons | Labeled `-1` |
| Varying density | Handled reasonably | Chains across density bridges | Weak: one `eps` for all clusters |
| Main parameters | Linkage, cut level | Cut level | `eps`, `min_samples` |
| Output | Full hierarchy | Full hierarchy | One flat labeling |
| Scaling cost | Quadratic memory | Quadratic memory (a faster algorithm exists for this linkage) | Near-linear with an index in low dimensions |
Ward linkage is only defined for Euclidean distance. If you need Manhattan, cosine, or a precomputed metric, use average, complete, or single linkage, or use DBSCAN.
Compare the methods on data with known answers
When you have a synthetic or labeled dataset, you can test how well each method recovers the structure. The script below runs four models on blobs and on moons. It scores each with the adjusted Rand index (ARI), which compares predicted labels to true labels. An ARI of 1 means perfect agreement, and values near 0 mean random agreement.
from sklearn.cluster import AgglomerativeClustering, DBSCAN
from sklearn.datasets import make_blobs, make_moons
from sklearn.metrics import adjusted_rand_score
from sklearn.preprocessing import StandardScaler
datasets = {
"blobs": make_blobs(n_samples=300, centers=3, cluster_std=0.6, random_state=7),
"moons": make_moons(n_samples=300, noise=0.05, random_state=0),
}
for name, (X, y_true) in datasets.items():
X = StandardScaler().fit_transform(X)
k = len(set(y_true))
models = {
"ward": AgglomerativeClustering(n_clusters=k, linkage="ward"),
"single": AgglomerativeClustering(n_clusters=k, linkage="single"),
"dbscan": DBSCAN(eps=0.3, min_samples=5),
}
for model_name, model in models.items():
labels = model.fit_predict(X)
n_found = len(set(labels)) - (1 if -1 in labels else 0)
ari = adjusted_rand_score(y_true, labels)
print(f"{name:6s} {model_name:7s} clusters={n_found} ARI={ari:.2f}")Expect Ward to do well on round blobs and poorly on moons, because it cuts the curved shapes into compact pieces. Single linkage and DBSCAN should recover the moons. Always read the output yourself. If DBSCAN's eps is wrong for the blobs, it may report extra clusters or many noise points, which shows how sensitive it is to that one parameter.
ARI treats DBSCAN's -1 as one more cluster. That is a simplification, so a DBSCAN result with many noise points can score lower than it deserves.
Failure modes to check for
Each method fails in a recognizable way. Look for these before trusting a result.
Chaining in single linkage
A thin line of points between two real groups can merge them. In a dendrogram, chaining looks like a staircase of small merges at nearly the same height. If you see it, try average linkage, or use DBSCAN with a larger min_samples, which requires a dense neighborhood instead of one close neighbor.
Uneven cluster sizes under Ward
Ward minimizes the increase in within-cluster variance, which favors clusters of similar size and spread. A small, tight group next to a large, diffuse one may be absorbed or split.
One `eps` for every cluster
DBSCAN applies a single density threshold. If one cluster is dense and another sparse, a small eps marks the sparse cluster as noise, and a large eps merges the dense cluster with its neighbors. This is the main reason to try OPTICS or HDBSCAN.
High dimensions
Distances between points become similar as the number of features grows, so nearest and farthest neighbors differ less. Both methods suffer. DBSCAN is hit harder, because eps becomes hard to tune and neighborhood searches lose the benefit of spatial indexes. Reduce dimensionality first, for example with PCA, or choose features that matter for your question.
Check stability and agreement
Because there is no ground truth in most real projects, compare methods and settings against each other:
- Run the candidate methods with a few reasonable parameter values.
- Compute an internal score such as the silhouette score, excluding DBSCAN noise points as described in the evaluation chapter.
- Compare label agreement between runs with ARI. If small parameter changes cause large changes in labels, the structure is fragile.
- Inspect a few points near cluster boundaries and a sample from each cluster. Ask whether a domain expert would call them similar.
A method that scores slightly lower but gives groups you can explain and act on is often the better choice.
Practical defaults
- Small dataset, want to explore: average or Ward linkage with a dendrogram. Look at the merge heights, then cut.
- Spatial or sensor data with noise: DBSCAN. Pick
min_samplesfrom domain knowledge, then readepsfrom the k-distance plot. - Clusters of different density: OPTICS or HDBSCAN.
- Very large dataset: sample first, or use a method designed for scale. Cluster the sample and assign the remaining points to the nearest cluster.
- Need to label new points later: neither method has a
predictfor new data. Train a classifier on the cluster labels, or assign each new point to the nearest cluster.
Exercise
A dataset has two dense clusters, one sparse cluster, and a handful of scattered outliers. You run DBSCAN with a small eps and the sparse cluster is labeled entirely as noise. Raising eps to fix that merges the two dense clusters. What are two reasonable next steps?
Show answer
The data has clusters of different density, which a single eps cannot handle. One option is OPTICS or HDBSCAN, which adapt to varying density. The other is average or Ward linkage, which does not use a density threshold, with an outlier check beforehand because it forces every point into a cluster.
Exercise
You need to cluster 500,000 low-dimensional points from a map, and you expect irregular shapes and noise. Why is plain agglomerative clustering a poor first choice, and what would you try?
Show answer
Agglomerative clustering needs a pairwise distance structure, so memory and run time grow roughly with the square of the number of points, which is impractical at this size. DBSCAN with a spatial index scales much better on low-dimensional data, handles irregular shapes, and labels noise. Pick eps from a k-distance plot computed on a sample.