Sub topic 11
Reducing embeddings with UMAP
This chapter assumes you can run Python with sentence-transformers installed. It also assumes you know what a sentence embedding is, which the previous chapter covered. You don't need to know the maths behind UMAP. You need a working model of what it does to your data and which settings change the result.
Why BERTopic reduces dimensions at all
A model such as all-MiniLM-L6-v2 turns each document into a vector of 384 numbers. The next stage of BERTopic, HDBSCAN, groups documents by density: it looks for regions where points are packed closely together. Density estimates degrade as the number of dimensions grows. In high dimensions, distances between points become similar to each other, so "dense" and "sparse" regions are hard to tell apart. This is one form of the curse of dimensionality.
UMAP (Uniform Manifold Approximation and Projection) reduces each vector to a few dimensions, typically 5, while trying to keep documents that were neighbours as neighbours. HDBSCAN then clusters the reduced points. UMAP is the middle step in this chain:
What UMAP does internally
UMAP works in two phases.
- Build a neighbour graph in the original space. For each point it finds the
n_neighborsnearest points under the chosen metric. It turns the distances into edge weights that say how strongly two points are connected. The weights are scaled locally, so a point in a sparse region still has meaningful connections. - Lay out a low-dimensional graph. UMAP starts from an initial layout, then moves points so that connected points are pulled together and unconnected points are pushed apart. It optimises this with stochastic gradient descent.
Two consequences matter in practice:
- UMAP preserves local structure well. Documents that were close stay close.
- It does not preserve global structure reliably. The distance between two clusters in the output, or the apparent size of a cluster, says little about the original space.
The parameters that matter
BERTopic's default UMAP settings are n_neighbors=15, n_components=5, min_dist=0.0 and metric="cosine". The table explains each one.
| Parameter | Effect | Typical direction |
|---|---|---|
| `n_neighbors` | Size of the neighbourhood UMAP looks at. Small values focus on fine local detail. Large values favour broader structure. | Lower gives more, smaller topics. Higher gives fewer, broader topics. |
| `n_components` | Number of output dimensions. | 5 to 10 for clustering. Use 2 only for plotting. |
| `min_dist` | How tightly UMAP may pack points together. | Use 0.0 for clustering, so dense regions stay dense. Larger values spread points out for nicer plots. |
| `metric` | Distance used in the original space. | `"cosine"` suits text embeddings. |
| `random_state` | Seed for reproducibility. | Set it for repeatable runs, with a cost described below. |
Reducing embeddings step by step
The script below embeds 2,000 newsgroup posts, reduces them to 5 dimensions, then clusters them with HDBSCAN. It repeats the process for several n_neighbors values so you can see how that setting changes the cluster count and the share of outliers.
import numpy as np
from hdbscan import HDBSCAN
from sentence_transformers import SentenceTransformer
from sklearn.datasets import fetch_20newsgroups
from umap import UMAP
raw = fetch_20newsgroups(
subset="all", remove=("headers", "footers", "quotes")
)["data"]
docs = [d for d in raw if d.strip()][:2000]
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = embedding_model.encode(docs, show_progress_bar=True)
print("Embedding shape:", embeddings.shape)
for n_neighbors in (5, 15, 50):
reduced = UMAP(
n_neighbors=n_neighbors,
n_components=5,
min_dist=0.0,
metric="cosine",
random_state=42,
).fit_transform(embeddings)
labels = HDBSCAN(
min_cluster_size=15, metric="euclidean"
).fit_predict(reduced)
n_clusters = len(set(labels) - {-1})
outlier_share = float(np.mean(labels == -1))
print(
f"n_neighbors={n_neighbors:>2} reduced shape={reduced.shape} "
f"clusters={n_clusters} outliers={outlier_share:.0%}"
)Exact numbers vary with the library versions. The pattern is usually the same: a small n_neighbors produces more clusters, and a large one produces fewer.
Note that UMAP uses the cosine metric, but HDBSCAN uses "euclidean". After reduction the output is a set of ordinary coordinates, and Euclidean distance on them is the standard choice.
Reusing the reduction
UMAP is the slowest part of a BERTopic run after embedding. When you tune the clustering or the topic words, you don't need to recompute it. BERTopic lets you pass precomputed embeddings, and you can pass a UMAP model you configured yourself:
# Assumes docs, embeddings, and UMAP are defined as in the previous script
from bertopic import BERTopic
umap_model = UMAP(
n_neighbors=15, n_components=5, min_dist=0.0, metric="cosine", random_state=42
)
topic_model = BERTopic(umap_model=umap_model, min_topic_size=15)
topics, probs = topic_model.fit_transform(docs, embeddings)Passing embeddings skips the embedding step. Each call to fit_transform still refits UMAP. To keep the reduced vectors fixed while you experiment with clustering, reduce once yourself and pass BaseDimensionalityReduction from bertopic.dimensionality as the umap_model. That class makes BERTopic skip the reduction and cluster the embeddings you give it, which in this case would be your 5-dimensional vectors.
Gotchas and failure modes
- Setting
random_statedisables parallelism. UMAP becomes single-threaded, so large corpora run more slowly. Without a seed, two runs on the same data produce different topics. Choose repeatability for reports and tests, and speed for exploration. - Plots are not the clustering space. A 2D UMAP plot of the embeddings is a separate reduction. Clusters that look merged or split in 2D may be separate in 5D. Use a 2D map to explore, not to judge topic quality.
- Overlapping topics are partly a UMAP effect. Because UMAP is lossy, two real themes can end up in one dense region. If a topic contains two obvious subjects, try a smaller
n_neighborsor a smallermin_cluster_sizein HDBSCAN. - Too few dimensions or too many neighbours blurs themes. With
n_components=2andn_neighbors=100, small topics are absorbed into larger ones. - Outliers can come from this stage. Documents that UMAP places in sparse regions become topic
-1in HDBSCAN. The outlier chapter covers how to reassign them. - New documents go through the fitted UMAP.
transformprojects unseen documents with the model learned during training. It is approximate, so projections of new data are less reliable than the training layout.
Exercises
Exercise
Your BERTopic run produces 150 tiny topics, many with near-duplicate top words. Name one UMAP setting you would change, say in which direction, and explain why it helps.
Show answer
Increase n_neighbors, for example from 15 to 50. UMAP then builds each point's neighbourhood from more documents, so the reduced space reflects broader structure and nearby fine-grained groups merge. HDBSCAN then finds fewer, larger clusters. Raising min_cluster_size in HDBSCAN works toward the same goal.
Exercise
A colleague fits UMAP with n_components=2 and sends you a scatter plot where two blobs sit far apart and one blob looks twice as large as the others. They conclude that the two distant topics are unrelated and the large topic has the most documents. Which parts of this conclusion are safe?
Show answer
Neither is safe. UMAP preserves local neighbourhoods, not global distances or cluster areas, so the gap between blobs and their apparent size can be artefacts of the layout. Topic sizes should be read from the topic counts, for example get_topic_info(). Topic similarity should be measured on the original embeddings or topic embeddings, not on a 2D plot.