W8: Topic Models and Their Variants
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)
| 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.
Reference: W7 scaling; Grimmer, Roberts & Stewart (2022)
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.
Reference: Grimmer, Roberts & Stewart (2022); ESS course
| 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 |
| 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.
Case 1 · Campaign priorities
Amy Catalinac
Journal of Politics, 2016
Reference: Catalinac (2016)
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)
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)
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)
Case 1 · The measure enters the result
Start with the red circle: broad policy promises rise before the new system is first used in 1996.
Reference: Catalinac (2016)
Case 1 · The measure enters the result
Now follow the lower line: local-benefit promises fall while broad policy promises rise.
Reference: Catalinac (2016)
Case 1 · A complementary comparison
Left panel: more same-party rivals are linked to more local-benefit promises.
Reference: Catalinac (2016)
Case 1 · A complementary comparison
Right panel: more same-party rivals are linked to fewer broad policy promises.
Reference: Catalinac (2016)
Case 1 · Opposition comparison
The opposition already makes many broad policy promises before 1996, and the line stays high.
Reference: Catalinac (2016)
Case 1 · Opposition comparison
The opposition’s local-benefit promises stay low. This observational comparison does not identify a causal effect.
Reference: Catalinac (2016)
Case 2 · Issue definition
Fabrizio Gilardi, Charles R. Shipan and Bruno Wüest
American Journal of Political Science, 2021
Reference: Gilardi, Shipan & Wüest (2021)
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.
Reference: Gilardi, Shipan & Wüest (2021)
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.
Reference: Gilardi, Shipan & Wüest (2021)
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.
Reference: Gilardi, Shipan & Wüest (2021)
Case 2 · Learning from other states
Moving right means more related states have adopted a ban. Restaurant concerns fall, while enforcement becomes more prominent.
Reference: Gilardi, Shipan & Wüest (2021)
Case 2 · Stable frame: Health
Health changes little as prior adoption rises.
Reference: Gilardi, Shipan & Wüest (2021)
Case 2 · Stable frame: Freedom
Freedom also stays nearly flat across adoption levels.
Reference: Gilardi, Shipan & Wüest (2021)
Case 2 · Optional detail · lower adoption
At lower adoption, the Rules topic has few strong correlations with the other frames.
Reference: Gilardi, Shipan & Wüest (2021)
Case 2 · Optional detail · higher adoption
At higher adoption, Rules is correlated with several practical, value and political frames.
Reference: Gilardi, Shipan & Wüest (2021)
Case 3 · Social media and issue attention
Pablo Barberá and colleagues
American Political Science Review, 2019
Reference: Barberá et al. (2019)
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.
Reference: Barberá et al. (2019)
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.
Reference: Barberá et al. (2019)
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.
Reference: Barberá et al. (2019)
Case 3 · Direction one
Gray: when public attention rises, politicians often pay more attention later.
Reference: Barberá et al. (2019)
Case 3 · Reverse direction and caveat
Black: when politicians’ attention rises, the public may pay more attention later.
Reference: Barberá et al. (2019)
Case 4 · Topic models for theory building
Jin Jiang, Shouzhi Xia and Dong Zhang
Political Behavior, 2024
Reference: Jiang, Xia & Zhang (2024)
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.
Reference: Jiang, Xia & Zhang (2024)
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.
Reference: Jiang, Xia & Zhang (2024)
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.
Reference: Jiang, Xia & Zhang (2024)
Case 4 · Theory-building evidence
News attention to social welfare falls after the mid-2010s. Dashed lines show 95% uncertainty.
Reference: Jiang, Xia & Zhang (2024)
Case 4 · Hypothesis development
Attention to HK–Mainland tensions rises. This pattern motivates a shared-values hypothesis.
Reference: Jiang, Xia & Zhang (2024)
Case 5 · Public issue priorities
Margaret E. Roberts and colleagues
American Journal of Political Science, 2014
Reference: Roberts et al. (2014)
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.
Reference: Roberts et al. (2014)
Case 5 · Human-coded benchmark
Left: the human-coded party gap is larger at higher education.
Reference: Roberts et al. (2014)
Case 5 · STM comparison
Right: the STM also shows a wider party gap; the Democratic line is roughly flat.
Reference: Roberts et al. (2014)
| 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.
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.
LDA application · 1/6
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.
LDA application · 2/6
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.
LDA application · 3/6
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.
LDA application · 4/6
Full DFM after cleaning: 719 × 2,831
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.
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.
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.
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.
Reference: Roberts et al. (2014)
STM application · 1/5 · In-class demonstration
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 application · 2/5 · In-class demonstration
Fit once · reference specification
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 application · 3/5 · In-class demonstration
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 application · 4/5 · In-class demonstration
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 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
| 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.
| 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.
| 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? |
Reference: ESS course; Grimmer, Roberts & Stewart (2022)
| 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.
Reference: Ying, Montgomery & Stewart (2022)
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.
| 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 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.
In-class demonstration · Choosing a topic resolution
Lower perplexity means better fit, not proof of the best K.
K=6 is our teaching resolution. R04b calculation · R04c plot.
Reference: Blei, Ng & Jordan (2003); Chang et al. (2009)
Another modelling choice · keyATM
Researchers supply a few keywords for concepts they want to measure. The model estimates topics and document mixtures, including topics without keywords.
Reference: Eshima, Imai & Sasaki (2024)
| 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.
| 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.
Reference: Blei & Lafferty (2007); Blei & Lafferty (2006)
Short-text applications · R package BTM
Original paper · WWW 2013
Your extension: compare BTM with LDA and check labels against the original texts.
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.
| 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.
| 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.
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.
Before class · Run R00b in W8.R.
R step-by-step Lab R00b. Same 719 speeches. Full step and output. Executed Console output.
Run together · Run R01a in W8.R.
| Document | Leader | Party | Date |
|---|---|---|---|
| ess_hoc_00002 | Margaret Thatcher | Conservative | 1979-05-15 |
| ess_hoc_00211 | James Callaghan | Labour | 1979-06-21 |
| ess_hoc_00004 | Margaret Thatcher | Conservative | 1979-06-26 |
Corpus: 719 complete speeches.
Run together · Check: Confirm that the corpus contains 719 speeches and identify the document ID, leader, party, and date.
R step-by-step Lab R01a. Same 719 speeches. Full step and output. Reformatted first three records and the executed corpus count.
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])Raw tokens from ess_hoc_00004
After corpus cleaning
Run together · Check: Explain the visible changes between the raw and cleaned words.
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.
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.
Run together · Run R02a in W8.R.
| LDA topic | First five of ten printed words |
|---|---|
| T1 | european, council, community, countries, agreed |
| T2 | government, state, made, members, service |
| T3 | prime, people, government, said, can |
| T4 | government, people, unemployment, economy, year |
| T5 | people, can, country, want, support |
| T6 | united, must, international, security, nations |
theta dimensions: 719 speeches × 6 topics.
Run together · Check: Choose two topics and write provisional labels. Later, check those labels against actual speeches.
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.
Run together · Run R02b in W8.R.
| Speech | T1 | T2 | T3 | T4 | T5 | T6 |
|---|---|---|---|---|---|---|
| 00002 | 0.044 | 0.188 | 0.049 | 0.197 | 0.470 | 0.053 |
| 00211 | 0.005 | 0.490 | 0.136 | 0.207 | 0.116 | 0.045 |
| 00004 | 0.874 | 0.067 | 0.012 | 0.002 | 0.012 | 0.032 |
Dominant-topic counts (T1–T6): 91, 80, 193, 143, 145, 67.
Full θ rows sum to 1. Ties use the first index.
Run together · Check: Which output can answer: Which issues does one speech discuss as a mixture?
R step-by-step Lab R02b. Same 719 speeches. Full step and output. Reformatted first three θ rows and deterministic dominant-topic summary.
Run together · Run R03a in W8.R.
A: ess_hoc_00004, Thatcher, 26 June 1979.
B: ess_hoc_05895, Corbyn, 25 March 2020.
| Speech | T1 | T2 | T3 | T4 | T5 | T6 |
|---|---|---|---|---|---|---|
| 00004 | 0.8738 | 0.0668 | 0.0124 | 0.0025 | 0.0124 | 0.0322 |
| 05895 | 0.0982 | 0.1339 | 0.2054 | 0.2232 | 0.2054 | 0.1339 |
Both complete mixtures sum to 1 before display rounding.
Run together · Check: How does retaining only the largest topic change the description compared with keeping all six proportions?
R step-by-step Lab R03a. Same 719 speeches. Full step and output. Reformatted metadata and all six proportions from both selected speeches.
Run together · Run R03b in W8.R.
A: ess_hoc_00004
With permission, Mr. Speaker I should like to make a statement on the European Council Meeting at Strasbourg. With my…
B: ess_hoc_05895
My hon. Friend understands the issue and represents his constituency extremely well. I know that a lot of his constituents…
Run together · Check: Find support and a possible challenge to the label. Complete E02; finish E03 after class.
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.
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))STM topic 4. K=6, prevalence ~ party_family + period.
| Word summary | Five printed 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 |
Run together · Check: Use the probability words and FREX words to assess the interpretation of the same STM topic.
R step-by-step Lab R05a. Same 719 speeches. Full step and output. All four labelTopics summaries printed by this step.
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.
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.
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.
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)Run together · Check: Intervals refer to the same fitted STM.
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.
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)| LDA topic | Conservative | Labour |
|---|---|---|
| T1 | 0.1510 | 0.1174 |
| T2 | 0.1311 | 0.1532 |
| T3 | 0.2245 | 0.2323 |
| T4 | 0.1745 | 0.1870 |
| T5 | 0.2171 | 0.2034 |
| T6 | 0.1019 | 0.1067 |
After class · Check: What quantity would you estimate if speeches were weighted by retained_tokens?
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.
After class · Run R03d in W8.R.
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.
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))| LDA topic | Five printed words |
|---|---|
| K=3, T1 | european, council, community, countries, united |
| K=6, T1 | european, council, community, countries, agreed |
| K=9, T3 | european, union, deal, europe, future |
| K=9, T5 | council, agreed, meeting, community, european |
Check: Match words before comparing topic numbers.
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.
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)| Model | K | Training perplexity |
|---|---|---|
| LDA | 3 | 1195.66 |
| LDA | 6 | 1062.50 |
| LDA | 9 | 989.21 |
| STM | 5 | 1053.16 |
| STM | 6 | 1012.57 |
Lower: better reconstruction of these training words.
Same DFM and token-weighted formula; check topic meaning separately.
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.
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)After class · Check: Fit uses the same training DFM.
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.
| 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.
Your research design · four minutes
Share one failure case: what evidence would make you change the topic label or abandon the measure?
Reference: Grimmer, Roberts & Stewart (2022)
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.
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.
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.
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.
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.