AI Wiki中文/EN

Topic models: let a document talk about more than one thing

主题模型

Derive pLSA EM, fold in unseen documents and distinguish predictive fit from meaningful topics.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A document need not fit in one drawer

Imagine six invented notes about fruit growing and space travel. Some contain apple pear orchard; others contain orbit rocket planet. A note about growing fruit on a space station could use both vocabularies. A clustering system might assign it one group. A topic model can instead represent it as a mixture, such as 60% of one word distribution and 40% of another.

A topic here is a distribution over vocabulary items. A document mixture gives the weights used to combine those distributions. A name such as “space travel” is an interpretation supplied after examining the words and documents; it is not an observed training label or a proof that the model found a natural category. The original pLSA aspect model associates a hidden class with each word occurrence and mixes those classes within a document. Aspect model, §2

These distinctions help when browsing a document collection, organizing search results or preparing features for another task. They also prevent a common mistake: a group of frequent names, boilerplate phrases or publishing dates may predict words well without describing the subjects a reader cares about. Decide what the representation should help someone do before choosing a topic count or assigning names.

The pLSA example fits two word distributions, checks an E-step by hand and evaluates five separate target tokens. Training fit, prediction and human interpretation answer different questions.
The pLSA example fits two word distributions, checks an E-step by hand and evaluates five separate target tokens. Training fit, prediction and human interpretation answer different questions.

Factor word probabilities, then count expected assignments

Let X be a D-by-V matrix of nonnegative integer token counts. Row d records a document; column w records a training-vocabulary word. Choose K topics. Theta has shape D-by-K and phi has shape K-by-V. Both have nonnegative entries and rows summing to one:

Pdw=p(w∣d)=∑k=1Kθdkϕkw,∑kθdk=1,∑wϕkw=1.P_{dw}=p(w\mid d)=\sum_{k=1}^{K}\theta_{dk}\phi_{kw},\qquad \sum_k\theta_{dk}=1,\quad\sum_w\phi_{kw}=1.

Every word occurrence receives its own latent topic assignment. This differs from a mixture that chooses one component for an entire document. Word order is ignored. Swapping “dog bites person” for “person bites dog” leaves the counts unchanged, so this representation cannot distinguish their roles. This is a limitation of the input and model, not something that more EM iterations repair.

We condition on the document identities and lengths. The conditional log likelihood of the observed token sequences is:

ℓ(θ,ϕ)=∑d,wXdwlog⁡Pdw.\ell(\theta,\phi)=\sum_{d,w}X_{dw}\log P_{dw}.

The program omits the multinomial coefficient for an unordered count vector. That coefficient is constant when fitting a fixed count matrix, but probability units still matter when comparing scores. Raw counts are used below; a TF–IDF entry is not literally a number of draws from a categorical distribution.

E-step. For each observed document-word pair, Bayes’ rule assigns a responsibility to every topic:

qdwk=p(z=k∣d,w)=θdkϕkw∑jθdjϕjw.q_{dwk}=p(z=k\mid d,w) =\frac{\theta_{dk}\phi_{kw}}{\sum_j\theta_{dj}\phi_{jw}}.

The responsibilities sum to one across k when the observed word has positive model probability. Repeated occurrences have the same responsibility under the current document mixture, but each occurrence contributes a count. If a word with positive count has zero probability under every topic, the implementation reports an error instead of silently adding smoothing.

M-step. Accumulate expected assignments within a document and normalize:

Ndk=∑wXdwqdwk,θdknew=NdkNd,Nd=∑wXdw.N_{dk}=\sum_w X_{dw}q_{dwk},\qquad \theta^{\mathrm{new}}_{dk}=\frac{N_{dk}}{N_d},\quad N_d=\sum_wX_{dw}.

For the topic-word distributions, accumulate across documents instead:

Nkw=∑dXdwqdwk,ϕkwnew=Nkw∑vNkv.N_{kw}=\sum_d X_{dw}q_{dwk},\qquad \phi^{\mathrm{new}}_{kw}=\frac{N_{kw}}{\sum_v N_{kv}}.

One way to obtain these updates is to maximize the expected complete log likelihood. The terms involving a document row are a sum of N_dk times log theta_dk. A Lagrange multiplier enforces a row sum of one; differentiating gives theta_dk proportional to N_dk. The word-row update follows the same argument. In an empty document the objective does not identify theta, so the code keeps its previous row. If a component receives no expected tokens, it keeps its previous phi row. These are explicit choices for zero-count rows, not extra observed evidence.

Hofmann gives equivalent symmetric and conditional parameterizations and EM updates. The article’s full training procedure also discusses tempered EM; the program here implements ordinary maximum-likelihood EM only. Its observed training likelihood should not decrease beyond rounding error, but a local optimum need not be the best fit. Model and fitting, §§2–3

For a hand check, take one document with counts [2,1], theta [0.6,0.4], and topic-word rows [0.8,0.2] and [0.1,0.9]. The word probabilities are 0.52 and 0.48. Topic 0’s responsibilities are 12/13 and 1/4. After one full update, theta is [109/156,47/156]; phi’s rows become [96/109,13/109] and [8/47,39/47]. The likelihood of the ordered word sequence rises from log(0.52² × 0.48) to log((2/3)² × 1/3).

Connection to matrix factorization. A normalized nonnegative product also reconstructs expected counts. With zero-count terms interpreted by continuity:

X^dw=NdPdw,DKL(X∥X^)=∑d,w[Xdwlog⁡XdwX^dw−Xdw+X^dw]=∑d,wXdwlog⁡Xdw−∑dNdlog⁡Nd−ℓ.\widehat X_{dw}=N_dP_{dw},\qquad D_{\mathrm{KL}}(X\Vert\widehat X) =\sum_{d,w}\left[X_{dw}\log\frac{X_{dw}}{\widehat X_{dw}}-X_{dw}+\widehat X_{dw}\right] =\sum_{d,w}X_{dw}\log X_{dw}-\sum_dN_d\log N_d-\ell.

For a fixed X, minimizing this generalized KL divergence is equivalent to maximizing the conditional likelihood. This does not make every NMF objective a probabilistic topic model. Squared-error NMF, arbitrary input weighting and unconstrained factor scales use different choices; read the NMF article for that broader family.

An unseen document. Freeze phi and optimize only the new document’s theta from its observed words. This is called fold-in; it is possible in pLSA even though its original conditional model does not place a generative prior on document mixtures. Fixed-factor fold-in, §4.6 LDA adds a probability model for those mixtures instead of treating each training document’s mixture as an unrelated fitted parameter. LDA construction, §3

For held-out prediction, split a new document into an observed part and a target part. Infer theta using only the observed part, then score the target:

PPL⁡=exp⁡(−1Ntarget∑d,wXdwtargetlog⁡∑kθ^dkobservedϕ^kwtrain).\operatorname{PPL} =\exp\left(-\frac{1}{N_{\mathrm{target}}}\sum_{d,w}X^{\mathrm{target}}_{dw} \log\sum_k\widehat\theta_{dk}^{\mathrm{observed}}\widehat\phi_{kw}^{\mathrm{train}}\right).

A perplexity is meaningful only with a stated tokenization, vocabulary, target denominator and inference policy. Here unknown observed words are ignored and reported. The five target tokens are all in the training vocabulary. A zero-length target has no perplexity; numerical overflow is reported with a null perplexity and a separate status, while log perplexity remains available.

For dense arrays, one EM step takes O(DKV) time and O(DKV) temporary space; the persistent parameter tables need O(DK+KV). Fold-in has the same dense responsibility cost for its new-document rows while phi remains fixed. The conditional model has D(K−1)+K(V−1) free row-probability parameters before special zero rows or identifiability issues. Increasing K changes both capacity and the interpretation problem.

Train on counts; keep the hidden words hidden

Save the following complete program as topic_models.py and run it with Python 3.12 and NumPy 1.26.4. It builds a vocabulary from six invented training notes, runs 80 ordinary EM updates, and folds in four new observed fragments without changing phi. The fourth fragment contains only unseen, which is outside the vocabulary; its mixture stays at the explicitly chosen uniform initialization.

"""Original dense pLSA teaching baseline: ordinary EM, not tempered EM."""
import json, math, sys
import numpy as np


def counts(value):
    raw=np.asarray(value)
    if raw.dtype.kind=='b':raise ValueError('Counts must be integers, not booleans')
    x=np.asarray(value,dtype=float)
    if x.ndim!=2 or min(x.shape)<1 or x.shape[0]>128 or x.shape[1]>256:raise ValueError('Use 1..128 documents and 1..256 words')
    if not np.isfinite(x).all() or (x<0).any() or (x!=np.floor(x)).any() or x.sum()>1e7:raise ValueError('Use finite nonnegative integer counts, total at most1e7')
    return x


def state(x,theta,phi):
    x=counts(x);theta=np.asarray(theta,dtype=float);phi=np.asarray(phi,dtype=float)
    if theta.ndim!=2 or phi.ndim!=2 or theta.shape[0]!=len(x) or phi.shape[1]!=x.shape[1] or theta.shape[1]!=len(phi):raise ValueError('Incompatible state dimensions')
    k=len(phi)
    if not 1<=k<=16 or x.size*k>1000000:raise ValueError('Teaching state exceeds its dense size cap')
    for a in (theta,phi):
        if not np.isfinite(a).all() or (a<0).any() or not np.allclose(a.sum(1),1,rtol=0,atol=1e-12):raise ValueError('State rows must be probability distributions')
    return x,theta,phi


def expectation(x,theta,phi):
    x,theta,phi=state(x,theta,phi);joint=theta[:,:,None]*phi[None,:,:];p=joint.sum(1)
    if ((p==0)&(x>0)).any():raise ValueError('An observed word has zero model probability')
    q=np.divide(joint,p[:,None,:],out=np.zeros_like(joint),where=p[:,None,:]>0)
    observed=x>0;ll=float(np.sum(x[observed]*np.log(p[observed])))
    return q,ll


def step(x,theta,phi,freeze_phi=False):
    x,theta,phi=state(x,theta,phi);q,before=expectation(x,theta,phi);expected=x[:,None,:]*q
    doc=expected.sum(2);n=doc.sum(1,keepdims=True)
    new_theta=np.divide(doc,n,out=theta.copy(),where=n>0)
    new_phi=phi.copy()
    if not freeze_phi:
        word=expected.sum(0);total=word.sum(1,keepdims=True);new_phi=np.divide(word,total,out=phi.copy(),where=total>0)
    _,after=expectation(x,new_theta,new_phi)
    if after<before-1e-10*(1+abs(before)):raise ArithmeticError('EM likelihood decreased beyond rounding tolerance')
    return new_theta,new_phi,after


def iterations(value):
    if isinstance(value,bool) or not isinstance(value,(int,np.integer)) or not 0<=value<=2000:raise ValueError('Use 0..2000 iterations')
    return int(value)


def fit(x,k=2,steps=80,seed=7):
    x=counts(x);steps=iterations(steps)
    if isinstance(k,bool) or not isinstance(k,(int,np.integer)) or not 1<=k<=16 or x.size*k>1000000:raise ValueError('Invalid topic count or dense size')
    if x.sum()==0:raise ValueError('Training corpus must contain a word')
    rng=np.random.default_rng(seed);theta=rng.random((len(x),k))+.1;theta/=theta.sum(1,keepdims=True)
    phi=rng.random((k,x.shape[1]))+.1;phi/=phi.sum(1,keepdims=True);trace=[expectation(x,theta,phi)[1]]
    for _ in range(steps):theta,phi,ll=step(x,theta,phi);trace.append(ll)
    return {'theta':theta,'phi':phi,'log_likelihood':trace}


def fold_in(x,phi,steps=80):
    x=counts(x);phi=np.asarray(phi,dtype=float)
    if phi.ndim!=2 or len(phi)<1:raise ValueError('Supply a topic-word matrix')
    theta=np.full((len(x),len(phi)),1/len(phi));trace=[expectation(x,theta,phi)[1]]
    for _ in range(iterations(steps)):theta,_,ll=step(x,theta,phi,True);trace.append(ll)
    return {'theta':theta,'log_likelihood':trace}


def vocabulary(documents):
    if not documents or any(not isinstance(doc,list) or any(not isinstance(w,str) or not w for w in doc) for doc in documents):raise ValueError('Supply lists of nonempty token strings')
    vocab=sorted({w for doc in documents for w in doc})
    if not 1<=len(vocab)<=256:raise ValueError('Training vocabulary must have 1..256 words')
    return vocab


def vectorize(documents,vocab):
    if len(set(vocab))!=len(vocab) or not vocab or len(vocab)>256 or any(not isinstance(w,str) or not w for w in vocab):raise ValueError('Invalid vocabulary')
    if not documents or len(documents)>128:raise ValueError('Use1..128 documents')
    index={w:i for i,w in enumerate(vocab)};x=np.zeros((len(documents),len(vocab)));ignored=[]
    for d,doc in enumerate(documents):
        if not isinstance(doc,list) or any(not isinstance(w,str) or not w for w in doc):raise ValueError('Supply token lists')
        ignored.append([w for w in doc if w not in index])
        for word in doc:
            if word in index:x[d,index[word]]+=1
    return counts(x),ignored


def score(x,theta,phi):
    x=counts(x);_,ll=expectation(x,theta,phi);n=int(x.sum())
    lp=-ll/n if n else None;status='empty_target' if lp is None else ('overflow' if lp>math.log(sys.float_info.max) else 'finite')
    return {'tokens':n,'log_likelihood':ll,'log_perplexity':lp,'perplexity':math.exp(lp) if status=='finite' else None,'perplexity_status':status,'scope':'Conditional known-vocabulary token score; no bag multinomial coefficient; empty target has no perplexity.'}


def demo():
    train=[s.split() for s in ['apple apple pear orchard','pear orchard apple','rocket orbit planet rocket','planet orbit rocket','apple rocket pear planet','orchard apple orbit rocket']]
    observed=[s.split() for s in ['apple pear','orbit rocket','apple orbit','unseen']]
    target=[s.split() for s in ['orchard','planet','pear planet','rocket']]
    vocab=vocabulary(train);x,_=vectorize(train,vocab);model=fit(x);seen,ignored=vectorize(observed,vocab);held,_=vectorize(target,vocab);folded=fold_in(seen,model['phi'])
    base=x.sum(0,keepdims=True)/x.sum();hand_x=np.array([[2,1]]);hand_theta=np.array([[.6,.4]]);hand_phi=np.array([[.8,.2],[.1,.9]])
    q,before=expectation(hand_x,hand_theta,hand_phi);new_theta,new_phi,after=step(hand_x,hand_theta,hand_phi)
    return {'training':train,'observed':observed,'targets':target,'vocabulary':vocab,'theta':model['theta'].tolist(),'phi':model['phi'].tolist(),'log_likelihood':model['log_likelihood'],'folded_theta':folded['theta'].tolist(),'ignored_observed':ignored,'held_out':score(held,folded['theta'],model['phi']),'unigram':score(held,np.ones((len(held),1)),base),'hand':{'responsibilities':q.tolist(),'theta_after':new_theta.tolist(),'phi_after':new_phi.tolist(),'before':before,'after':after},'scope':'Invented tokenized documents, ordinary dense maximum-likelihood pLSA with fixed iterations; not TEM, real-corpus performance, human interpretability or a discovered true topic count.'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))

The training log likelihood changes from −41.746873 to −29.021147. On five separate target tokens, pLSA perplexity is 5.017873 and the fitted corpus-unigram baseline is 6.621123. These are computations on this constructed split, not estimates of performance on real documents. The target words never participate in fold-in. Changing them changes the reported evaluation, not the learned factors or observed-document mixtures.

The code limits document, vocabulary and topic dimensions and total counts. These caps keep the dense example inspectable; they do not provide a general memory guarantee for arbitrary input construction. Positive random initialization, a fixed seed and a fixed iteration count make this example reproducible, but do not establish that all useful modes or all local optima have been explored.

Prediction and interpretation need different evidence

Two runs can permute topic indices and describe the same word probabilities. They can also reach genuinely different factorizations. Compare distributions and representative documents, not just whether “topic 0” keeps the same label. A document’s inferred mixture depends on what counts as a document: splitting a long report into paragraphs gives the model more separately fitted mixtures.

Inspect boilerplate, near duplicates, rare tokens and domain-specific names before interpreting the top words. Retuning preprocessing or K after repeatedly checking the final test set leaks information into the evaluation. Use training data for vocabulary and factors, validation data for choices, and a held-out test for the final stated question. Compare a unigram or other simple baseline under the same vocabulary and target policy.

A predictive score does not directly ask whether a reader understands the topic. Chang and colleagues construct a word-intrusion task by mixing a topic’s high-probability words with a word unlikely under that topic, and a topic-intrusion task by mixing plausible document topics with an unlikely one. Those tasks evaluate human judgments about different parts of the representation. They are not reproduced by declaring the model’s own rankings correct. Task definitions, §§3.1–3.2

The implementation fits ordinary pLSA, not LDA, a contextual embedding model or a complete retrieval system. LSA, NMF and probabilistic models make different constraints; a topic mixture is also different from a supervised category prediction. Choose the representation and evaluation to match the use, and retain uncertainty when short or mixed documents admit several readings.

Test the meaning of each number

  1. A document has theta [0.6,0.4] and the first-word probabilities under the two topics are 0.8 and 0.1. What is its probability of that word, and what is the first topic’s responsibility?

Answer: The word probability is 0.6 × 0.8 + 0.4 × 0.1 = 0.52. Conditional on observing it, topic 0 receives 0.48/0.52 = 12/13. The mixture weight 0.6 and posterior responsibility 12/13 answer different questions.

  1. For the hand document [2,1], derive the next document mixture. Why not average the two distinct word responsibilities equally?

Answer: Topic 0’s expected token count is 2 × 12/13 + 1/4 = 109/52. Divide by three tokens to get 109/156; the other weight is 47/156. Averaging distinct vocabulary entries would ignore the repeated first word and optimize a different dataset.

  1. Increase K and try three fixed seeds. Training likelihood improves but held-out perplexity becomes worse. Has the EM implementation necessarily failed?

Answer: No. EM improves its observed training objective, while extra components can fit training-specific structure. Check the same split, vocabulary, target counts and observed-only fold-in, then compare validation results across seeds. The final test must not become the parameter-selection set. Numerical monotonicity and generalization are separate checks.

  1. You re-fit theta using both observed and target fragments, then report the target perplexity. Explain the error and repair it. What should happen if all observed words are unknown?

Answer: The target influences the document representation used to predict itself, so the claimed held-out task has changed. Keep phi frozen and infer theta only from the observed fragment. Under this program’s declared policy, all-unknown observations produce an all-zero count row and retain uniform theta; their ignored tokens must remain visible in the report. A production system could instead use a learned prior or an abstention policy, evaluated separately.

Read the model and the evaluation together

Start with Hofmann’s aspect model and standard EM equations, then its fixed-factor fold-in description. Keep the paper’s tempered training and retrieval experiments separate from this ordinary-EM baseline. Read Blei, Ng and Jordan’s LDA construction to see what a document-mixture prior changes. Finally, use Chang and colleagues’ task definitions to ask what evidence would support a semantic interpretation. The next LDA topic develops the probabilistic prior and a different inference algorithm.

Make a prediction, then check

An unseen document is encoded with pLSA fold-in. Which parameters should remain fixed?

Choose one answer

Learning objectives

  • Distinguish a document mixture from a cluster label and a topic name.
  • Derive ordinary pLSA EM from expected token counts.
  • Infer unseen-document proportions while holding word factors fixed.
  • Separate predictive fit, interpretability and evaluation leakage.

Prerequisites & connections

Explore related knowledge →

References

  1. Probabilistic Latent Semantic Indexing
    Thomas Hofmann · 1999
  2. Latent Dirichlet Allocation
    David M. Blei, Andrew Y. Ng, Michael I. Jordan · 2003
  3. Reading Tea Leaves: How Humans Interpret Topic Models
    Jonathan Chang, Jordan Boyd-Graber, Sean Gerrish, Chong Wang, David M. Blei · 2009

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-12 · Single AI author checked seven paired equations and four explained exercises against scoped Hofmann aspect/EM/fold-in, Blei LDA construction and named-author Chang intrusion tasks. Complete ordinary pLSA differs from source TEM. Independent assignment enumeration,12/13 responsibility,109/156 updated mixture, expected counts, empty/unused rows, row permutations, KL identity, zero probability and perplexity overflow checked. Five synthetic target tokens are separate from observed fold-in; perplexity5.017873 vs6.621123 is not a corpus or human-interpretability result.

  • Single AI author checked seven paired equations and four explained exercises against scoped Hofmann aspect/EM/fold-in, Blei LDA construction and named-author Chang intrusion tasks. Complete ordinary pLSA differs from source TEM. Independent assignment enumeration,12/13 responsibility,109/156 updated mixture, expected counts, empty/unused rows, row permutations, KL identity, zero probability and perplexity overflow checked. Five synthetic target tokens are separate from observed fold-in; perplexity5.017873 vs6.621123 is not a corpus or human-interpretability result.
  • Four computed SVGs bind exact bilingual MDX. Eight numeric/encoding checks and12 isolated language/width cases with four fallback fonts passed; four actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.

Source locations checked:

  • Probabilistic Latent Semantic Indexing · Original SIGIR paper mirrored by a university course. Sections2/3, layout63–151 and visually inspected printed51: aspect parameterizations and standard EM. Section4.6 layout329–364 and500–510: fixed-factor query fold-in. Full TEM policy and retrieval experiments not reproduced.
  • Latent Dirichlet Allocation · Scoped introduction and section3, local layout164–247: exchangeability, document topic mixtures, initially fixed topic-word matrix, length conditioning and joint/marginal model. Full variational updates and experiments not reproduced.
  • Reading Tea Leaves: How Humans Interpret Topic Models · Named-author version, header1–17 and layout174–231 sections3.1/3.2: word and topic intrusion task construction. Earlier anonymous filename was not used for attribution. Full human experimental results not independently checked or reproduced.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.