W8: Topic Models and Their Variants
W7 asked “where does a speaker stand on a dimension?” W8 asks a different question: “what do political actors choose to talk about?” — that is, issue attention. The tools are topic models: LDA and STM.
From “position” to “attention”
| Research task | Political science question |
|---|---|
| W7: text scaling | Where does a speaker stand on a predefined dimension? |
| W8: issue attention | What do political actors choose to discuss? |
This week’s guiding question: how do political scientists turn large volumes of text into evidence about political behavior and political communication? The class first reads five political science studies (campaign promises, news framing, policy diffusion, social media), then unpacks how the model works, and finally applies the model to political speeches in R.
W7 is like finding each MP’s position on a “support/oppose the budget” ruler; W8 is like making a “time-allocation sheet” for each speech: 70% of this speech is about Europe, 20% about the economy, 10% about other things. The focus is no longer position but how attention is allocated.
What you should be able to explain this week
The “R workflow” table on slide 69 divides the class into four stages, each with a “What you should explain” line. Treat these as this week’s learning goals:
- Read and prepare (R01a–R01c): define what counts as a document, and explain what the cleaning steps changed.
- Fit and read LDA (R02a–R02b): read one speech’s full topic mixture.
- Check labels (R03a–R03b, E02): support a topic label with original text, and identify one possible counterexample.
- Compare with STM (R05a–R05e, E05): interpret the direction, size, and uncertainty of a difference in percentage points.
Slide 69’s reminder: on the same texts, LDA uses only word counts; STM adds document metadata (party, period). After finishing a chapter, come back and tick the goals you feel you can now meet (stored only in this browser):
Concept map: from speeches to evidence
Click a box in the diagram to show its explanation below. The flow is compiled from slide 42, “Applying topic models to political speeches,” and the R workflow on slide 69.
Static summary: question (which issues receive attention?) → document (one full speech) → word counts (tokenize, clean, DFM) → topic model (LDA; STM adds party and period) → research use (interpret, compare, check K), and every step must go back to the original texts for validation.
This week’s five research cases
| Case | Texts | How the model is used | In these notes |
|---|---|---|---|
| 1 · Catalinac (2016) | Japanese candidate election manifestos | Measure campaign promises (pork vs. policy) | 03 |
| 2 · Gilardi, Shipan & Wüest (2021) | US newspaper paragraphs | Study policy diffusion and framing | 03 |
| 3 · Barberá et al. (2019) | Tweets | Measure daily issue attention | 03 |
| 4 · Jiang, Xia & Zhang (2024) | Hong Kong news | Develop hypotheses, then test them separately | 04 |
| 5 · Roberts et al. (2014) | Open-ended survey responses | Compare priority issues with human coding | 04 |
Four questions for reading each case
Slide 5 gives a framework for reading cases, and the instructor adds: use the same four questions when you design your own text study. Click each step for an explanation:
- Political question: what puzzle does the study want to explain?
- Texts and document unit: what counts as one document? Whose language is it?
- Model contribution: what does the topic model discover or measure?
- Evidence and limits: which comparison, dynamic model, or experiment supports the claim?
This week’s practice data
- Source: Essex Summer School 2026, Day 7 (Martijn Schoonvelde’s ESS course).
- Eligible raw texts: 3,897 non-empty speeches (source terms ≥ 80).
- Teaching sample: 719 complete speeches, at most 30 per “party × period”; dates 1979-05-15 to 2025-12-17.
- Two parties: Conservative and Labour; periods are the 47th–58th Parliaments (12 in total).
- File:
W8/analysis/ess_lab/sample_raw.rds(plus the instructor’s pre-fittedlda3/6/9.rdsandstm5/6.rds).
Slide 68 note: sampling seed 20261028; the sample is a “near-balanced party × period sample” and does not represent the word-count shares of parliamentary speech.
What would happen if all speeches by each party were merged into “one document”?
Suggested reasoning (supplement)
You would be left with only 2 documents. The model could not estimate a mixture for “each speech,” nor see differences between speeches within the same party; the topics would be dominated by the vocabulary differences between the two parties (topics become “parties”) rather than “issues.” The document unit determines which questions you can answer: Barberá et al. deliberately aggregated tweets into “day × party × chamber” documents precisely because daily attention was what they wanted.
We actually checked the sample structure (R table(party_family, period)): across the 12 Parliaments, every party × period cell has 30 speeches, except Conservative in the 48th Parliament (1983–1987) with 29, giving 359 Conservative and 360 Labour speeches in total. Chapter 05 uses this “near balance” to explain why the raw and adjusted differences are almost identical.
How to use these notes
- Reading the chapters on the left in order works best; if you have never met topic models, read Chapters 01 and 02 first (supplement, not from the lecture), then move on to the cases and R.
- Badges marked are clickable: the slide panel on the right (or the button at the bottom right) opens that slide, and it follows along as you scroll.
- The blue “interactive lab” boxes can be operated directly. The labs in Chapters 05, 06, and 08–11 use this week’s real data: the full texts of the 719 speeches, plus θ and topic–word probabilities from the instructor’s saved LDA (
lda6.rds) and the re-fitted STM, exported from R and embedded in this file — no network needed. - The generative simulator and Gibbs sampler in Chapters 01–02 and the “reweighting” in Chapter 05 are toy demos (supplement) for building intuition; their numbers are not course results.
- Each chapter ends with a “Self-check”; Chapter 14 has a final review (you can redo only the questions you got wrong) and a research-design plan builder.
- Progress and notes are stored only in this browser’s localStorage; Chapter 14 can clear them with one click.
W8/README.md)Deadlines and announcements (per README, read on 2026-11-06)
- EPSS 2027 (Copenhagen) call for papers: 2026-11-13 23:59 CET (Taipei time 11-14 06:59).
- 11-20 (W11): no class (university sports day).
- TASPAA 22nd Annual Conference: abstract and panel proposal deadline 2026-12-01.
- Midterm research design report: 2026-12-04 (W13). The “research design plan” builder in Chapter 14 is a warm-up for it (slide 90).
- Next week’s topics (slide 91): readability, similarity, and word embeddings.
The IPSA World Congress abstract deadline passed on 2026-11-04. README.md is authoritative for dates; if in doubt, ask the instructor or the TA Matt Lee via the office hour link in the README.
From zero: what does a topic model do?
This chapter is a Supplement (not from the lecture): plain language and two simulators you can play with, to make sense of the terms “topic,” “topic mixture,” and “α.” Term usage follows the slides, with slide numbers marked.
An analogy: the buffet plate
Supplement (not from the lecture): imagine each speech is a buffet plate, and the restaurant has only 6 food stations (6 topics). Each station has its typical dishes (words): the “Europe station” is mostly european, council, community; the “economy station” is mostly unemployment, economy, budget.
- Each plate (speech) can take food from several stations — that is the “topic mixture”: a speech is 87% from the Europe station, 7% from the government station…
- The topic model cannot see the “station signs.” It only sees which dishes are on each plate, and then works backwards: which dishes tend to appear together (= a topic), and how much each plate took from each station (= the mixture proportions).
- The sign (topic name) is something you write yourself after looking at the dishes and the actual plates, which is why it is called a “provisional label.”
A fitted model stores two tables
Answers: which words characterize each topic? Each topic is a “probability distribution over words”; the probabilities of all words sum to 1. terms(lda_6, 10) prints the 10 highest-probability words of each topic. In a seededlda object it is called $phi; in an stm object it is stored on the log scale in $beta$logbeta.
Answers: which topics appear in each speech? One row per speech, one column per topic, and each row sums to 1. This week’s lda_6$theta is 719 × 6.
Slide 46’s summary: one speech can mix several topics; each topic favors different words. LDA estimates both tables simultaneously from word patterns across the whole corpus.
Interactive: generative story simulator (supplement)
LDA is a “generative model”: it assumes each document was written like this (the setup of Blei, Ng & Jordan 2003, simplified here for teaching):
- First, draw a set of topic proportions θ for the document (e.g., 60% Europe, 30% economy, 10% security). α controls whether these proportions are “concentrated” or “even.”
- For each word: first roll a die according to θ to decide “which topic this word belongs to,” then draw a word from that topic’s word distribution.
Estimating the model means running this process in reverse: seeing only the words, infer θ and the topic–word distributions. The simulator below lets you run it forwards once. The words of the three topics are a toy setup (common words from this week’s real LDA topics, but with made-up probabilities).
Adjust α and the document length, then press “Write a document.” Each word’s color = the topic it was drawn from. A real model cannot see the colors, only the words.
Try it: drag α to the minimum (0.05) and click several times, then drag it to the maximum (2.0) and click several times. What is the difference?
When α is small, θ is almost entirely concentrated on one topic (documents are “focused”); when α is large, the three topic proportions tend to be even (documents are “mixed”). This week’s R02a uses alpha = .5. Slide 55 lists “Alpha and initialization” as one of the researcher’s modeling choices: are the mixtures and results stable under reasonable settings?
Interactive: α triangle (supplement)
With only 3 topics, every θ can be drawn as a point in a triangle: the closer to a corner, the more concentrated on that topic; the exact center = 1/3 each. Below, 400 θs are drawn at a time.
Ten terms you must know
| Term | Meaning | This week’s example |
|---|---|---|
| Document | The model’s unit of analysis. Change the unit and you change the questions you can answer. | One full speech (719 in total) |
| Bag of words | Only counts how often words appear, ignoring order. | DFM 719 × 2,831 |
| Topic | A “probability distribution over words”; not a predefined category. | T1: european, council, community… |
| Topic mixture θ | A document’s proportions across topics, summing to 1. | ess_hoc_00004: T1 = .874 |
| K | The number of topics, specified by the researcher; change K and issues split or merge. | K = 6 in class |
| α / β priors | α affects how concentrated document mixtures are; β affects how concentrated topic–word distributions are. | alpha = .5, beta = .1 |
| Dominant topic | Keeps only the number of the topic with the largest proportion; a kind of summary. | max.col() in R02b |
| Provisional label | A name the researcher gives after reading the words and the texts; it must be validated further. | “European Council negotiations” |
| Topic prevalence | How much a topic is discussed; STM lets it vary with metadata. | prevalence = ~ party_family + period |
| Perplexity | A model-fit score; lower is better, but a lower score by itself cannot decide K. | LDA K=6: 1062.5 |
Self-check
lda_6$theta (one speech) represent?$phi.LDA: how the computer “guesses” topics
Chapter 01 “wrote” documents forwards; this chapter shows how LDA “infers backwards”: seeing only the words, it simultaneously estimates the topic–word distributions and each document’s mixture. The core algorithm is shown with a toy version of Gibbs sampling (supplement, not from the lecture).
Intuition for inferring backwards (supplement)
At the start, each word is randomly assigned to a topic. Then words are reassigned one at a time, each time asking two questions:
If most other words in the document are assigned to topic k, this word is also more likely to be k. (Corresponds to θ, influenced by α)
If council is often assigned to k in other documents, it is also more likely to be k here. (Corresponds to φ, influenced by β)
Multiplying the two gives the probability of re-drawing the topic (the conditional probability in collapsed Gibbs sampling):
P(z = k | all other assignments) ∝ (nd,k + α) × (nk,w + β) / (nk + V·β) nd,k: number of words in document d (excluding this one) assigned to k nk,w: number of times word w is assigned to k across the corpus nk: total words in topic k; V: vocabulary size
After many rounds (R02a sets max_iter = 500), “words that often appear together” get pulled into the same topic. set.seed() lets the same machine reproduce the sampling path, but slide 75 cautions that seeds and a finite number of iterations support reproducibility, not automatic validity.
Interactive: watch Gibbs sampling “cluster” words (supplement)
10 toy “speeches” (words taken from common words of this week’s real topics), K topics. Press “One sweep” to see how each word’s color (its current topic assignment) changes; on the right are the most common words currently in each topic.
Try it: with the same K = 3, run 50 sweeps each with three different seeds. Are the topic “numbers” the same? Is the topic “content” the same?
The numbers often change (this run’s topic 1 might be the last run’s topic 3), but the content is usually similar. This is the point of slides 52 and 86: topic numbers belong only to their own fit; when comparing models, match the words, not the numbers. That is also why this week’s STM topic 4 and LDA topic 4 are not the same issue.
Try it: change K to 2 or 4. What happens to the “Europe” and “security” words?
With a small K, related issues (e.g., European affairs and international security) may merge into one topic; with a large K, one issue may split, or a topic propped up by only one or two documents may appear. Slide 55: “Which issues split or merge when the number of topics changes?” Chapter 11 looks at the same phenomenon with the instructor’s saved real K = 3/6/9 models.
Modeling choices shape the topics before they are named
| Modeling choice | Question the researcher must ask | This week’s counterpart (supplement) |
|---|---|---|
| Bag of words | Does word order carry information we need? | “not good” is split into not, good |
| Common set of topics | Are language and topic meaning comparable across the corpus? | Does “european” mean the same in 1979 and 2025? |
| Document boundaries | Does one speech provide enough context to support a mixture? | Very short interjections have only a few words |
| Vocabulary selection | Which distinctions survive cleaning and trimming? | Removing “minister”; trimming max_docfreq = .75 |
| K | Which issues split or merge when the number of topics changes? | K = 3/6/9 (R04a) |
| Alpha and initialization | Are mixtures and results stable under reasonable settings? | alpha = .5, seed 20260710 |
Slide 55’s conclusion: “These choices shape the topics before researchers name or compare them.”
Full mixture vs. dominant topic
ess_hoc_00004 (Thatcher, 1979-06-26): T1 .874, T2 .067, T3 .012, T4 .002, T5 .012, T6 .032. At a glance, it is almost entirely about T1.
ess_hoc_05895 (Corbyn, 2020-03-25): the largest is only T4 .223, with the rest at .098–.205; it is the most dispersed of all 719 speeches.
Both would be collapsed into “one topic number”: 00004 → T1, 05895 → T4. But T4 is only 22% of 05895, so calling it “an economy speech” would be misleading. max.col(..., ties.method = "first") takes the first in case of ties — an easily reproducible but less informative rule.
Self-check
Cases 1–3: campaign promises, policy framing, daily attention
Three studies use the same family of tools to answer very different political questions. Each case is unpacked with the four questions from slide 5: political question, document unit, model contribution, evidence and limits.
Case 1 · Catalinac (2016): from pork to policy
Puzzle: Japan’s 1994 electoral reform reduced competition among candidates from the same party, yet later research still described campaigns as pork-oriented. Question: did candidates shift from “benefits for narrow groups” toward “broader public policy”?
Evidence: 7,497 candidate election manifestos across eight elections, 1986–2009.
- Discover topics: LDA finds 69 recurring topics in the 7,497 manifestos.
- Read and check: for each topic, read the 15 top words and 10 representative manifestos.
- Define the concept: use “who benefits” to sort topics into 14 pork and 52 policy topics.
- Measure candidates: for each manifesto, sum the proportions of topics in the same category.
- Test the puzzle: compare these proportions across elections and levels of same-party competition.
| Figure | How the slides read it |
|---|---|
| Pork and policy across elections | First look at the red circle: broad policy promises began to rise before the new system was first used in 1996; then look at the lower line: local-benefit promises fall and policy promises rise. |
| Same-party competition and campaign emphasis | Left panel: the more same-party rivals, the more local-benefit promises; right panel: the more same-party rivals, the fewer broad policy promises. |
| Opposition party comparison | Opposition parties were already making many policy promises before 1996 and stayed high; their local-benefit promises stayed low throughout. This is an observational comparison and does not identify a causal effect. |
Supplement: these notes only obtained Catalinac’s publicly available online appendix (the journal article is paywalled). The appendix states that 20 to 200 topics were tried, and 69 was chosen because it was “one of the lowest settings that produced sufficiently fine-grained topics”; after removing 3 credit-claiming topics, the remaining 66 were classified by “claimed beneficiary” (Appendix pp. 2, 11). This matches the slides’ 14 + 52 = 66. See Chapter 12 for details.
Case 2 · Gilardi, Shipan & Wüest (2021): diffusion happens before “adoption”
Puzzle: policy diffusion research usually observes “adoption” only after debate has begun. Question: do other states’ earlier smoking bans change how a state’s newspapers define the issue?
Evidence: 52,675 paragraphs from newspapers in 49 states, 1996–2013.
- Collect coverage: search newspapers in 49 states.
- Keep relevant paragraphs: train an SVM relevance filter with crowd-sourced annotations.
- Discover frames: fit a 12-topic STM to the 52,675 paragraphs.
- Measure issue definition: estimate how common each frame is (topic prevalence).
- Study diffusion: link frame prevalence to earlier adoptions in “related states.”
| Result | How the slides read it |
|---|---|
| Practical frames change | Further to the right (more related states have adopted), “restaurant concerns” decline and “enforcement” becomes more prominent. |
| Stable frames | Health barely changes with earlier adoptions; Freedom is also nearly flat. |
| Frame correlations (optional) | With fewer adoptions, the Rules topic has few strong correlations with other frames; with more adoptions, Rules correlates with several practical, value, and political frames, forming a broader frame. |
Why STM rather than LDA? Because the authors want “earlier adoptions” to enter the estimation of topic prevalence directly — exactly the prevalence covariates of STM in Chapter 05. The reading card in Chapter 12 gives the limits the authors state themselves (e.g., they cannot study “frame-to-frame” diffusion).
Case 3 · Barberá et al. (2019): who leads? who follows?
Question: do politicians lead public attention, or follow it?
Texts: tweets by members of Congress, the public, and the media, 2013–2014. Use: compare daily attention to shared issues.
- Define documents: aggregate congressional tweets by “day × party × chamber.”
- Discover shared topics: fit a 100-topic LDA to the aggregated congressional texts.
- Interpret issues: read topic words and merge related political topics.
- Build measures: estimate daily issue attention for politicians, public samples, and the media.
- Analyze time series: compare whose earlier attention predicts another group’s later attention.
A single tweet is too short for the model to estimate a mixture; aggregating tweets into “daily documents” solves the short-text problem and matches the measurement unit the study needs (daily attention). Compare BTM in Chapter 07: another way to handle short texts.
| Figure | How the slides read it |
|---|---|
| Direction one (gray) | When public attention rises, politicians often pay more attention afterwards. |
| Reverse direction and caveat (black) | When politicians’ attention rises, the public may pay more attention afterwards. |
Supplement (from the paper itself): the authors use a VAR to compare “who moves first,” and state explicitly that this is a descriptive analysis — a VAR cannot rule out confounding by unobserved factors (Barberá et al. 2019, p. 884). See Chapter 12 for details.
Interactive: case breakdown cards
Answer in your head first, then click a button to flip the card and compare. Content compiled from slides 6–41.
Self-check
Cases 4–5: theory building, open-ended survey responses
The last two cases show two other uses of topic models: helping to come up with hypotheses and comparing against human coding. The summary table on slide 41 ties them together at the end.
Case 4 · Jiang, Xia & Zhang (2024): using a topic model to “build” theory
Puzzle: existing research emphasizes economic and cultural concerns and says less about shared political values. Question: can shared democratic values reduce support for restrictive immigration policy?
Evidence: the researchers use STM results to develop hypotheses, then test them with a preregistered experiment.
- Discover concerns: STM finds 5 topics in 4,453 news articles.
- Read and label: look at characteristic words and representative articles.
- Compare over time: estimate changes in topic prevalence over 2003–2020.
- Form hypotheses: rising political attention leads to the “shared values” argument.
- Test separately: randomly assign messages in a preregistered experiment.
Reading the figure: news attention to social welfare declines after the mid-2010s (dashed lines are 95% uncertainty); attention to “Hong Kong–mainland tensions” rises, and this pattern leads to the shared-values hypothesis.
STM results are used to develop the hypothesis; the causal message effect is tested by random assignment. The same texts cannot be used both to “come up with” and to “prove” a hypothesis.
These notes did not obtain the full text of this paper (paywalled by the publisher; the SSRN version has a bot check), so the content is based only on the slides.
Case 5 · Roberts et al. (2014): respondents’ own words
- Question: who names war as the nation’s most important problem?
- Document: one ANES open-ended response (most-important-national-problem).
- Model input: a 60-topic STM; covariates are party, education, age, and party × education.
- Output used: the estimated proportion of the “war” topic in each response.
- Check: compare with ANES’s human-coded war category.
The human category codes provide a benchmark for comparison and were not used to train the STM. Left panel (human coding): the higher the education, the larger the party gap; right panel (STM): it also shows a wider party gap, and the Democratic line is roughly flat.
Supplement (from the paper itself): the authors report that the STM and the human coding produce very similar category counts on the ANES, and that the Iraq War topic’s relationship with party and education is also close to the human coding (Roberts et al. 2014, Early View pp. 16–17). This is also one of the methods papers for the R package stm.
Summary table: from topics to political evidence
| Study | Model contribution | Next research step |
|---|---|---|
| Catalinac | Topic shares | Define pork/policy; compare candidates |
| Gilardi et al. | Frame shares | Link frames to prior policy adoptions |
| Barberá et al. | Daily attention | Compare who moves first |
| Jiang et al. | Topic trends | Develop hypotheses; test separately |
| Roberts et al. | Survey topic shares | Compare patterns with human coding |
Interactive: which design can support this claim?
Each sentence is a claim someone might write in a paper. Decide whether it is “supported by the design of this week’s case” or “goes beyond the evidence.” Designed around the caveats on slides 15, 34, 38, and 41 (the items are a supplement).
Self-check
STM: putting party and period into the model
LDA looks only at words. STM (Structural Topic Model) does one more thing: it lets each document’s topic prevalence vary with document information (party, electoral period), and directly estimates these associations and their uncertainty.
What carries over from LDA, and what STM adds
| Kept from the LDA example | Added in the STM example |
|---|---|
| The same 719 complete speeches | Each speech’s party and electoral period |
| The same word-count matrix | A model of “how topic shares vary with this information” |
Question: do Conservative and Labour leaders emphasize the same issues? The focus is topic prevalence: how much a topic is discussed.
LDA: θ_d ~ Dirichlet(α) # every document's mixture comes from the same distribution
STM: θ_d ~ LogisticNormal(X_d γ, Σ) # the "mean" of the mixture varies with document covariates X_d
X_d = [intercept, party_family, period] # prevalence = ~ party_family + periodSupplement: STM uses a logistic-normal rather than a Dirichlet; the advantage is that it can include covariates and also estimate correlations between topics (Gilardi et al. use this to study frame correlations, slides 23–24). This week’s example uses only prevalence covariates and no content covariates: word use within topics is shared by both parties.
Five steps (in-class demonstration, same settings as Lab R05)
| Step | Key points and real numbers |
|---|---|
| 1 · Add metadata | 719 rows of metadata, in the same order as the 719 documents. Thatcher’s ess_hoc_00004: Conservative, 47th Parliament (1979–1983). period is categorical, not a numeric time trend. |
| 2 · Specify the model | stm(..., K = 6, prevalence = ~ party_family + period, seed = 20260710, init.type = "Spectral"); θ is 719 × 6. Metadata enter topic estimation. |
| 3 · Read Topic 4 | Probability: council, community, agreed, united, european; FREX: argentine, commonwealth, nations, agreed, meeting. Provisional label “International affairs?”; the same Thatcher speech is 97.9% this topic. |
| 4 · Raw averages | Mean Topic 4 share: Conservative 13.66%, Labour 7.63%; Labour − Conservative = −6.03 percentage points. Each sampled speech is weighted equally. |
| 5 · Account for period | estimateEffect(1:6 ~ party_family + period, uncertainty = "Global", nsims = 50), then a contrast from 1,000 simulations: Labour − Conservative = −5.99 percentage points, 95% interval [−9.27, −2.78]. This is a conditional association. |
Probability words are the words “most common within this topic,” and common words (such as agreed) show up in many topics; FREX considers both frequency (FRequency) and exclusivity (EXclusivity), picking words that are “common and appear mainly in this topic.” Topic 4’s FREX surfaces argentine and commonwealth, suggesting that this topic contains Falklands War language — so a label cannot rest on the Probability words alone. R05a also prints Lift words: dependencies, falklands, islanders…
Raw difference −6.03, adjusted −5.99: why almost the same?
Slide 53 cautions that raw averages are descriptive and that “speeches come from different electoral periods.” If one party’s speeches happen to be concentrated in certain periods, and those periods involve a lot of talk about international affairs anyway, the raw difference will mix in the effect of period. Adjusting for period means comparing the two parties within the same period.
In this week’s sample, nearly every “party × period” cell has 30 speeches (Chapter 00), so the two parties’ period composition is almost identical, and the results before and after adjustment are about the same. The lab below lets you pretend the sample is unbalanced and see what happens.
Interactive: how can period composition fool you? (real θ + hypothetical weights · supplement)
The lines are the real STM (K = 6) topic shares, averaged within each “party × period” cell (about 30 speeches each). The slider only changes “the share of Labour speeches falling in each period in a hypothetical sample,” to demonstrate composition effects; it is not a course result.
Interactive: raw and adjusted differences for six topics (real data)
Data source: the STM re-fitted locally following R05a–R05d (spectral initialization is deterministic; the maximum difference in θ from the instructor’s saved stm6.rds is 2.6 × 10⁻⁸); the Topic 4 numbers match slides 80–82 exactly. Raw differences are computed directly from θ; adjusted differences and intervals come from estimateEffect + plot(..., method = "difference", omit.plot = TRUE).
Self-check
prevalence = ~ party_family + period allow to vary with party and period?Assumptions, validation, perplexity, and K
A topic model will always produce topics. The real question is whether these topics can serve as the political measure you want. This chapter separates five kinds of validation, explains how to read perplexity, and shows how K affects the way issues are carved up.
Topic validation asks different questions
| Check | Question |
|---|---|
| Held-out word fit | Can the model explain words it has not seen? |
| Words and documents | Does the label describe the content? |
| Coherence and exclusivity | Are the prominent words related to each other, and distinctive? |
| Sensitivity | Does the interpretation hold up under reasonable choices? |
| External prediction | Can topic shares predict outcomes outside the estimation? |
Checking a topic label: STM Topic 4
| Evidence | What to check |
|---|---|
| Probability words | council, community, agreed, united, european |
| FREX words | argentine, commonwealth, nations, agreed, meeting |
| The same Thatcher speech | European Council meeting in Strasbourg; T4 = 97.9% |
| Other speeches | Read high-share texts and possible counterexamples |
One speech supports a label; it must be validated on other texts (Ying, Montgomery & Stewart 2022). The “speech browser” in Chapter 09 can sort all speeches by STM Topic 4, so you can read high-share speeches and borderline cases directly.
Reading perplexity
Slide 58 removed the formula and replaced it with four steps for “how to compare K using perplexity”; the three-word example on slide 60 was replaced with a real K = 3 vs. K = 9 comparison. This chapter has been rewritten to follow the new version, and the old content is kept as a “supplement.”
K: the number of topics. Perplexity: a model fit score.
| Step | What to do (slide 58) |
|---|---|
| 1 · Fit candidate models | Same texts and vocabulary; e.g., LDA K = 3, 6, 9 |
| 2 · Compare scores | Lower perplexity = better fit to the words being scored |
| 3 · Read the topics | Look at topic words and texts: are the labels useful? |
| 4 · Choose a useful K | Look at scores and interpretation together |
Slide 58: Lab R04 uses training words. A lower score alone does not establish the best K.
Supplement (not from the lecture): the perplexity formula (shown on the old slide 58; Lab R04b’s code computes exactly this)
perplexity = exp( − Σd,v xdv log pdv / Σd,v xdv ), pdv = Σk θdk βkv xdv: count of word v in document d; pdv: probability the model gives to word v in document d Steps: take the log probability of each word → average weighted by counts → negate → exponentiate
Intuition: perplexity ≈ “how many equally likely words the model is guessing among, on average.” 1062.5 is roughly like guessing each word from among 1,000-odd candidates. Corresponds to Lab R04b’s exp(-sum(counts * log(probabilities)) / sum(counts)).
Same texts, different K
| Number of topics | Possible topic label (selected topic) | Training perplexity |
|---|---|---|
| K = 3 | Europe-related discussion | 1,195.7 |
| K = 9 | EU agreements / Council meetings | 989.2 |
K = 9 has a lower score and also splits “Europe” into two finer topics; but a lower score by itself cannot decide K. Ask: is the split useful for your research question? Data sources: Lab R04a (topic words) and R04b (actual training perplexity). Re-running R04b locally gives the same numbers (Chapter 11).
Supplement (not from the lecture): a three-word perplexity calculator
This example comes from the old slide 60 (replaced by the instructor at 15:19 on 2026-11-06) and is kept as an intuition exercise.
The held-out text is tax tax jobs. Change the probabilities each model gives to these three words and see how the geometric mean and perplexity change.
Conclusion of the old example: higher word probabilities → lower perplexity; in this example, probabilities ×2 means perplexity ×½ (2.52 vs. 5.04). But topic labels still need to be checked.
Held-out prediction and topic meaning
| Evidence | How to read it |
|---|---|
| Training perplexity ↓ | Better reconstruction of the words used for estimation |
| Held-out prediction | Hide evaluation words before fitting, then score them after fitting |
| STM workflow | make.heldout() → fit → eval.heldout(); compare K with searchK() |
| Topic meaning | Read the texts; check stability and independent evidence |
STM’s held-out log probability: higher is better; perplexity: lower is better. Chang et al. (2009), “Reading Tea Leaves”: predictive fit and human interpretation can run in opposite directions.
Supplement: a minimal held-out example with STM (not run locally; syntax illustration only)
heldout <- make.heldout(stm_input$documents, stm_input$vocab, seed = 20260710) fit_h <- stm(heldout$documents, heldout$vocab, K = 6, prevalence = ~ party_family + period, data = metadata, init.type = "Spectral", verbose = FALSE) eval.heldout(fit_h, heldout$missing)$expected.heldout # higher is better
Function names follow slide 59; arguments follow the stm package documentation. This code was not run for these notes, so no output is provided.
Checking the number of topics K
- LDA, K = 3 / 6 / 9: 1195.7 → 1062.5 → 989.2
- STM, K = 5 / 6: 1053.2 → 1012.6
The larger K is, the lower the training perplexity, almost always (more parameters reconstruct the training words better). So it cannot single out the “best K” by itself.
Read the words and the same texts: do the extra topics add useful distinctions? K = 6 is this course’s teaching resolution. Lower perplexity means better fit, not proof of the best K.
The “K resolution browser” in Chapter 11 uses the instructor’s saved K = 3/6/9 models: click a word (e.g., european) to see how it splits or merges under different K. → Go there
Self-check
Extensions: keyATM, seeded LDA, CTM, DTM, BTM
Beyond LDA and STM, several variants each answer different research questions. The slides present them as “alternative modeling choices” or extensions; the Lab has no keyword-guidance exercise.
Keyword-guided topic models
| Method | Researcher input | Use in W8 |
|---|---|---|
| keyATM (Eshima, Imai & Sasaki, AJPS 2024) | Supply a few keywords for the concepts to be measured; the model simultaneously estimates topics without keywords and document mixtures | Method and package overview: install.packages("keyATM") |
| Seeded LDA | Seed dictionary, pseudo-count weights, residual topics | Independent extension; the runnable ESS Day 7 example uses textmodel_seededlda() |
Both use substantive information to guide topic discovery; the models and outputs differ, and each fit must be interpreted and validated on its own.
Supplement: what does seeded LDA syntax look like? (not from the lecture; not run)
dict <- dictionary(list(
europe = c("european", "council", "community", "summit"),
economy = c("unemployment", "economy", "budget", "inflation")))
seeded <- textmodel_seededlda(topic_dfm, dict, residual = 2)
terms(seeded, 10)The function name follows slide 63; the residual argument follows the seededlda package documentation. The dictionary contents are for illustration. W7’s LSS also uses “seed words,” but it outputs a polarity scale, not a topic mixture.
Correlated topics and change over time
| Model | Research question | Researcher supplies |
|---|---|---|
| Correlated Topic Model (CTM; Blei & Lafferty 2007) | Which issues tend to appear together in the same document? | Word counts and a chosen number of topics |
| Dynamic Topic Model (DTM; Blei & Lafferty 2006) | How does an issue’s language change across periods? | Comparable texts and ordered periods |
Supplement: Mueller & Rauh’s paper happens to note that the vocabulary of the conflict topic changed between 1995 and 2015 (serb, gulf → terrorist, insurg, sunni; postprint pp. 14–16), and its conclusion says that dynamic topic models or STM could be used in future work. This is exactly the problem DTM aims to address.
Short texts: the biterm topic model
Texts: short survey responses, posts, or headlines. BTM (Yan et al. 2013; R package BTM) pools the unordered word pairs (biterms) in short texts across the whole corpus to estimate topics, avoiding the problem of too few words per short text. Extension exercise: compare BTM with LDA and check the labels against the texts.
Contrast: issue classification with labels defined first
| Research step | What Gilardi, Gessler, Kubli & Müller (2022) do |
|---|---|
| Specify labels | Define issue categories before fitting |
| Train and validate | Use separately annotated samples of news and tweets |
| Measure attention | Aggregate the classified texts into daily shares for each group |
| Compare time series | Model how each group’s earlier attention predicts later attention |
| Interpret | Examine differences across actors and issues |
Interactive: which model should my study use?
Answer four questions, and the approaches mentioned in this week’s slides that best fit your needs will be listed below. This is a starting point, not a rule.
More political science applications
Slide 64 lists Wratil et al. (2023), Motolinia (2021), Mueller & Rauh (2018), and Kraft (2024); the further reading on slide 91 tags Wratil et al. (2023) as “government rhetoric and public opinion.” These notes did not read the full texts of these papers (except Mueller & Rauh; see Chapter 12).
Self-check
R00–R01c: packages, loading, cleaning, DFM
Both models share the same count matrix (DFM). This chapter reads in the speeches, tokenizes, cleans, compounds common phrases, and trims the vocabulary, ending with a 719 × 2,831 DFM containing 70,813 tokens in total.
W8/classroom/W8.Rwas run once from start to finish (R CMD BATCH) on the machine used to build these notes (Linux aarch64) with R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, seededlda 1.4.3 (also re-run with 1.4.4, identical results), stm 1.3.8. Every “R console output” block below is real output from that run, with only comment lines removed and long full-text speeches truncated.- The numbers for R00–R01c, R04, and R05 match the slides exactly. The LDA in R02–R03 is the exception: re-running it locally produced a different topic ordering (see Chapter 09), so those steps show two outputs side by side: “loading the instructor’s saved
lda6.rds” and “re-fitting locally.” - Course route (slide 69): before class R00; in class R01 → R02 → R03a–R03b and E02 → R05a–R05e and E05; after class R03c–R04c and the remaining exercises.
R00a–R00b: packages and project folder (before class)
# R00a Load the R packages
required <- c("quanteda", "quanteda.textstats", "seededlda", "stm",
"dplyr", "tidyr", "ggplot2", "jsonlite")
missing <- required[!vapply(required, requireNamespace,
quietly = TRUE, FUN.VALUE = logical(1))]
if (length(missing)) stop("Install these packages first: ",
paste(missing, collapse = ", "))
invisible(lapply(required, function(p)
suppressPackageStartupMessages(library(p, character.only = TRUE))))
options(width = 100, seededlda_threads = 1)
cat("Packages loaded:", paste(required, collapse = ", "), "\n")> required <- c("quanteda", "quanteda.textstats", "seededlda", "stm",
+ "dplyr", "tidyr", "ggplot2", "jsonlite")
> missing <- required[!vapply(required, requireNamespace,
+ quietly = TRUE, FUN.VALUE = logical(1))]
> if (length(missing)) stop("Install these packages first: ",
+ paste(missing, collapse = ", "))
> invisible(lapply(required, function(p)
+ suppressPackageStartupMessages(library(p, character.only = TRUE))))
> options(width = 100, seededlda_threads = 1)
> cat("Packages loaded:", paste(required, collapse = ", "), "\n")
Packages loaded: quanteda, quanteda.textstats, seededlda, stm, dplyr, tidyr, ggplot2, jsonlite # R00b Locate the speech input
lab_file <- function(name) file.path("analysis", "ess_lab", name)
if (!file.exists(lab_file("sample_raw.rds"))) {
stop("Open W8_lab.Rproj, then run R00b again.")
}
party_colors <- c(Conservative = "#003B73", Labour = "#B00020")
cat("W8 speech input found. Ready to build and fit both models.\n")> lab_file <- function(name) file.path("analysis", "ess_lab", name)
> if (!file.exists(lab_file("sample_raw.rds"))) {
+ stop("Open W8_lab.Rproj, then run R00b again.")
+ }
> party_colors <- c(Conservative = "#003B73", Labour = "#B00020")
> cat("W8 speech input found. Ready to build and fit both models.\n")
W8 speech input found. Ready to build and fit both models.- If you see “Install these packages first,” install the listed packages and re-run.
- If a file cannot be found, reopen
W8_lab.Rprojand run R00b again:lab_file()uses the relative pathanalysis/ess_lab/.
R01a: load the file and build the corpus
# R01a Read file
topic_docs <- readRDS(lab_file("sample_raw.rds"))
topic_corpus <- corpus(
topic_docs, text_field = "text", docid_field = "doc_id")
print(topic_docs[1:3,
c("doc_id", "leader", "party_family", "date")])
print(c(speeches = ndoc(topic_corpus)))> topic_docs <- readRDS(lab_file("sample_raw.rds"))
> topic_corpus <- corpus(
+ topic_docs, text_field = "text", docid_field = "doc_id")
> print(topic_docs[1:3,
+ c("doc_id", "leader", "party_family", "date")])
# A tibble: 3 × 4
doc_id leader party_family date
<chr> <chr> <fct> <date>
1 ess_hoc_00002 Margaret Thatcher Conservative 1979-05-15
2 ess_hoc_00211 James Callaghan Labour 1979-06-21
3 ess_hoc_00004 Margaret Thatcher Conservative 1979-06-26
> print(c(speeches = ndoc(topic_corpus)))
speeches
719 Slide 43: here “one document = one complete speech.” The corpus keeps each speech together with its ID and background information; the words have not yet been split or counted.
R01b: tokenizing and cleaning
# R01b Split and clean the words
id <- "ess_hoc_00004"
raw_tokens <- tokens(topic_corpus[id], what = "word")
parliamentary_stopwords <- c("hon", "member", "right", "friend", "sir",
"gentleman", "lady", "house", "commons", "speaker", "minister",
"secretary", "asked", "question", "mr", "mrs", "ms", "â", "ã")
clean_tokens <- tokens(topic_corpus, remove_punct = TRUE,
remove_symbols = TRUE, remove_numbers = TRUE, remove_url = TRUE,
remove_separators = TRUE, split_hyphens = FALSE) |>
tokens_tolower() |> tokens_remove(stopwords("en")) |>
tokens_remove(parliamentary_stopwords)
print(raw_tokens[[id]][1:21])
print(clean_tokens[[id]][1:8])> id <- "ess_hoc_00004"
> raw_tokens <- tokens(topic_corpus[id], what = "word")
> parliamentary_stopwords <- c("hon", "member", "right", "friend", "sir",
+ "gentleman", "lady", "house", "commons", "speaker", "minister",
+ "secretary", "asked", "question", "mr", "mrs", "ms", "â", "ã")
> clean_tokens <- tokens(topic_corpus, remove_punct = TRUE,
+ remove_symbols = TRUE, remove_numbers = TRUE, remove_url = TRUE,
+ remove_separators = TRUE, split_hyphens = FALSE) |>
+ tokens_tolower() |> tokens_remove(stopwords("en")) |>
+ tokens_remove(parliamentary_stopwords)
> print(raw_tokens[[id]][1:21])
[1] "With" "permission" "," "Mr" "." "Speaker" "I"
[8] "should" "like" "to" "make" "a" "statement" "on"
[15] "the" "European" "Council" "Meeting" "at" "Strasbourg" "."
> print(clean_tokens[[id]][1:8])
[1] "permission" "like" "make" "statement" "european" "council" "meeting"
[8] "strasbourg"How to read it: 21 raw tokens (including “,” “.” “Mr” “I” “to” “a” “the”…) shrink to only 8 content words after cleaning. “Every removal rule is a research choice and needs a justification.”
Interactive: cleaning pipeline (real speech ess_hoc_00004)
The starting point is the real raw tokens R produced from Thatcher’s 1979-06-26 speech (– in total). The switches below use JavaScript to apply the same rules as R01b in order (the stopword list is also exported from R); removed words are struck through. The JS is only a reproduction for demonstration; R is authoritative.
R01c: compound phrases, build the DFM, trim
# R01c Turn cleaned words into a DFM collocations <- textstat_collocations( clean_tokens, min_count = 8, size = 2:3) |> arrange(desc(lambda)) model_tokens <- tokens_compound(clean_tokens, phrase(head(collocations$collocation, 30))) topic_dfm <- dfm(model_tokens) |> dfm_trim(min_termfreq = 5, min_docfreq = 2) |> dfm_trim(max_docfreq = .75, docfreq_type = "prop") topic_dfm <- topic_dfm[ntoken(topic_dfm) > 0, ] topic_docs <- topic_docs[match(docnames(topic_dfm), topic_docs$doc_id), ] topic_docs$retained_tokens <- as.numeric(ntoken(topic_dfm)) stopifnot(identical(topic_docs$doc_id, docnames(topic_dfm))) print(c(speeches = ndoc(topic_dfm), features = nfeat(topic_dfm), tokens = sum(ntoken(topic_dfm)))) print(topfeatures(topic_dfm, 6))
> collocations <- textstat_collocations(
+ clean_tokens, min_count = 8, size = 2:3) |> arrange(desc(lambda))
> model_tokens <- tokens_compound(clean_tokens,
+ phrase(head(collocations$collocation, 30)))
> topic_dfm <- dfm(model_tokens) |>
+ dfm_trim(min_termfreq = 5, min_docfreq = 2) |>
+ dfm_trim(max_docfreq = .75, docfreq_type = "prop")
> topic_dfm <- topic_dfm[ntoken(topic_dfm) > 0, ]
> topic_docs <- topic_docs[match(docnames(topic_dfm), topic_docs$doc_id), ]
> topic_docs$retained_tokens <- as.numeric(ntoken(topic_dfm))
> stopifnot(identical(topic_docs$doc_id, docnames(topic_dfm)))
> print(c(speeches = ndoc(topic_dfm), features = nfeat(topic_dfm),
+ tokens = sum(ntoken(topic_dfm))))
speeches features tokens
719 2831 70813
> print(topfeatures(topic_dfm, 6))
prime government people can now country
992 728 590 490 382 354 - 719 speeches, 2,831 features, 70,813 retained tokens. Rows are speeches, columns are words or compounded phrases, cells are counts. LDA and STM both use these same counts.
- Most frequent retained words: prime 992, government 728, people 590, can 490, now 382, country 354. Note that many instances of
primeare leftovers of “Prime Minister” (minister was removed) — a side effect of the cleaning choices.
See the 30 collocations actually compounded (real output)
Exported from R: collocation, count, and λ from head(collocations, 30).
Interactive: how many words do the trimming thresholds remove? (real counts)
The DFM before trimming (after compounding) has – features. Drag the thresholds to see how many features and tokens are kept. The defaults = the R01c settings and should give 2,831 features and 70,813 tokens.
R run checklist
Self-check
hon, member, and friend separately?dfm_trim(max_docfreq = .75, docfreq_type = "prop") do?stopifnot(identical(topic_docs$doc_id, docnames(topic_dfm))) in R01c protect?R02a–R03b: fit LDA, read full mixtures, return to the texts (E02)
Fit a 6-topic LDA, read the topic words and each speech’s full mixture, then pick two speeches and go back to the texts to write provisional topic labels and look for counterexamples.
- Re-running R02a unchanged on Linux aarch64, the topic contents are broadly the same but the numbering and proportions differ: e.g., the European issue becomes topic3, with topic3 = 0.819 for ess_hoc_00004; the dominant-topic counts are 82/71/77/121/177/191, not the slides’ 91/80/193/143/145/67.
- Causes ruled out: the input data are identical (the DFM matches the
$datastored in the instructor’slda6.rdscell by cell, with the same row and column order); the package version is not the cause either (re-running with seededlda 1.4.3, the version used when the instructor saved the file, gives the same result as 1.4.4). - Suspected cause (unconfirmed): the random numbers in Gibbs sampling produce different sequences on different operating systems / C++ standard libraries. Running it on a Mac will very likely match the slides.
- What these notes do: R02a–R03d use
readRDS("analysis/ess_lab/lda6.rds")(the K = 6 fit the instructor saved with the same call) as the main output; this version matches every number on slides 75–77 and 84–85. The output from the local re-fit is placed in expandable blocks for comparison. All LDA interactive labs also uselda6.rds.
This is also a concrete instance of the point in Chapter 02: a seed supports reproducibility; it does not guarantee validity, nor that the same numbering is obtained across platforms.
R02a: fit a 6-topic LDA
# R02a Fit a six-topic LDA model set.seed(20260710) lda_6 <- textmodel_lda(topic_dfm, k = 6, alpha = .5, beta = .1, max_iter = 500, auto_iter = FALSE, batch_size = 1, verbose = FALSE) print(terms(lda_6, 10)) print(dim(lda_6$theta))
lda_6 <- readRDS("analysis/ess_lab/lda6.rds"), the instructor's saved fit, matches the slides)> set.seed(20260710)
> lda_6 <- readRDS(lab_file("lda6.rds")) # instructor's saved K=6 fit (same call, seededlda 1.4.3)
> print(terms(lda_6, 10))
topic1 topic2 topic3 topic4 topic5 topic6
[1,] "european" "government" "prime" "government" "people" "united"
[2,] "council" "state" "people" "people" "can" "must"
[3,] "community" "made" "government" "unemployment" "country" "international"
[4,] "countries" "members" "said" "economy" "want" "security"
[5,] "agreed" "service" "can" "year" "support" "nations"
[6,] "economic" "shall" "now" "chancellor" "sure" "now"
[7,] "union" "matter" "us" "per_cent" "well" "government"
[8,] "summit" "report" "country" "budget" "also" "british"
[9,] "agreement" "public" "last" "million" "work" "action"
[10,] "meeting" "way" "health" "years" "many" "forces"
> print(dim(lda_6$theta))
[1] 719 6Comparison: real output of re-fitting textmodel_lda(...) locally (differs from the slides)
textmodel_lda() re-fitted on Linux aarch64, differs from the slides)> set.seed(20260710)
> lda_6 <- textmodel_lda(topic_dfm, k = 6, alpha = .5, beta = .1,
+ max_iter = 500, auto_iter = FALSE, batch_size = 1, verbose = FALSE)
> print(terms(lda_6, 10))
topic1 topic2 topic3 topic4 topic5 topic6
[1,] "government" "united" "european" "people" "prime" "government"
[2,] "state" "security" "council" "can" "can" "people"
[3,] "made" "must" "community" "country" "people" "year"
[4,] "make" "nations" "economic" "one" "said" "labour"
[5,] "public" "first" "agreed" "work" "country" "health"
[6,] "service" "action" "countries" "sure" "now" "per_cent"
[7,] "report" "international" "summit" "today" "government" "budget"
[8,] "members" "forces" "states" "also" "us" "million"
[9,] "must" "world" "new" "many" "deal" "chancellor"
[10,] "debate" "now" "statement" "years" "say" "unemployment"
> print(dim(lda_6$theta))
[1] 719 6| Topic | Top five words (slide 47) | Provisional reading on the slide |
|---|---|---|
| T1 | european, council, community, countries, agreed | European Council negotiations |
| T2 | government, state, made, members, service | Government and public service? |
| T3 | prime, people, government, said, can | General political leadership? |
| T4 | government, people, unemployment, economy, year | Economy and unemployment |
| T5 | people, can, country, want, support | Public appeals and support? |
| T6 | united, must, international, security, nations | International security |
Note the question marks: the instructor put question marks on the labels for T2, T3, and T5 because their words are very generic (government, people, can). Topic words can only suggest a provisional label; the texts decide whether it holds up.
Interactive: name them yourself first, then check (E02 warm-up)
Look at the words and probability bars and write your label (it will be saved), then press “Compare with the slide” and “See the highest-share speeches.” Click a speech to open its text in the speech browser below.
R02b: read the full topic mixture
# R02b Read complete topic mixtures print(round(head(lda_6$theta, 3), 3)) print(range(rowSums(lda_6$theta))) dominant_topic <- max.col(lda_6$theta, ties.method = "first") names(dominant_topic) <- topic_docs$doc_id print(head(dominant_topic, 5)) print(table(dominant_topic))
lda_6 <- readRDS("analysis/ess_lab/lda6.rds"), the instructor's saved fit, matches the slides)> print(round(head(lda_6$theta, 3), 3))
topic1 topic2 topic3 topic4 topic5 topic6
ess_hoc_00002 0.044 0.188 0.049 0.197 0.470 0.053
ess_hoc_00211 0.005 0.490 0.136 0.207 0.116 0.045
ess_hoc_00004 0.874 0.067 0.012 0.002 0.012 0.032
> print(range(rowSums(lda_6$theta)))
[1] 1 1
> dominant_topic <- max.col(lda_6$theta, ties.method = "first")
> names(dominant_topic) <- topic_docs$doc_id
> print(head(dominant_topic, 5))
ess_hoc_00002 ess_hoc_00211 ess_hoc_00004 ess_hoc_00006 ess_hoc_00008
5 2 1 1 2
> print(table(dominant_topic))
dominant_topic
1 2 3 4 5 6
91 80 193 143 145 67 Comparison: R02b output from the local re-fit
textmodel_lda() re-fitted on Linux aarch64, differs from the slides)> print(round(head(lda_6$theta, 3), 3))
topic1 topic2 topic3 topic4 topic5 topic6
ess_hoc_00002 0.266 0.095 0.007 0.396 0.030 0.206
ess_hoc_00211 0.601 0.015 0.005 0.015 0.146 0.217
ess_hoc_00004 0.097 0.052 0.819 0.002 0.027 0.002
> print(range(rowSums(lda_6$theta)))
[1] 1 1
> dominant_topic <- max.col(lda_6$theta, ties.method = "first")
> names(dominant_topic) <- topic_docs$doc_id
> print(head(dominant_topic, 5))
ess_hoc_00002 ess_hoc_00211 ess_hoc_00004 ess_hoc_00006 ess_hoc_00008
4 1 3 3 1
> print(table(dominant_topic))
dominant_topic
1 2 3 4 5 6
82 71 77 121 177 191 Slide 76’s check question: “Which output can answer: Which issues does one speech discuss as a mixture?” The answer is a row of θ.
Interactive: how “mixed” are the 719 speeches really? (real θ)
If every speech were focused, the largest shares would cluster near 1; if speeches are very mixed, they fall around 0.2–0.5. Drag the threshold: for speeches whose largest share is below it, describing them by their “dominant topic” would be distorting.
R03a: pick the most concentrated and most dispersed speeches
# R03a Retrieve concentrated and mixed speeches
theta <- lda_6$theta
high_i <- which.max(theta[, 1])
mixed_i <- which.min(apply(theta, 1, max))
print(topic_docs[c(high_i, mixed_i),
c("doc_id", "leader", "party_family", "date")])
print(round(theta[c(high_i, mixed_i), ], 4))
print(rowSums(theta[c(high_i, mixed_i), , drop = FALSE]))lda_6 <- readRDS("analysis/ess_lab/lda6.rds"), the instructor's saved fit, matches the slides)> theta <- lda_6$theta
> high_i <- which.max(theta[, 1])
> mixed_i <- which.min(apply(theta, 1, max))
> print(topic_docs[c(high_i, mixed_i),
+ c("doc_id", "leader", "party_family", "date")])
# A tibble: 2 × 4
doc_id leader party_family date
<chr> <chr> <fct> <date>
1 ess_hoc_00004 Margaret Thatcher Conservative 1979-06-26
2 ess_hoc_05895 Jeremy Corbyn Labour 2020-03-25
> print(round(theta[c(high_i, mixed_i), ], 4))
topic1 topic2 topic3 topic4 topic5 topic6
ess_hoc_00004 0.8738 0.0668 0.0124 0.0025 0.0124 0.0322
ess_hoc_05895 0.0982 0.1339 0.2054 0.2232 0.2054 0.1339
> print(rowSums(theta[c(high_i, mixed_i), , drop = FALSE]))
ess_hoc_00004 ess_hoc_05895
1 1 Comparison: R03a output from the local re-fit (picks different speeches)
textmodel_lda() re-fitted on Linux aarch64, differs from the slides)> theta <- lda_6$theta
> high_i <- which.max(theta[, 1])
> mixed_i <- which.min(apply(theta, 1, max))
> print(topic_docs[c(high_i, mixed_i),
+ c("doc_id", "leader", "party_family", "date")])
# A tibble: 2 × 4
doc_id leader party_family date
<chr> <chr> <fct> <date>
1 ess_hoc_00941 Margaret Thatcher Conservative 1989-01-10
2 ess_hoc_01433 John Major Conservative 1994-11-16
> print(round(theta[c(high_i, mixed_i), ], 4))
topic1 topic2 topic3 topic4 topic5 topic6
ess_hoc_00941 0.9500 0.0100 0.0100 0.0100 0.0100 0.0100
ess_hoc_01433 0.1562 0.1771 0.0521 0.1562 0.2188 0.2396
> print(rowSums(theta[c(high_i, mixed_i), , drop = FALSE]))
ess_hoc_00941 ess_hoc_01433
1 1 In the local fit, topic1 is “government, state, made…” (not Europe), so which.max(theta[, 1]) picks a Thatcher speech of 1989-01-10 about merger rules. This shows exactly that topic numbers have no fixed meaning: when code hard-codes “topic 1,” first confirm which issue it is.
They were selected based on model results for interpretation. To validate a label, you still need to read other high-share texts and possible counterexamples (slide 57).
R03b: read the texts
# R03b Read the original speech
cat("Document:", topic_docs$doc_id[high_i], "\n")
cat(topic_docs$text[high_i], "\n")
cat("Mixed document:", topic_docs$doc_id[mixed_i], "\n")
cat(topic_docs$text[mixed_i], "\n")lda_6 <- readRDS("analysis/ess_lab/lda6.rds"), the instructor's saved fit, matches the slides)> cat("Document:", topic_docs$doc_id[high_i], "\n")
Document: ess_hoc_00004
> cat(topic_docs$text[high_i], "\n")
With permission, Mr. Speaker I should like to make a statement on the European Council Meeting at Strasbourg. With my noble Friend, the Foreign and Commonwealth Secretary I attended the European Council in Strasbourg at the end of last week. Among the matters we discussed were, first, contributions to the Community budget. I made our dissatisfaction with the results of the present system very plain. The European Coun … [truncated; full output in tad/labs/W8/run_output_savedLDA.txt]
> cat("Mixed document:", topic_docs$doc_id[mixed_i], "\n")
Mixed document: ess_hoc_05895
> cat(topic_docs$text[mixed_i], "\n")
My hon. Friend understands the issue and represents his constituency extremely well. I know that a lot of his constituents are in that situation. We have to have better regulation of the private rented sector, with security of tenure and realistic rent levels. We also have to have the spirit of what was said, which was that there would be protection for people in the future. The danger, as he points out, is the oppos … [truncated; full output in tad/labs/W8/run_output_savedLDA.txt]The full speeches are long, so only the first few hundred words are shown here; both full texts can be read in the speech browser below (IDs: ess_hoc_00004, ess_hoc_05895). Check: find passages that support the label, and also one possible challenge; after reading the relevant passages, see whether the other passages would change your interpretation of the whole speech.
Interactive: speech browser + topic highlighter (719 real speeches)
E02: words and provisional labels (in-class focus)
List the top ten words of the 6-topic LDA. Propose two provisional labels. Support one of them with a document ID and a quotation from the text, and describe a text that might challenge the label.
Suggested approach (supplement; not a model answer)
R code: terms(lda_6, 10); i <- match("ess_hoc_00004", topic_docs$doc_id); round(lda_6$theta[i, ], 3); cat(topic_docs$text[i]).
Support: T1 “European Council negotiations” — ess_hoc_00004 has T1 = .874, and the text opens with “I should like to make a statement on the European Council Meeting at Strasbourg.” (slide 48).
How to find a challenge: in the speech browser, sort by “LDA T1 share” and read further down the speeches with T1 between 0.3 and 0.6, checking whether they discuss international summits other than “Europe” (e.g., G7, Commonwealth). If so, the label may need to be broadened to “international summits and negotiations”; if only Europe, retain it. This is exactly slide 57’s “retain, narrow, broaden or reject.”
Self-check
R05a–R05e: STM and party comparison (E05)
Fit an STM on the same DFM plus party and period, first compute the raw mean difference, then the conditional difference and interval after accounting for period, and finally draw the plot. The numbers from re-running this part locally match the slides exactly.
R05a: fit the STM
# R05a Fit STM with party and period metadata <- data.frame( doc_id = topic_docs$doc_id, party_family = topic_docs$party_family, period = topic_docs$period) design <- model.matrix(~ party_family + period, metadata) stopifnot(qr(design)$rank == ncol(design)) stm_input <- convert(topic_dfm, to = "stm") stm_6 <- stm(stm_input$documents, vocab = stm_input$vocab, K = 6, prevalence = ~ party_family + period, data = metadata, seed = 20260710, init.type = "Spectral", max.em.its = 100, emtol = 1e-4, verbose = FALSE) print(labelTopics(stm_6, topics = 4, n = 5))
> metadata <- data.frame( + doc_id = topic_docs$doc_id, + party_family = topic_docs$party_family, + period = topic_docs$period) > design <- model.matrix(~ party_family + period, metadata) > stopifnot(qr(design)$rank == ncol(design)) > stm_input <- convert(topic_dfm, to = "stm") > stm_6 <- stm(stm_input$documents, vocab = stm_input$vocab, K = 6, + prevalence = ~ party_family + period, data = metadata, + seed = 20260710, init.type = "Spectral", max.em.its = 100, + emtol = 1e-4, verbose = FALSE) > print(labelTopics(stm_6, topics = 4, n = 5)) Topic 4 Top Words: Highest Prob: council, community, agreed, united, european FREX: argentine, commonwealth, nations, agreed, meeting Lift: dependencies, falklands, islanders, moore, shareholders Score: names, argentine, council, islands, commonwealth
STM topic 4 and LDA topic 4 are not the same issue: numbers belong only to their own fit.
R05b: raw party difference within the same STM
# R05b Calculate raw STM party differences
stm_theta <- as.data.frame(stm_6$theta)
colnames(stm_theta) <- paste0("topic_", seq_len(ncol(stm_theta)))
stm_theta$party_family <- topic_docs$party_family
stm_party_means <- stm_theta |> pivot_longer(starts_with("topic_"),
names_to = "topic", values_to = "proportion") |>
group_by(party_family, topic) |>
summarise(mean = mean(proportion), .groups = "drop")
stm_raw_differences <- stm_party_means |>
pivot_wider(id_cols = topic, names_from = party_family, values_from = mean) |>
mutate(difference = Labour - Conservative)
print(stm_raw_differences[stm_raw_differences$topic == "topic_4", ])> stm_theta <- as.data.frame(stm_6$theta)
> colnames(stm_theta) <- paste0("topic_", seq_len(ncol(stm_theta)))
> stm_theta$party_family <- topic_docs$party_family
> stm_party_means <- stm_theta |> pivot_longer(starts_with("topic_"),
+ names_to = "topic", values_to = "proportion") |>
+ group_by(party_family, topic) |>
+ summarise(mean = mean(proportion), .groups = "drop")
> stm_raw_differences <- stm_party_means |>
+ pivot_wider(id_cols = topic, names_from = party_family, values_from = mean) |>
+ mutate(difference = Labour - Conservative)
> print(stm_raw_differences[stm_raw_differences$topic == "topic_4", ])
# A tibble: 1 × 4
topic Conservative Labour difference
<chr> <dbl> <dbl> <dbl>
1 topic_4 0.137 0.0763 -0.0603The difference is defined as Labour − Conservative; negative = Labour discusses it less. The raw averages and the later conditional comparison use the same STM, so the gap between them cannot be mistaken for an effect of “switching models.”
R05c: estimate the conditional comparison
# R05c Estimate the conditional comparison set.seed(20260710) stm_party_effects <- estimateEffect(1:6 ~ party_family + period, stmobj = stm_6, metadata = metadata, uncertainty = "Global", nsims = 50) set.seed(20260710) adjusted_result <- plot(stm_party_effects, covariate = "party_family", method = "difference", cov.value1 = "Labour", cov.value2 = "Conservative", topics = 1:6, nsims = 1000, omit.plot = TRUE, labeltype = "numbers") print(adjusted_result$means[4]) print(adjusted_result$cis[[4]])
> set.seed(20260710)
> stm_party_effects <- estimateEffect(1:6 ~ party_family + period,
+ stmobj = stm_6, metadata = metadata,
+ uncertainty = "Global", nsims = 50)
> set.seed(20260710)
> adjusted_result <- plot(stm_party_effects,
+ covariate = "party_family", method = "difference",
+ cov.value1 = "Labour", cov.value2 = "Conservative",
+ topics = 1:6, nsims = 1000, omit.plot = TRUE,
+ labeltype = "numbers")
> print(adjusted_result$means[4])
[[1]]
[1] -0.05993053
> print(adjusted_result$cis[[4]])
2.5% 97.5%
-0.09272104 -0.02778845 Which level of uncertainty does this interval describe? Does it cover choices of vocabulary, sampling, or naming? — No. It is a simulation interval within this fitted model.
R05d: comparison table
# R05d Create a comparison table
adjusted_differences <- data.frame(topic = paste0("topic_", 1:6),
difference = unlist(adjusted_result$means),
lower = vapply(adjusted_result$cis, `[`, numeric(1), 1),
upper = vapply(adjusted_result$cis, `[`, numeric(1), 2))
print(adjusted_differences[adjusted_differences$topic == "topic_4", ],
row.names = FALSE)> adjusted_differences <- data.frame(topic = paste0("topic_", 1:6),
+ difference = unlist(adjusted_result$means),
+ lower = vapply(adjusted_result$cis, `[`, numeric(1), 1),
+ upper = vapply(adjusted_result$cis, `[`, numeric(1), 2))
> print(adjusted_differences[adjusted_differences$topic == "topic_4", ],
+ row.names = FALSE)
topic difference lower upper
topic_4 -0.05993053 -0.09272104 -0.02778845lower and upper are approximate endpoints of the model simulation interval; they do not identify a causal effect of party identity. For the numbers on all 6 topics, see the forest plot in Chapter 05.
R05e: plot the STM associations in R
# R05e Plot the STM associations in R
p_stm_adjusted <- ggplot(adjusted_differences, aes(difference, topic)) +
geom_vline(xintercept = 0, linetype = 2) + geom_point() +
geom_errorbar(aes(xmin = lower, xmax = upper),
orientation = "y", width = .15) +
labs(x = "Labour minus Conservative: conditional association", y = NULL) +
theme_minimal(base_size = 16)
print(p_stm_adjusted)The vertical line marks zero difference, and the horizontal lines are simulation intervals. What concept each topic represents still has to be interpreted from the words and texts.
E05: STM associations (in-class focus)
For STM topic 4: examine the Probability and FREX words, the raw party averages, and the adjusted Labour − Conservative comparison. Report the direction and size of the adjusted difference in percentage points, and explain what the covariates and the interval mean. Write one conclusion the evidence supports, and one causal claim it cannot establish.
Choose the most appropriate statement in each row; press “Check” to see which choices are wrong and why. All numbers come from the real output of R05a–R05d.
Self-check
qr(design)$rank == ncol(design)?After class: R03c–R04c party averages, K, and training perplexity
After-class exercises: average the LDA proportions by party (R03c–R03d), read the instructor’s pre-fitted K = 3/6/9 models and STM K = 5/6 (R04a), and compute and plot training perplexity (R04b–R04c).
R03c–R03d: LDA party averages
# R03c Calculate party means
lda_theta <- as.data.frame(theta)
colnames(lda_theta) <- paste0("topic_", seq_len(ncol(theta)))
lda_theta$doc_id <- topic_docs$doc_id
lda_theta$party_family <- topic_docs$party_family
lda_theta_long <- lda_theta |> pivot_longer(starts_with("topic_"),
names_to = "topic", values_to = "proportion")
party_topic_means <- lda_theta_long |> group_by(party_family, topic) |>
summarise(mean_proportion = mean(proportion), .groups = "drop")
print(as.data.frame(party_topic_means), row.names = FALSE)lda_6 <- readRDS("analysis/ess_lab/lda6.rds"), the instructor's saved fit, matches the slides)> lda_theta <- as.data.frame(theta)
> colnames(lda_theta) <- paste0("topic_", seq_len(ncol(theta)))
> lda_theta$doc_id <- topic_docs$doc_id
> lda_theta$party_family <- topic_docs$party_family
> lda_theta_long <- lda_theta |> pivot_longer(starts_with("topic_"),
+ names_to = "topic", values_to = "proportion")
> party_topic_means <- lda_theta_long |> group_by(party_family, topic) |>
+ summarise(mean_proportion = mean(proportion), .groups = "drop")
> print(as.data.frame(party_topic_means), row.names = FALSE)
party_family topic mean_proportion
Conservative topic_1 0.1509542
Conservative topic_2 0.1311229
Conservative topic_3 0.2244570
Conservative topic_4 0.1745095
Conservative topic_5 0.2170729
Conservative topic_6 0.1018834
Labour topic_1 0.1173659
Labour topic_2 0.1532040
Labour topic_3 0.2323498
Labour topic_4 0.1870214
Labour topic_5 0.2033525
Labour topic_6 0.1067064Comparison: R03c output from the local re-fit
textmodel_lda() re-fitted on Linux aarch64, differs from the slides)> lda_theta <- as.data.frame(theta)
> colnames(lda_theta) <- paste0("topic_", seq_len(ncol(theta)))
> lda_theta$doc_id <- topic_docs$doc_id
> lda_theta$party_family <- topic_docs$party_family
> lda_theta_long <- lda_theta |> pivot_longer(starts_with("topic_"),
+ names_to = "topic", values_to = "proportion")
> party_topic_means <- lda_theta_long |> group_by(party_family, topic) |>
+ summarise(mean_proportion = mean(proportion), .groups = "drop")
> print(as.data.frame(party_topic_means), row.names = FALSE)
party_family topic mean_proportion
Conservative topic_1 0.1303574
Conservative topic_2 0.1106336
Conservative topic_3 0.1360123
Conservative topic_4 0.1717899
Conservative topic_5 0.2354478
Conservative topic_6 0.2157590
Labour topic_1 0.1670497
Labour topic_2 0.1082648
Labour topic_3 0.1050097
Labour topic_4 0.1598399
Labour topic_5 0.2299747
Labour topic_6 0.2298613# R03d Plot the party means in R p_lda_party <- ggplot(party_topic_means, aes(topic, mean_proportion, fill = party_family)) + geom_col(position = "dodge") + coord_flip() + scale_fill_manual(values = party_colors) + labs(x = NULL, y = "Mean proportion per speech", fill = NULL) + theme_minimal(base_size = 16) print(p_lda_party)
Each sampled speech is weighted equally; these averages are not adjusted for period and do not identify causal effects.
Interactive: “each speech equal” or “each word equal”? (real θ)
Slide 84 asks: if you weight by retained_tokens, what quantity are you estimating? Switch the weights and see.
R04a: read different topic resolutions
# R04a Read alternative topic resolutions
k_candidates <- c(3, 6, 9)
lda_models <- lapply(k_candidates, function(k_value)
readRDS(lab_file(paste0("lda", k_value, ".rds"))))
names(lda_models) <- paste0("K", k_candidates)
stm_models <- lapply(c(5, 6), function(k_value)
readRDS(lab_file(paste0("stm", k_value, ".rds"))))
print(lapply(lda_models, terms, 5))> k_candidates <- c(3, 6, 9)
> lda_models <- lapply(k_candidates, function(k_value)
+ readRDS(lab_file(paste0("lda", k_value, ".rds"))))
> names(lda_models) <- paste0("K", k_candidates)
> stm_models <- lapply(c(5, 6), function(k_value)
+ readRDS(lab_file(paste0("stm", k_value, ".rds"))))
> print(lapply(lda_models, terms, 5))
$K3
topic1 topic2 topic3
[1,] "european" "prime" "people"
[2,] "council" "government" "government"
[3,] "community" "said" "prime"
[4,] "countries" "one" "country"
[5,] "united" "can" "can"
$K6
topic1 topic2 topic3 topic4 topic5 topic6
[1,] "european" "government" "prime" "government" "people" "united"
[2,] "council" "state" "people" "people" "can" "must"
[3,] "community" "made" "government" "unemployment" "country" "international"
[4,] "countries" "members" "said" "economy" "want" "security"
[5,] "agreed" "service" "can" "year" "support" "nations"
$K9
topic1 topic2 topic3 topic4 topic5 topic6 topic7 topic8
[1,] "economic" "people" "european" "prime" "council" "also" "government" "government"
[2,] "countries" "health" "union" "said" "agreed" "members" "people" "made"
[3,] "summit" "can" "deal" "now" "meeting" "country" "chancellor" "state"
[4,] "need" "national" "europe" "can" "community" "one" "per_cent" "service"
[5,] "world" "support" "future" "government" "european" "many" "budget" "matter"
topic9
[1,] "united"
[2,] "nations"
[3,] "security"
[4,] "must"
[5,] "british" Each model has its own topic numbering, and the same number does not mean the same issue; “match the words” before comparing. Slide 86’s example: T1 at K = 3, T1 at K = 6, and T3 and T5 at K = 9 all carry the european/council set of words.
Interactive: K resolution browser (real K = 3/6/9)
Click any word, and the topics containing it in all three models light up. Try european, council, health, unemployment, united.
R04b–R04c: training perplexity
# R04b Calculate training perplexity
training_perplexity <- function(model, data) {
is_stm <- inherits(model, "STM")
vocab <- if (is_stm) model$vocab else colnames(model$phi)
phi <- if (is_stm) exp(model$beta$logbeta[[1]]) else model$phi
counts <- as.matrix(data[, vocab])
probabilities <- pmax(model$theta %*% phi, 1e-12)
exp(-sum(counts * log(probabilities)) / sum(counts))
}
perplexity_results <- data.frame(Model = c("LDA", "LDA", "LDA", "STM", "STM"),
k = c(3, 6, 9, 5, 6), perplexity = vapply(c(lda_models, stm_models),
training_perplexity, numeric(1), data = topic_dfm))
print(perplexity_results, row.names = FALSE)> training_perplexity <- function(model, data) {
+ is_stm <- inherits(model, "STM")
+ vocab <- if (is_stm) model$vocab else colnames(model$phi)
+ phi <- if (is_stm) exp(model$beta$logbeta[[1]]) else model$phi
+ counts <- as.matrix(data[, vocab])
+ probabilities <- pmax(model$theta %*% phi, 1e-12)
+ exp(-sum(counts * log(probabilities)) / sum(counts))
+ }
> perplexity_results <- data.frame(Model = c("LDA", "LDA", "LDA", "STM", "STM"),
+ k = c(3, 6, 9, 5, 6), perplexity = vapply(c(lda_models, stm_models),
+ training_perplexity, numeric(1), data = topic_dfm))
> print(perplexity_results, row.names = FALSE)
Model k perplexity
LDA 3 1195.6619
LDA 6 1062.4988
LDA 9 989.2069
STM 5 1053.1552
STM 6 1012.5678# R04c Plot training fit in R
p_perplexity <- ggplot(perplexity_results, aes(k, perplexity)) +
geom_line() + geom_point(color = "#B00020", size = 3) +
facet_wrap(~ Model) + scale_x_continuous(breaks = c(3, 5, 6, 9)) +
labs(x = "Number of topics (K)", y = "Training perplexity",
subtitle = "Same training words; token-weighted plug-in score") +
theme_minimal(base_size = 16)
print(p_perplexity)All five scores reuse the same training words (resubstitution, not held-out). A lower value cannot by itself pick the best K, nor prove which “family,” LDA or STM, is better: the two have different model structures and fitting procedures. Name one check that uses topic words or original texts.
After-class exercises E01, E03 (and the R04 checks that go with E04)
| Exercise | What to do (W8.R) | Where to practice in these notes |
|---|---|---|
| E01 From speeches to word counts | Confirm that one document = one complete speech; compare the raw and cleaned words of ess_hoc_00004; report the number of documents, features, and tokens in the DFM; explain how phrase compounding and vocabulary trimming change the input to both models. | Cleaning pipeline, trimming lab |
| E03 Mixtures and party averages | Use doc_id to extract reading texts A and B, print the six proportions and their sum, and compare with “keeping only the largest topic”; compare LDA Topic 1 using party_family averages; report the two averages, state the weighting, and explain why the plot cannot establish a causal effect of party. | Speech browser, weighting lab |
| R04 checks of K | Read K = 3/6/9 and STM K = 5/6; compute and plot training perplexity; name one check that uses topic words or original texts. | K browser |
E03 reference numbers (real output, lda6)
A = ess_hoc_00004: .8738 / .0668 / .0124 / .0025 / .0124 / .0322 (sum 1); B = ess_hoc_05895: .0982 / .1339 / .2054 / .2232 / .2054 / .1339 (sum 1). LDA Topic 1 party averages: Conservative 0.1510, Labour 0.1174 (each speech weighted equally, not adjusted for period).
Self-check
Reading guide
The W8 repo has no papers/ folder. The core reading on slide 91 is Chapter 13 of Grimmer, Roberts & Stewart (2022) Text as Data, with §§21.3–21.4 optional (the book is not provided, so it is not summarized here). The reading cards below are based on publicly available full texts we could legally obtain, with page numbers given according to each file’s version.
- Barberá et al.: published open-access version; page numbers = journal pages (883–901).
- Gilardi et al.: the accepted manuscript archived by the University of Zurich, cited as “ms p. N,” not journal pages (21–35).
- Roberts et al.: the Early View version on an author’s website, cited as “EV p. N” (1–19), not mapped to the final volume pages (1064–1082).
- Mueller & Rauh: the author postprint from Digital.CSIC, cited as “postprint p. N,” not journal pages (358–375).
Gilardi, Shipan & Wüest (2021). Policy Diffusion: The Issue-Definition Stage. AJPS 65(1): 21–35.
prevalence = ~ party_family + period in Chapter 05, just with “prior adoptions” as the covariate.Source: accepted-manuscript PDF from ZORA (University of Zurich repository), CC BY 4.0; DOI 10.1111/ajps.12521.
Barberá et al. (2019). Who Leads? Who Follows? APSR 113(4): 883–901.
Source: Cambridge Core open-access PDF (CC BY 4.0); DOI 10.1017/S0003055419000352.
Roberts et al. (2014). Structural Topic Models for Open-Ended Survey Responses. AJPS 58(4): 1064–1082.
estimateEffect(..., uncertainty = "Global") is exactly this approach of “carrying measurement uncertainty into the regression.” Human coding serves only as a benchmark (slide 38).Source: the publisher’s Early View version on co-author Brandon Stewart’s website (with supplementary appendix); DOI 10.1111/ajps.12103.
Mueller & Rauh (2018). Reading Between the Lines: Prediction of Political Violence Using Newspaper Text. APSR 112(2): 358–375.
Source: author postprint from Digital.CSIC (2017-10-24); DOI 10.1017/S0003055417000570.
Catalinac (2016). From Pork to Policy. Journal of Politics 78(1): 1–18. (online appendix only)
Source: Online Appendix publicly available on the author’s website; DOI 10.1086/683073.
Further reading list (slide 91)
| Reference | Research use | In these notes |
|---|---|---|
| Wratil et al. (2023) | Government rhetoric and public opinion | Full text not read |
| Roberts et al. (2014) | Survey responses and human coding | Reading card |
| Eshima et al. (2024) | Keyword-assisted measurement | Chapter 07 (based on the slides) |
| Gilardi et al. (2022) | Supervised issue classification | Chapter 07 (based on slide 89) |
The correct title of Jiang, Xia & Zhang (2024) is “Birds of a Feather: Sharing Democratic Values Eases Immigration in a Postmaterialist Society,” Political Behavior 46(3): 1887–1911 (DOI 10.1007/s11109-023-09900-y). The full text is paywalled; it is available through the NTU Library or the university VPN.
Common pitfalls and glossary
Ten common pitfalls (click to see why)
1. Using the first few words from terms() directly as the topic name
Words only suggest a provisional label; read the texts and look for counterexamples, then decide to retain, narrow, broaden, or reject.
2. Matching “numbers” rather than “words” across models
STM topic 4 ≠ LDA topic 4; T1 at K = 6 becomes T3 and T5 at K = 9. When LDA was re-run locally, the European issue also moved from T1 to topic3.
3. Reporting only the dominant topic
dominant_topic discards the other five proportions; the largest share of 05895 is only 22%. To say a speech discusses several issues, use a row of θ.
4. Using training perplexity to choose the “best K”
Training perplexity usually falls as K grows; it is resubstitution, not held-out, and it does not measure meaning.
5. Describing STM party differences as causal effects
−5.99 percentage points is a conditional association after accounting for period; the interval only describes uncertainty within this fit.
6. Forgetting to state the direction of the difference
This week’s definition is Labour − Conservative; negative = Labour discusses it less. When reporting, state the direction and the percentage points.
7. Not stating how an average is weighted
R03c weights each speech equally; weighting by tokens answers “what share of all words belongs to this topic,” which is a different quantity.
8. Cleaning rules without justification
Removing minister leaves only prime from “Prime Minister,” and prime becomes the most frequent word. Every removal rule needs to be explained.
9. Using hand-picked examples as validation
The two speeches in R03a were picked based on model results, not a random validation sample; validation requires reading other high-share texts and counterexamples.
10. Assuming the sample represents all parliamentary speech
The 719 speeches are a near-balanced party × period sample and do not represent the word-count shares of parliamentary speech.
Glossary (searchable)
Final review, your research design plan, references
Final review quiz
Your project: validation plan
Slide 90 (research design, four minutes): define the concept, the population, and “one document”; choose LDA or STM and explain what information you supply; explain the comparison, denominator, and weighting; specify one sensitivity check and one piece of independent evidence. Finally, share one failure case: what evidence would make you change a topic label or abandon the measure? These answers can also become paragraphs of the 12-04 midterm research design report directly.
My progress
Only records starting with w8: are cleared; the W7 notes are not affected.
References
Methods and validation
- Blei, D. M., A. Y. Ng, and M. I. Jordan. 2003. “Latent Dirichlet Allocation.” JMLR 3: 993–1022.
- Roberts, M. E., et al. 2014. “Structural Topic Models for Open-Ended Survey Responses.” AJPS 58(4): 1064–1082. doi:10.1111/ajps.12103
- Eshima, S., K. Imai, and T. Sasaki. 2024. “Keyword-Assisted Topic Models.” AJPS 68(2): 730–750.
- Ying, L., J. M. Montgomery, and B. M. Stewart. 2022. “Topics, Concepts, and Measurement.” Political Analysis 30(4): 570–589.
- Grimmer, J., M. E. Roberts, and B. M. Stewart. 2022. Text as Data. Princeton University Press. Ch. 13; optional §§21.3–21.4.
- Schoonvelde, M. 2026. Introduction to Quantitative Text Analysis. Essex Summer School, Day 7 slides and lab.
Variants and model evaluation
- Blei, D. M., and J. D. Lafferty. 2007. “A Correlated Topic Model of Science.” Annals of Applied Statistics 1(1): 17–35.
- Blei, D. M., and J. D. Lafferty. 2006. “Dynamic Topic Models.” ICML: 113–120.
- Chang, J., et al. 2009. “Reading Tea Leaves: How Humans Interpret Topic Models.” NeurIPS 22.
- Wallach, H. M., et al. 2009. “Evaluation Methods for Topic Models.” ICML: 1105–1112.
- Roberts, M. E., B. M. Stewart, and D. Tingley. 2019. “stm: An R Package for Structural Topic Models.” JSS 91(2): 1–40.
- Yan, X., et al. 2013. A biterm topic model for short texts (WWW 2013; slide 66).
Applied studies
- Catalinac, A. 2016. “From Pork to Policy: The Rise of Programmatic Campaigning in Japanese Elections.” JOP 78(1): 1–18. doi:10.1086/683073
- Gilardi, F., C. R. Shipan, and B. Wüest. 2021. “Policy Diffusion: The Issue-Definition Stage.” AJPS 65(1): 21–35. doi:10.1111/ajps.12521
- Barberá, P., et al. 2019. “Who Leads? Who Follows?” APSR 113(4): 883–901. doi:10.1017/S0003055419000352
- Jiang, J., S. Xia, and D. Zhang. 2024. “Birds of a Feather: Sharing Democratic Values Eases Immigration in a Postmaterialist Society.” Political Behavior 46(3): 1887–1911. doi:10.1007/s11109-023-09900-y
- Mueller, H., and C. Rauh. 2018. “Reading Between the Lines: Prediction of Political Violence Using Newspaper Text.” APSR 112(2): 358–375. doi:10.1017/S0003055417000570
- Wratil, C., J. Wäckerle, and S.-O. Proksch. 2023. “Government Rhetoric and the Representation of Public Opinion in International Negotiations.” APSR 117(3): 1105–1122.
- Gilardi, F., T. Gessler, M. Kubli, and S. Müller. 2022. Supervised issue classification (slide 89; for the full citation, see the link on slide 91).
- Bernhard-Harrer, J., et al. 2026. “Beyond Standardization: A Comprehensive Review of Topic Modeling Validation Methods for Computational Social Science Research.” PSRM 14(3): 833–851.
Software
- quanteda, quanteda.textstats (corpus, DFM, collocations); seededlda (
textmodel_lda); stm (STM,estimateEffect,labelTopics); dplyr, tidyr, ggplot2, jsonlite.