Text as Data

W8: Topic Models and Their Variants

Yen-Chieh Liao

2026-10-30Fall 2026 (115-1) · National Taiwan University (GIND)
NTLDEV 7191 · Fri. 16:30–18:20 · GIND 204
Last compiled: 2026-11-06 16:22:26 (Asia/Taipei)

Political positions and issue attention

Research task Political question
W7: text scaling Where does a speaker stand on a defined dimension?
W8: issue attention What does a political actor choose to discuss?

Campaign promises, newspaper frames, policy diffusion and social media show different uses of topic models.

We begin with each study’s political puzzle.

Research questions and model use

Guiding question: How do political scientists turn large text collections into evidence about political behavior and communication?

We first read five political studies. Then we unpack how the models work and apply them to political speeches in R.

Topic models in political research

Case Texts How the model is used
1 · Catalinac (2016) Japanese manifestos Measure campaign promises
2 · Gilardi et al. (2021) U.S. news paragraphs Study policy diffusion and framing
3 · Barberá et al. (2019) Tweets Measure daily issue attention
4 · Jiang et al. (2024) Hong Kong news Develop and test a hypothesis
5 · Roberts et al. (2014) Survey answers Compare priorities with human coding

How we will read each case

What to find Question for the reader
Political question What puzzle does the study want to explain?
Texts and document unit What counts as one document, and whose language appears?
Model contribution What does the topic model discover or measure?
Evidence and limits What comparison, dynamic model or experiment supports the claim?

Use the same four questions when you design your own text research.

Teaching guide for the five cases introduced on the previous page.

Electoral rules and campaign promises

Case 1 · Campaign priorities

User-supplied Journal of Politics issue and article heading: From Pork to Policy, Amy Catalinac.

Amy Catalinac

Journal of Politics, 2016

  • Puzzle: the 1994 reform reduced same-party competition, but later studies still described campaigns as pork-oriented.
  • Question: did candidates shift from benefits for small groups to broader public policies?
  • Evidence: 7,497 candidate manifestos from eight elections, 1986–2009.

Reference: Catalinac (2016)

Manifestos become campaign-priority measures

Case 1 · How LDA is used · 1/3

Research step What Catalinac does
Discover topics LDA identifies 69 recurring themes in 7,497 manifestos
Read and check Inspect 15 top words and 10 representative manifestos per topic
Define concepts Use who benefits to classify 14 pork and 52 policy topics
Measure candidates Sum each category's topic shares within every manifesto
Test the puzzle Compare those shares across elections and levels of same-party competition

LDA finds recurring themes; close reading gives them political meaning.

Reference: Catalinac (2016)

Manifestos become campaign-priority measures

Case 1 · How LDA is used · 2/3

Research step What Catalinac does
Discover topics LDA identifies 69 recurring themes in 7,497 manifestos
Read and check Inspect 15 top words and 10 representative manifestos per topic
Define concepts Use who benefits to classify 14 pork and 52 policy topics
Measure candidates Sum each category's topic shares within every manifesto
Test the puzzle Compare those shares across elections and levels of same-party competition

Catalinac classifies interpreted topics by who benefits, creating pork and policy measures.

Reference: Catalinac (2016)

Manifestos become campaign-priority measures

Case 1 · How LDA is used · 3/3

Research step What Catalinac does
Discover topics LDA identifies 69 recurring themes in 7,497 manifestos
Read and check Inspect 15 top words and 10 representative manifestos per topic
Define concepts Use who benefits to classify 14 pork and 52 policy topics
Measure candidates Sum each category's topic shares within every manifesto
Test the puzzle Compare those shares across elections and levels of same-party competition

Candidate-level shares are compared across elections and levels of same-party competition.

Reference: Catalinac (2016)

Pork and policy across Japanese elections

Case 1 · The measure enters the result

Original Figure 1 screenshot with complete caption: LDP mean manifesto shares for pork and policy, 1986 through 2009.

Start with the red circle: broad policy promises rise before the new system is first used in 1996.

Reference: Catalinac (2016)

Pork and policy across Japanese elections

Case 1 · The measure enters the result

Original Figure 1 screenshot with complete caption: LDP mean manifesto shares for pork and policy, 1986 through 2009.

Now follow the lower line: local-benefit promises fall while broad policy promises rise.

Reference: Catalinac (2016)

Competition and campaign priorities

Case 1 · A complementary comparison

Original Figure 3 screenshot with both panels and caption: manifesto pork and policy shares versus intraparty competition under SNTV-MMD.

Left panel: more same-party rivals are linked to more local-benefit promises.

Reference: Catalinac (2016)

Competition and campaign priorities

Case 1 · A complementary comparison

Original Figure 3 screenshot with both panels and caption: manifesto pork and policy shares versus intraparty competition under SNTV-MMD.

Right panel: more same-party rivals are linked to fewer broad policy promises.

Reference: Catalinac (2016)

Opposition candidates emphasize policy

Case 1 · Opposition comparison

Original Figure 4 and caption: mean pork and policy discussion in 4,505 opposition manifestos across eight Japanese elections.

The opposition already makes many broad policy promises before 1996, and the line stays high.

Reference: Catalinac (2016)

Opposition candidates emphasize policy

Case 1 · Opposition comparison

Original Figure 4 and caption: mean pork and policy discussion in 4,505 opposition manifestos across eight Japanese elections.

The opposition’s local-benefit promises stay low. This observational comparison does not identify a causal effect.

Reference: Catalinac (2016)

Policy diffusion before adoption

Case 2 · Issue definition

AJPS webpage heading for Policy Diffusion: The Issue-Definition Stage, by Fabrizio Gilardi, Charles R. Shipan and Bruno Wüest.

Fabrizio Gilardi, Charles R. Shipan and Bruno Wüest

American Journal of Political Science, 2021

  • Puzzle: diffusion research usually observes policy adoption after the debate has already begun.
  • Question: do earlier smoking bans elsewhere change how a state’s newspapers define the issue?
  • Evidence: 52,675 paragraphs from 49 state newspapers, 1996–2013.

News paragraphs become policy frames

Case 2 · How STM is used · 1/3

Research step What the researchers do
Collect reporting Search 49 state newspapers, 1996–2013
Keep relevant paragraphs Use crowd labels to train an SVM relevance filter
Discover frames Fit a 12-topic STM to 52,675 paragraphs
Measure issue definition Estimate how common each frame is
Study diffusion Relate frame prevalence to earlier adoptions in other states

First collect possible reports, then use human labels to keep relevant paragraphs.

News paragraphs become policy frames

Case 2 · How STM is used · 2/3

Research step What the researchers do
Collect reporting Search 49 state newspapers, 1996–2013
Keep relevant paragraphs Use crowd labels to train an SVM relevance filter
Discover frames Fit a 12-topic STM to 52,675 paragraphs
Measure issue definition Estimate how common each frame is
Study diffusion Relate frame prevalence to earlier adoptions in other states

STM finds recurring frames; topic prevalence measures how common each frame is.

News paragraphs become policy frames

Case 2 · How STM is used · 3/3

Research step What the researchers do
Collect reporting Search 49 state newspapers, 1996–2013
Keep relevant paragraphs Use crowd labels to train an SVM relevance filter
Discover frames Fit a 12-topic STM to 52,675 paragraphs
Measure issue definition Estimate how common each frame is
Study diffusion Relate frame prevalence to earlier adoptions in other states

The analysis relates frame prevalence to earlier policy adoptions in connected states.

Practical policy frames change

Case 2 · Learning from other states

Original Figure 2 title and upper panels: Rules, Enforcement, and Bars and restaurants versus prior policy adoptions.

Moving right means more related states have adopted a ban. Restaurant concerns fall, while enforcement becomes more prominent.

Some frames remain stable

Case 2 · Stable frame: Health

Original Figure 2 panels: Health and Freedom versus prior policy adoptions.

Health changes little as prior adoption rises.

Some frames remain stable

Case 2 · Stable frame: Freedom

Original Figure 2 panels: Health and Freedom versus prior policy adoptions.

Freedom also stays nearly flat across adoption levels.

Frames remain separate at lower adoption

Case 2 · Optional detail · lower adoption

Original Figure 3 center panel: topic correlations in the lower prior-adoption group.

At lower adoption, the Rules topic has few strong correlations with the other frames.

A broader frame emerges at higher adoption

Case 2 · Optional detail · higher adoption

Original Figure 3 bottom panel: topic correlations in the higher prior-adoption group.

At higher adoption, Rules is correlated with several practical, value and political frames.

Who leads? Who follows?

Case 3 · Social media and issue attention

Cambridge Core article page for Who Leads? Who Follows?, including the APSR cover, title, publication date and seven authors.

Pablo Barberá and colleagues

American Political Science Review, 2019

  • Question: do politicians lead public attention, or follow it?
  • Texts: Congress, public and media tweets, 2013–2014.
  • Use: compare daily attention to shared issues.

Tweets become daily issue-attention measures

Case 3 · How the topic model is used · 1/3

Research step What the researchers do
Define documents Combine congressional tweets by day, party and chamber
Discover shared themes Fit a 100-topic LDA to the grouped congressional texts
Interpret issues Read topic words and merge related political themes
Construct measures Estimate daily issue attention for politicians, public samples and media
Analyse timing Compare whose earlier attention predicts another group's later attention

Tweets are grouped into comparable daily documents before LDA finds recurring themes.

Tweets become daily issue-attention measures

Case 3 · How the topic model is used · 2/3

Research step What the researchers do
Define documents Combine congressional tweets by day, party and chamber
Discover shared themes Fit a 100-topic LDA to the grouped congressional texts
Interpret issues Read topic words and merge related political themes
Construct measures Estimate daily issue attention for politicians, public samples and media
Analyse timing Compare whose earlier attention predicts another group's later attention

Researchers turn interpreted topics into comparable daily attention measures.

Tweets become daily issue-attention measures

Case 3 · How the topic model is used · 3/3

Research step What the researchers do
Define documents Combine congressional tweets by day, party and chamber
Discover shared themes Fit a 100-topic LDA to the grouped congressional texts
Interpret issues Read topic words and merge related political themes
Construct measures Estimate daily issue attention for politicians, public samples and media
Analyse timing Compare whose earlier attention predicts another group's later attention

Daily attention enters a time-series model that compares who moves first.

Who responds to whose attention?

Case 3 · Direction one

Complete original Figure 3, including four public-group panels, axes, legend and 95% confidence intervals.

Gray: when public attention rises, politicians often pay more attention later.

Who responds to whose attention?

Case 3 · Reverse direction and caveat

Complete original Figure 3, including four public-group panels, axes, legend and 95% confidence intervals.

Black: when politicians’ attention rises, the public may pay more attention later.

Immigration and shared democratic values

Case 4 · Topic models for theory building

Original Political Behavior article heading: Birds of a Feather: Sharing Democratic Values Eases Immigration in a Postmaterialist Society, Jin Jiang, Shouzhi Xia and Dong Zhang.

Jin Jiang, Shouzhi Xia and Dong Zhang

Political Behavior, 2024

  • Puzzle: research emphasizes economic and cultural concerns more than shared political values.
  • Question: can shared democratic values reduce support for restrictive immigration policy?
  • Evidence: researchers use the STM results to develop the hypothesis. A preregistered experiment tests it.

From news topics to a hypothesis

Case 4 · How STM supports theory building · 1/3

Research step Use in this article
Discover concerns STM identifies five topics in 4,453 news articles
Read and label Inspect characteristic words and representative news
Compare over time Estimate changes in topic prevalence, 2003–2020
Build a hypothesis Rising political attention motivates a shared-values argument
Test separately Randomize messages in a preregistered experiment

STM finds recurring concerns; researchers read the texts and supply the labels.

From news topics to a hypothesis

Case 4 · How STM supports theory building · 2/3

Research step Use in this article
Discover concerns STM identifies five topics in 4,453 news articles
Read and label Inspect characteristic words and representative news
Compare over time Estimate changes in topic prevalence, 2003–2020
Build a hypothesis Rising political attention motivates a shared-values argument
Test separately Randomize messages in a preregistered experiment

Changes in topic attention motivate the shared-democratic-values hypothesis.

From news topics to a hypothesis

Case 4 · How STM supports theory building · 3/3

Research step Use in this article
Discover concerns STM identifies five topics in 4,453 news articles
Read and label Inspect characteristic words and representative news
Compare over time Estimate changes in topic prevalence, 2003–2020
Build a hypothesis Rising political attention motivates a shared-values argument
Test separately Randomize messages in a preregistered experiment

Researchers use the STM results to develop the hypothesis. Random assignment tests the message effect.

Changing attention to mainland immigration

Case 4 · Theory-building evidence

Selected complete upper panels from original Figure 4: Social Welfare and HK–Mainland Tensions, with all axes and confidence bands.

News attention to social welfare falls after the mid-2010s. Dashed lines show 95% uncertainty.

Changing attention to mainland immigration

Case 4 · Hypothesis development

Selected complete upper panels from original Figure 4: Social Welfare and HK–Mainland Tensions, with all axes and confidence bands.

Attention to HK–Mainland tensions rises. This pattern motivates a shared-values hypothesis.

National problems in respondents’ own words

Case 5 · Public issue priorities

Original article heading: Structural Topic Models for Open-Ended Survey Responses.

Margaret E. Roberts and colleagues

American Journal of Political Science, 2014

  • Question: who names war as a national problem?
  • Document: one ANES open-ended answer.
  • Comparison: party identification and education.

Survey answers become issue comparisons

Case 5 · How the model is used

Step Role in the research design
Texts Answers to the most-important-national-problem question
Model inputs 60-topic STM; party, education, age and party × education
Output used Estimated war-related share in each answer
Political comparison War-topic relationship with party and education
Check Compare with ANES human-coded war categories

Human category codes provide a benchmark; they do not train this STM.

Survey priorities and human-coded evidence

Case 5 · Human-coded benchmark

Original Figure 18 comparing human-coded and STM War-topic relationships with party and education.

Left: the human-coded party gap is larger at higher education.

Survey priorities and human-coded evidence

Case 5 · STM comparison

Original Figure 18 comparing human-coded and STM War-topic relationships with party and education.

Right: the STM also shows a wider party gap; the Democratic line is roughly flat.

From topics to political evidence

Study Model contribution Next research step
Catalinac Topic shares Define pork/policy; compare candidates
Gilardi et al. Frame proportions Relate frames to prior policy adoption
Barberá et al. Daily attention Compare who moves first
Jiang et al. Topic trends Develop a hypothesis; test separately
Roberts et al. Survey topic shares Compare patterns with human coding

The research design determines what the evidence supports.

Applying topic models to political speeches

In-class demonstration

Political question: Which issues do party leaders emphasize in their speeches?

We will explore themes with LDA, add document information with STM, then compare topic resolutions using perplexity and original texts.

One workflow: fit, interpret, compare and validate.

Data source: Essex Summer School 2026, Day 7; British House of Commons party-leader speeches. W8 fixed teaching sample: 719 speeches.

Step 1: Read the speeches

LDA application · 1/6

library(quanteda)

data_dir <- "analysis/ess_lab"
topic_docs <- readRDS(file.path(
  data_dir, "sample_raw.rds"))

topic_corpus <- corpus(
  topic_docs,
  text_field = "text",
  docid_field = "doc_id")

Corpus = a collection of texts

719 complete speeches

The example used on all six pages

Field Value
ID ess_hoc_00004
Leader Margaret Thatcher
Party Conservative
Date 1979-06-26

Here, one document means one complete speech. The corpus keeps each speech together with its ID and background information.

Data source: Essex Summer School 2026, Day 7, British House of Commons party-leader speeches (p. 3). W8 fixed teaching sample: 719 speeches.

Step 2: Split one speech into words

LDA application · 2/6

id <- "ess_hoc_00004"

raw_tokens <- tokens(
  topic_corpus[id],
  what = "word")

raw_tokens[[id]][1:21]

Original sentence

“With permission, Mr. Speaker I should like to make a statement on the European Council Meeting at Strasbourg.”

First 21 raw tokens

“With” “permission” “,” “Mr” “.” “Speaker”
“I” “should” “like” “to” “make” “a” “statement”
“on” “the” “European” “Council” “Meeting” “at” “Strasbourg” “.”

Tokenization splits a speech into separate units. At this stage, punctuation and common words can still appear.

Data source: Essex Summer School 2026, Day 7; British House of Commons party-leader speeches. Example: speech ess_hoc_00004.

Step 3: Remove words that do not help

LDA application · 3/6

clean_tokens <- tokens(
  topic_corpus,
  remove_punct = TRUE,
  remove_numbers = TRUE) |>
  tokens_tolower() |>
  tokens_remove(c(
    stopwords("en"),
    "mr", "speaker"))

clean_tokens[[id]][1:8]

First eight cleaned tokens

“permission” “like” “make” “statement”
“european” “council” “meeting” “strasbourg”

Remove punctuation
Use lowercase
Remove very common words

Cleaning keeps the words that the model will compare. Every removal rule needs a reason.

Data source: Essex Summer School 2026, Day 7; British House of Commons party-leader speeches. W8 fixed teaching sample: 719 speeches.

Step 4: Fit the LDA model

LDA application · 4/6

Full DFM after cleaning: 719 × 2,831

# Use the DFM constructed in Lab R01c.
set.seed(20260710)
lda_6 <- seededlda::textmodel_lda(
  topic_dfm,
  k = 6,
  alpha = .5, beta = .1,
  max_iter = 500,
  auto_iter = FALSE,
  batch_size = 1,
  verbose = FALSE)

What the fitted model stores

Output Question it answers
Topic–word probabilities Which words characterize each topic?
Document–topic proportions Which topics appear in each speech?

A speech can mix topics; each topic favors different words. LDA estimates both from word patterns across the corpus.

This fit uses the full DFM built in the Lab. The short cleaning example on the previous page is for illustration.

Data source: Essex Summer School 2026, Day 7, British House of Commons party-leader speeches (p. 21). seededlda documentation.

Step 5: Topic words

LDA application · 5/6

terms(lda_6, 5) shows the five highest-probability words in each topic.

Topic Highest-probability words Provisional reading
T1 european, council, community, countries, agreed European Council negotiations
T2 government, state, made, members, service Government and public service?
T3 prime, people, government, said, can General political leadership?
T4 government, people, unemployment, economy, year Economy and unemployment
T5 people, can, country, want, support Public appeals and support?
T6 united, must, international, security, nations International security

Topic words suggest a provisional label. Original speeches show whether the label holds.

Data source: W8 six-topic LDA fitted to the fixed sample of 719 British House of Commons party-leader speeches. Student Lab R02a.

Step 6: One document’s topics

LDA application · 6/6

topic_names <- c(
  "European Council negotiations",
  "Government and public service?",
  "General political leadership?",
  "Economy and unemployment",
  "Public appeals and support?",
  "International security")

id <- "ess_hoc_00004"
i <- match(id, topic_docs$doc_id)

doc_topics <- lda_6$theta[i, ]
round(doc_topics, 3)

dominant_topic <- which.max(doc_topics)
topic_names[dominant_topic]

Document ess_hoc_00004

T1 T2 T3 T4 T5 T6
.874 .067 .012 .002 .012 .032

Largest share: T1
Provisional name: European Council negotiations

“…a statement on the European Council Meeting at Strasbourg.”

The document keeps all six proportions. The dominant topic is a short summary of its largest share.

Data source: W8 six-topic LDA and original speech ess_hoc_00004. Student Lab R02b–R03b.

Using STM to compare party attention

Question: do Conservative and Labour leaders emphasize the same issues?

Keep from the LDA example Add for the STM example
The same 719 complete speeches Party and election period for each speech
The same word-count matrix A model of how topic shares vary with this information

We will follow the same Thatcher speech, then compare one topic across parties.

Focus: topic prevalence — how much a topic is discussed.

STM Step 1: Add document information

STM application · 1/5 · In-class demonstration

metadata <- data.frame(
  doc_id = topic_docs$doc_id,
  party_family = topic_docs$party_family,
  period = topic_docs$period)
i <- match("ess_hoc_00004", metadata$doc_id)
metadata[i, c("party_family", "period")]

The same speech: ess_hoc_00004

Field Stored value
Party Conservative
Election period 47th Parliament (1979-1983)

719 metadata rows, in the same order as the 719 speech documents.

period is a category, not a numeric time trend.

One speech, one metadata row. Party and period now accompany the word counts.

W8 in-class demonstration. Same 719 speeches and STM specification as Lab R05.

STM Step 2: Specify the model

STM application · 2/5 · In-class demonstration

Fit once · reference specification

stm_input <- convert(topic_dfm, to = "stm")
stm_6 <- stm::stm(
  documents = 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)

Read the fitted result

dim(stm_6$theta)

Output: 719 documents × 6 topics.

prevalence = ~ party_family + period

Party and period help model topic shares. Word choice within topics is shared in this example.

Metadata enters topic estimation. R05a fits this specification in the Lab.

W8 in-class demonstration. Same 719 speeches and STM specification as Lab R05. stm reference.

STM Step 3: Read one topic

STM application · 3/5 · In-class demonstration

stm::labelTopics(
  stm_6, topics = 4, n = 5)

round(stm_6$theta[i, 4], 3)

STM Topic 4

Word summary Five characteristic words
Probability council, community, agreed, united, european
FREX argentine, commonwealth, nations, agreed, meeting

Provisional label: International affairs?

The same Thatcher speech has 97.9% in this STM topic.

Read words and original text together. Topic numbers belong to their own fitted model.

W8 in-class demonstration. Same 719 speeches and STM specification as Lab R05. Selected probability/FREX words from R05a; original speech ess_hoc_00004.

STM Step 4: Compare party averages

STM application · 4/5 · In-class demonstration

party_means <- tapply(
  stm_6$theta[, 4],
  metadata$party_family, mean)

round(100 * party_means, 2)

Mean share of STM Topic 4

Party Mean topic share
Conservative 13.66%
Labour 7.63%

Raw Labour − Conservative: -6.03 percentage points.

Each sampled speech has equal weight.

These are descriptive averages. The speeches come from different election periods.

W8 in-class demonstration. Same 719 speeches and STM specification as Lab R05. Same unadjusted means as R05b.

STM Step 5: Account for election period

STM application · 5/5 · In-class demonstration

set.seed(20260710)
party_effects <- stm::estimateEffect(
  1:6 ~ party_family + period,
  stm_6, metadata, uncertainty = "Global", nsims = 50)
set.seed(20260710)
z <- plot(party_effects, covariate = "party_family",
  method = "difference", cov.value1 = "Labour",
  cov.value2 = "Conservative", topics = 1:6,
  nsims = 1000, omit.plot = TRUE, labeltype = "numbers")
round(100 * c(z$means[[4]], z$cis[[4]]), 2)

Adjusted comparison · Topic 4

Same R05 conditional Topic 4 association: Labour minus Conservative, with a 95 percent simulation interval.

Quantity Percentage points
Labour − Conservative -5.99
95% interval [-9.27, -2.78]

The comparison accounts for election period. It describes a conditional association.

W8 in-class demonstration. Same 719 speeches and STM specification as Lab R05. Exact R05c–R05d conditional difference; plot selects Topic 4 only.

Assumptions and document boundaries

Modelling choice Question for the researcher
Bag of words Does word order carry information we need?
A common set of topics Are language and topic meanings comparable across the corpus?
Document boundaries Does one speech contain enough context for a mixture?
Vocabulary selection Which distinctions survive cleaning and trimming?
K Which issues split or merge when the number of topics changes?
Alpha and initialization Are mixtures and results stable across reasonable settings?

These choices shape the topics before researchers name or compare them.

Topic validation asks different questions

Check Question
Held-out word fit Can the model account for unseen words?
Words and documents Does the label describe the content?
Coherence and exclusivity Are prominent words related and distinctive?
Sensitivity Does the interpretation survive reasonable choices?
External prediction Do topic shares predict an outcome outside estimation?

Checking a topic label

STM Topic 4 · provisional label: “International affairs”
Evidence What to check
Probability words council, community, agreed, united, european
FREX words argentine, commonwealth, nations, agreed, meeting
Same Thatcher speech European Council meeting in Strasbourg; T4 = 97.9%
Other speeches Read high-share texts and possible counterexamples

Decision: retain, narrow, broaden or reject the label.

One speech supports a label; validate it on other texts.

Reading perplexity

K: number of topics. Perplexity: a model fit score.

Step What to do
1 · Fit candidate models Same texts and vocabulary; e.g. LDA K = 3, 6, 9
2 · Compare scores Lower perplexity = better fit to the words being scored
3 · Read the topics Check topic words and original texts: are the labels useful?
4 · Choose a useful K Use the score and interpretation together

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

Held-out prediction and topic meaning

Evidence How to read it
Training perplexity ↓ Better reconstruction of the estimation words
Held-out prediction Hide evaluation words before fitting, then score them
STM workflow make.heldout() → fit → eval.heldout(); compare K with searchK()
Topic meaning Read texts; check stability and independent evidence

STM held-out log probability: higher is better. Perplexity: lower is better.

Chang et al. (2009): predictive fit and human interpretation can diverge.

Same texts, different K

Same speeches and words · selected topics

Topics Possible topic labels Training
perplexity
K = 3 Europe-related discussion 1,195.7
K = 9 EU agreements
Council meetings
989.2

Choose useful detail.
A lower score alone does not choose K.

Source: W8 Lab R04a (selected word lists) and R04b (actual training scores).

Checking the number of topics

In-class demonstration · Choosing a topic resolution

Actual training perplexity for LDA K=3,6,9 and STM K=5,6, calculated from the same training words.

  • LDA, K=3/6/9: 1195.7 → 1062.5 → 989.2.
  • STM, K=5/6: 1053.2 → 1012.6.
  • Read words and the same texts: does extra K add a useful distinction?

Lower perplexity means better fit, not proof of the best K.

K=6 is our teaching resolution. R04b calculation · R04c plot.

Keyword-assisted topic models

Another modelling choice · keyATM

Method paper

Original title of Keyword-Assisted Topic Models, AJPS.

Eshima, Imai & Sasaki · AJPS 2024

R package

Unchanged screenshot of the official keyATM R package homepage.

install.packages("keyATM")

Researchers supply a few keywords for concepts they want to measure. The model estimates topics and document mixtures, including topics without keywords.

Extension · Keyword guidance in two models

Method Researcher input W8 use
keyATM Keywords for defined topics, plus topics without keywords Method and package overview
Seeded LDA Seed dictionary, pseudo-count weight and residual topics Independent extension

Both use substantive information to guide topic discovery.

The models and outputs differ; interpret and validate each fit.

keyATM and seededlda. ESS Day 7’s runnable example uses textmodel_seededlda().

More applications in political research

Extension · Correlated topics and change over time

Model Research question What the analyst supplies
Correlated Topic Model Which issues tend to appear together in documents? Text counts and a chosen topic resolution
Dynamic Topic Model How does the language of an issue change across periods? Comparable texts and ordered time periods

CTM estimates which issues appear together. DTM tracks how topic vocabulary changes across ordered periods.

Extension · Short texts with a biterm model

Short-text applications · R package BTM

Original paper · WWW 2013

Original first-page title and authors: A Biterm Topic Model for Short Texts, by Xiaohui Yan, Jiafeng Guo, Yanyan Lan and Xueqi Cheng.

  • Texts: short survey answers, posts or headlines.
  • BTM: pools unordered word pairs across short texts.

R package example

User-supplied BTM package example: short R package descriptions in NLP and machine learning are grouped into topics such as topic modelling and neural networks.

R package descriptions, grouped into topics.

Your extension: compare BTM with LDA and check labels against the original texts.

Break

Back at 17:36.

Next: the RStudio project, complete topic mixtures and party comparisons.

Student Lab ZIP includes the RStudio project, step-by-step R script, data and saved models.

W8 classroom materials. Run the R script one checkpoint at a time and keep the original speeches available.

One speech as one document

Corpus choice Shared classroom input
Source Commons leader speeches from two parties
Eligible source texts 3,897 nonempty speeches, source terms ≥ 80
Fixed teaching sample 719 complete speeches, up to 30 per party-period
Sample dates 15 May 1979 to 17 December 2025
Model input Same document IDs across the fitted R models

Discuss: what changes if every party’s speeches become one document?

Data source: Essex Summer School 2026, Day 7; British House of Commons party-leader speeches. W8 sampling seed 20261028. Nearly balanced party-period sample, not parliamentary word volume.

R workflow and model objects

Class stage Steps What you should explain
1 · Read and prepare R01a–R01c Define a document; explain what cleaning changes
2 · Fit and read LDA R02a–R02b Read a complete topic mixture
3 · Check a label R03a–R03b; E02 Support a label with text and name a challenge
4 · Compare with STM R05a–R05e; E05 Interpret direction, percentage points and uncertainty

Same texts: LDA uses counts; STM adds metadata.

Before class: R00 packages and project setup. Open W8_lab.Rproj, then W8.R.

After class: R03c–R04c compare party summaries and K diagnostics. The project plan and reading close the deck.

R00a: R packages

Before class · Run R00a in W8.R.

R packages add functions for text analysis, models and plotting.

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

R step-by-step Lab R00a. Same 719 speeches. Full step and output. Executed Console output.

R00b: Project folders

Before class · Run R00b in W8.R.

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 step-by-step Lab R00b. Same 719 speeches. Full step and output. Executed Console output.

R01a: Read file

Run together · Run R01a in W8.R.

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

R step-by-step Lab R01a. Same 719 speeches. Full step and output. Reformatted first three records and the executed corpus count.

R01b: Split and clean words

Run together · Run R01b in W8.R.

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

R step-by-step Lab R01b. Same 719 speeches. Full step and output. All executed raw and cleaned tokens from the same speech, reflowed six per line. Full Console formatting remains in the Lab.

R01c: Build the DFM

Run together · Run R01c in W8.R.

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

R step-by-step Lab R01c. Same 719 speeches. Full step and output. Executed DFM dimensions, retained-token total and all six most frequent retained features.

R02a: Fit six-topic LDA

Run together · Run R02a in W8.R.

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

R step-by-step Lab R02a. Same 719 speeches. Full step and output. Selected first five words from each printed distribution. The Lab retains all ten.

R02b: Complete topic mixtures

Run together · Run R02b in W8.R.

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

R step-by-step Lab R02b. Same 719 speeches. Full step and output. Reformatted first three θ rows and deterministic dominant-topic summary.

R03a: Two selected speeches

Run together · Run R03a in W8.R.

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

R step-by-step Lab R03a. Same 719 speeches. Full step and output. Reformatted metadata and all six proportions from both selected speeches.

R03b: Original speech texts

Run together · Run R03b in W8.R.

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 step-by-step Lab R03b. Same 719 speeches. Full step and output. Opening excerpts from the exact two printed source texts. Complete output in Lab.

R05a: Fit STM

Run together · Run R05a in W8.R.

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

R step-by-step Lab R05a. Same 719 speeches. Full step and output. All four labelTopics summaries printed by this step.

R05b: Raw STM party means

Run together · Run R05b in W8.R.

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 step-by-step Lab R05b. Same 719 speeches. Full step and output. Executed Console output for this exact step.

R05c: Estimate party differences

Run together · Run R05c in W8.R.

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

R step-by-step Lab R05c. Same 719 speeches. Full step and output. Executed Console output for this exact step.

R05d: Comparison table

Run together · Run R05d in W8.R.

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 step-by-step Lab R05d. Same 719 speeches. Full step and output. Executed Console output for this exact step.

R05e: STM interval plot

Run together · Run R05e in W8.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)

R step-by-step Lab R05e. Same 719 speeches. Full step and output. Research design. Actual R plot from the exact displayed step. Console values and the full plot are in the Lab.

R03c: LDA party means

After class · Run R03c in W8.R.

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 step-by-step Lab R03c. Same 719 speeches. Full step and output. Same twelve printed means, reshaped to a wide table and rounded to four decimals.

R03d: LDA party plot

After class · Run R03d in W8.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)

R step-by-step Lab R03d. Same 719 speeches. Full step and output. Actual R03d plot; the Topic 1 percentages are the same party means calculated in R03c.

R04a: Alternative resolutions

After class · Run R04a in W8.R.

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 step-by-step Lab R04a. Same 719 speeches. Full step and output. Four selected columns from the printed K=3/6/9 word lists. All columns remain in Lab.

R04b: Training perplexity

After class · Run R04b in W8.R.

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)

R step-by-step Lab R04b. Same 719 speeches. Full step and output. All five executed scores, rounded to two decimals; full precision and the common formula remain in the Lab. Training fit does not establish a superior model family or the best K.

R04c: Training-fit plot

After class · Run R04c in W8.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)

R step-by-step Lab R04c. Same 719 speeches. Full step and output. Actual R plot from the exact displayed step. Console values and the full plot are in the Lab.

Extended comparison: Issue classification

Research step How this study proceeds
Specify labels Define the issue categories before fitting
Train and validate Use separately labelled news and tweet samples
Measure attention Aggregate classified texts to daily group shares
Compare timing Model how groups’ earlier attention predicts later attention
Interpret Check differences across actors and issues

Compare: Barberá et al. discover themes; this study starts with issue labels.

A validation plan for your project

Your research design · four minutes

  • Define the concept, population and one document.
  • Choose LDA or STM; explain what information you supply.
  • State the comparison, denominator and weighting.
  • Specify a sensitivity check and independent evidence.

Share one failure case: what evidence would make you change the topic label or abandon the measure?

Reading and the next class

Core: Text as Data, ch. 13; selected §§21.3–21.4.

Further reading Research use
Wratil et al. (2023) Government rhetoric and public opinion
Roberts et al. (2014) Survey answers and human coding
Eshima et al. (2024) Keyword-assisted measurement
Gilardi et al. (2022) Supervised issue classification

Practice: E01–E05. Optional diagnostics appear before these closing pages.

Next: readability, similarity and word embeddings.

References: Methods and validation

Catalinac, A. 2016. “From Pork to Policy: The Rise of Programmatic Campaigning in Japanese Elections.” JOP 78(1): 1–18. DOI.

Blei, D. M., A. Y. Ng, and M. I. Jordan. 2003. “Latent Dirichlet Allocation.” JMLR 3: 993–1022. Article.

Roberts, M. E., et al. 2014. “Structural Topic Models for Open-Ended Survey Responses.” AJPS 58(4): 1064–1082. DOI.

Eshima, S., K. Imai, and T. Sasaki. 2024. “Keyword-Assisted Topic Models.” AJPS 68(2): 730–750. DOI.

Original-study figures retain the source versions and page locators printed on their slides.

References: Readings and reproducibility

Ying, L., J. M. Montgomery, and B. M. Stewart. 2022. “Topics, Concepts, and Measurement.” Political Analysis 30(4): 570–589. DOI.

Grimmer, J., M. E. Roberts, and B. M. Stewart. 2022. Text as Data. Princeton University Press. Ch. 13; selected §§21.3–21.4. Contents.

Schoonvelde, M. 2026. Introduction to Quantitative Text Analysis. Essex Summer School, Day 7 slides and lab. ESS course.

W8 classroom practical: LDA and STM from texts to findings. Full Lab · Student lab ZIP.

W8 sources, model recipes and input metadata accompany the classroom materials. Presenter notes remain outside the student package.

References: 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. DOI.

Blei, D. M., and J. D. Lafferty. 2006. “Dynamic Topic Models.” ICML: 113–120. DOI.

Chang, J., et al. 2009. “Reading Tea Leaves: How Humans Interpret Topic Models.” NeurIPS 22. Paper.

Wallach, H. M., et al. 2009. “Evaluation Methods for Topic Models.” ICML: 1105–1112. DOI.

Roberts, M. E., B. M. Stewart, and D. Tingley. 2019. “stm: An R Package for Structural Topic Models.” JSS 91(2): 1–40. DOI.

Original methods and maintained software documentation. Method choices and output definitions are separate from political identification.

References: Applications and developments

Gilardi, F., C. R. Shipan, and B. Wüest. 2021. “Policy Diffusion: The Issue-Definition Stage.” AJPS 65(1): 21–35. DOI.

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. DOI.

Barberá, P., et al. 2019. “Who Leads? Who Follows?” APSR 113(4): 883–901. DOI.

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. DOI.

Issue publication years are shown. Follow the linked original articles for sources.