Sub topic 2
Preparing text for topic models
This chapter assumes you know Python basics, what tokenisation, stop words and TF-IDF are, and have a rough idea of what a vector embedding is. You will clean a corpus for LDA with gensim, then see why BERTopic needs much less cleaning and where its preprocessing goes instead.
Why preprocessing matters differently for each method
Both methods end up counting words, but they count at different moments.
- LDA models word counts directly. Every token in your vocabulary becomes a dimension of the model. Noise tokens such as "the", "http", or a typo that appears once consume probability mass and show up in topic word lists.
- BERTopic first turns each document into a sentence embedding, then clusters those embeddings. Embedding models are trained on natural text, so stripped or lemmatised input can hurt them. Counting only happens later, when c-TF-IDF describes each cluster. That is the step where stop words and n-grams are handled.
So the rule of thumb is: clean aggressively for LDA, and clean lightly before embedding for BERTopic.
The LDA preprocessing pipeline
A typical pipeline has six steps. Order matters, because several steps depend on the output of the one before.
- Remove boilerplate. Strip email headers, signatures, HTML tags, URLs, and page navigation text. These repeat across many documents, and LDA will happily build a topic out of them.
- Tokenise and lowercase. Split text into word tokens. Dropping punctuation and very short tokens is usually fine here.
- Remove stop words. Stop words are very common function words such as "the" and "of". LDA has no built-in way to ignore them, so they would dominate every topic.
- Normalise. Lemmatisation maps "teams" and "team" to one token. Without it, the model splits one idea across several vocabulary entries.
- Detect phrases. Join frequent word pairs such as "machine learning" into a single token so the model treats them as one unit.
- Filter by frequency. Drop tokens that appear in too few or too many documents.
A runnable gensim example
This example uses only gensim, so it needs no model downloads. It tokenises, removes stop words, learns bigrams, and builds a filtered dictionary and corpus.
from gensim import corpora
from gensim.models.phrases import Phrases, ENGLISH_CONNECTOR_WORDS
from gensim.parsing.preprocessing import STOPWORDS
from gensim.utils import simple_preprocess
raw_docs = [
"The football team won the league after a great season.",
"The coach praised the team and the players after the match.",
"The government passed a new law after the vote in parliament.",
"The minister defended the new law in a vote on government policy.",
"Players and coaches prepare for the next season of the league.",
"Parliament will vote on the policy proposed by the government.",
]
# 1. Tokenise and lowercase. simple_preprocess drops punctuation and
# tokens shorter than 2 characters by default.
tokens = [simple_preprocess(doc) for doc in raw_docs]
# 2. Remove stop words.
tokens = [[t for t in doc if t not in STOPWORDS] for doc in tokens]
# 3. Learn bigrams from the corpus and apply them.
bigram = Phrases(
tokens,
min_count=2,
threshold=1.0,
connector_words=ENGLISH_CONNECTOR_WORDS,
)
tokens = [bigram[doc] for doc in tokens]
# 4. Build the dictionary and prune it.
dictionary = corpora.Dictionary(tokens)
dictionary.filter_extremes(no_below=2, no_above=0.8)
# 5. Convert to bag-of-words vectors.
corpus = [dictionary.doc2bow(doc) for doc in tokens]
print("Vocabulary size:", len(dictionary))
print("Tokens kept per document:", [len(doc) for doc in corpus])filter_extremes is the most consequential line. no_below=2 removes tokens that appear in fewer than 2 documents. no_above=0.8 removes tokens that appear in more than 80% of documents. On a real corpus you would use larger values, for example no_below=5 or no_below=20, and no_above between 0.3 and 0.5.
Lemmatisation with spaCy
gensim has no lemmatiser, so most people use spaCy. You must download the model once with python -m spacy download en_core_web_sm.
import spacy
nlp = spacy.load("en_core_web_sm", disable=["parser", "ner"])
def lemmatise(text, allowed_pos=("NOUN", "PROPN", "ADJ", "VERB")):
doc = nlp(text.lower())
return [
tok.lemma_
for tok in doc
if tok.pos_ in allowed_pos and not tok.is_stop and len(tok.lemma_) > 2
]
print(lemmatise("The players were training for the next season."))Keeping only nouns, proper nouns, adjectives and verbs is a common choice. It removes function words and tends to give topics that read as subjects. Nouns only gives even more concrete topics, at the cost of losing verbs that carry meaning.
Choosing frequency thresholds
Frequency filtering has a direct effect on what topics look like.
| Setting | Too loose | Too strict |
|---|---|---|
| `no_below` | Typos and rare names enter the vocabulary, which slows training and adds noise | Real but niche topics lose their vocabulary and vanish |
| `no_above` | Corpus-wide words such as "said" or "also" appear in every topic | Words central to a domain corpus get removed |
Look at the data before choosing. Print the most common tokens and the tokens with the highest document frequency. If "said" or "people" top the list in a news corpus, add them to a custom stop word list. Domain stop words are corpus-specific, so generic lists never cover them.
from gensim.parsing.preprocessing import STOPWORDS
custom_stopwords = set(STOPWORDS) | {"said", "also", "would", "could"}What BERTopic needs instead
BERTopic takes raw strings. Three points are different from LDA.
- Do not lemmatise or strip stop words before embedding. Embedding models use word order and function words to understand a sentence. "Not good" and "good" must stay different.
- Do remove obvious noise. Headers, markup, and repeated boilerplate still distort embeddings. The 20 Newsgroups example in this tutorial passes
remove=("headers", "footers", "quotes")for this reason. - Put stop word and n-gram handling in the vectoriser. A
CountVectorizer(stop_words="english", ngram_range=(1, 2))only affects how clusters are labelled. It does not change the clusters. You can therefore change it and refit the labels without re-running the embedding step.
Document length also matters. Sentence embedding models truncate their input. For example, all-MiniLM-L6-v2 reads at most 256 word pieces, so the rest of a long document is ignored. For long texts, split them into paragraphs or sentences and model those, or choose an embedding model with a longer input limit.
Common errors
- Preprocessing the same way for both methods. Lemmatised, stop-word-free text sent to an embedding model usually gives worse clusters than the raw text.
- Fitting phrase detection or filtering on test data. If you plan to infer topics for new documents, build the dictionary and phrase model on the training set only, and reuse them. Unseen tokens are ignored by
doc2bow. - Empty documents after filtering. Short texts can lose every token. An empty bag of words gives no information, so drop those documents and keep track of their original indices.
- Silent vocabulary loss. Always print the vocabulary size and the number of documents kept before and after each step.
- Duplicates. Repeated or near-identical documents (forwarded emails, reposted articles) give their topic extra weight. Deduplicate first.
Exercise
You are preparing the same news corpus for LDA and for BERTopic. Name two preprocessing steps you would apply for LDA but not before the BERTopic embedding step, and say where BERTopic handles the equivalent need.
Show answer
Stop word removal and lemmatisation (also acceptable: frequency filtering or phrase detection). LDA needs them because it models raw word counts and would otherwise fill topics with function words and split inflected forms. BERTopic embeds the near-raw text so the model sees natural sentences. It handles stop words and n-grams afterwards in the vectoriser (for example CountVectorizer(stop_words="english")), which only affects the c-TF-IDF topic descriptions.
Exercise
After calling dictionary.filter_extremes(no_below=5, no_above=0.4) you realise your corpus list was created before that call. What goes wrong, and how do you fix it?
Show answer
Filtering removes tokens and reassigns ids, so the old bag-of-words vectors refer to ids that are missing or point to different words. Rebuild the corpus after filtering with corpus = [dictionary.doc2bow(doc) for doc in tokens].