⌂ Course index
🐞 Feedback
中文
Interactive features failed to initialize, so a static version with all chapters expanded in order is shown; just scroll down to read. (The interactive labs, quiz scoring, progress, and slide panel need JavaScript; if an in-app preview shows no interactivity, use “Share → Open in Safari” or open the file in a desktop browser.)
00 · Week overview

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” Slides 2–3

Research taskPolitical science question
W7: text scalingWhere does a speaker stand on a predefined dimension?
W8: issue attentionWhat 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.Slides 2–3

In plain words (supplement)

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 Slide 69

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:

  1. Read and prepare (R01a–R01c): define what counts as a document, and explain what the cleaning steps changed.
  2. Fit and read LDA (R02a–R02b): read one speech’s full topic mixture.
  3. Check labels (R03a–R03b, E02): support a topic label with original text, and identify one possible counterexample.
  4. 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).Slide 69 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 Slides 42, 69

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.

🗺Interactive concept mapClick a box for details
Click any box to start.

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.Slide 42

This week’s five research cases Slide 4

CaseTextsHow the model is usedIn these notes
1 · Catalinac (2016)Japanese candidate election manifestosMeasure campaign promises (pork vs. policy)03
2 · Gilardi, Shipan & Wüest (2021)US newspaper paragraphsStudy policy diffusion and framing03
3 · Barberá et al. (2019)TweetsMeasure daily issue attention03
4 · Jiang, Xia & Zhang (2024)Hong Kong newsDevelop hypotheses, then test them separately04
5 · Roberts et al. (2014)Open-ended survey responsesCompare priority issues with human coding04

Four questions for reading each case Slide 5

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?Slide 5

This week’s practice data Slide 68

UK House of Commons party leader speeches (fixed teaching sample)
  • 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-fitted lda3/6/9.rds and stm5/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.Slide 68

Discuss (slide 68)

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.Slide 26

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 Slide N 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.
Core idea this week: topic models find recurring word patterns; what gives them “political meaning” is the researcher’s reading and research design. Labels must be checked against the original texts, party comparisons are observational associations, and training perplexity alone cannot prove that a political measure is valid. (W8/README.md)

Deadlines and announcements (per README, read on 2026-11-06)

Upcoming dates
  • 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.

01 · Building intuition

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…Slide 48
  • 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.”Slide 47

A fitted model stores two tables Slide 46

Topic–word probabilities (topic–word, β or φ)

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.

Document–topic proportions (document–topic, θ)

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.Slide 46

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):

  1. 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.”
  2. 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).

🎲Generative story simulatorToy demo · supplement

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.

This document’s true θ (the drawn proportions)
Share of each topic among the words actually written
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?Slide 55

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.

🔺Dirichlet α triangleToy demo · supplement

Ten terms you must know

TermMeaningThis week’s example
DocumentThe model’s unit of analysis. Change the unit and you change the questions you can answer.Slide 68One full speech (719 in total)
Bag of wordsOnly counts how often words appear, ignoring order.Slide 55DFM 719 × 2,831
TopicA “probability distribution over words”; not a predefined category.T1: european, council, community…
Topic mixture θA document’s proportions across topics, summing to 1.Slide 48ess_hoc_00004: T1 = .874
KThe number of topics, specified by the researcher; change K and issues split or merge.Slide 55K = 6 in class
α / β priorsα affects how concentrated document mixtures are; β affects how concentrated topic–word distributions are.alpha = .5, beta = .1
Dominant topicKeeps only the number of the topic with the largest proportion; a kind of summary.Slides 48, 76max.col() in R02b
Provisional labelA name the researcher gives after reading the words and the texts; it must be validated further.Slide 47“European Council negotiations”
Topic prevalenceHow much a topic is discussed; STM lets it vary with metadata.Slide 49prevalence = ~ party_family + period
PerplexityA model-fit score; lower is better, but a lower score by itself cannot decide K.Slide 58LDA K=6: 1062.5

Self-check

1. Which description best fits a “topic” output by a topic model?
A topic is a probability distribution over words; labels are provisional and must be checked against the texts.Slide 47
2. What does one row of lda_6$theta (one speech) represent?
θ holds document–topic proportions; word probabilities are in $phi.Slides 46, 76
3. In the generative simulator, what happens to documents when α is set very small?
α controls how concentrated document mixture proportions are; word distributions are governed by the β side. (Supplementary demo)
02 · Building intuition

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:

① Which topic does this document currently favor?

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 α)

② Which topic is this word often assigned to across the corpus?

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):

Formula (supplement)
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.Slides 46, 75

Interactive: watch Gibbs sampling “cluster” words (supplement)

🧮Mini LDA: collapsed Gibbs samplingToy corpus · 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.

Iterations completed
0
Training perplexity (lower is better)
–
Words reassigned this sweep
–
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.Slides 52, 86

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.Slides 55, 86

Modeling choices shape the topics before they are named Slide 55

Modeling choiceQuestion the researcher must askThis week’s counterpart (supplement)
Bag of wordsDoes word order carry information we need?“not good” is split into not, good
Common set of topicsAre language and topic meaning comparable across the corpus?Does “european” mean the same in 1979 and 2025?
Document boundariesDoes one speech provide enough context to support a mixture?Very short interjections have only a few words
Vocabulary selectionWhich distinctions survive cleaning and trimming?Removing “minister”; trimming max_docfreq = .75
KWhich issues split or merge when the number of topics changes?K = 3/6/9 (R04a)
Alpha and initializationAre 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.”Slide 55

Full mixture vs. dominant topic Slides 48, 76–77

Full mixture (keep all 6 proportions)

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.

Dominant topic (keep only the largest)

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.Slide 76

Self-check

1. With the same DFM, the same parameters, and the same seed, will re-fitting LDA always give the same topic numbers as last time?
A seed supports reproducibility, not validity; when these notes actually re-ran the model on Linux, a different topic ordering came out (see Chapter 09).Slide 75
2. To claim that “one speech discusses several issues at once,” which output should you use?
R02b’s reminder: to show that a speech discusses multiple topics, use a row of θ, not dominant_topic.Slide 76
3. Slide 55 says “these choices shape the topics before researchers name or compare them.” Which of the following is not one of the modeling choices it lists?
Slide 55 lists: bag of words, common set of topics, document boundaries, vocabulary selection, K, alpha and initialization.Slide 55
03 · Research cases

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 Slides 6–15

Political question Slide 6

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.

How LDA is used Slides 7–9
  1. Discover topics: LDA finds 69 recurring topics in the 7,497 manifestos.
  2. Read and check: for each topic, read the 15 top words and 10 representative manifestos.
  3. Define the concept: use “who benefits” to sort topics into 14 pork and 52 policy topics.
  4. Measure candidates: for each manifesto, sum the proportions of topics in the same category.
  5. Test the puzzle: compare these proportions across elections and levels of same-party competition.
Slide 7 in one sentence: LDA finds recurring topics; close reading gives them political meaning. Catalinac then classifies the interpreted topics by “who benefits” to build pork and policy measures.Slides 7–8
FigureHow the slides read it
Pork and policy across electionsFirst 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.Slides 10–11
Same-party competition and campaign emphasisLeft panel: the more same-party rivals, the more local-benefit promises; right panel: the more same-party rivals, the fewer broad policy promises.Slides 12–13
Opposition party comparisonOpposition 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.Slides 14–15

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” Slides 16–24

Political question Slide 16

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.

How STM is used Slides 17–19
  1. Collect coverage: search newspapers in 49 states.
  2. Keep relevant paragraphs: train an SVM relevance filter with crowd-sourced annotations.
  3. Discover frames: fit a 12-topic STM to the 52,675 paragraphs.
  4. Measure issue definition: estimate how common each frame is (topic prevalence).
  5. Study diffusion: link frame prevalence to earlier adoptions in “related states.”
ResultHow the slides read it
Practical frames changeFurther to the right (more related states have adopted), “restaurant concerns” decline and “enforcement” becomes more prominent.Slide 20
Stable framesHealth barely changes with earlier adoptions; Freedom is also nearly flat.Slides 21–22
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.Slides 23–24

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? Slides 25–30

Political question Slide 25

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.

How the topic model is used Slides 26–28
  1. Define documents: aggregate congressional tweets by “day × party × chamber.”
  2. Discover shared topics: fit a 100-topic LDA to the aggregated congressional texts.
  3. Interpret issues: read topic words and merge related political topics.
  4. Build measures: estimate daily issue attention for politicians, public samples, and the media.
  5. Analyze time series: compare whose earlier attention predicts another group’s later attention.
The document unit is a deliberate design choice Slide 26

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.

FigureHow the slides read it
Direction one (gray)When public attention rises, politicians often pay more attention afterwards.Slide 29
Reverse direction and caveat (black)When politicians’ attention rises, the public may pay more attention afterwards.Slide 30

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

🗂Four questions × five casesPick a case, then a question

Answer in your head first, then click a button to flip the card and compare. Content compiled from slides 6–41.

Self-check

1. In Catalinac’s pork/policy measure, which step mainly supplies the “political meaning”?
LDA finds recurring themes; close reading gives them political meaning. The classification rule is “who benefits.”Slides 7–8
2. Before fitting the STM, what method did Gilardi et al. use to select relevant paragraphs?
Use crowd labels to train an SVM relevance filter — supervised classification (W6) serves as preprocessing here.Slide 17
3. Why did Barberá et al. aggregate tweets by day, party, and chamber into one document?
Tweets are grouped into comparable daily documents before LDA finds recurring themes.Slide 26
04 · Research cases

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 Slides 31–36

Political question Slide 31

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.

How STM supports theory building Slides 32–34
  1. Discover concerns: STM finds 5 topics in 4,453 news articles.
  2. Read and label: look at characteristic words and representative articles.
  3. Compare over time: estimate changes in topic prevalence over 2003–2020.
  4. Form hypotheses: rising political attention leads to the “shared values” argument.
  5. 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.Slides 35–36

The key division of labor Slide 34

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 Slides 37–40

Design Slides 37–38
  • 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.
Human coding is a benchmark, not training data Slides 38–40

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 Slide 41

StudyModel contributionNext research step
CatalinacTopic sharesDefine pork/policy; compare candidates
Gilardi et al.Frame sharesLink frames to prior policy adoptions
Barberá et al.Daily attentionCompare who moves first
Jiang et al.Topic trendsDevelop hypotheses; test separately
Roberts et al.Survey topic sharesCompare patterns with human coding
Slide 41: The research design determines what the evidence supports. Topic models only provide measurement; what you can claim depends on the design you put the measurement into.

Interactive: which design can support this claim?

⚖️Evidence matchingPick one per item

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

1. Where does Jiang et al.’s causal evidence come from?
STM is used to develop hypotheses; random assignment tests the message effect.Slide 34
2. What role does the ANES human coding play in Roberts et al.?
Human category codes provide a benchmark; they do not train this STM.Slide 38
05 · STM, validation, and extensions

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 Slide 49

Kept from the LDA exampleAdded in the STM example
The same 719 complete speechesEach speech’s party and electoral period
The same word-count matrixA 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.Slide 49

Conceptual form (supplement, simplified)
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 + period

Supplement: 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.Slide 51

Five steps (in-class demonstration, same settings as Lab R05) Slides 50–54

→ → → →
StepKey points and real numbers
1 · Add metadata719 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.Slide 50
2 · Specify the modelstm(..., K = 6, prevalence = ~ party_family + period, seed = 20260710, init.type = "Spectral"); θ is 719 × 6. Metadata enter topic estimation.Slide 51
3 · Read Topic 4Probability: council, community, agreed, united, european; FREX: argentine, commonwealth, nations, agreed, meeting. Provisional label “International affairs?”; the same Thatcher speech is 97.9% this topic.Slide 52
4 · Raw averagesMean Topic 4 share: Conservative 13.66%, Labour 7.63%; Labour − Conservative = −6.03 percentage points. Each sampled speech is weighted equally.Slide 53
5 · Account for periodestimateEffect(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.Slide 54
What is FREX? (supplement)

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…Slide 79

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.Slides 53–54

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)

⚖️Party × period: STM topic averagesReal data + reweighting demo

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.

Raw difference (Labour − Con)
–
Average within-period difference
–
Difference in each of the 12 Parliaments, then averaged
R05c adjusted (real, unaffected by the slider)
–

Interactive: raw and adjusted differences for six topics (real data)

📊Labour − Conservative (percentage points)Numbers from R05b–R05e
Click any topic row to see its Probability/FREX words.

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

1. In this week’s STM, what does prevalence = ~ party_family + period allow to vary with party and period?
Party and period help model topic shares. Word choice within topics is shared in this example.Slide 51
2. What is the best reading of “Labour − Conservative = −5.99 percentage points, 95% interval [−9.27, −2.78]”?
The interval describes uncertainty within this fitted model; it does not cover choices of vocabulary, sampling, naming, and so on.Slides 54, 81
3. Why are this week’s raw difference (−6.03) and adjusted difference (−5.99) almost the same?
About 30 speeches per cell (29 for Con in the 48th). If the composition were unbalanced, period could confound the raw comparison — try it in the lab above.Slide 68
06 · STM, validation, and extensions

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 Slide 56

CheckQuestion
Held-out word fitCan the model explain words it has not seen?
Words and documentsDoes the label describe the content?
Coherence and exclusivityAre the prominent words related to each other, and distinctive?
SensitivityDoes the interpretation hold up under reasonable choices?
External predictionCan topic shares predict outcomes outside the estimation?

Checking a topic label: STM Topic 4 Slide 57

EvidenceWhat to check
Probability wordscouncil, community, agreed, united, european
FREX wordsargentine, commonwealth, nations, agreed, meeting
The same Thatcher speechEuropean Council meeting in Strasbourg; T4 = 97.9%
Other speechesRead high-share texts and possible counterexamples
Decision: keep, narrow, broaden, or reject the label Slide 57

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

Instructor’s update, 2026-11-06 15:19 (commits 298c144, 068cfae)

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.Slide 58

StepWhat to do (slide 58)
1 · Fit candidate modelsSame texts and vocabulary; e.g., LDA K = 3, 6, 9
2 · Compare scoresLower perplexity = better fit to the words being scored
3 · Read the topicsLook at topic words and texts: are the labels useful?
4 · Choose a useful KLook at scores and interpretation together

Slide 58: Lab R04 uses training words. A lower score alone does not establish the best K. Slide 58

Supplement (not from the lecture): the perplexity formula (shown on the old slide 58; Lab R04b’s code computes exactly this)
Formula
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 Slide 60

Number of topicsPossible topic label (selected topic)Training perplexity
K = 3Europe-related discussion1,195.7
K = 9EU agreements / Council meetings989.2
Choose useful detail. Slide 60

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.

🧮Perplexity calculatorSupplement · defaults = old slide 60

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.

Model A
Model B

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 Slide 59

EvidenceHow to read it
Training perplexity ↓Better reconstruction of the words used for estimation
Held-out predictionHide evaluation words before fitting, then score them after fitting
STM workflowmake.heldout() → fit → eval.heldout(); compare K with searchK()
Topic meaningRead the texts; check stability and independent evidence
Two numbers that point in opposite directions Slide 59

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)
R · Supplement (not from the lecture; not run)
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 Slide 61

Real numbers (R04b)
  • 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.

Slide 61’s approach

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

1. LDA K = 9 has a lower training perplexity (989.2) than K = 6 (1062.5). What can you conclude?
A lower score alone does not choose K.Slides 58, 60
2. Supplement (the calculator above): Model B gives every word half the probability Model A does. B’s perplexity is how many times A’s?
The geometric mean becomes ½; taking the reciprocal, perplexity doubles: 2.52 → 5.04.
3. Which is an “external prediction” type of validation?
External prediction: Do topic shares predict an outcome outside estimation? (The example in this question is a supplement, not from the lecture; the design is taken from Mueller & Rauh 2018, listed on slide 64.)Slide 56
07 · STM, validation, and extensions

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 Slides 62–63

MethodResearcher inputUse 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 mixturesMethod and package overview: install.packages("keyATM")
Seeded LDASeed dictionary, pseudo-count weights, residual topicsIndependent 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.Slide 63

Supplement: what does seeded LDA syntax look like? (not from the lecture; not run)
R · Supplement (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 Slide 65

ModelResearch questionResearcher 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 Slide 66

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.Slide 66

Contrast: issue classification with labels defined first Slide 89

Research stepWhat Gilardi, Gessler, Kubli & Müller (2022) do
Specify labelsDefine issue categories before fitting
Train and validateUse separately annotated samples of news and tweets
Measure attentionAggregate the classified texts into daily shares for each group
Compare time seriesModel how each group’s earlier attention predicts later attention
InterpretExamine differences across actors and issues
Contrast (slide 89): Barberá et al. discover topics; this study starts from issue labels (supervised classification, W6). Both routes yield “daily attention”; the difference is who defines the categories, and when.

Interactive: which model should my study use?

🧭Model selection helperSupplement · compiled from slides 49, 62–66, 89

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

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

1. What is the biggest difference between keyATM and ordinary LDA?
Researchers supply a few keywords for concepts they want to measure…including topics without keywords.Slide 62
2. To learn “how the vocabulary of the immigration issue changed from the 2000s to the 2020s,” which model does slide 65 point to?
DTM tracks how topic vocabulary changes across ordered periods.Slide 65
08 · R lab

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.

Where the R output in these notes comes from
  • W8/classroom/W8.R was 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) Slides 70–71

R · R00a (W8/classroom/W8.R)
# 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(...)
The 8 packages used this week: quanteda, quanteda.textstats, seededlda, stm, dplyr, tidyr, ggplot2, jsonlite.
vapply(required, requireNamespace, ...)
Checks one by one whether each is installed; if any are missing, stop() lists their names.
options(seededlda_threads = 1)
LDA samples with a single thread, so results are reproducible on the same machine.
R console output (run locally: 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)
> 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 
R · R00b (W8/classroom/W8.R)
# 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")
R console output (run locally: 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)
> 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.
Checks (slides 70–71)
  • If you see “Install these packages first,” install the listed packages and re-run.
  • If a file cannot be found, reopen W8_lab.Rproj and run R00b again: lab_file() uses the relative path analysis/ess_lab/.

R01a: load the file and build the corpus Slides 43, 72

R · R01a (W8/classroom/W8.R)
# 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)))
readRDS(lab_file("sample_raw.rds"))
Reads the table of 719 speeches (columns include doc_id, leader, party_family, date, period, text).
corpus(topic_docs, text_field = "text", docid_field = "doc_id")
One row per complete speech; document names are the doc_id, and the other columns become docvars.
R console output (run locally: 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)
> 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.Slide 43

R01b: tokenizing and cleaning Slides 44–45, 73

R · R01b (W8/classroom/W8.R)
# 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])
tokens(topic_corpus[id], what = "word")
Produces “unprocessed” tokens for ess_hoc_00004 only, for comparison.
parliamentary_stopwords
Parliamentary courtesy terms (hon, member, right, friend…) and encoding residue (â, ã). They are frequent in every speech and would swamp the topics.
remove_punct/symbols/numbers/url/separators
Removes punctuation, symbols, numbers, URLs, and whitespace; split_hyphens = FALSE keeps hyphenated words.
tokens_tolower() |> tokens_remove(stopwords("en"))
Lowercases everything and removes common English words (the, to, I…).
R console output (run locally: 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)
> 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.”Slides 45, 73

Interactive: cleaning pipeline (real speech ess_hoc_00004)

🧹Toggle one cleaning step at a timeReal tokens + JS reproduction

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.

Tokens kept
–
Distinct words (types)
–
Top 5 kept words
–

R01c: compound phrases, build the DFM, trim Slide 74

R · R01c (W8/classroom/W8.R)
# 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))
textstat_collocations(..., min_count = 8, size = 2:3)
Finds 2–3 word collocations occurring at least 8 times, sorted by λ (strength of association).
tokens_compound(..., phrase(head(..., 30)))
Glues the top 30 collocations into single tokens (e.g., per_cent), so each is one word in the model.
dfm_trim(min_termfreq = 5, min_docfreq = 2)
Removes words that occur fewer than 5 times in the whole corpus, or in only 1 speech.
dfm_trim(max_docfreq = .75, docfreq_type = "prop")
Removes words that occur in more than 75% of speeches (too common to distinguish topics).
stopifnot(identical(...))
Confirms that the row order of the metadata and the DFM is identical, so STM later does not match the wrong speeches.
R console output (run locally: 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)
> 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 
How to read the output Slide 74
  • 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 prime are 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)

✂️dfm_trim threshold experimentReal pre-trim term and document frequencies

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.

Features kept
–
Tokens kept
–
Features removed by max_docfreq
–
Words that occur in too many speeches

R run checklist

✅I have run this in RStudioStored in this browser

Self-check

1. Why remove words such as hon, member, and friend separately?
Every removal rule needs a justification; this list is a research choice specific to the House of Commons corpus.Slides 45, 73
2. What does dfm_trim(max_docfreq = .75, docfreq_type = "prop") do?
Words that are too common cannot distinguish topics. In the trimming lab above, drag it to 1.00 to see the difference.
3. What does stopifnot(identical(topic_docs$doc_id, docnames(topic_dfm))) in R01c protect?
Slide 50 also stresses that the 719 rows of metadata are in the same order as the 719 documents.Slide 50
09 · R lab

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-fitting LDA locally gives numbers different from the slides (scope of the cause checked)
  • 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 $data stored in the instructor’s lda6.rds cell 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 use lda6.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 Slides 46, 75

R · R02a (W8/classroom/W8.R)
# 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))
set.seed(20260710)
Fixes the random starting point so the same environment can reproduce the result.
textmodel_lda(topic_dfm, k = 6, alpha = .5, beta = .1, ...)
Standard LDA (Gibbs sampling) from the seededlda package; K = 6, α = 0.5, β = 0.1.
max_iter = 500, auto_iter = FALSE, batch_size = 1
Runs exactly 500 iterations, with no early stopping and no batching.
terms(lda_6, 10)
The 10 highest-probability words of each topic (from $phi).
R console output (run locally; 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   6
Comparison: real output of re-fitting textmodel_lda(...) locally (differs from the slides)
R console output (run locally; 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
TopicTop five words (slide 47)Provisional reading on the slide
T1european, council, community, countries, agreedEuropean Council negotiations
T2government, state, made, members, serviceGovernment and public service?
T3prime, people, government, said, canGeneral political leadership?
T4government, people, unemployment, economy, yearEconomy and unemployment
T5people, can, country, want, supportPublic appeals and support?
T6united, must, international, security, nationsInternational 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.Slide 47

Interactive: name them yourself first, then check (E02 warm-up)

🏷Write provisional labels for the 6 topicsReal lda6: top 15 words and probabilities

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 Slides 48, 76

R · R02b (W8/classroom/W8.R)
# 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))
round(head(lda_6$theta, 3), 3)
The full 6-column proportions of the first three speeches.
range(rowSums(lda_6$theta))
Confirms that every row sums to 1.
max.col(lda_6$theta, ties.method = "first")
Keeps only the number of the largest-share topic for each speech; ties go to the first.
R console output (run locally; 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
R console output (run locally; 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 θ.Slide 76

Interactive: how “mixed” are the 719 speeches really? (real θ)

📈Distribution of each speech’s “largest topic share”Real lda6 θ

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 Slide 77

R · R03a (W8/classroom/W8.R)
# 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]))
which.max(theta[, 1])
The speech with the highest T1 share.
which.min(apply(theta, 1, max))
The speech whose “largest share” is smallest — that is, the one with the most dispersed mixture.
R console output (run locally; 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)
R console output (run locally; 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.

These two are not a random validation sample Slide 77

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 Slide 78

R · R03b (W8/classroom/W8.R)
# 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")
R console output (run locally; 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.Slide 78

Interactive: speech browser + topic highlighter (719 real speeches)

🔎Read the text, see the mixture, see which topic each word is assigned toReal data
Jump to:

LDA (lda6) full mixture
STM (K = 6) full mixture
Highlighter:
Supplement: the coloring rule is “which topic this word most likely belongs to under φ (β),” and strength = that topic’s share of the word’s total probability across topics. This is a word-level approximation, not the model’s actual assignment at each position in this speech; words removed by cleaning or trimming are not colored.

E02: words and provisional labels (in-class focus)

Task (W8.R)

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.

✍️E02 answer areaAutosaved · copyable
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

1. The largest topic share of ess_hoc_05895 is only 0.223 (T4). What is wrong with calling it “an economy speech”?
05895 is the speech with the most dispersed mixture of all.Slide 77
2. Why does slide 47 put question marks on the labels for T2, T3, and T5?
Topic words suggest a provisional label. Original speeches show whether the label holds.Slide 47
10 · R lab

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 Slides 51, 79

R · R05a (W8/classroom/W8.R)
# 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, party_family, period)
One row per speech; period is categorical (12 Parliaments).
model.matrix(...) + qr(design)$rank
Confirms the design matrix has full rank: party and period are not perfectly collinear, so the coefficients can be estimated.
convert(topic_dfm, to = "stm")
Converts the quanteda DFM into the documents/vocab format stm needs.
init.type = "Spectral"
Spectral initialization is deterministic, so STM gives the same results on different machines (the maximum difference between the local θ and the instructor’s stm6.rds is 2.6 × 10⁻⁸).
labelTopics(stm_6, topics = 4, n = 5)
Prints four word summaries for Topic 4: Highest Prob, FREX, Lift, Score.
R console output (run locally: 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)
> 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.Slides 52, 79

R05b: raw party difference within the same STM Slides 53, 80

R · R05b (W8/classroom/W8.R)
# 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", ])
R console output (run locally: 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)
> 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.0603

The 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.”Slide 80

R05c: estimate the conditional comparison Slides 54, 81

R · R05c (W8/classroom/W8.R)
# 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]])
estimateEffect(1:6 ~ party_family + period, uncertainty = "Global", nsims = 50)
Regresses the proportions of the 6 topics; “Global” carries the estimation uncertainty of θ (50 simulations) along.
plot(..., method = "difference", cov.value1 = "Labour", cov.value2 = "Conservative")
Computes Labour minus Conservative; after resetting the seed, the interval is computed from 1,000 simulations.
omit.plot = TRUE
Draws no plot and only returns the numbers ($means, $cis) for the next step’s table.
R console output (run locally: 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)
> 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 
Check (slide 81)

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 Slide 82

R · R05d (W8/classroom/W8.R)
# 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)
R console output (run locally: 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)
> 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.02778845

lower 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.Slide 82

R05e: plot the STM associations in R Slide 83

R · R05e (W8/classroom/W8.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)
R05e STM adjusted differences plot
Real output of R05e (local R 4.5.3 / ggplot2 4.0.3). The dashed line is 0; the horizontal lines are simulation intervals. Only topic_4’s interval lies entirely to the left of 0.

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.Slide 83

E05: STM associations (in-class focus)

Task (W8.R)

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.

🧩E05 sentence builderPick the right pieces to assemble a conclusion

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

1. Why does R05a check qr(design)$rank == ncol(design)?
If some period had only one party, party and period could not be separated.
2. Why do the slides call −5.99 percentage points a “conditional association” rather than a causal effect of party?
It describes a conditional association. The interval only describes uncertainty within the model.Slides 54, 83
11 · R lab (after class)

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 Slides 84–85

R · R03c (W8/classroom/W8.R)
# 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)
R console output (run locally; 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.1067064
Comparison: R03c output from the local re-fit
R console output (run locally; 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
R · R03d (W8/classroom/W8.R)
# 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)
R03d LDA party means plot
The R03d plot, redrawn locally from the instructor’s saved lda6.rds with the same ggplot code. Topic 1: Conservative 15.1%, Labour 11.7%.

Each sampled speech is weighted equally; these averages are not adjusted for period and do not identify causal effects.Slide 85

Interactive: “each speech equal” or “each word equal”? (real θ)

⚖️Answering slide 84’s check questionlda6 θ × retained_tokens

Slide 84 asks: if you weight by retained_tokens, what quantity are you estimating? Switch the weights and see.

R04a: read different topic resolutions Slide 86

R · R04a (W8/classroom/W8.R)
# 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))
R console output (run locally: 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)
> 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.Slide 86

Interactive: K resolution browser (real K = 3/6/9)

🔬How issues split and mergeTop 10 words from the instructor’s saved lda3/6/9.rds

Click any word, and the topics containing it in all three models light up. Try european, council, health, unemployment, united.

R04b–R04c: training perplexity Slides 87–88

R · R04b (W8/classroom/W8.R)
# 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)
phi <- if (is_stm) exp(model$beta$logbeta[[1]]) else model$phi
STM stores log probabilities, which need exp() to convert back; LDA uses $phi directly.
counts <- as.matrix(data[, vocab])
Aligns the DFM columns with the model’s vocabulary.
probabilities <- pmax(model$theta %*% phi, 1e-12)
pdv = Σk θdk βkv for each word in each document; avoids log(0).
exp(-sum(counts * log(probabilities)) / sum(counts))
The token-weighted mean log probability, negated and exponentiated (formula in the Chapter 06 supplement; the new slide 58 no longer shows the formula).
R console output (run locally: 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)
> 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
R · R04c (W8/classroom/W8.R)
# 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)
R04c training perplexity plot
Real output of R04c (local). LDA and STM in separate facets, on the same scale.
What these five scores cannot prove Slides 87–88

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)

ExerciseWhat to do (W8.R)Where to practice in these notes
E01 From speeches to word countsConfirm 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 averagesUse 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 KRead 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).Slides 77, 84

Self-check

1. What is the denominator of the party mean in R03c?
The denominator of each mean is the number of sampled speeches for that party.Slide 84
2. Which topic at K = 9 most resembles T1 at K = 6 (european, council…)?
Match words before comparing topic numbers.Slide 86
12 · Wrap-up

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.

How to read the page numbers
  • 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. Slides 16–24

Research questionDiffusion research looks almost only at “adoption.” This paper looks at the first stage of the policy process: can other states’ earlier adoptions predict how a state frames the issue? The authors call this “policy-to-frame diffusion” (ms p. 1–2, note 2).
DataUS state smoking bans; document unit = newspaper paragraph; 49 newspapers in 49 states, 1996–2013; a broad search first, then crowd annotation + machine learning to exclude irrelevant paragraphs, leaving 52,675 paragraphs (ms p. 12).
MethodSTM (because it can include covariates). They estimated 47 models from K = 3 to 50, then chose K = 12 by qualitative inspection; the key covariate is the spatial lag of prior adoptions (ms pp. 13–15). The 12 topics are grouped into 7 categories, such as Freedom, Health, Regulations (ms p. 16).
FindingsRules, Bars and restaurants, etc. decline with prior adoptions, while Enforcement, Casinos, Electoral politics, etc. rise (ms p. 18); practical frames that can be verified from other states’ experience “learn,” whereas the normative Freedom and Health frames barely change (ms pp. 18–22); the more widespread the policy, the more composite the frames (ms p. 23).
LimitationsTopic proportions sum to 1 and crowd each other out, so only positive correlations are analyzed (ms p. 13); only one policy area is studied; “frame-to-frame” diffusion cannot be studied; the results are predictive, not causal (ms pp. 27–28).
Link to this weekSTM’s prevalence covariates are the same mechanism as 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. Slides 25–30

Research questionDo members of Congress lead or follow the public on issue attention? Which public do they follow? Three responsiveness models are compared: Downsian (the general public), Attentive (the politically attentive), and Supporter (the party’s own supporters) (p. 883; p. 886).
Data2013-01-01 to 2014-12-31 (113th Congress); 651,116 legislator tweets; four public samples and 36 media accounts; retweets excluded (pp. 888–889).
MethodLDA with 1-grams and 2-grams; document = daily aggregated tweets by “party × chamber”; the model is estimated on legislator tweets only and then applied to the other groups; K = 100 (cross-validation); five coders classified the topics, yielding 46 issues; the daily proportions go into a VAR (pp. 889–892).
FindingsLegislators’ attention correlates most strongly with their own party’s supporters; legislators follow more often than they lead; the Supporter model receives the most support; the media tend to follow the politically engaged public (pp. 890–897). Original text: “legislators are more likely to follow, than to lead” (p. 883).
LimitationsDescriptive rather than causal: the VAR “cannot rule out confounding by unobservable factors” (p. 884); the authors themselves call the homogeneity assumption of issue fixed effects “an inaccurate assumption” (p. 892); only the 113th Congress is analyzed (p. 898).
Link to this weekThe daily posterior topic proportions are used directly as attention time series (note to Figure 1, p. 891): the topic model is the measurement, and the inference comes from the time-series model — matching slide 41, “the research design determines what the evidence supports.”

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. Slides 37–40, 49

Research questionOpen-ended survey responses are rarely analyzed, and almost always by human coding. The authors propose STM, which can put document-level covariates (gender, party, experimental treatment) into the model and estimate treatment and moderation effects (EV p. 1, p. 3).
DataDocument unit = one open-ended response per respondent; includes two experiments and the ANES “most important national problem” open-ended question.
MethodSTM; topic proportions serve as the outcome, with treatment effects estimated in the prevalence regression incorporating measurement uncertainty (EV p. 5, note); content covariates are used to compare “how different groups talk about the same topic.”
FindingsIn the experiments, both STM and human coding find treatment effects, and the two are significantly correlated (EV pp. 11–12); on the ANES, the category counts are very close to the human coding, and the Iraq War topic’s relationship with party and education is also close to the human coding (EV pp. 16–17).
LimitationsThe multimodal objective function creates a model selection problem, with some subjectivity (EV p. 18); unsupervised topics do not necessarily map one-to-one onto human categories, and grab-bag topics such as “get” and “go” appear (EV pp. 12, 17).
Link to this weekThe STM reference on slide 49; R05’s 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. Slide 64

NoteThe instructor’s update of 2026-11-06 16:32 (commit ccf7681) removed this study from the main cases; the slides now list it only among further applications (slide 64). This card is kept for reference.
Research questionCan news text predict the timing of armed conflict outbreaks, not just which countries are at risk? Existing predictors vary mainly across countries and miss new conflicts in previously peaceful countries (postprint pp. 1–3).
DataThe Economist, NYT, and Washington Post, 1975–2015, articles with a country or capital name in the headline — more than 700,000 articles in total, covering 185 countries; modeled at the article level and aggregated to country × year (postprint pp. 2, 11–16).
MethodLDA (Gibbs), K = 15, α = 3.33, β = 0.01, with 5, 50, and 70 topics as robustness checks (postprint p. 13); for each T, re-estimated using texts only up to year T to forecast T + 1 (p. 14); panel regressions with country fixed effects, evaluated by ROC/AUC (p. 17).
FindingsCivil war outbreaks: about an 80% true positive rate at about a 20% false positive rate (p. 17); in previously peaceful countries, the within model net of fixed effects performs clearly better (p. 22); dropping the conflict topic and using only the other topics, the within AUC is still 0.79 (civil war) (p. 25).
LimitationsPrediction is not causation; “for five warnings made, four will be false warnings” (p. 27); coverage volume differs enormously across countries, which the authors handle by using topic “shares” (p. 12).
Link to this weekTopics are predictive features, and the evidence is out-of-sample prediction (the external prediction on slide 56); note 17 points out that topics enter the regression anonymously, so whether topic identities are consistent across years does not affect the forecasts — a completely different research use from “describing issues.”

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) Slides 6–15

StatusThe journal article is paywalled; these notes did not read the main text. For the research question, results, and limitations, rely on slides 6–15.
Method, from the appendix7,497 Japanese candidate manifestos; tokenized with MeCab, with the same word written in different scripts unified by hand; 2,843 word stems (Appendix pp. 1–2).
How K was chosen20 to 200 topics were tried and 69 chosen: “one of the lowest specifications that appeared to produce topics that were fine-grained enough” (Appendix p. 2).
Labeling and validationFor each topic, the top 15 stems and 10 manifestos were read; e.g., the “agriculture, forestry, and fisheries” topic takes up 3.5% of manifestos in very rural districts versus 1.6% in other districts (Appendix pp. 2–3, 9).
ClassificationAfter removing 3 credit-claiming topics, the remaining 66 were classified as particularistic or programmatic according to the “claimed beneficiary” (Appendix p. 11).
Link to this weekA good example of “checking topics against externally known facts”: rural districts should talk about agriculture, and female candidates should talk more about women-friendly policies — corresponding to the words-and-documents and external checks on slide 56.

Source: Online Appendix publicly available on the author’s website; DOI 10.1086/683073.

Further reading list (slide 91)

ReferenceResearch useIn these notes
Wratil et al. (2023)Government rhetoric and public opinionFull text not read
Roberts et al. (2014)Survey responses and human codingReading card
Eshima et al. (2024)Keyword-assisted measurementChapter 07 (based on the slides)
Gilardi et al. (2022)Supervised issue classificationChapter 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.

13 · Wrap-up

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.Slides 47, 57

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.Slides 52, 86

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 θ.Slides 76–77

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.Slides 58–61, 87–88

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.Slides 54, 81–83

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.Slides 80, 83

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.Slide 84

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.Slides 45, 74

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.Slides 77, 57

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.Slide 68

Glossary (searchable)

📖Term lookupSearchable
14 · Wrap-up

Final review, your research design plan, references

Final review quiz

📝16-question final reviewNot answered yet

Your project: validation plan Slide 90

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.

🗒Validation plan builderAutosaved · exportable

    

My progress

📌Progress overviewStored only in this browser

Only records starting with w8: are cleared; the W7 notes are not affected.

References Slides 92–95

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.
These notes are based on the NTLDEV 7191 W8 slides (Yen-Chieh Liao, 2026-10-30; 95-page PDF, build of 2026-11-06 16:22, repo commit ccf7681), W8/classroom/W8.R, W8/analysis/ess_lab/*.rds, W8/README.md, and W8/lab/README.md. R output was re-run locally (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); the LDA in R02–R03 primarily uses the instructor’s saved lda6.rds, alongside the local re-fit results (see the note in Chapter 09). The reading guide is based on publicly available full texts (see Chapter 12). Passages and toy demos marked “Supplement (not from the lecture)” are additional explanations. Prepared on 2026-11-06.
NTLDEV 7191 Text as Data · W8 interactive self-study notes · based on the 2026-10-30 slides (2026-11-06)