Sub topic 15
Understanding and reducing outliers
This chapter covers outlier documents in BERTopic: why they appear, how to measure them, and how to reassign them. It assumes you can run the BERTopic pipeline from the previous chapter, know what HDBSCAN does at a high level, and are comfortable with NumPy arrays and lists of documents.
What topic -1 means
LDA gives every document a mixture over all topics. BERTopic works differently. It clusters document embeddings with HDBSCAN, and HDBSCAN does not force every point into a cluster. A document that sits in a sparse region, or between dense regions, receives the label -1. BERTopic reports this label as topic -1, the outlier topic.
Topic -1 is not a theme. Its top words are usually generic ("the", "like", "just" or common verbs), because it is a pile of unrelated documents. Do not read it as a topic.
Why outliers appear
Several causes combine in practice.
- Density threshold. HDBSCAN only forms clusters of at least
min_cluster_sizepoints, and it only keeps points that are dense enough relative to their neighbours. Raisingmin_cluster_sizeormin_samplesproduces more outliers. - Short or generic text. Tweets, titles, and replies such as "thanks, that worked" have weak embeddings that sit between clusters.
- Mixed-theme documents. A document about both politics and sport lies between two clusters.
- Genuinely off-topic text. Spam, boilerplate, and wrong-language text should stay outliers.
- Dimensionality reduction. UMAP changes the local density structure that HDBSCAN sees. Different
n_neighborsandn_componentsvalues change which points look isolated.
On the 20 Newsgroups corpus used in this tutorial, it is common for a large share of documents, often a third or more, to land in topic -1 with default settings. Treat that number as something to inspect, not as a failure.
Measuring the outlier share
Before changing anything, find out how many documents are outliers.
from bertopic import BERTopic
from sklearn.datasets import fetch_20newsgroups
docs = fetch_20newsgroups(
subset="all", remove=("headers", "footers", "quotes")
)["data"]
topic_model = BERTopic(language="english", min_topic_size=15)
topics, probs = topic_model.fit_transform(docs)
n_outliers = sum(1 for t in topics if t == -1)
print(f"Outliers: {n_outliers} of {len(docs)} ({n_outliers / len(docs):.1%})")
info = topic_model.get_topic_info()
print(info[info["Topic"] == -1])get_topic_info() lists Topic, Count, Name, and the representation columns. The row for -1 shows its size next to the real topics.
Inspecting outliers before reassigning them
Reassigning blindly can hide useful information. Read a sample first.
import random
random.seed(0)
outlier_docs = [d for d, t in zip(docs, topics) if t == -1]
for doc in random.sample(outlier_docs, 5):
print(repr(doc[:200]))
print("---")Sort what you see into three groups.
- Junk such as empty strings, signatures, or encoded text. Remove these in preprocessing, not in topic modelling.
- Documents that clearly fit an existing topic. Reassign these.
- Documents about a theme with too few examples. Lower
min_topic_sizeor accept that the theme is too rare to model.
The pipeline around the outlier decision
Reducing outliers with `reduce_outliers`
BERTopic's reduce_outliers method assigns each outlier to an existing topic using a chosen strategy. It returns a new list of topic labels. It does not change the model.
# Assumes topic_model, docs, and topics come from topic_model.fit_transform(docs)
new_topics = topic_model.reduce_outliers(docs, topics)
topic_model.update_topics(docs, topics=new_topics)
print(topic_model.get_topic_info().head())The second call, update_topics, matters. Without it the model still holds the old assignments and the old topic keywords. After the call, c-TF-IDF is recomputed from the new document groups, so the topic words reflect the added documents.
Strategies
The strategy argument selects how the new topic is chosen.
| Strategy | What it uses | Notes |
|---|---|---|
| `"distributions"` (default) | The topic distribution from `approximate_distribution` | Works on token sets inside each document, so it can handle mixed documents. Slower on large corpora. |
| `"c-tf-idf"` | Similarity between the document's bag of words and each topic's c-TF-IDF vector | Fast, relies on shared vocabulary. Weak for short texts with no topic words. |
| `"embeddings"` | Cosine similarity between document and topic embeddings | Uses meaning, not just words. Good for short texts. Pass `embeddings=` if you have them. |
| `"probabilities"` | The probability matrix from HDBSCAN | Needs `calculate_probabilities=True` when fitting. |
new_topics = topic_model.reduce_outliers(
docs, topics, strategy="c-tf-idf", threshold=0.1
)The threshold argument sets a minimum similarity. A document whose best score is below the threshold stays in -1. A threshold of 0 (the default) reassigns every outlier. A higher value is safer, because it reassigns only documents with a clear match.
Using precomputed embeddings
If you computed embeddings once and passed them to fit_transform, reuse them. This avoids a second embedding pass and keeps the strategy consistent with how the model was fit.
from sentence_transformers import SentenceTransformer
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = embedding_model.encode(docs, show_progress_bar=False)
topic_model = BERTopic(embedding_model=embedding_model, min_topic_size=15)
topics, probs = topic_model.fit_transform(docs, embeddings)
new_topics = topic_model.reduce_outliers(
docs, topics, strategy="embeddings", embeddings=embeddings, threshold=0.3
)
topic_model.update_topics(docs, topics=new_topics)Reducing outliers at the source
reduce_outliers repairs labels after clustering. You can also change the clustering so fewer points become outliers.
- Lower
min_cluster_sizeormin_samplesin HDBSCAN. Smaller values accept sparser clusters.min_sampleshas a strong effect: a lower value makes the algorithm less conservative. - Use
cluster_selection_method="leaf". This yields many small, homogeneous clusters, where"eom"favours fewer, larger ones. It can raise the topic count sharply. - Change UMAP. A larger
n_neighborsgives a more global view and often fewer isolated points. Keeprandom_statefixed so comparisons are fair. - Use a better embedding model for your domain or language. Weak embeddings make clusters diffuse.
from bertopic import BERTopic
from hdbscan import HDBSCAN
hdbscan_model = HDBSCAN(
min_cluster_size=15,
min_samples=5,
metric="euclidean",
cluster_selection_method="eom",
prediction_data=True,
)
topic_model = BERTopic(hdbscan_model=hdbscan_model)Common errors and trade-offs
- Forgetting
update_topics. The labels you hold differ from the labels inside the model, andget_topic_info()still shows the old counts. - Reassigning everything. With the default threshold of 0, junk documents join real topics and blur their keywords. Inspect first, then set a threshold.
- Passing the wrong
topicslist.reduce_outliersexpects the list returned byfit_transform, aligned withdocs. If you filtereddocsafterwards, the lengths no longer match. - Using
"probabilities"without probabilities. The model must be fitted withcalculate_probabilities=True, which costs time and memory. - Judging success by outlier count alone. A model with zero outliers may simply have merged unrelated documents. Check topic words and sample documents after reassigning.
- Comparing runs without a fixed seed. UMAP is stochastic, so outlier counts shift between runs unless
random_stateis set.
A practical workflow
- Fit the model and measure the outlier share.
- Read a sample of outliers and sort them into junk, reassignable, and rare themes.
- Tune HDBSCAN and UMAP if the share is far higher than you can justify.
- Call
reduce_outlierswith a strategy suited to your text length and a non-zero threshold. - Call
update_topics, then reread the topic words and sample documents.
Exercise
You fit BERTopic on 10,000 product reviews, many only a few words long. 40% land in topic -1. You call reduceoutliers with strategy="c-tf-idf" and the default threshold, then read the topic words, but gettopic_info() shows the same counts as before. Give two things you should change or check.
Show answer
First, call topicmodel.updatetopics(docs, topics=newtopics). reduceoutliers only returns new labels and does not modify the model, which is why the counts did not change. Second, reconsider the strategy. Very short reviews share few words with topic c-TF-IDF vectors, so "c-tf-idf" matches them poorly. Use strategy="embeddings" with the embeddings you computed, and set a threshold above 0 so that only clear matches are reassigned. Reading a sample of the outliers first would also show whether some are junk that should stay in -1.
Exercise
Why can lowering min_samples in HDBSCAN reduce outliers, and what is the risk?
Show answer
min_samples controls how many neighbours a point needs to count as dense. A lower value makes HDBSCAN less conservative, so more points join clusters instead of being labelled noise. The risk is that loosely related documents form or join clusters, which makes topics less coherent and their keywords less clear.