Sub topic 7
Training and reading an LDA model with gensim
This chapter assumes you have read the earlier chapters on bag-of-words counts, the LDA generative story, and Dirichlet priors. You should also be comfortable with Python and the idea of a probability distribution. By the end you will be able to train a gensim LdaModel, read its two outputs, and choose its main settings.
The workflow
Training LDA in gensim has five steps. Each step feeds the next, and mistakes early on show up as unreadable topics later.
Preparing the dictionary and corpus
gensim represents each document as a list of (word_id, count) pairs. A Dictionary maps words to ids. Call filter_extremes before building the corpus. It removes words that are too rare to form patterns and words so common that they appear in every topic.
from gensim import corpora
from gensim.models import LdaModel
from gensim.parsing.preprocessing import STOPWORDS
from gensim.utils import simple_preprocess
from sklearn.datasets import fetch_20newsgroups
categories = ["sci.space", "rec.sport.hockey", "talk.politics.misc", "comp.graphics"]
raw = fetch_20newsgroups(
subset="train",
categories=categories,
remove=("headers", "footers", "quotes"),
)["data"]
docs = [
[w for w in simple_preprocess(text, min_len=3) if w not in STOPWORDS]
for text in raw
]
docs = [d for d in docs if d] # drop documents left empty after cleaning
dictionary = corpora.Dictionary(docs)
dictionary.filter_extremes(no_below=10, no_above=0.5)
corpus = [dictionary.doc2bow(doc) for doc in docs]
print(len(dictionary), "words kept;", len(corpus), "documents")The two arguments to filter_extremes matter:
no_below=10drops words that appear in fewer than 10 documents.no_above=0.5drops words that appear in more than half of the documents.
Documents can end up empty after filtering. Such a document has no evidence for any topic, so check for this if you filter harder than shown here.
Training the model
lda = LdaModel(
corpus=corpus,
id2word=dictionary,
num_topics=4,
alpha="auto",
eta="auto",
passes=10,
iterations=100,
chunksize=2000,
random_state=42,
)These are the parameters you will tune most often:
| Parameter | Meaning | Practical guidance |
|---|---|---|
| `num_topics` | Number of topics, K | Must be chosen by you. See the next sections. |
| `alpha` | Prior on document-topic mixtures | `"asymmetric"` or `"auto"` often helps. Lower values give sparser mixtures. |
| `eta` | Prior on topic-word distributions | `"auto"` learns it. A low value gives topics with fewer dominant words. |
| `passes` | Full sweeps over the corpus | Increase if topics keep changing between runs. |
| `iterations` | Maximum inference loops per document per chunk | Increase if the log shows documents not converging. |
| `chunksize` | Documents processed per update | Larger values use more memory and give steadier updates. |
| `random_state` | Seed | Set it so a run can be repeated. |
Reading the two outputs
An LDA model gives you two things, matching the two distributions in the generative story.
The topic-word distributions describe what each topic is about:
for topic_id in range(lda.num_topics):
words = [f"{w} ({p:.3f})" for w, p in lda.show_topic(topic_id, topn=8)]
print(topic_id, ", ".join(words))The document-topic distribution describes what one document is made of:
mixture = lda.get_document_topics(corpus[0], minimum_probability=0.0)
print(sorted(mixture, key=lambda pair: pair[1], reverse=True))Set minimum_probability=0.0 so that every topic is returned. By default gensim hides topics below a small threshold, which makes mixtures look like they do not add up to 1.
A topic is not labelled by the model. You name it yourself after reading its top words and a few documents that score high on it. The word list is ordered by probability, so words near the top define the topic most strongly.
Choosing the number of topics
LDA has no built-in way to pick K. A common approach is to train several models and compare topic coherence, then check the winner by reading it. The c_v measure needs the tokenised texts.
from gensim.models import CoherenceModel
scores = {}
for k in (2, 4, 6, 8, 12):
model = LdaModel(
corpus=corpus,
id2word=dictionary,
num_topics=k,
alpha="auto",
eta="auto",
passes=10,
random_state=42,
)
cm = CoherenceModel(
model=model, texts=docs, dictionary=dictionary,
coherence="c_v", processes=1,
)
scores[k] = cm.get_coherence()
for k, score in scores.items():
print(k, round(score, 3))Do not simply take the highest score. Coherence often rises and then plateaus, and the best value may be a K that merges or splits real themes. Prefer the smallest K near the top of the curve, then read its topics. The next chapter covers coherence in more detail.
Common errors and fixes
- Topics full of generic words. Words like "people" or "think" survive stop-word removal. Lower
no_above, or add corpus-specific stop words. - Topics that look like noise. Too many rare words, too few passes, or K too high. Raise
no_below, raisepasses, and try smaller K. - Several topics that look the same. K is probably too high. Reduce it, or try
alpha="asymmetric". - Different topics on every run. Fix
random_state. If topics still change, increasepassesanditerations. - Mixtures that do not sum to 1. You left
minimum_probabilityat its default. c_vfails or hangs. On Windows or in notebooks, multiprocessing can cause trouble. Passprocesses=1as shown.- Short texts such as tweets. Each document has too few words to estimate a mixture. LDA struggles here, and a later chapter covers alternatives.
Saving and using a model on new text
lda.save("lda_newsgroups.model")
loaded = LdaModel.load("lda_newsgroups.model")
new_doc = simple_preprocess("The rocket launch was delayed by weather", min_len=3)
bow = loaded.id2word.doc2bow([w for w in new_doc if w not in STOPWORDS])
print(loaded.get_document_topics(bow, minimum_probability=0.0))Words not in the dictionary are silently ignored by doc2bow. If a new document has almost no known words, its mixture will mostly reflect the learned priors rather than the text.
Exercise
You train an LDA model with numtopics=10 and print the topics. Topics 3 and 7 share most of their top words, and `getdocument_topics(bow)` for one document returns only three of the ten topics. Give one change that explains or fixes each observation.
Show answer
Topics 3 and 7 repeating each other suggests K is too high, so try a smaller numtopics (or alpha="asymmetric"), then compare cv coherence and re-read the topics. The document returning only three topics is expected: by default gensim drops topics under a small probability threshold. Pass minimum_probability=0.0 to see all ten, which will then sum to 1.
Exercise
Why must you pass texts=docs to CoherenceModel when using coherence="c_v", and why is it a problem to compute c_v on the four-document toy corpus from the spine?
Show answer
c_v measures how often a topic's top words appear together in the original token lists, using a sliding window, so it needs the tokenised texts rather than the bag-of-words corpus. With only four short documents, the co-occurrence counts are tiny and noisy, so the score is unreliable and cannot support a choice of K.