Sub topic 8
Judging topics: coherence and manual inspection
This chapter assumes you can train an LDA model with gensim and know what a BERTopic topic list looks like. It also assumes you are comfortable with the probability notions behind pointwise mutual information (PMI). It covers how to decide whether the topics a model returned are any good.
Why topic models are hard to judge
A topic model is unsupervised. No label says which topic a document "should" get, so there is no accuracy to compute. You have two practical tools:
- Topic coherence is a number that estimates how well a topic's top words belong together.
- Manual inspection means reading topics and example documents yourself.
Use both. Coherence ranks many candidate models cheaply. Inspection tells you whether the winner is useful for your task.
Perplexity, the held-out likelihood that gensim reports for LDA, is a poor substitute. Chang et al. (2009) found that it can move in the opposite direction to human judgement of topic quality. Treat it as a training diagnostic, not a model-selection metric.
How coherence works
A coherence score takes a topic's top N words (usually 10) and measures how often those words occur together in a reference corpus. Words that co-occur often give a high score. Words that rarely appear together give a low one.
The common measures differ in how they count co-occurrence:
| Measure | Counts co-occurrence in | Reference text needed | Typical range |
|---|---|---|---|
| `u_mass` | Whole documents, using log conditional probability | Bag-of-words corpus | Negative, closer to 0 is better |
| `c_uci` | Sliding windows, using PMI | Tokenised texts | Unbounded |
| `c_npmi` | Sliding windows, using normalised PMI | Tokenised texts | -1 to 1 |
| `c_v` | Sliding windows, NPMI context vectors compared by cosine similarity | Tokenised texts | 0 to 1 |
c_v is the most popular default because it correlated best with human ratings in Röder et al. (2015). u_mass is faster and needs no texts argument, but it only looks at the training corpus and its sign convention confuses people.
The c_v measure has several gotchas:
- It is relative. A value of 0.55 means nothing on its own. Compare models only if they use the same measure, the same top-N, the same texts, and the same dictionary.
- It does not transfer between corpora. A 0.45 on tweets and a 0.45 on legal text are not comparable.
- Tiny corpora give noisy scores. With four short documents, as in a toy example, the window statistics are almost meaningless. Use a few thousand documents or more.
- It rewards redundancy. A model with three nearly identical "hockey" topics can score well while telling you less. Coherence says nothing about whether topics are distinct.
- It cannot see junk that is internally consistent. A topic made of email headers or boilerplate can be highly coherent and useless.
Choosing the number of topics with coherence
The standard workflow is to train models over a range of num_topics, compute coherence for each, and look at the curve. This example uses four newsgroups so it runs in a few minutes.
from gensim import corpora
from gensim.models import LdaModel, CoherenceModel
from gensim.parsing.preprocessing import STOPWORDS
from gensim.utils import simple_preprocess
from sklearn.datasets import fetch_20newsgroups
raw = fetch_20newsgroups(
subset="all",
categories=["rec.sport.hockey", "sci.space", "talk.politics.misc", "comp.graphics"],
remove=("headers", "footers", "quotes"),
)["data"]
docs = [
[t for t in simple_preprocess(text, min_len=3) if t not in STOPWORDS]
for text in raw
]
dictionary = corpora.Dictionary(docs)
dictionary.filter_extremes(no_below=5, no_above=0.5)
corpus = [dictionary.doc2bow(doc) for doc in docs]
scores = {}
models = {}
for k in range(2, 11, 2):
lda = LdaModel(
corpus=corpus, id2word=dictionary, num_topics=k,
passes=5, random_state=42,
)
cm = CoherenceModel(
model=lda, texts=docs, dictionary=dictionary,
coherence="c_v", topn=10, processes=1,
)
scores[k] = cm.get_coherence()
models[k] = lda
print(k, round(scores[k], 3))Pass the same docs and dictionary to every CoherenceModel. Words removed by filter_extremes are absent from the dictionary, so the model's topics cannot contain them, and the scores stay comparable.
Do not pick the maximum blindly. Coherence often climbs, plateaus, and then wobbles. Pick the start of the plateau, or the smaller k among near-ties, then inspect the candidates by hand. A different random_state can shift scores by a few hundredths, so average over a few seeds before trusting small gaps.
Manual inspection
Read the topics yourself. Three checks catch most problems:
- Top words. Can you name the topic in a few words? Look for stop-word-like terms, boilerplate, and mixed themes.
- Example documents. Top words can look fine while the documents behind them do not. Read the three to five documents that score highest for each topic.
- Topic sizes and overlap. Note topics that cover almost every document, topics that cover almost none, and pairs that share most of their top words.
This helper prints the best-matching documents for each LDA topic. It uses lda, corpus, and raw from the previous block.
def show_topics(lda, corpus, raw_texts, n_docs=2, n_words=8, width=200):
best = {k: [] for k in range(lda.num_topics)}
for i, bow in enumerate(corpus):
for k, p in lda.get_document_topics(bow, minimum_probability=0.0):
best[k].append((p, i))
for k in range(lda.num_topics):
words = ", ".join(w for w, _ in lda.show_topic(k, topn=n_words))
print(f"\nTopic {k}: {words}")
for p, i in sorted(best[k], reverse=True)[:n_docs]:
snippet = " ".join(raw_texts[i].split())[:width]
print(f" [{p:.2f}] {snippet}")
show_topics(models[4], corpus, raw)If a topic's best documents are short or near-duplicates, the topic may be capturing a quirk of the data and not a theme.
Evaluating BERTopic topics
Coherence applies to BERTopic too, because it only needs lists of words per topic. Two details matter. First, exclude topic -1, the outlier group, which is not a coherent theme. Second, tokenise the reference texts with the same analyzer BERTopic used, so the words in the topics exist in your dictionary.
from gensim.corpora import Dictionary
from gensim.models.coherencemodel import CoherenceModel
def bertopic_coherence(topic_model, docs, topn=10):
analyzer = topic_model.vectorizer_model.build_analyzer()
tokens = [analyzer(doc) for doc in docs]
dictionary = Dictionary(tokens)
topic_words = []
for topic_id in topic_model.get_topics():
if topic_id == -1:
continue
words = [w for w, _ in topic_model.get_topic(topic_id)[:topn] if w]
topic_words.append(words)
cm = CoherenceModel(
topics=topic_words, texts=tokens, dictionary=dictionary,
coherence="c_v", processes=1,
)
return cm.get_coherence()For manual inspection, topic_model.get_representative_docs(topic_id) returns documents closest to a topic. Also check how many documents sit in topic -1. A high coherence over only 40% of the corpus is a weaker result than it looks, so report coverage next to the score.
Common mistakes
- Comparing coherence across different preprocessing pipelines. Changing stop words changes the scores.
- Computing
c_von the toy corpus from a tutorial and reading meaning into the number. - Choosing
kby the highest score without reading the topics. - Scoring only top-3 words for one model and top-10 for another.
Exercise
You trained LDA models with 5, 10, and 15 topics. The c_v scores are 0.48, 0.52, and 0.52. Reading the 15-topic model shows that three topics share the words "game", "team", and "season". Which model do you choose, and why?
Show answer
Choose the 10-topic model. The 10 and 15 scores tie, so the smaller model is simpler. The 15-topic model also splits one theme into three near-duplicate topics, which coherence cannot detect but manual inspection can. Before settling, try a few random seeds to confirm that the 0.04 gap to the 5-topic model is larger than seed-to-seed variation.
Exercise
Why must you exclude topic -1 when computing coherence for a BERTopic model?
Show answer
Topic -1 holds outlier documents that were not assigned to any cluster. Its c-TF-IDF words are a mix of unrelated terms, not a theme, so including it lowers the score and misrepresents the quality of the real topics. Report the share of documents in topic -1 separately.