Sign in

Latent Dirichlet Allocation (LDA)

Latent Dirichlet Allocation

An unsupervised model that finds the hidden topics in a collection of documents.

Overview

Every document is a blend of topics, and every topic is a bag of likely words. A gym's blog post might be 60% "training", 30% "pricing" and 10% "events". LDA works backward from the words to recover both blends.

A short history

David Blei, Andrew Ng and Michael Jordan introduced LDA in 2003 as a fully probabilistic successor to probabilistic latent semantic analysis. Griffiths and Steyvers showed in 2004 that collapsed Gibbs sampling trains it simply and well. It was the standard way to discover topics in text for more than a decade, until embedding-based methods took over for short texts.

How it works

  1. Choose K, the number of topics.
  2. For each document, draw a topic mix θ\theta from a Dirichlet(α\alpha) prior.
  3. For each word slot, draw a topic zz from θ\theta, then draw the word from that topic's word distribution β\beta.
  4. Training inverts this story with Gibbs sampling or variational inference, learning θ\theta per document and β\beta per topic.

Watch out for

  • K is a guess; check topic coherence across several values.
  • It is bag-of-words, so word order and context are lost.
  • Short texts (posts, captions) give weak topics; embedding-based methods such as BERTopic often do better there.
  • Stopwords and rare words must be filtered first or they dominate topics.

Use cases

When to use it

Exploring or tagging a large text corpus, or turning text into compact topic vectors for a recommender's cold-start features.

In industry

Publishing and media
Tagging large news or article archives by theme so that editors and readers can browse by topic.
Customer support
Grouping thousands of support tickets or survey comments into themes to see what customers raise most.
Recommendation
Turning item descriptions into topic vectors that give a new item useful features before it has any clicks.

Choosing it: what must hold

  • Documents long enough to carry several topics each, typically a paragraph or more.
  • A cleaned vocabulary with stopwords and very rare words removed.
  • A need for topics a person can read and name, not only for good vectors.

When to choose something else

IfUse instead
The texts are short posts or captionsAn embedding-based method such as BERTopic
You only need document vectors for a downstream modelSentence embeddings from a pretrained language model

Math foundations

  1. The generative story

    θd∼Dir⁡(α),zd,n∼Cat⁡(θd),wd,n∼Cat⁡(βzd,n)\theta_d \sim \operatorname{Dir}(\alpha), \qquad z_{d,n} \sim \operatorname{Cat}(\theta_d), \qquad w_{d,n} \sim \operatorname{Cat}(\beta_{z_{d,n}})

    How LDA imagines a document was written: pick the document's topic mix, then for every word slot pick a topic from that mix and a word from that topic.

  2. The chance of a word in a document

    p(w∣d)=∑k=1Kθd,k βk,wp(w \mid d) = \sum_{k=1}^{K} \theta_{d,k} \, \beta_{k,w}

    The chance of word ww in document dd is a topic-weighted mix: each topic's chance of producing the word, weighted by how much of the document that topic makes up.

  3. The collapsed Gibbs update

    p(zd,n=k∣rest)  ∝  (nd,k+α) nk,w+ηnk+Vηp(z_{d,n} = k \mid \text{rest}) \;\propto\; \big(n_{d,k} + \alpha\big) \, \frac{n_{k,w} + \eta}{n_{k} + V\eta}

    Training resamples the topic of one word at a time. A topic is likely if the document already uses it a lot (first factor) and if it already produces this word a lot (second factor). All counts leave out the word being resampled.

  4. Reading the answers off the counts

    θ^d,k=nd,k+αnd+Kα,β^k,w=nk,w+ηnk+Vη\hat{\theta}_{d,k} = \frac{n_{d,k} + \alpha}{n_d + K\alpha}, \qquad \hat{\beta}_{k,w} = \frac{n_{k,w} + \eta}{n_k + V\eta}

    After sampling settles, the topic mix of a document and the word distribution of a topic are smoothed shares of the final counts.

Symbols

KK
number of topics
VV
vocabulary size
θd\theta_d
topic mix of document dd
βk\beta_k
word distribution of topic kk
zd,nz_{d,n}
topic assigned to word slot nn of document dd
α, η\alpha,\ \eta
Dirichlet priors on topic mixes and on topic word distributions
nd,kn_{d,k}
words in document dd assigned to topic kk
nk,wn_{k,w}
times word ww is assigned to topic kk in the whole corpus

Worked by hand

A document is 60% topic A and 40% topic B. Topic A produces the word "squat" with probability 0.10 and topic B with probability 0.01.

p(squat∣d)=0.6×0.10+0.4×0.01=0.064p(\text{squat} \mid d) = 0.6 \times 0.10 + 0.4 \times 0.01 = 0.064

About 6 words in 100 of this document are expected to be "squat", nearly all of them coming from topic A.

Visual example

Loading the example.

Try this

  • Press Start over, then Step: the first colours are random, and each sweep sorts the words a little more.
  • Choose a word such as discount in a mixed document and read the two factors that decide its topic.
  • Set the number of topics to 2 and see which two of the three themes get merged.

Code sample

from impl import LDA, build_document_term_matrix
from config import LDAConfig

docs = [["goal", "match", "team", "goal"], ["vote", "law", "vote", "party"],
        ["team", "match", "goal"], ["law", "party", "vote"]]
X, vocab = build_document_term_matrix(docs)          # counts, shape (4, 6)
model = LDA(LDAConfig(n_topics=2, n_iter=100, burn_in=50)).fit(X, vocabulary=vocab)
print(model.top_words(0, 3), model.top_words(1, 3))  # the three most probable words of each topic
theta = model.transform(X)                           # topic mix per document, shape (4, 2)
print(model.perplexity(X))                           # lower is better; 6 (the vocabulary size) = knows nothing
Read the implementation (204 lines)
"""Latent Dirichlet Allocation (the topic model), trained by collapsed Gibbs sampling.

Generative story: there are K topics, each a distribution beta[k] over the V words of the vocabulary. For each
document d draw a topic mix theta[d] ~ Dirichlet(alpha). For each word slot of the document draw a topic z from
theta[d], then draw the word from beta[z]. The probability of word w in document d is therefore

    p(w | d) = sum_k theta[d, k] * beta[k, w]

Training sees only the words and has to find theta and beta. Collapsed Gibbs sampling integrates theta and beta
out and resamples the topic of one word slot at a time from

    p(z = k | everything else)  proportional to  (n_dk + alpha) * (n_kw + eta) / (n_k + V * eta)

where n_dk counts the slots of document d given to topic k, n_kw the times word w is given to topic k and n_k
the slots given to topic k, all without the slot being resampled. NumPy and the standard library only.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import LDAConfig
except ImportError:  # run from the template's own folder
    from config import LDAConfig


def build_document_term_matrix(documents, vocabulary=None):
    """Count words per document.

    documents:  list of D tokenised documents, each a list of string tokens.
    vocabulary: optional list of the V words to count, in column order. Tokens outside it are dropped.
                When omitted, the vocabulary is every token seen, sorted.
    Returns (X, vocabulary): X is an integer array of shape (D, V), X[d, w] = times word w occurs in document d.
    """
    if vocabulary is None:
        vocabulary = sorted({token for doc in documents for token in doc})
    vocabulary = list(vocabulary)
    index = {word: i for i, word in enumerate(vocabulary)}
    counts = np.zeros((len(documents), len(vocabulary)), dtype=np.int64)
    for d, doc in enumerate(documents):
        for token in doc:
            w = index.get(token)
            if w is not None:
                counts[d, w] += 1
    return counts, vocabulary


def _check_counts(X) -> np.ndarray:
    """Return X as a 2-D integer count matrix, or raise ValueError."""
    X = np.asarray(X)
    if X.ndim != 2:
        raise ValueError(f"X must be a 2-D document-term count matrix, got shape {X.shape}")
    if np.any(X < 0) or np.any(X != np.floor(X)):
        raise ValueError("X must hold non-negative whole counts")
    return X.astype(np.int64)


class LDA:
    """Topic model. After `fit`:

    beta_:  shape (K, V), row k is topic k's distribution over words (rows sum to 1).
    theta_: shape (D, K), row d is training document d's topic mix (rows sum to 1).
    """

    def __init__(self, config: LDAConfig | None = None) -> None:
        self.config = config or LDAConfig()
        self.beta_: np.ndarray | None = None
        self.theta_: np.ndarray | None = None
        self.vocabulary_: list | None = None

    def fit(self, X, vocabulary=None) -> "LDA":
        """Run the collapsed Gibbs sampler.

        X:          document-term counts, shape (D, V).
        vocabulary: optional list of V words, so `top_words` can return words instead of column numbers.
        """
        cfg = self.config
        X = _check_counts(X)
        n_docs, n_words = X.shape
        if vocabulary is not None and len(vocabulary) != n_words:
            raise ValueError(f"vocabulary has {len(vocabulary)} words but X has {n_words} columns")
        if X.sum() == 0:
            raise ValueError("X holds no words")
        K, alpha, eta = cfg.n_topics, cfg.alpha, cfg.eta
        rng = np.random.default_rng(cfg.seed)

        # One entry per word slot of the corpus: its document, its word and its current topic.
        d_idx, w_idx = np.nonzero(X)
        repeats = X[d_idx, w_idx]
        doc_of = np.repeat(d_idx, repeats).tolist()
        word_of = np.repeat(w_idx, repeats).tolist()
        n_slots = len(doc_of)
        topic_of = rng.integers(0, K, size=n_slots).tolist()

        # Plain Python lists: the inner loop touches single numbers, where lists beat NumPy arrays.
        n_dk = [[0] * K for _ in range(n_docs)]
        n_kw = [[0] * n_words for _ in range(K)]
        n_k = [0] * K
        for d, w, k in zip(doc_of, word_of, topic_of):
            n_dk[d][k] += 1
            n_kw[k][w] += 1
            n_k[k] += 1

        v_eta = n_words * eta
        topics = range(K)
        weights = [0.0] * K
        sum_dk = np.zeros((n_docs, K))
        sum_kw = np.zeros((K, n_words))
        kept = 0
        for sweep in range(cfg.n_iter):
            uniforms = rng.random(n_slots).tolist()
            for i in range(n_slots):
                d, w, k = doc_of[i], word_of[i], topic_of[i]
                row = n_dk[d]
                row[k] -= 1
                n_kw[k][w] -= 1
                n_k[k] -= 1
                total = 0.0
                for j in topics:
                    total += (row[j] + alpha) * (n_kw[j][w] + eta) / (n_k[j] + v_eta)
                    weights[j] = total  # running sum, so weights is the cumulative distribution
                target = uniforms[i] * total
                k = 0
                while k < K - 1 and weights[k] < target:
                    k += 1
                topic_of[i] = k
                row[k] += 1
                n_kw[k][w] += 1
                n_k[k] += 1
            if sweep >= cfg.burn_in:
                sum_dk += np.asarray(n_dk, dtype=float)
                sum_kw += np.asarray(n_kw, dtype=float)
                kept += 1

        mean_dk = sum_dk / kept
        mean_kw = sum_kw / kept
        self.theta_ = (mean_dk + alpha) / (mean_dk.sum(axis=1, keepdims=True) + K * alpha)
        self.beta_ = (mean_kw + eta) / (mean_kw.sum(axis=1, keepdims=True) + v_eta)
        self.vocabulary_ = list(vocabulary) if vocabulary is not None else None
        return self

    def _require_fit(self) -> None:
        if self.beta_ is None:
            raise RuntimeError("call fit first")

    def transform(self, X) -> np.ndarray:
        """Infer the topic mix of documents with the learned topics held fixed.

        X: counts, shape (D, V) with the same V columns as in `fit`.
        Returns theta, shape (D, K), rows sum to 1. Uses the fixed-point (EM) update for the posterior mode
        under the Dirichlet(alpha) prior smoothed as in the Gibbs estimate:
            r[d, w, k] proportional to theta[d, k] * beta[k, w]      (who explains word w in document d)
            theta[d, k] = (sum_w X[d, w] * r[d, w, k] + alpha) / (n_d + K * alpha)
        A document with no words gets the uniform mix.
        """
        self._require_fit()
        X = _check_counts(X).astype(float)
        if X.shape[1] != self.beta_.shape[1]:
            raise ValueError(f"X has {X.shape[1]} columns, the model was fit on {self.beta_.shape[1]}")
        K, alpha = self.config.n_topics, self.config.alpha
        theta = np.full((X.shape[0], K), 1.0 / K)
        lengths = X.sum(axis=1, keepdims=True)
        for _ in range(self.config.transform_iter):
            mix = theta @ self.beta_                                   # (D, V): p(w | d)
            ratio = np.divide(X, mix, out=np.zeros_like(X), where=mix > 0)
            expected = theta * (ratio @ self.beta_.T)                  # (D, K): expected slots per topic
            theta = (expected + alpha) / (lengths + K * alpha)
        return theta

    def word_probabilities(self, theta) -> np.ndarray:
        """p(w | d) = sum_k theta[d, k] * beta[k, w]. theta: shape (D, K). Returns shape (D, V)."""
        self._require_fit()
        return np.asarray(theta, dtype=float) @ self.beta_

    def top_words(self, topic: int, n: int = 10) -> list:
        """The n most probable words of a topic, most probable first.

        Returns words when a vocabulary was given to `fit`, else column numbers.
        """
        self._require_fit()
        if not 0 <= topic < self.config.n_topics:
            raise ValueError(f"topic must be in [0, {self.config.n_topics}), got {topic}")
        order = np.argsort(-self.beta_[topic], kind="stable")[:n]
        if self.vocabulary_ is None:
            return [int(i) for i in order]
        return [self.vocabulary_[i] for i in order]

    def perplexity(self, X, theta=None) -> float:
        """exp(-(log likelihood of every word slot) / (number of word slots)). Lower is better.

        X:     counts, shape (D, V).
        theta: topic mixes to score with, shape (D, K). When omitted they are inferred with `transform`.
        A model that knows nothing scores V (uniform over the vocabulary).
        """
        self._require_fit()
        X = _check_counts(X).astype(float)
        if theta is None:
            theta = self.transform(X)
        probs = self.word_probabilities(theta)
        total = X.sum()
        if total == 0:
            raise ValueError("X holds no words")
        log_lik = float((X * np.log(np.where(X > 0, probs, 1.0))).sum())
        return float(np.exp(-log_lik / total))
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Run scikit-learn's LatentDirichletAllocation on the 20 Newsgroups dataset with K = 10. Print the top 10 words per topic and name each one.

Check on learning

  1. Two runs of LDA on the same corpus with different random seeds give topics in a different order and with slightly different words. Is one of them wrong? How would you compare the runs?
    A way to think about it

    Topics have no fixed identity, only their word distributions do. Think about matching topics across runs by the similarity of their β\beta rows before you compare anything.

  2. The Gibbs update multiplies a document factor by a word factor. Describe a case where the two factors disagree, and say which one wins as the document gets longer.
    A way to think about it

    Take a word that is typical of topic A appearing in a document that is otherwise all topic B. Look at how nd,kn_{d,k} grows with document length while the word factor stays fixed.

  3. Why does LDA struggle on a corpus of five-word captions, when the same model does well on full articles?
    A way to think about it

    Count how much evidence nd,kn_{d,k} carries for a five-word document and compare it with the prior α\alpha. Then consider how many word co-occurrences a short text offers.

  4. You raise α\alpha from 0.1 to 10. Predict how the topic mixes of documents change, and what that does to how useful they are as features.
    A way to think about it

    A large α\alpha adds the same big count to every topic in the formula for θ^\hat{\theta}. Ask what that does to the difference between documents.