Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Topic modelling: LDA, LSA and NMF

Topic modelling finds latent 'topics' (soft clusters of words) in a corpus; main algorithms are LSA (SVD on a term-document matrix), NMF (nonnegative factorization), and LDA (probabilistic model with Dirichlet priors).

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Topic modelling is used by engineers to summarise, search and explore large text collections without manual labelling. You will use it in document clustering, recommendation, search-result diversification and as features for downstream NLP (classification, summarisation). These methods give different trade-offs: LSA and NMF are algebraic/matrix methods, LDA is a generative probabilistic model.

Key ideas

  • Document: an item in the corpus (e.g., an article, a paragraph).

  • Term (word): an atomic token after tokenisation (assume stopwords handled as required).

  • Topic: a probability distribution over terms, or intuitively a coherent set of words representing a theme.

  • Topic modelling: the algorithmic task of discovering topics and representing documents as mixtures of topics.

  • Broad approaches:

    • Latent Semantic Analysis (LSA): an algebraic method. Build a term-document matrix (often TF-IDF weighted). Apply Singular Value Decomposition (SVD) and keep top k singular values/vectors to produce a low-rank approximation. LSA captures co-occurrence structure (latent concepts) via linear algebra.
    • Non-negative Matrix Factorisation (NMF): an optimisation method. Given a non-negative term-document matrix A, find non-negative matrices W (terms × k) and H (k × documents) so that A ≈ W·H, typically by minimising Frobenius norm. The non-negativity often yields parts-based, more interpretable topics because components add (no cancellation).
    • Latent Dirichlet Allocation (LDA): a probabilistic generative model. Each document has a latent topic mixture (drawn from a Dirichlet prior). For each word position in a document, first select a topic from the document's mixture, then draw a word from that topic's word distribution (also drawn from a Dirichlet prior). Inference estimates the hidden topic assignments and the topic distributions.
  • Exact statements and assumptions:

    • SVD theorem (matrix version used in LSA): For any real matrix A (m × n) there exist orthogonal matrices U (m × m) and V (n × n) and a diagonal matrix Σ (m × n) with non-negative diagonal entries (singular values) such that A = U·Σ·V^T. Truncating Σ to top k singular values gives the best rank-k approximation in the Frobenius norm (Eckart–Young theorem). Assumptions: A real matrix; best approximation measured by Frobenius norm.
    • NMF problem statement: Given A ≥ 0 (entrywise), find W ≥ 0 and H ≥ 0 to minimise ||A − W·H||_F^2. This is non-convex in (W,H) together; typically solved by alternating updates. Assumptions: A has non-negative entries; solutions are local minima.
    • LDA generative model (exact): For T topics and vocabulary size V,
      1. For each topic t = 1..T, draw topic-word distribution φ_t ∼ Dirichlet(β) over V words.
      2. For each document d, draw topic proportions θ_d ∼ Dirichlet(α) over T topics.
      3. For each word position n in document d: draw topic z_{d,n} ∼ Multinomial(θ_d); then draw word w_{d,n} ∼ Multinomial(φ_{z_{d,n}}). Assumptions: exchangeability of words within a document, fixed T, symmetric or asymmetric Dirichlet priors as chosen.
  • What to draw for an exam (diagrams):

    • For LSA: draw the term-document matrix as a rectangle with terms as rows and documents as columns. Then show decomposition arrows to U (terms×k), Σ (k×k diagonal) and V^T (k×documents). Label: U columns = term-concepts, columns of V^T = document-concepts, Σ = singular strengths.
    • For LDA: draw the plate diagram. Draw a big plate for documents indexed by d (size D). Inside it draw a plate for words indexed by n (size N_d). Outside, draw a node φ_t for each topic t (repeat T times). Inside the document plate draw θ_d. From θ_d draw z_{d,n} into the word plate and from z_{d,n} draw w_{d,n}. Label α on θ_d and β on φ_t. This exactly matches the generative description.
  • Relationships and intuition:

    • LSA is linear algebra capturing global co-occurrence patterns; it is deterministic once matrix formed and k chosen.
    • NMF enforces non-negativity and gives additive parts (useful where negative components are hard to interpret).
    • LDA models uncertainty and gives a principled probabilistic interpretation (documents are mixtures of topics); hyperparameters α and β control sparsity of mixtures and of topic-word distributions respectively.

Formulas

A = U · Σ · V^T — A is the term-document matrix (m×n), U is m×m orthogonal, Σ is m×n diagonal with singular values (non-negative), V is n×n orthogonal. Applies for any real matrix A.

A_k = U_k · Σ_k · V_k^T — truncated rank-k SVD approximation. U_k is m×k, Σ_k is k×k, V_k is n×k. Gives best rank-k approximation in Frobenius norm.

min_{W,H >= 0} ||A - W·H||_F^2 — NMF objective. A is m×n non-negative, W is m×k, H is k×n, ||.||_F is Frobenius norm.

W_{ik} <- W_{ik} * ( (A·H^T)_{ik} / (W·H·H^T)_{ik} ) — multiplicative update for W (Lee and Seung). Applies when minimizing Frobenius norm with W,H non-negative (do similarly for H).

H_{kj} <- H_{kj} * ( (W^T·A)_{kj} / (W^T·W·H)_{kj} ) — multiplicative update for H.

(LDA generative) φ_t ∼ Dirichlet(β), θ_d ∼ Dirichlet(α), z_{d,n} ∼ Multinomial(θ_d), w_{d,n} ∼ Multinomial(φ_{z_{d,n}}) — define φ_t (topic-word distribution), θ_d (document-topic distribution), z (topic assignment), w (observed word).

(Collapsed Gibbs sampling update for LDA) P(z_{d,n}=t | z_{-}, w) ∝ (n_{t,w_{d,n}}^{(-)} + β) / (n_{t}^{(-)} + V·β) * (n_{d,t}^{(-)} + α) / (n_{d}^{(-)} + T·α) — where counts with superscript (-) exclude current token. Applies in collapsed Gibbs inference for LDA.

Definitions of symbols used above are given inline where formula appears; there are no SI units here.

Worked examples

  1. Model answer: Explain LSA on a small corpus (conceptual exam-style answer)

    • Question: Describe the pipeline for LSA, showing how SVD finds latent concepts and how to represent documents and terms in k-dimensional space.
    • Answer (model): Steps:
      1. Preprocess: tokenise, optional stopword removal, optional lemmatisation or stemming.
      2. Construct term-document matrix A (m terms × n documents). Use raw counts or TF-IDF weights (TF-IDF emphasises discriminative terms).
      3. Compute SVD: A = U·Σ·V^T. Keep top k singular values to get U_k, Σ_k, V_k^T.
      4. Represent terms by rows of U_k·Σ_k and documents by rows of V_k·Σ_k (or columns of V_k·Σ_k depending on orientation). Similarity between documents can be computed by cosine similarity in this reduced k-dimensional space.
      5. Draw diagram: show A and arrows to U_k, Σ_k, V_k^T and label which matrices are used for term and document vectors.
    • Exam-level note: State Eckart–Young theorem: the truncated SVD gives the best rank-k approximation in Frobenius norm; hence the approximation minimises reconstruction error.
  2. Worked Gibbs sampling step for LDA (short numeric table)

    • Setup: Vocabulary V = {apple, banana, car}, T = 2 topics, D = 2 documents. Choose α = 1.0, β = 1.0 (symmetric Dirichlet).
    • Small corpus: doc1 = [apple, banana], doc2 = [banana, car]. Initialize topic assignments randomly: z_{1,1}=1, z_{1,2}=2, z_{2,1}=1, z_{2,2}=2.
    • Counts excluding a token: consider token w = doc1 word 1 (apple) and we will compute probability of assigning topic t=1 or 2 to it. Compute counts excluding current token (superscript (-)):
      • n_{t,w}^{(-)}: topic-word counts excluding current token. Suppose initial other counts give n_{1,apple}^{(-)} = 0, n_{2,apple}^{(-)} = 0.
      • n_t^{(-)}: total words assigned to topic t excluding current token. Suppose n_1^{(-)} = 1, n_2^{(-)} = 2.
      • n_{d,t}^{(-)}: words in document 1 assigned to topic t excluding current token. Suppose n_{1,1}^{(-)} = 0 (since current token excluded), n_{1,2}^{(-)} = 1.
      • Plug into Gibbs formula (with V=3, T=2):
        • For t=1: (0 + 1) / (1 + 31) * (0 + 1) / (1 + 21) = 1/4 * 1/3 = 1/12 ≈ 0.0833.
        • For t=2: (0 + 1) / (2 + 31) * (1 + 1) / (1 + 21) = 1/5 * 2/3 = 2/15 ≈ 0.1333.
      • Normalise: P(t=1) = 0.0833/(0.0833+0.1333)=0.3846, P(t=2)=0.6154. So assign topic 2 with higher probability.
    • This single-step calculation shows how counts and α,β affect assignment. Repeat many times to converge.
  3. NMF numeric iteration (short)

    • Let A = [[2,0],[0,2]] (2×2). Choose k=1. Initialise W = [[1],[1]] and H = [[1,1]]. Multiplicative updates for one iteration (Frobenius norm):
      • Compute W update numerator: (A·H^T) = [[2+0],[0+2]] = [[2],[2]]. Denominator: (W·H·H^T) = W·(H·H^T) = [[1*(1+1)],[1*(1+1)]] = [[2],[2]]. So W <- W * ([[2],[2]] / [[2],[2]]) = W unchanged = [[1],[1]].
      • Compute H update similarly: (W^T·A) = [[12 + 10, 10 + 12]] = [[2,2]]; denominator (W^T·W·H) = [[(1+1)*[1,1]]] = [[2,2]]. So H unchanged in this symmetric case. This simple example shows multiplicative updates preserve non-negativity and converge; real problems have non-trivial updates.

Common mistakes

  • Not normalising document/topic vectors before comparing (cosine similarity vs Euclidean matters).
  • For NMF: forgetting non-negativity constraints when describing updates.
  • In LDA Gibbs formula: misplacing the V·β or T·α terms in denominators (they come from normalising Dirichlet-multinomial counts).
  • Using raw counts without TF-IDF for LSA on corpora where high-frequency common words dominate topics.

For your exam

Kinds of questions:

  • Definitions and short notes: define LSA, NMF, LDA, Dirichlet distribution, TF-IDF.
  • Derivations: show SVD decomposition and explain Eckart–Young theorem; derive multiplicative update rules for NMF (usually shown in exams at a high level or derived using Lagrange multipliers); derive the collapsed Gibbs sampling update for LDA from Dirichlet–multinomial conjugacy.
  • Numerical/algorithmic: perform one Gibbs sampling step given counts; perform one iteration of NMF multiplicative updates on a small matrix.
  • Diagrams: draw SVD factorisation diagram for LSA and the plate diagram for LDA.

What a full-marks answer includes:

  • Precise definitions (bold terms), clear assumptions (e.g., A ≥ 0 for NMF), complete derivation steps with notation explained, diagrams labelled exactly as above, and a short discussion of pros/cons and complexity (SVD O(min(mn^2, m^2n)), NMF depends on iterations, LDA inference via Gibbs or variational methods is approximate). Additionally, state how to choose the number of topics/dimensions k or T (e.g., via held-out likelihood/perplexity for LDA, topic coherence or stability measures for all methods) and typical weighting choices (counts for LDA; counts or TF-IDF for LSA/NMF).

Quick check

  1. What is the matrix decomposition used in LSA?
  2. In LDA, which distributions generate θ_d and φ_t?
  3. What constraint does NMF add that SVD does not?

Answers: 1. SVD (A = U·Σ·V^T). 2. Dirichlet distributions (θ_d ∼ Dirichlet(α), φ_t ∼ Dirichlet(β)). 3. Non-negativity of factors (W,H ≥ 0).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?