Sub topic 14
Running the BERTopic pipeline end to end
This chapter assumes you can run Python and install packages with pip. It also assumes you know what a sentence embedding is and have seen TF-IDF. Earlier chapters covered each stage separately: embeddings, UMAP, HDBSCAN and c-TF-IDF. Here you run them as one pipeline and learn which settings matter.
What the pipeline does
BERTopic treats a topic as a cluster of semantically similar documents, described by the words that set that cluster apart from the others. In LDA a topic is a probability distribution over words. In BERTopic the clusters come first and the word lists are derived from them afterwards.
A call to fit_transform runs four stages in order:
- An embedding model turns each document into a dense vector.
- UMAP reduces those vectors to a few dimensions, because density-based clustering works poorly in hundreds of dimensions.
- HDBSCAN groups the reduced vectors into clusters. Documents that fit no cluster get the label -1.
- A vectoriser counts words, and c-TF-IDF scores the words of each cluster against all other clusters.
The stages are independent. Clustering uses only the embeddings, and word lists use only the cluster labels and the raw text. This explains most of BERTopic's behaviour. Changing the vectoriser changes the labels of the topics but never which documents belong together. Changing UMAP or HDBSCAN changes the grouping.
Fitting with the defaults
The following code fits BERTopic on the 20 Newsgroups corpus with default components. The first run downloads the corpus and an embedding model, and it is slow without a GPU.
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)
print(topic_model.get_topic_info().head(10))
print(topic_model.get_topic(0))topics holds one integer per document. get_topic_info() returns a table with one row per topic: its id, its document count, and a name built from its top words. get_topic(0) returns a list of (word, c-TF-IDF score) pairs for topic 0. Topics are numbered by size, so topic 0 is the largest real topic. Topic -1 collects outliers and appears in the table too.
min_topic_size is passed to HDBSCAN as min_cluster_size. It is the main control on topic count. A larger value gives fewer, broader topics and more outliers. A smaller value gives many narrow topics.
Swapping components
Pass each stage as an argument. This version sets every stage explicitly and fixes UMAP's random seed.
from bertopic import BERTopic
from hdbscan import HDBSCAN
from sentence_transformers import SentenceTransformer
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import CountVectorizer
from umap import UMAP
docs = fetch_20newsgroups(
subset="all", remove=("headers", "footers", "quotes")
)["data"]
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
umap_model = UMAP(
n_neighbors=15, n_components=5, min_dist=0.0, metric="cosine", random_state=42
)
hdbscan_model = HDBSCAN(
min_cluster_size=15,
metric="euclidean",
cluster_selection_method="eom",
prediction_data=True,
)
vectorizer_model = CountVectorizer(stop_words="english", ngram_range=(1, 2))
topic_model = BERTopic(
embedding_model=embedding_model,
umap_model=umap_model,
hdbscan_model=hdbscan_model,
vectorizer_model=vectorizer_model,
)
topics, probs = topic_model.fit_transform(docs)
print(topic_model.get_topic_info().head())The table below shows what each argument controls and when to change it.
| Stage | Key settings | Change it when |
|---|---|---|
| Embedding model | Model name | Your text is not English, is very short, or is domain-specific |
| UMAP | `n_neighbors`, `n_components`, `random_state` | Topics are too fragmented, or runs must be repeatable |
| HDBSCAN | `min_cluster_size`, `min_samples` | You have too many or too few topics, or too many outliers |
| Vectoriser | `stop_words`, `ngram_range`, `min_df` | Topic words are dominated by filler or by single words with no context |
How c-TF-IDF picks the words
All documents in a topic are joined into one long document. The score of term t in topic c is:
W(t, c) = tf(t, c) × log(1 + A / f(t))
Here tf(t, c) is the count of t in topic c. A is the average number of words per topic. f(t) is the count of t across all topics. A word scores high when it is frequent in one topic and rare elsewhere. Frequent words that appear in every topic have a large f(t), so they score low. Stop words are the extreme case, which is why the vectoriser option above cleans up the labels.
Reading the results
Beyond get_topic_info(), two calls are used most:
topic_model.get_document_info(docs)returns one row per document with its topic, name, top words and probability. Use it to read example documents for each topic, as the evaluation chapter recommends.topic_model.get_representative_docs(topic_id)returns the documents closest to a topic's centre.
probs is not a full topic mixture as in LDA. By default it holds one value per document, the strength of its membership in its assigned cluster. Each document belongs to exactly one topic. A document about both politics and sport will land in one of them. If you need soft assignments, set calculate_probabilities=True. This costs extra time and memory.
Failure modes
Several problems recur when running the pipeline.
- Different topics on each run. UMAP is stochastic. Set
random_stateon UMAP, which also makes UMAP run on a single thread and so slower. - A very large topic -1. HDBSCAN labels documents as noise when no dense region covers them. On short or varied text, outliers can be 30 to 40 per cent of the corpus. Lower
min_cluster_sizeormin_samples, or use the outlier reduction covered in the next chapter. - Topics that split one theme. The clusters are too fine. Raise
min_topic_size, or reduce the topic count afterwards withnr_topics. - Repeated words in every topic. The default vectoriser keeps stop words. Pass
CountVectorizer(stop_words="english"). - Slow embedding. Embedding dominates run time. Compute embeddings once, save them, and pass them to
fit_transform(docs, embeddings)while you tune UMAP and HDBSCAN.
Exercise
You fit BERTopic and 35 per cent of documents land in topic -1. You want to keep the embedding model and the vectoriser unchanged. Which stage do you adjust first, and which parameter?
Show answer
Adjust HDBSCAN, the clustering stage. Lower minclustersize (or mintopicsize in BERTopic) or lower minsamples so that smaller or looser dense regions count as clusters. The embedding model and vectoriser do not decide which documents are noise, so changing them would not fix this directly. Reassigning outliers afterwards with reduceoutliers is the other option.
Exercise
Why does changing the vectoriser's stop_words setting change the topic labels but not the topic assignments of any document?
Show answer
The vectoriser runs after clustering. HDBSCAN assigns documents to topics using only the UMAP-reduced embeddings. The vectoriser and c-TF-IDF only compute word scores for clusters that already exist, so they change the descriptions and not the grouping.