Sub topic 16
Refining topics: reduction, merging, and better labels
This chapter assumes you can fit a BERTopic model with fit_transform, that you know the pipeline stages (embedding, UMAP, HDBSCAN, c-TF-IDF), and that you know what topic -1 means. It covers what to do after a first fit: cut the topic count, combine topics that overlap, and replace noisy keyword lists with better labels.
Why the first fit needs refining
A default BERTopic run rarely gives the topic set you want. HDBSCAN decides the number of clusters from density, not from your needs. Three problems are common:
- Too many small topics. A corpus you expected to hold 20 themes yields 150.
- Split themes. One theme, such as "baseball", appears as two or three topics with near-identical keywords.
- Poor labels. The c-TF-IDF keywords repeat word forms ("game, games, games played") or include generic terms.
BERTopic splits these fixes into two kinds. Reduction and merging change which documents belong to which topic. Representation changes only how a topic is described. Keeping them apart helps you debug: if the documents are grouped well but the words are bad, change the representation and leave the clusters alone.
Reducing the number of topics
You can set a target count before fitting, with BERTopic(nr_topics=30). You can also let BERTopic choose with nr_topics="auto". Both run after clustering, so they cost little extra. Fitting first and reducing afterwards is usually better, because you can look at the full topic set before deciding.
from bertopic import BERTopic
from sklearn.datasets import fetch_20newsgroups
docs = fetch_20newsgroups(
subset="all", remove=("headers", "footers", "quotes")
)["data"]
topic_model = BERTopic(min_topic_size=15)
topics, probs = topic_model.fit_transform(docs)
print("topics before:", len(topic_model.get_topic_info()) - 1)
topic_model.reduce_topics(docs, nr_topics=30)
topics = topic_model.topics_
print("topics after:", len(topic_model.get_topic_info()) - 1)reduce_topics works from the smallest topics upward. It compares the c-TF-IDF vectors of topics, finds the most similar larger topic for each small one, and merges them. Then it recomputes c-TF-IDF for the new groups. Note three consequences:
- Topic IDs are renumbered by size after reduction, so an ID you noted earlier may now mean something else.
- Topic -1 is left alone. Reduction does not push outliers into topics.
- Document assignments are updated in
topic_model.topics_. Older BERTopic versions returned the new topics and probabilities fromreduce_topics. Newer versions change the model in place and return the model. Check your installed version before relying on a return value.
Merging chosen topics
Reduction is automatic and can merge things you wanted separate. When you know which topics overlap, use merge_topics with lists of IDs. Each inner list becomes one topic.
similar_ids, scores = topic_model.find_topics("baseball", top_n=3)
print(similar_ids, scores)
# Inspect the candidates before merging them.
for topic_id in similar_ids:
print(topic_id, topic_model.get_topic(topic_id)[:5])
topic_model.merge_topics(docs, [similar_ids[:2]])find_topics embeds your query and returns the topics closest to it, which is a quick way to locate duplicates without reading the whole table. Always print the keywords first. A high similarity score between "baseball" and "hockey" topics reflects shared sports vocabulary, not a reason to merge.
To see which merges the data supports, build a hierarchy:
hierarchical_topics = topic_model.hierarchical_topics(docs)
print(topic_model.get_topic_tree(hierarchical_topics))The tree shows the order in which topics would join as the distance threshold rises. Topics that join at a low distance are good merge candidates. Topics that join only near the root are distinct themes.
Improving labels with representation models
By default, a topic's words are the top c-TF-IDF terms. A representation model re-ranks or rewrites those words after clustering. The clusters do not change. The three common ones are in bertopic.representation:
| Model | What it does | Use it when |
|---|---|---|
| `KeyBERTInspired` | Re-ranks candidate words by embedding similarity to the topic's documents | Keywords are frequent but not very meaningful |
| `MaximalMarginalRelevance` | Picks words that are relevant but different from each other | Keywords repeat near-synonyms or word forms |
| `PartOfSpeech` | Keeps words matching part-of-speech patterns, using spaCy | You want noun phrases as labels |
PartOfSpeech needs spaCy and an English model such as en_core_web_sm installed. You can also plug in a language model that writes a short label from each topic's keywords and example documents. That adds cost and an outside dependency, so try the first three before you reach for it.
You can pass a representation model to the constructor, or apply it to a fitted model with update_topics, which avoids refitting:
from bertopic.representation import KeyBERTInspired, MaximalMarginalRelevance
topic_model.update_topics(
docs,
representation_model=MaximalMarginalRelevance(diversity=0.3),
)
print(topic_model.get_topic(0))To keep several descriptions side by side, pass a dictionary. The "Main" key replaces the default topic words. The other keys are stored as extra aspects that you can read from get_topic_info().
representation_model = {
"Main": KeyBERTInspired(),
"Diverse": MaximalMarginalRelevance(diversity=0.3),
}
topic_model.update_topics(docs, representation_model=representation_model)
print(topic_model.get_topic_info().head())You can also change the c-TF-IDF step itself. A ClassTfidfTransformer with reduce_frequent_words=True downweights words shared across many topics. bm25_weighting=True is a milder alternative that stabilises weighting on small corpora. Pass it as ctfidf_model to update_topics.
Setting human-readable labels
Keyword lists are not display names. set_topic_labels stores a custom name per topic and shows it in the CustomName column of get_topic_info() and in visualisations.
topic_model.set_topic_labels({0: "Space missions", 1: "Hockey"})
print(topic_model.get_topic_info()[["Topic", "Count", "CustomName"]].head())If you want automatic names from the top words, use generate_topic_labels(nr_words=3, separator=" / ") and pass the result to set_topic_labels.
A practical order of work
- Fit and read the topic table, including each topic's size and a few example documents.
- Reduce outliers with
reduce_outliers, then runupdate_topicsso the keywords reflect the new assignments. - Reduce or merge topics. Prefer
merge_topicswhen you can name the pairs, andreduce_topicswhen you only know a target count. - Apply a representation model.
- Set custom labels.
Check the outcome by reading documents, not only keywords. After a merge, sample 10 documents from the merged topic. If you can't write one sentence that covers them all, the merge was too aggressive. Coherence scores can support this check, but they do not replace reading.
Exercise
After fitting, you see two topics with keywords "game, games, team, season" and "baseball, pitcher, inning, hits". A colleague proposes calling reduce_topics(docs, nr_topics=10) to combine them. Give one reason to prefer merge_topics, and name the step you should do before and after merging.
Show answer
reduce_topics merges small topics into whatever larger topic is most similar, so it can merge pairs you wanted kept apart and it renumbers topic IDs. merge_topics combines only the IDs you list. Before merging, print the keywords and sample documents for both topics to confirm they describe one theme. After merging, apply any representation model and then set custom labels, because the IDs and keywords have changed.