Sub topic 2
Training and reading an LDA model with gensim
This chapter assumes you know Python, can install packages with pip, and understand bag-of-words counts and TF-IDF. You will train a Latent Dirichlet Allocation (LDA) model, judge its topics, then look at an embedding-based alternative.
Training an LDA model
Gensim is a Python library for topic modelling. Its LdaModel takes a bag-of-words corpus and a dictionary that maps word IDs back to words.
from gensim import corpora
from gensim.models import LdaModel
docs = [
["goal", "match", "player", "team", "season"],
["election", "vote", "party", "government", "policy"],
["team", "coach", "league", "season", "win"],
["minister", "government", "vote", "law", "policy"],
]
dictionary = corpora.Dictionary(docs)
corpus = [dictionary.doc2bow(doc) for doc in docs]
lda = LdaModel(corpus=corpus, id2word=dictionary,
num_topics=2, passes=10, random_state=42)
for topic_id, words in lda.print_topics(num_words=5):
print(topic_id, words)Each topic is a probability distribution over words. Each document is a mixture of topics. Read the top words of each topic, then check which topics each document leans toward with lda.get_document_topics(corpus[0]).
To choose num_topics, train several models with different values and compare them using the evaluation methods below.
Judging topics: coherence and manual inspection
Coherence scores how often a topic's top words appear together in the source documents. Gensim computes the c_v variant:
from gensim.models import CoherenceModel
coherence = CoherenceModel(model=lda, texts=docs,
dictionary=dictionary, coherence="c_v").get_coherence()
print("c_v coherence:", coherence)Coherence alone can mislead. Always read the top words yourself, and read a few documents assigned to each topic. A topic whose words are coherent but meaningless to a reader is still a poor topic.
Where LDA struggles
LDA treats documents as bags of words, so word order and meaning are lost. It also cannot tell that "car" and "automobile" mean the same thing unless both appear in the same contexts. Short texts, such as tweets, give LDA too few word counts per document. Results also change between runs unless you fix random_state.
Sentence embeddings as document representations
A sentence embedding is a list of numbers that represents a passage's meaning. Documents with similar meaning get nearby vectors, even when they use different words. A pretrained model such as all-MiniLM-L6-v2 produces these vectors. Embedding models usually produce hundreds of dimensions, which is too many for density-based clustering to work well.
Reducing embeddings with UMAP
UMAP (Uniform Manifold Approximation and Projection) is a method that maps high-dimensional vectors to fewer dimensions while keeping nearby points close. The random_state argument makes results repeatable.
Clustering with HDBSCAN
HDBSCAN (Hierarchical Density-Based Spatial Clustering of Applications with Noise) groups points that sit in dense regions and labels sparse points as noise. Noise receives the label -1. Each remaining cluster becomes a topic.
from sklearn.datasets import fetch_20newsgroups
from sentence_transformers import SentenceTransformer
from umap import UMAP
from hdbscan import HDBSCAN
docs = fetch_20newsgroups(subset="all",
remove=("headers", "footers", "quotes"))["data"][:2000]
embeddings = SentenceTransformer("all-MiniLM-L6-v2").encode(docs)
reduced = UMAP(n_components=5, n_neighbors=15, metric="cosine",
random_state=42).fit_transform(embeddings)
labels = HDBSCAN(min_cluster_size=15).fit_predict(reduced)
print("clusters:", len(set(labels)) - (1 if -1 in labels else 0))
print("noise documents:", list(labels).count(-1))Exercise
You train an LDA model with num_topics=2 and the top words of both topics look unrelated. Name two checks you would run before changing the model.
Show answer
Check that the preprocessing removed stop words and kept the right tokens, and check the number of documents and their lengths. Then train with other num_topics values, compare coherence scores, and read example documents for each topic.