Sub topic 12
Clustering with HDBSCAN
This chapter explains the clustering stage of the BERTopic pipeline. It assumes you know what a sentence embedding is and have read the chapter on reducing embeddings with UMAP. You should also be comfortable with Python and with the idea of distance between vectors. In the pipeline, UMAP hands HDBSCAN a set of low-dimensional document vectors. HDBSCAN groups them into clusters, and each cluster becomes a topic.
Why BERTopic uses a density-based clusterer
A topic model needs to group documents that are about the same thing. K-means, the best-known clustering method, is a poor fit for this job for three reasons.
- It needs the number of clusters in advance. For a new corpus you rarely know it.
- It assigns every point to some cluster. Documents that fit no theme still get forced into one, which pollutes the topic descriptions.
- It assumes round, similarly sized clusters. Real topics vary a lot in size and shape.
HDBSCAN stands for Hierarchical Density-Based Spatial Clustering of Applications with Noise. It treats clusters as dense regions of points separated by sparse regions. It finds the number of clusters itself, allows clusters of different sizes and densities, and labels points in sparse regions as noise. BERTopic reports that noise as topic -1, the outlier topic. The chapter on outliers covers how to deal with it.
How HDBSCAN works
The algorithm has five steps. You do not need to implement them, but knowing them explains the parameters.
- Core distance. For each point, find the distance to its
min_samples-th nearest neighbour. Points in dense areas have a small core distance. Points in sparse areas have a large one. - Mutual reachability distance. The distance between two points A and B is the largest of three values: the core distance of A, the core distance of B, and their ordinary distance. This pushes sparse points away from everything, so noise stays apart from dense regions.
- Minimum spanning tree. Build a tree that connects all points with the smallest total mutual reachability distance.
- Cluster hierarchy. Remove the tree's edges from longest to shortest. Each removal splits a group. This produces a tree of clusters from one big group down to single points.
- Condensing and selecting. Any split that would create a group smaller than
min_cluster_sizeis not a real split. The small piece is treated as points falling out of the parent cluster. The algorithm then picks the most stable clusters from the condensed tree. Stability measures how long a cluster persists as the density threshold changes.
The parameters that matter
BERTopic accepts any HDBSCAN object through its hdbscan_model argument. Four parameters do most of the work.
| Parameter | Meaning | Effect of raising it |
|---|---|---|
| `min_cluster_size` | Smallest group that can count as a cluster | Fewer, larger topics and more outliers |
| `min_samples` | Neighbour count used for core distance | Stricter density requirement and more outliers |
| `metric` | Distance function | Changes which points count as near |
| `cluster_selection_method` | `"eom"` or `"leaf"` | `"leaf"` gives many small, fine-grained clusters |
By default min_samples equals min_cluster_size. Setting min_samples lower makes the algorithm more willing to include borderline points, which reduces noise without changing the minimum topic size.
"eom" means excess of mass. It selects the most stable clusters, which can be large and general. "leaf" selects the clusters at the bottom of the hierarchy. It produces more topics of similar size, which is useful when "eom" gives one huge cluster that mixes several themes.
Metric choice after UMAP
Sentence embeddings are usually compared with cosine similarity. After UMAP, though, the vectors live in a new low-dimensional space where straight-line distance is meaningful. The BERTopic default is therefore metric="euclidean" for HDBSCAN, even when UMAP used metric="cosine". HDBSCAN does not accept "cosine" for all of its fast algorithms, which is another reason to keep Euclidean here.
Running HDBSCAN on its own
You can test the clustering stage separately from BERTopic. This example creates three synthetic blobs and a scatter of random noise points. It then runs HDBSCAN and counts what it finds.
import numpy as np
from sklearn.datasets import make_blobs
from hdbscan import HDBSCAN
rng = np.random.default_rng(42)
blobs, _ = make_blobs(
n_samples=300,
centers=[(0, 0), (6, 6), (0, 7)],
cluster_std=0.6,
random_state=42,
)
noise = rng.uniform(low=-3, high=10, size=(40, 2))
points = np.vstack([blobs, noise])
clusterer = HDBSCAN(
min_cluster_size=15,
min_samples=5,
metric="euclidean",
cluster_selection_method="eom",
)
labels = clusterer.fit_predict(points)
unique, counts = np.unique(labels, return_counts=True)
for label, count in zip(unique, counts):
name = "noise" if label == -1 else f"cluster {label}"
print(f"{name}: {count} points")You should see three clusters of roughly 100 points each. Most of the 40 random points are labelled as noise, though a few may be absorbed into a cluster when they land inside a blob. Try changing min_cluster_size to 120 and watch the clusters disappear into noise, because no group meets the minimum size.
Using HDBSCAN inside BERTopic
Pass the configured object to BERTopic. Set prediction_data=True so that BERTopic can assign topics to new documents and compute soft probabilities later.
from bertopic import BERTopic
from hdbscan import HDBSCAN
hdbscan_model = HDBSCAN(
min_cluster_size=30,
min_samples=10,
metric="euclidean",
cluster_selection_method="eom",
prediction_data=True,
)
topic_model = BERTopic(hdbscan_model=hdbscan_model)
# topics, probs = topic_model.fit_transform(docs)Here min_cluster_size=30 asks for topics of at least 30 documents, and min_samples=10 keeps the density test looser than the size test.
Tuning in practice
Tune one parameter at a time and look at both the topic count and the outlier share. topic_model.get_topic_info() lists each topic with its document count, and topic -1 shows the outliers.
- If you get hundreds of tiny topics, raise
min_cluster_size. - If more than about half the corpus is outliers, lower
min_samplesfirst, then consider loweringmin_cluster_size. - If one topic swallows a large share of documents and reads as vague, try
cluster_selection_method="leaf". - If topics look different on each run, the cause is usually UMAP, not HDBSCAN. HDBSCAN is deterministic for fixed input, so fix the UMAP
random_state.
Gotchas and edge cases
- Outliers are a feature, not a failure. A noisy corpus, such as short social media posts, will have many. Reassigning them is a choice you make afterwards.
- Very short corpora behave badly. With a few hundred documents, a
min_cluster_sizeof 15 may leave nearly everything as noise. Lower it, or consider LDA. - Results depend on the UMAP output. Different
n_componentsorn_neighborsvalues change the density structure that HDBSCAN sees. Change them deliberately and compare. - Cluster count is not a quality score. More topics is not better. Judge the result by reading topic words and example documents.
- High dimensions hurt density estimates. This is why UMAP comes before HDBSCAN. Clustering the raw 384-dimensional embeddings directly usually gives mostly noise.
Summary of decisions
| Situation | Adjustment |
|---|---|
| Too many small topics | Increase `min_cluster_size` |
| Too many outliers | Decrease `min_samples` |
| One broad, vague topic | Use `cluster_selection_method="leaf"` |
| Topics change between runs | Fix UMAP `random_state` |
| Need topics for new documents | Set `prediction_data=True` |
Exercise
You fit BERTopic and find that 60% of documents are in topic -1, while the topics that do exist look coherent. Which HDBSCAN parameter would you change first, and in which direction? Why?
Show answer
Lower minsamples. It sets the neighbour count used for core distance, so a smaller value makes the density test less strict and lets borderline points join clusters. This leaves minclustersize, and therefore the minimum topic size, unchanged. If outliers remain high, then lower minclustersize or reassign outliers with reduceoutliers afterwards.
Exercise
A colleague says that because UMAP used metric="cosine", HDBSCAN should also use cosine. What is the usual setup and the reason for it?
Show answer
The usual setup is metric="euclidean" for HDBSCAN. Cosine was used to build UMAP's neighbour graph from the raw embeddings. UMAP's output is a new low-dimensional space where Euclidean distance is the meaningful measure, and HDBSCAN's fast algorithms support Euclidean directly.