W9: Word Embeddings and Political Language
The topic models of W8 answered "what are people talking about, and how much?" W9 asks a different question: is the same word used differently by different people, or in different periods? The approach is to turn a word (or each occurrence of a word) into a string of numbers learned from a corpus — a vector — and then compare directions with cosine. This week has four political science cases, a small Flair lab, and a conText (embedding regression) lab.
Opening question: what does security mean?
Slide 2 opens with security: the same word appears in three contexts — defence (Security Council), energy (energy security) and the economy (social security). The lecturer poses two questions: which nearby words help us tell these uses apart? and how do we test whether these uses differ across parties or periods? The whole week is about answering these two questions.
Imagine you could only guess a word's meaning from "which words often appear next to it". If security appears next to council, nations, it is probably about the UN; if it appears next to social, benefits, it is probably about welfare. Word embeddings compress this "who are the neighbours" information into a string of numbers. Embedding regression, in the second half of the week, goes one step further: each occurrence gets its own vector, so we can compare how Democrats and Republicans use the same word.
What you should be able to explain this week
Compiled from the Lab goals on slide 77 ("what vectors represent, how to compare them, how to check interpretations") and the three research design steps on slide 92. Come back and tick them off after each chapter:
- What vectors represent: distinguish "one vector per word type" (static GloVe) from "one vector per occurrence" (ALC / conText).
- How to compare: compute and read cosine; know that distances on a 2D PCA plot are not the same as full-dimensional cosine.
- The four cases: for each study, "what gets a vector, what is compared, and what evidence supports the political interpretation".
- conText results: explain what
party_Rcompares "holding gender fixed", and support it with one neighbour word and one context. - Design your own study: write a paragraph stating the question, unit, corpus, representation, comparison, and the evidence that would change your conclusion.
Lecture route (110 minutes)
Per W9/README.md: 112 slides in total, main lecture 1–94, supplement 95–112; Lab 30 minutes (17:40–18:10). Click each segment for the key points:
| Segment | Slides | Question (paraphrased from the README) |
|---|---|---|
| Concepts and research map | 1–16 | What do vectors represent? How are they learned? |
| Case 1 · Rheault & Cochrane | 17–26 | Can parliamentary language position parties? |
| Case 2 · Rodman | 27–36 | Can word associations reveal conceptual change? |
| Case 3 · Müller & Proksch | 37–46 | How do neighbour words help build and validate a nostalgia measure? |
| Case 4 · Embedding regression | 47–71 | How do we compare different groups' use of the same word? |
| Multilingual resources and applications | 72–76 | Where else is this method used? |
| Lab overview and break | 77–80 | What will the Lab compare? |
| Flair and PCA | 81–85 | Load GloVe, get vectors, compare security, read the projection plot |
| conText | 86–91 | Build context vectors, read neighbours and passages, compare parties holding gender fixed |
| Research design and references | 92–94 | What evidence can support our own comparisons? |
| Supplement | 95–112 | Extra concepts, sentiment measurement, evaluation, readability |
The four cases at a glance
| Case | Text | What gets a vector | How the question is answered |
|---|---|---|---|
| 1 · Rheault & Cochrane (2020) | Parliamentary speeches | A party in a legislative term (party-term) | PC1 gives a speech-based scale, interpreted with Voteview |
| 2 · Rodman (2020) | NYT articles with equality in the headline | A word in a historical period | Cosine tracks associations; news passages show what changed |
| 3 · Müller & Proksch (2024) | European party manifestos | Seed words and candidate words | Neighbours expand the dictionary; scores enter a regression |
| 4 · Rodriguez, Spirling & Stewart (2023) | U.S. Congressional Record | Each occurrence of the target word | Regression estimates the gap; neighbours and passages explain it |
Table compiled from slide 16 (cases and texts) and slide 109 (Four ways embeddings support an answer).
How to use these materials
- The "Slide panel" on the right follows the section you are reading and switches to the matching slide; every tag is clickable.
- All R code and output were actually run locally (R 4.5.3 (aarch64-conda-linux-gnu), quanteda 4.5.1, quanteda.textstats 0.97.2); Flair was run via the Python route (Python 3.11.2, flair 0.15.1, torch 2.5.1, numpy 1.26.4, gensim 4.4.0). Every number has been checked against the slides; where they do not match, both are shown side by side.
- Anything marked "Supplement (not from the lecture)" is a plain-language explanation or toy demo I added, not content from the lecturer's slides.
Chapter quiz
From one-hot to word embeddings: windows, CBOW / Skip-gram, cosine
The problem with one-hot: every pair of different words has cosine 0
Slides 3–6 (based on Hung-yi Lee's teaching figures and Grimmer, Roberts & Stewart 2022, ch. 8, p. 78): one-hot gives each word its own dedicated coordinate, so the vectors for dog and cat do not overlap at all, cosine = 0, and we cannot see that they are similar. Word embeddings instead use "coordinates learned from usage", so dog, cat and rabbit end up close together when they appear in similar contexts.
The embedding coordinates are 3-dimensional toy values I made up, only to show that "one-hot gives all zeros, embeddings give closer and farther pairs"; real models have 30, 100 or 300 dimensions.
Context windows: c = 1 and c = 2
Slide 7 (Text as Data §8.2.4, p. 83) uses “The cute cat jumps over …” as an example: with window c = 1, the context of cat is cute and jumps; with c = 2, The and over are added. CBOW (Continuous Bag of Words) predicts cat from its context; Skip-gram predicts the context from cat. Once trained, cosine is used to compare the direction of the vectors.
Cosine calculator
Slide 101 (numerical example from Schoonvelde 2026, ESS Day 3): the counts for the Defence speech are (security=1, forces=1, energy=0), and for the Energy speech (1, 0, 1).
cos(a, b) = a·b / (‖a‖‖b‖) = 1 / (√2·√2) = 0.50
| security | forces | energy | |
|---|---|---|---|
| Defence (a) | |||
| Energy (b) |
Cosine looks only at direction, not length. Multiply every count in the Defence speech by 10 (making it a very long speech) and cosine is still 0.50 — try changing row a above to 10, 10, 0.
Learning coordinates by prediction
Supplementary slides 95–98: the input is a vocabulary position (one-hot), the middle layer holds the learned coordinates z1, z2, and the output is the probability of the next word (target attends); prediction errors update the connection weights. The middle-layer weights left after training are the word vectors. The movie review example on slide 99 (GRS 2022 §8.1, p. 80) shows why this is useful: the training data contain great, while a new review uses fantastic; if the two word vectors are close, the classifier can "carry over" what it has learned.
Chapter quiz
Training choices determine what kind of vectors you get
Four methods, two kinds of representation
| Method or interface | Learning signal | Representation |
|---|---|---|
| Word2Vec | CBOW: context → word; Skip-gram: word → context | Static word vectors |
| GloVe (Global Vectors for Word Representation) | Fits co-occurrence statistics of the whole corpus | Static word vectors |
| fastText | Predicts from context with character n-grams | Static word vectors |
| FlairEmbeddings | A character language model uses the surrounding text | Contextual token vectors |
The Lab choice on slide 11: load static GloVe with Flair's WordEmbeddings("glove"). Note: the Flair package can also produce contextual vectors (FlairEmbeddings), but this week's Lab uses the static GloVe it wraps — which is why the three security vectors in ch08 are identical.
"Using Flair" ≠ "using contextual vectors". WordEmbeddings("glove") is a lookup table: the same word type always returns the same row.
What does each row represent?
Slide 100 (Schoonvelde 2026, ESS Day 3, p. 6): in a document count matrix, each row is the feature counts of one speech; in a static word embedding, each row is the learned coordinates of one word type. Comparing two speeches → compare two rows of the DFM; comparing two words → compare two rows of the embedding matrix.
Averaging word vectors into a document vector
Slide 102 (GRS 2022 §8.3, pp. 86–87): average coordinate by coordinate. First token (1, 0), second (0, 2), document average (0.5, 1.0). Repeated words contribute repeatedly. R06 in W9.R builds document vectors this way (ch10).
Flip cards: static or contextual?
Chapter quiz
Case 1 · Rheault & Cochrane (2020): positioning parties from parliamentary speech
Question and data
Background: roll-call votes are one way to position parties. Question: can speech also reveal party positions, and how do positions change across terms? Text: parliamentary debates in the U.S., the U.K. and Canada; the model learns one vector for each party in each term. (Political Analysis 28(1): 112–133)
How embeddings are used: Predict → Represent → Project
- Predict: the model predicts a word (the example is work) from the context plus a party-term label.
- Represent: each party-term gets a vector, e.g. Labour 2005.
- Project: PCA projects all party-term vectors, which are compared on PC1.
Source: slide 18, citing the authors' preprint Figure 1, p. 8.
Reading the figure: PC1 over time
The horizontal axis is the year and the vertical axis is PC1 (the direction of greatest variation in the party-term vectors). Around 1920 the gap between the two parties is small (Democrats dashed blue line, Republicans solid red line); by 2000 the two parties are much farther apart on this speech-based scale. (Authors' preprint Figure 2b, p. 15)
Validating outside the model
| U.S. House (1921–2016) | Figure |
|---|---|
| Correlation between speech-based PC1 and Voteview party averages | 0.918 |
| Agreement rate of pairwise party-term orderings | 85.66% |
Conclusion: in this overlapping period PC1 can be read as a left–right scale; but the degree of agreement varies across benchmarks. (Authors' preprint Table 2, p. 20)
PCA only guarantees that PC1 is "the direction of greatest variation", not that it is ideology — it could also be era, issue or parliamentary procedure. Only by comparing with an independent source such as Voteview do we have grounds to call it left–right. This is the same logic as Wordfish in W7.
Chapter quiz
Case 2 · Rodman (2020): how the meaning of equality changes
Question and data
Background: the word equality has always been around, but the debates surrounding it keep changing. Question: in different eras, which groups and issues are linked with equality? Text: 3,105 articles from the NYT Article API with equality in the headline, 1855–2016. (Political Analysis 28(1): 87–111)
Turning news contexts into historical evidence
| Research step | What Rodman does |
|---|---|
| Collect contexts | Uses the headline, abstract and (if available) first paragraph; splits the articles into seven eras. |
| Estimate embeddings | Compares four Word2Vec training schemes, each producing word vectors for every era. |
| Track associations | Computes the cosine between equality and selected words within each era, then tracks it across eras. |
Slide 28 cites the author's manuscript §§5.2, 5.4.
Choosing a model: which is closest to human coding?
Reading the columns: lower deviation and higher correlation with the benchmark are better. The chronological row has the highest correlation (0.611) and the lowest deviation, coming closest to the five human-coded topic trends. Rodman then uses it to track new word pairs. (Author's manuscript Table 2, p. 25)
All four training schemes "run", but only by using human coding as a benchmark can we tell which one is most credible. This is the substantive / extrinsic evaluation discussed in ch11: the point is not whether the vectors look nice, but whether they can reproduce human judgements.
Reading the social–equality curve
"Does the rebound to .30 mean the early usage is still around?" The answer on slide 36: go back and read the passages. The same cosine can come from completely different usages.
Chapter quiz
Case 3 · Müller & Proksch (2024): building a nostalgia dictionary from neighbour words
Question and data
Background: references to the past can be praise, criticism or nostalgia. Question: do culturally conservative parties appeal more often to "a better past"? Text: 1,648 party manifestos from 24 European countries, 1946–2018. (BJPS 54(3): 993–1005; this paper is an optional W10 reading, used as a case in W9.)
From neighbour words to a nostalgia measure
- Find candidate words: search for neighbours of the seed words in pretrained GloVe and in vectors trained on the manifestos.
- Screen: three coders review the neighbour words; the words that pass form the embeddings-based dictionary.
- Score: combine the two dictionaries; the number of flagged sentences per 1,000 sentences becomes the outcome variable for comparing parties.
Slide 38 cites Figure 1 panels 1–2, p. 996; Supplement §B.2.
Below are the kinds of neighbours an embedding might give "if the seed word is tradition" (demo words I made up, not the paper's word list). Tick the words you would keep in the nostalgia dictionary, then look at the hints.
Validate the measure first, then compare parties
They compare manifesto scores from dictionaries (M1–M4) and sentence classifiers (M5–M6), checking 50 manifestos against two coders:
| Method | Agreement with coders (slide figures) |
|---|---|
| Base dictionary (base) | .61 |
| Expanded dictionary (expanded, adding embedding neighbours) | .54 |
| SVM (sentence classifier) | .87 |
| DistilBERT (sentence classifier) | .86 |
Slide 43: “We see lower agreement after expansion.” Embedding neighbours increase coverage but also bring in noise. An expanded dictionary is not guaranteed to be better; it must be validated. (Figure 2, p. 998; sentence validation p. 997)
Comparing parties across six measures
The six standardised nostalgia scores are the columns; M2 uses the expanded dictionary, and M4 additionally requires positive sentiment. In the boxed row, M2 is .08 and M4 is .07. Each one-point increase on the cultural conservatism scale is associated with .07–.10 standard deviations more manifesto nostalgia (six models, controlling for other variables). (Table 1, p. 1001; the cultural conservatism scale is in Supplement §C.6)
Chapter quiz
Case 4 intuition: same word, different contexts → ALC → regression
chips: British fries, American crisps
The same word chips: British usage appears next to ketchup, knife and fork (hot fries); American usage appears next to a bag (crisps). "Meaning" here is the pattern of use. (The slide notes this is a constructed example; Embedding Regression Non-Technical Explainer §1)
One context becomes one ALC vector
- Look up: look up the vectors of the context words in the same pretrained space.
- Average: ui = (1/|Ci|) Σw∈Ci vw (the words around this occurrence).
- Calibrate: yi = A ui; A is a learned linear transformation that corrects the bias introduced by averaging.
One use → one vector. Different uses of the same word can get different representations in the same space.
When context word vectors are averaged directly, common words (like the, and) pull every average in the same direction. The à la carte method of Khodak et al. (2018) learns a matrix A so that "the context average after transformation by A" is as close as possible to the word's original pretrained vector. conText's cr_transform is the A learned to go with cr_glove_subset — which is why the slides keep stressing that E and A must be a matched pair.
ALC toy calculator (Supplement (not from the lecture))
A 2-dimensional toy space (numbers made up by me): x-axis ≈ "hot food / cutlery", y-axis ≈ "packaged snacks". Tick the words next to this occurrence of chips:
The context vector is the regression outcome
Observation = one use of chips; outcome = its D-dimensional context vector.
yi = β0 + UKi βUK + εi (UKi: US = 0, UK = 1)
Both coefficients are D-dimensional vectors. Reading the results: use the coefficient length (norm) for the size of the difference, then use neighbour words and passages to explain its content; use permutation to assess uncertainty. The next step swaps English varieties for parties to study immigration. (Explainer §§3–5)
In an ordinary regression, y is a single number; here y is a whole row of 300 numbers, which amounts to running 300 regressions at once with the same X. The row of numbers βUK says "in which direction British usage leans on average". Its length is "how much it leans".
conText: from contexts to regression
| Step | Content |
|---|---|
| 1 · One row per occurrence | Keep the context, party and gender. n uses → an n × D outcome matrix Y. |
| 2 · Build outcome vectors | Average the context word vectors (excluding the target word), then apply the shared ALC transformation: ui = mean vw, yi = A ui. |
| 3 · Regress on every coordinate | yi = α + Ri βR + Mi βM + εi (R: Republican; M: male); α, βR and βM each have D elements. |
| 4 · Read the coefficients | α is the Democrat / female reference group; βR is the party comparison holding gender fixed. Plot the lengths, and combine coefficients to get each group's neighbour words. |
Slide 59 cites RSS (2023) pp. 1258–1259, 1264–1266 and the official Quick Start. toks: text + metadata; E and A: a matched pair.
Chapter quiz
Case 4 results: immigration, multilingual extensions and other applications
Question and data
Background: the two parties may mention immigration equally often but in different contexts. Question: how does the use of the same word vary by party and gender? Text: the U.S. Congressional Record, 111th–114th Congresses. (APSR 117(4): 1255–1274, W9 core reading)
Comparing the lengths of party and gender differences
Height = length of the adjusted difference vector: 0 means no vector difference, and larger means a bigger difference; error bars are 95% bootstrap intervals. immigration: party .175 (holding gender fixed), gender .087 (holding party fixed). For all three political terms the party gap is larger. (Figure 5; Supplement Table J.4)
Left: L2 lengths from the paper's Figure 5 / Table J.4 (slide 63). Right: normed.estimate.deflated from re-running the Quick Start locally (the bias-corrected squared length, slide 91). The two sets differ in units and in data size (the Lab has only a 400-document sample), so each can only be compared on its own for the direction "party > gender".
What is in the group difference? Neighbour words
Each row is the ten words with the highest cosine to that party's estimated immigration vector. In the boxed part, the Democrats' neighbourhood is about changing the system, and the Republicans' is about enforcing existing law; enact and legislation appear in both rows. (Table 4, p. 1267)
Back to the original passages
Reading the passages closest to each party's estimated vector: the Democratic passages talk about reform, the Republican passages about enforcement. Scope limit: these passages only illustrate the contrast; estimating how common a usage is requires a broader sample. (Table 5, p. 1267)
Beyond English: multilingual embeddings
Wirsching et al. (2025, Political Analysis, Figure 1, p. 159) compare ALC estimates with pretrained vectors within each language. Per W9/reading/README.md: this check does not imply cross-lingual alignment; non-English studies can use a model for that language, but should not compare coordinates across languages.
If you want to work on Chinese (e.g. interpellations in the Legislative Yuan), the workflow is the same: Chinese pretrained vectors E + an A learned for them. The conText Quick Start only ships the English cr_glove_subset / cr_transform; for Chinese you need to find a separate matched resource (Wirsching et al. 2025 provide 157 languages).
Four embedding regression applications
| Study | Comparison |
|---|---|
| Gonthier (2025) · SPSR | How different ideological groups use the French word peuple |
| Van Matre et al. (2026) · PSJ | Climate frames × party × Congress |
| Karell & Sachs (2023) · Socius | Minority group language before and after a political signal (Trump's return to Twitter) |
| Kim & Kesari (2021) · JOTS | “Chinese virus”: hate / counter-hate × time |
Chapter quiz
Lab A (17:40–17:55): load static GloVe in Flair, compare security, read the PCA
F00: set up the environment and model before class
Slide 81: before class, use Lab F00 to prepare Python, the packages and GloVe; from the course root run source("W9/lab/flair/flair_prepare.R") (the R route needs reticulate + flaiR); if R does not work, switch to the Python route. Installation and downloads are all done before class.
This machine is a Linux container with 2 GB of memory and no flaiR/reticulate, so I took the Python route: I created a clean venv and, following W9/lab/flair/requirements.txt, installed flair[word-embeddings]==0.15.1 and numpy < 2 (Python 3.11.2, flair 0.15.1, torch 2.5.1, numpy 1.26.4, gensim 4.4.0). The first WordEmbeddings('glove') call downloads a model of about 20.5 MB to ~/.flair/embeddings/glove.gensim; peak RSS while loading is about 1237 MB. The R route (flaiR) was not run locally; the instructor's runtime.json records that the R and Python vectors differ by less than 1e-6.
On your own Mac: python3.11 -m venv .venv && .venv/bin/pip install -r W9/lab/flair/requirements.txt, then run .venv/bin/python W9/lab/flair/flair_lab.py --download-glove to pre-load the model and --check to check. If you see “Imports OK. Device: CPU.” you are good to go.
Three steps: load → 11 × 100 → 3 × 100
In class we use the R version flair_steps.R (its three parts map one-to-one to the Python version):
# W9 Flair: run these three sections after sourcing flair_prepare.R.
# Keep the same R session. PCA remains in the separate after-class exercise.
# ==== Step 1: Load the model ====
embedding <- WordEmbeddings(glove_path)
print(embedding$embedding_length)
# ==== Step 2: Get word vectors ====
word_list <- paste("King Queen man woman Paris London",
"apple orange Taiwan Dublin Bamberg")
word_sentence <- Sentence(word_list)
embedding$embed(word_sentence)
word_vectors <- do.call(rbind, lapply(word_sentence$tokens,
function(token) as.numeric(token$embedding$tolist())))
print(dim(word_vectors))
# ==== Step 3: Compare security ====
security_texts <- c("Social security supports households.",
"The United Nations Security Council met.",
"Energy security matters for jobs.")
sentences <- lapply(security_texts, Sentence)
embedding$embed(sentences)
security_vectors <- do.call(rbind, lapply(sentences, function(sentence) {
token <- Filter(function(t) tolower(t$text) == "security",
sentence$tokens)[[1]]
as.numeric(token$embedding$tolist())
}))
print(dim(security_vectors))
unit <- security_vectors / sqrt(rowSums(security_vectors ^ 2))
security_cosine <- tcrossprod(unit)
print(round(security_cosine, 6))Full output of the Python version flair_steps.py (which first imports flair_prepare.py), actually run locally:
$ python flair_steps.py Python 3.11.2 at …/env/flair/bin/python flair 0.15.1 torch 2.5.1 numpy 1.26.4 matplotlib 3.11.2 gensim 4.4.0 Imports OK. Device: CPU. Cached model file: ~/.flair/embeddings/glove.gensim Ready for Step 1: load the model. 100 (11, 100) (3, 100) [[1. 1. 1.] [1. 1. 1.] [1. 1. 1.]]
| Checkpoint | Slides | Local |
|---|---|---|
embedding_length | 100 (Slide 82) | 100 ✓ |
| Matrix of 11 words | 11 × 100 (Slide 83) | (11, 100) ✓ |
| security in three sentences | 3 × 100, pairwise cosine 1 (Slide 84) | (3, 100), all 1 ✓ |
Social security, Security Council and Energy security are three completely different uses, but a static lookup returns the same word-type vector, so cosine = 1. This is exactly the problem Case 4 sets out to solve: a static vector mixes all uses of a word together. (Note that GloVe lowercases first, so Security and security look up the same row.)
11 × 11 full-dimensional cosine (actually run locally with flair_lab.py --run)
The numbers match the instructor's repo W9/lab/flair/example-output/word-cosine.csv to 4 decimal places (e.g. King–Queen 0.7508, man–woman 0.8323, London–Dublin 0.6913).
PCA: reading the 2024 word-vector map
Core call: prcomp(word_vectors, center = TRUE, scale. = TRUE). Slide 85 lists King (−2.91, 1.29), Queen (−2.24, 2.27), man (−5.64, 2.98); PC1 + PC2 retain 38.24% of the standardized variance. Local Python output:
$ python flair_lab.py --run --output-dir … … PCA scores (PC1, PC2, PC3): King -2.9121 1.2852 -1.9505 Queen -2.2414 2.2667 -1.0902 man -5.6382 2.9845 3.5546 woman -6.4891 2.4586 3.5669 Paris 3.0702 5.0391 -2.6596 London 5.3196 4.3684 -2.6073 apple 0.3363 -8.6794 -0.4475 orange -0.0485 -4.4041 0.7715 Taiwan -2.7994 -4.1493 -6.3330 Dublin 5.8994 1.0633 -0.0927 Bamberg 5.5032 -2.2330 7.2878 PC1 and PC2 retain 38.24% of the standardized variance.
The two principal components retain only 38.24% of the variance; the remaining 61.76% is not on the plot. Being close on the plot does not guarantee full-dimensional similarity — try clicking Dublin above: on the plot it is closest to London and Bamberg, but its full-dimensional cosine with Bamberg is only 0.1655.
E06 answer box
Chapter quiz
word_vectors, what are the rows and columns?Lab B (17:55–18:10): conText Quick Start C00–C05
Everything below is real output from running W9/classroom/W9-conText.R locally (conText 3.0.1, quanteda 4.5.1, text2vec 0.6.6; took about 2 seconds, R gc max memory used about 265 MB). Every number has been checked against Slides 86–91.
C00: text, vectors, and the paired transformation matrix
# ==== C00: Prepare the three guide objects ====
library(conText)
library(quanteda)
quanteda_options(threads = 1)
data(list = c("cr_sample_corpus", "cr_glove_subset",
"cr_transform"))
docvars(cr_sample_corpus, "party") <- factor(
docvars(cr_sample_corpus, "party"), levels = c("D", "R"))
docvars(cr_sample_corpus, "gender") <- factor(
docvars(cr_sample_corpus, "gender"), levels = c("F", "M"))
toks <- tokens(cr_sample_corpus, remove_punct = TRUE,
remove_symbols = TRUE, remove_numbers = TRUE,
remove_separators = TRUE, padding = TRUE)
toks <- tokens_tolower(toks)
toks_nostop <- tokens_select(toks, pattern = stopwords("en"),
selection = "remove", min_nchar = 3, padding = TRUE)
feats <- featnames(dfm_trim(dfm(toks_nostop),
min_termfreq = 5))
toks_nostop_feats <- tokens_select(toks_nostop, feats,
padding = TRUE)
print(c(documents = ndoc(cr_sample_corpus)))
print(rbind(E = dim(cr_glove_subset), A = dim(cr_transform)))
# Empty pads retain the positions of removed tokens.> library(conText)
> library(quanteda)
> quanteda_options(threads = 1)
> data(list = c("cr_sample_corpus", "cr_glove_subset",
+ "cr_transform"))
> docvars(cr_sample_corpus, "party") <- factor(
+ docvars(cr_sample_corpus, "party"), levels = c("D", "R"))
> docvars(cr_sample_corpus, "gender") <- factor(
+ docvars(cr_sample_corpus, "gender"), levels = c("F", "M"))
> toks <- tokens(cr_sample_corpus, remove_punct = TRUE,
+ remove_symbols = TRUE, remove_numbers = TRUE,
+ remove_separators = TRUE, padding = TRUE)
> toks <- tokens_tolower(toks)
> toks_nostop <- tokens_select(toks, pattern = stopwords("en"),
+ selection = "remove", min_nchar = 3, padding = TRUE)
> feats <- featnames(dfm_trim(dfm(toks_nostop),
+ min_termfreq = 5))
> toks_nostop_feats <- tokens_select(toks_nostop, feats,
+ padding = TRUE)
> print(c(documents = ndoc(cr_sample_corpus)))
documents
400
> print(rbind(E = dim(cr_glove_subset), A = dim(cr_transform)))
[,1] [,2]
E 500 300
A 300 300The Check on Slide 86: Which object has the text? cr_sample_corpus (400 speeches + metadata). Which two must be paired? cr_glove_subset (500 words × 300 coordinates) and cr_transform (300 × 300). padding = TRUE leaves an empty slot where words were removed, so the window calculation does not pull together words that were not originally adjacent.
C01: one row per occurrence
# ==== C01: Keep each immigration context and its metadata ==== immig_toks <- tokens_context(toks_nostop_feats, pattern = "immigration", window = 6L, valuetype = "fixed", rm_keyword = TRUE) print(c(contexts = ndoc(immig_toks))) print(table(docvars(immig_toks, "party"))) print(head(docvars(immig_toks), 3)) # One row is one use of immigration, not one speech.
> immig_toks <- tokens_context(toks_nostop_feats,
+ pattern = "immigration", window = 6L, valuetype = "fixed",
+ rm_keyword = TRUE)
924 instances of "immigration" found.
> print(c(contexts = ndoc(immig_toks)))
contexts
924
> print(table(docvars(immig_toks, "party")))
D R
486 438
> print(head(docvars(immig_toks), 3))
pattern party gender nominate_dim1
1 immigration D F -0.402
2 immigration D F -0.402
3 immigration D F -0.402924 contexts, D 486, R 438 (Slide 87 ✓). A row is one use of immigration, carrying that speech's metadata — not one speech.
C02: contexts → ALC vectors → party averages
# ==== C02: Build ALC vectors and average within party ==== immig_dfm <- dfm(immig_toks) immig_dem <- dem(immig_dfm, pre_trained = cr_glove_subset, transform = TRUE, transform_matrix = cr_transform, verbose = FALSE) immig_wv_party <- dem_group(immig_dem, groups = immig_dem@docvars$party) print(rbind(DFM = dim(immig_dfm), DEM = dim(immig_dem), party_vectors = dim(immig_wv_party))) # DEM: one context per row. Party vectors: one party per row.
> immig_dfm <- dfm(immig_toks)
> immig_dem <- dem(immig_dfm, pre_trained = cr_glove_subset,
+ transform = TRUE, transform_matrix = cr_transform,
+ verbose = FALSE)
> immig_wv_party <- dem_group(immig_dem,
+ groups = immig_dem@docvars$party)
> print(rbind(DFM = dim(immig_dfm), DEM = dim(immig_dem),
+ party_vectors = dim(immig_wv_party)))
[,1] [,2]
DFM 924 2014
DEM 924 300
party_vectors 2 300DEM 924 × 300: one ALC context vector per row; party averages 2 × 300 (Slide 88 ✓). Answer to the Check: still 300 coordinates, but a row now represents one party's average usage.
C03: reading nearest words
# ==== C03: Read neighbours and compare reform with enforce ====
immig_nns <- nns(immig_wv_party,
pre_trained = cr_glove_subset, N = 3,
candidates = immig_wv_party@features, as_list = FALSE)
immig_cosines <- cos_sim(immig_wv_party,
pre_trained = cr_glove_subset,
features = c("reform", "enforce"), as_list = FALSE)
print(immig_nns)
print(immig_cosines)
# These party averages are exploratory, before regression adjustment.> immig_nns <- nns(immig_wv_party,
+ pre_trained = cr_glove_subset, N = 3,
+ candidates = immig_wv_party@features, as_list = FALSE)
> immig_cosines <- cos_sim(immig_wv_party,
+ pre_trained = cr_glove_subset,
+ features = c("reform", "enforce"), as_list = FALSE)
> print(immig_nns)
# A tibble: 6 × 4
target feature rank value
<fct> <chr> <int> <dbl>
1 R immigration 1 0.875
2 D immigration 1 0.848
3 R illegal 2 0.708
4 D broken 2 0.680
5 D comprehensive 3 0.661
6 R enforcement 3 0.645
> print(immig_cosines)
target feature value
1 D reform 0.6580804
2 R reform 0.4899631
3 D enforce 0.4939719
4 R enforce 0.6365299| Slide 89 | Local | |
|---|---|---|
| D neighbours | immigration (0.848), broken (0.680), comprehensive (0.661) | Same ✓ |
| R neighbours | immigration (0.875), illegal (0.708), enforcement (0.645) | Same ✓ |
cos_sim values not shown on the slide: reform is 0.658 for D and 0.490 for R; enforce is 0.494 for D and 0.637 for R — the direction agrees with the neighbours. These are still unadjusted descriptive averages.
C04: reading nearest contexts
# ==== C04: Read the nearest context to each party vector ====
immig_ncs <- ncs(immig_wv_party, contexts_dem = immig_dem,
contexts = immig_toks, N = 1, as_list = FALSE)
print(immig_ncs[, c("target", "rank", "value")])
cat(paste(immig_ncs$target, immig_ncs$context, sep = ": "),
sep = "\n")
# D/R label the queried party vector, not the source speaker.
# These are processed context words, not complete original speeches.> immig_ncs <- ncs(immig_wv_party, contexts_dem = immig_dem,
+ contexts = immig_toks, N = 1, as_list = FALSE)
> print(immig_ncs[, c("target", "rank", "value")])
# A tibble: 2 × 3
target rank value
<chr> <int> <dbl>
1 D 1 0.802
2 R 1 0.798
> cat(paste(immig_ncs$target, immig_ncs$context, sep = ": "),
+ sep = "\n")
D: end conversation passed immigration bill comprehensive bill clean broken immigration system year
R: america suggest immigration can good thing illegal immigration legal immigration mean meansD 0.802, R 0.798; both passages match Slide 90 ✓. Note: D/R are the queried party average vectors, not the speaker's party; the candidate pool includes both parties, and the texts are processed context words, not the full original text.
Interactive: browser for 924 immigration contexts (real data)
Tip: sort by "Leans R" and filter speaker = D, and you will find "Democratic members using contexts close to the Republican average" — which is why a single hand-picked passage cannot represent a party.
C05: embedding regression, comparing parties holding gender fixed
# ==== C05: Compare party while adjusting for gender ==== set.seed(2021L) fit <- conText(immigration ~ party + gender, data = toks_nostop_feats, pre_trained = cr_glove_subset, transform = TRUE, transform_matrix = cr_transform, jackknife = FALSE, permute = TRUE, num_permutations = 100, window = 6L, valuetype = "fixed", verbose = FALSE) print(dim(fit)) print(rownames(fit)) print(fit@normed_coefficients) # Input is the original processed tokens with metadata, not the DEM. # Current conText reports squared norms and a bias correction. # A displayed p.value of 0 means 0 exceedances in 100 permutations. # These numbers are not the 2023 article's L2 coefficient lengths.
> set.seed(2021L) > fit <- conText(immigration ~ party + gender, + data = toks_nostop_feats, pre_trained = cr_glove_subset, + transform = TRUE, transform_matrix = cr_transform, + jackknife = FALSE, permute = TRUE, + num_permutations = 100, window = 6L, + valuetype = "fixed", verbose = FALSE) > print(dim(fit)) [1] 3 300 > print(rownames(fit)) [1] "(Intercept)" "party_R" "gender_M" > print(fit@normed_coefficients) coefficient normed.estimate.orig normed.estimate.deflated normed.estimate.beta.error.null n 1 party_R 10.139940 8.668252 1.471687 924 2 gender_M 6.908761 5.154713 1.754048 924 n_obs covariate_mean p.value 1 924 0.4740260 0 2 924 0.6709957 0
| Coefficient | Slide 91: debiased squared norm | Local deflated | Local orig (not debiased) | Permutation p |
|---|---|---|---|---|
party_R | 8.668 | 8.668 | 10.140 | 0 |
gender_M | 5.155 | 5.155 | 6.909 | 0 |
① party_R is the Republican vs Democratic difference vector holding gender fixed; it differs from the unadjusted averages in C02. ② A p shown as 0 means "0 of 100 permutations exceeded it", not that p is truly 0 (it is on the order of ≤ 1/100). ③ Current conText reports the debiased squared norm, not the L2 norm in the 2023 paper (.175/.087); the two cannot be compared directly.
E04: connecting one observation, the evidence and the coefficient
Chapter quiz
conText() take in C05?Classroom R: security neighbours, raw contexts and the PCA trap in W9.R
W9/classroom/W9.R is a different route: 719 party-leader speeches from the UK House of Commons (the same sample as W8) + a 30-dimensional teaching GloVe (1,653 word types) the instructor trained on this sample. According to Data/README.md, this model was trained for only five epochs and its neighbours are "visibly noisy"; it is not a validated semantic measure. In class we only do R00 and R05; the rest is after class.
R00: packages and files
# ==== R00 Packages and files ====
required <- c("quanteda", "quanteda.textstats")
missing <- required[!vapply(required, requireNamespace, logical(1), quietly = TRUE)]
if (length(missing)) stop("Install before class: ", paste(missing, collapse = ", "))
suppressPackageStartupMessages({library(quanteda); library(quanteda.textstats)})
quanteda_options(threads = 1)
options(width = 100)
w9_root <- if (dir.exists("W9/classroom")) normalizePath("W9") else if (dir.exists("classroom/Data")) normalizePath(".") else stop("Run from the course repository root or W9.")
speeches <- readRDS(file.path(w9_root, "classroom/Data/w9_speeches.rds"))
speech_corpus <- corpus(speeches, text_field = "text", docid_field = "doc_id")
raw_tokens <- tokens(speech_corpus) # Preserve original contexts for R05 without running R02.
stopifnot(!anyDuplicated(speeches$doc_id), !anyNA(speeches$text), all(nzchar(speeches$text)))
print(c(speeches = ndoc(speech_corpus)))
print(table(speeches$party_family))
print(speeches[1:3, c("doc_id", "leader", "party_family", "date")], row.names = FALSE)
# One row is one complete speech. This is a nearly balanced teaching sample, not all speech volume.> required <- c("quanteda", "quanteda.textstats")
> missing <- required[!vapply(required, requireNamespace, logical(1), quietly = TRUE)]
> if (length(missing)) stop("Install before class: ", paste(missing, collapse = ", "))
> suppressPackageStartupMessages({library(quanteda); library(quanteda.textstats)})
> quanteda_options(threads = 1)
> options(width = 100)
> w9_root <- if (dir.exists("W9/classroom")) normalizePath("W9") else if (dir.exists("classroom/Data")) normalizePath(".") else stop("Run from the course repository root or W9.")
> speeches <- readRDS(file.path(w9_root, "classroom/Data/w9_speeches.rds"))
> speech_corpus <- corpus(speeches, text_field = "text", docid_field = "doc_id")
> raw_tokens <- tokens(speech_corpus) # Preserve original contexts for R05 without running R02.
> stopifnot(!anyDuplicated(speeches$doc_id), !anyNA(speeches$text), all(nzchar(speeches$text)))
> print(c(speeches = ndoc(speech_corpus)))
speeches
719
> print(table(speeches$party_family))
Conservative Labour
359 360
> print(speeches[1:3, c("doc_id", "leader", "party_family", "date")], row.names = FALSE)
doc_id leader party_family 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-26R05: static word vectors and raw contexts
# ==== R05 Static word vectors and original contexts ==== # Step 1: Load the word vectors embedding <- readRDS(file.path(w9_root, "classroom/Data/w9_glove.rds")) word_vectors <- embedding$vectors print(dim(word_vectors)) # Step 2: Find security neighbours word_unit <- word_vectors / sqrt(rowSums(word_vectors ^ 2)) security_cosine <- drop(word_unit %*% word_unit["security", ]) security_cosine["security"] <- NA_real_ top <- head(sort(security_cosine, decreasing = TRUE), 8) security_neighbours <- data.frame(word = names(top), cosine = unname(top)) print(security_neighbours, row.names = FALSE) # Step 3: Read the original contexts security_contexts <- kwic(raw_tokens, pattern = "security", valuetype = "fixed", window = 7) print(head(as.data.frame(security_contexts), 3), row.names = FALSE) # Every occurrence of security receives the SAME learned vector. # E04: Name a neighbour, quote a supporting KWIC phrase, then name another security use. # After E04, continue with the Flair mini-lab. A separate query and PCA are after class.
> embedding <- readRDS(file.path(w9_root, "classroom/Data/w9_glove.rds"))
> word_vectors <- embedding$vectors
> print(dim(word_vectors))
[1] 1653 30
> word_unit <- word_vectors / sqrt(rowSums(word_vectors ^ 2))
> security_cosine <- drop(word_unit %*% word_unit["security", ])
> security_cosine["security"] <- NA_real_
> top <- head(sort(security_cosine, decreasing = TRUE), 8)
> security_neighbours <- data.frame(word = names(top), cosine = unname(top))
> print(security_neighbours, row.names = FALSE)
word cosine
resolution 0.6612895
council 0.6608147
national 0.5949308
system 0.5732534
ministers 0.5551598
conclusions 0.5483960
discussed 0.5130478
together 0.5054836
> security_contexts <- kwic(raw_tokens, pattern = "security",
+ valuetype = "fixed", window = 7)
> print(head(as.data.frame(security_contexts), 3), row.names = FALSE)
docname from to pre keyword
ess_hoc_00308 1876 1876 than unemployed people in terms of social security
ess_hoc_00308 1916 1916 . When we look at the social security
ess_hoc_00085 585 585 by the President of the United Nations Security
post pattern
benefits . [ Interruption . ] Maybe security
benefits paid to a striker's family , security
Council in support of the United Nations securityEvery occurrence of security gets the same learned vector. The neighbours resolution, council, national… suggest that in this party-leader speech sample security often co-occurs with UN resolutions and the Security Council (this is a noisy teaching model, so read the KWIC lines to check); the first three KWIC lines already show two uses, social security and United Nations Security Council.
The PCA map changes the nearest words
Slide 103: on the 2D map the word closest to security is discussed; but across all 30 dimensions the highest cosine is resolution (0.661); PC1 + PC2 retain only 9.54% of the variance of this model's unit vectors. Recomputed locally (export_W9a.R, prcomp(center = TRUE) on the unit vectors):
PCA on unit vectors: PC1+PC2 share = 9.54 % top full-space neighbour of security: resolution 0.661 closest on 2D map: discussed 0.014
All three numbers match Slide 103 ✓.
Raw contexts of security (real KWIC, 60 sampled / 144 total)
R06: averaging known word vectors and reporting coverage (after class)
# ==== R06 Average known word vectors and report coverage ====
# After class, optional. Restore R00, R02, R03, R05 first if the R session was restarted.
# Match count columns to supplied vectors; unseen tokens contribute no vector.
# Repeated terms are weighted by their counts. This is a simple bag-of-vectors average.
embedding_counts <- dfm_match(dfm(content_tokens), features = rownames(word_vectors))
known_tokens <- as.numeric(ntoken(embedding_counts))
all_content_tokens <- as.numeric(ntoken(content_tokens))
embedding_coverage <- data.frame(doc_id = docnames(embedding_counts), known_tokens,
content_tokens = all_content_tokens,
coverage = ifelse(all_content_tokens > 0, known_tokens / all_content_tokens, NA_real_))
doc_vectors <- as.matrix(embedding_counts %*% word_vectors)
doc_vectors[known_tokens > 0, ] <- doc_vectors[known_tokens > 0, , drop = FALSE] / known_tokens[known_tokens > 0]
doc_norms <- sqrt(rowSums(doc_vectors ^ 2))
valid_embedding <- known_tokens > 0 & is.finite(doc_norms) & doc_norms > 0
doc_unit <- doc_vectors[valid_embedding, , drop = FALSE] / doc_norms[valid_embedding]
embedding_similarity <- tcrossprod(doc_unit)
diag(embedding_similarity) <- NA_real_
stopifnot(query_id %in% rownames(embedding_similarity))
embedding_rank <- order(embedding_similarity[query_id, ], decreasing = TRUE, na.last = NA)
embedding_neighbours <- data.frame(doc_id = colnames(embedding_similarity)[head(embedding_rank, 5)],
cosine = embedding_similarity[query_id, head(embedding_rank, 5)], row.names = NULL)
embedding_neighbours$coverage <- embedding_coverage$coverage[match(embedding_neighbours$doc_id, embedding_coverage$doc_id)]
print(summary(embedding_coverage$coverage))
print(embedding_neighbours, row.names = FALSE)
cat("Excluded zero embedding documents:", sum(!valid_embedding), "\n")
# Word order and negation scope disappear in this average. These vectors are static,
# not contextual transformer embeddings or a conText/ALC estimate of contextual meaning.
# E05: Compare count, TF-IDF and embedding neighbours for the same query. Support one
# interpretation with original text and report coverage. Why is a high cosine score
# insufficient to claim agreement, influence or a causal effect?> embedding_counts <- dfm_match(dfm(content_tokens), features = rownames(word_vectors))
> known_tokens <- as.numeric(ntoken(embedding_counts))
> all_content_tokens <- as.numeric(ntoken(content_tokens))
> embedding_coverage <- data.frame(doc_id = docnames(embedding_counts), known_tokens,
+ content_tokens = all_content_tokens,
+ coverage = ifelse(all_content_tokens > 0, known_tokens / all_content_tokens, NA_real_))
> doc_vectors <- as.matrix(embedding_counts %*% word_vectors)
> doc_vectors[known_tokens > 0, ] <- doc_vectors[known_tokens > 0, , drop = FALSE] / known_tokens[known_tokens > 0]
> doc_norms <- sqrt(rowSums(doc_vectors ^ 2))
> valid_embedding <- known_tokens > 0 & is.finite(doc_norms) & doc_norms > 0
> doc_unit <- doc_vectors[valid_embedding, , drop = FALSE] / doc_norms[valid_embedding]
> embedding_similarity <- tcrossprod(doc_unit)
> diag(embedding_similarity) <- NA_real_
> stopifnot(query_id %in% rownames(embedding_similarity))
> embedding_rank <- order(embedding_similarity[query_id, ], decreasing = TRUE, na.last = NA)
> embedding_neighbours <- data.frame(doc_id = colnames(embedding_similarity)[head(embedding_rank, 5)],
+ cosine = embedding_similarity[query_id, head(embedding_rank, 5)], row.names = NULL)
> embedding_neighbours$coverage <- embedding_coverage$coverage[match(embedding_neighbours$doc_id, embedding_coverage$doc_id)]
> print(summary(embedding_coverage$coverage))
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.5185 0.7533 0.8025 0.7980 0.8491 1.0000
> print(embedding_neighbours, row.names = FALSE)
doc_id cosine coverage
ess_hoc_00174 0.9018980 0.8191781
ess_hoc_00042 0.9004335 0.8346667
ess_hoc_01328 0.8860238 0.8160677
ess_hoc_00430 0.8856149 0.7838710
ess_hoc_02293 0.8826469 0.8145957
> cat("Excluded zero embedding documents:", sum(!valid_embedding), "\n")
Excluded zero embedding documents: 0 Document vector = count-weighted average of the known token vectors (the approach on Slide 102). The script comments remind us: word order and negation scope disappear in the average; this is a static vector average, not a transformer and not conText/ALC.
R01: readability (Flesch and LIX)
# ==== R01 Readability from original text ====
# After class: full code and E01. In class, the teacher briefly previews saved output.
readability <- textstat_readability(speech_corpus, measure = "Flesch",
remove_hyphens = TRUE, min_sentence_length = 1, max_sentence_length = 10000,
intermediate = TRUE)
readability$words_per_sentence <- readability$W / readability$St
# Installed quanteda.textstats 0.97.2 has no named LIX measure. W7C is its
# intermediate count of words of at least seven characters (= more than six).
readability$LIX <- readability$words_per_sentence + 100 * readability$W7C / readability$W
# Cross-check the implementation's historical LIW label against the transparent formula.
lix_check <- textstat_readability(speech_corpus, measure = "LIW")
stopifnot(isTRUE(all.equal(readability$LIX, lix_check$LIW)))
readability$party <- speeches$party_family[match(readability$document, speeches$doc_id)]
print(head(readability[, c("document", "Flesch", "LIX", "W", "St", "words_per_sentence")], 4), row.names = FALSE)
readability_summary <- aggregate(cbind(Flesch, LIX, words_per_sentence) ~ party,
readability, FUN = median)
print(readability_summary, row.names = FALSE)
# Flesch uses sentence length and estimated English syllables. Higher scores indicate
# easier reading under this formula; they do not measure reader comprehension directly.
# LIX = words/sentences + 100*(words with more than six characters)/words.
# Higher LIX indicates harder reading under this formula. LIX connects to the
# Bischof & Senninger (2018) assigned study; Flesch is a teaching comparison.
# E01: Read one high-LIX and one low-LIX speech, then compare their Flesch scores.
# Which language choices do the formulas capture? Name one important aspect of
# comprehension that they cannot observe. State the opposite score directions.> readability <- textstat_readability(speech_corpus, measure = "Flesch",
+ remove_hyphens = TRUE, min_sentence_length = 1, max_sentence_length = 10000,
+ intermediate = TRUE)
> readability$words_per_sentence <- readability$W / readability$St
> readability$LIX <- readability$words_per_sentence + 100 * readability$W7C / readability$W
> lix_check <- textstat_readability(speech_corpus, measure = "LIW")
> stopifnot(isTRUE(all.equal(readability$LIX, lix_check$LIW)))
> readability$party <- speeches$party_family[match(readability$document, speeches$doc_id)]
> print(head(readability[, c("document", "Flesch", "LIX", "W", "St", "words_per_sentence")], 4), row.names = FALSE)
document Flesch LIX W St words_per_sentence
ess_hoc_00002 67.95802 35.75018 603 42 14.35714
ess_hoc_00211 69.10086 33.34576 322 21 15.33333
ess_hoc_00004 38.39723 54.16042 445 18 24.72222
ess_hoc_00006 44.02528 48.32183 712 28 25.42857
> readability_summary <- aggregate(cbind(Flesch, LIX, words_per_sentence) ~ party,
+ readability, FUN = median)
> print(readability_summary, row.names = FALSE)
party Flesch LIX words_per_sentence
Conservative 58.21930 42.02824 20.46667
Labour 57.24104 42.95662 21.75000LIX = words per sentence + percentage of long words (> 6 characters); higher means harder. Flesch Reading Ease: higher means easier. Party medians: Conservative Flesch 58.22/LIX 42.03, Labour 57.24/42.96. Splitting sentences changes both scores at once, while the policy content stays the same.
Supplementary Slides 95–112: manufacturing, evaluation, emotion measurement, readability
How do presidents talk about manufacturing?
GRS 2022 §8.2.7 (p. 85): US State of the Union addresses, 1900–1959 vs 1960–2016, 53 occurrences of manufacturing in total. ① Collect the words around each occurrence; ② represent them with pretrained embeddings; ③ average within each period and apply a learned linear transformation — à la carte, giving one 300-dimensional manufacturing vector per period. Neighbours: early period exportation, oil-related (trade, energy); later period retooling, jobs, energy-intensive, offshoring (restructuring, employment).
Validating representations for a purpose
| Evaluation | Question |
|---|---|
| Intrinsic | Do the vector relationships match external judgments about words? |
| Extrinsic | Do the vectors help a downstream task, such as predicting labels? |
| Substantive | Can this comparison support the interpretation the research question needs? |
GRS 2022 §8.4, p. 87. Discussion question on the slide: for the manufacturing period contrast, which passages should we read to check it?
W10 comparison: measuring emotion in German political text
Widmann & Wich (2023): 9,898 annotated sentences from parliamentary speeches and party Facebook posts; three routes: an ed8 dictionary expanded with neighbours, word2vec sentence averages + a neural network, and fine-tuned ELECTRA. F1 on held-out sentences:
| Model | Anger | Fear |
|---|---|---|
| ed8 | .59 | .52 |
| word2vec + NN | .79 | .55 |
| ELECTRA | .84 | .64 |
Table 1, p. 634; the authors also test on a new random sample of sentences; robustness checks pp. 635–638.
Evaluating embeddings by purpose
| Purpose of the vectors | What to check |
|---|---|
| Features for prediction | Performance on held-out text or a new corpus |
| Measurement of political language | Human judgments, raw passages, appropriate baselines |
| Cross-corpus comparison | Domain, vocabulary coverage, stability across model settings |
| Social associations | Target and attribute word sets, composition of the source corpus, sensitivity of the comparison |
Rodriguez & Spirling (2022) compare window size, dimensions, multiple training runs and human judgments of word associations (pp. 105–108, 112–113).
Claim check
Reading guide: the three assigned readings
Rodriguez, Spirling & Stewart (2023). Embedding Regression. APSR 117(4): 1255–1274
Full text: Cambridge open-access version (CC BY 4.0), read in full locally; page numbers are journal page numbers.
| Item | Content | Pages |
|---|---|---|
| Research question | Social scientists often want to know how word usage varies with time, party or other document-level covariates, e.g. how the two parties understand “immigration” differently; the authors propose the à la carte on text (conText) embedding regression model to answer this. | p. 1255 (abstract) |
| Data | The main application uses the US Congressional Record, 111th–114th Congresses (Gentzkow, Shapiro & Taddy 2018); there are also a replication of Rodman's (2020) NYT corpus, distinguishing Trump/trump, “Empire” in the UK and US (Hansard vs the Congressional Record), and Conservative backbenchers' sentiment on the EU. | pp. 1257, 1261–1264, 1269–1271 |
| Method | ALC: take the average of the pretrained vectors of the context words around the target word and multiply by a matrix A; A is used to down-weight common but uninformative words in the average. Treat the ALC vector of each occurrence as a multivariate outcome and regress it on group indicators; take the length (norm) of the coefficients, and assess uncertainty with permutation tests and the bootstrap. | pp. 1258–1260, 1264–1265 |
| Findings | ALC performs comparably to the original study on Rodman's corpus and works with few documents; in distinguishing Trump/trump it comes close to RoBERTa. Party differences for immigration are larger than gender differences (Figure 5); Democratic neighbours lean toward reform, Republican ones toward enforcement (Tables 4–5). | pp. 1261–1263, 1266–1267 |
| Limitations and advice | No tuning is needed, but choices remain: window size, preprocessing; preprocessing of ALC contexts should match that used to estimate the embeddings and A; with little data, large pretrained vectors (e.g. Stanford GloVe) are a reasonable approximation, and a corpus-specific A can be estimated. The final substantive interpretation still needs to be validated by the researcher (semantic, aggregate construct, predictive validity, etc.). | pp. 1268–1270 |
| Relation to this week's methods | This is exactly conText() in Lab B; ch06–ch07, ch09. | — |
Rodriguez & Spirling (2022). Word Embeddings: What Works, What Doesn’t, and How to Tell the Difference for Applied Research. JOP 84(1): 101–115
Full text: not available locally (JOP is not open access). The table below is based only on Slide 110 and the reading README; page numbers are those cited on the slide.
| Item | Content based on the slides |
|---|---|
| Topic | Choosing and evaluating word embeddings for research tasks (README). |
| Approach | Compares window size, dimensions and multiple training runs, against human judgments of word associations (pp. 105–108, 112–113). |
| Relation to this week | The basis for "evaluate embeddings by purpose" on Slide 110; the experiments in RSS (2023) also extend it (RSS 2023 p. 1268). |
Bischof & Senninger (2018). Simple Politics for the People? EJPR 57(2): 473–495
Full text: Unpaywall points to the accepted manuscript on Aarhus University's Pure, but the local download returned a web page rather than a PDF, so the full text was not read. The table below is based only on Slides 111–112.
| Item | Content based on the slides |
|---|---|
| Research question | The simpler a party manifesto, the closer are voters' left–right placements of the party to expert placements? (pp. 477–481, 486–490) |
| Data and measurement | German and Austrian party manifestos, complexity measured with LIX; voters' and experts' left–right placements compared. |
| Findings | The simpler the manifesto, the smaller the placement gap. |
| Measurement note | Higher LIX is more complex, higher Flesch is easier; splitting sentences changes the scores but not the policy content (p. 479). |
| Relation to this week | R01 in W9.R (ch10). |
For Rodriguez & Spirling (2022), use your library access to download it from doi:10.1086/715162; for Bischof & Senninger (2018), the accepted manuscript can be downloaded from doi:10.1111/1475-6765.12235 or the Aarhus University Pure page. With the full texts, complete reading cards with page numbers can be added later.
Common pitfalls and glossary
Ten common pitfalls
WordEmbeddings("glove") is a static lookup; the three security vectors have cosine = 1.
The 11-word plot retains only 38.24%, and the 30-dimensional model in W9.R only 9.54%; nearest in 2D is discussed, nearest in full dimensions is resolution.
Rheault & Cochrane read it that way only after validating against Voteview (r = 0.918).
For Rodman's social–equality you need to go back and read the passages.
Müller & Proksch: agreement after expansion .61 → .54.
cr_glove_subset and cr_transform are a pair; if you switch to your own vectors you need your own A.
In conText a row is one occurrence (924 contexts, not 400 speeches).
Only party_R in C05 holds gender fixed.
Current conText reports the debiased squared norm, the paper the L2 norm; the data also differ.
Passages only illustrate a contrast; estimating frequency needs a broader sample. In C04, D/R are the queried average vectors, not the speakers.
Glossary
Final review, research design and references
Final test (20 questions)
Designing an embedding study in one paragraph
The three steps on Slide 92: ① start from the political question and "what gets a vector"; ② choose the corpus, representation and comparison for this question; ③ identify evidence that could change the interpretation. Prompt: How would you compare the usage of a policy term across parties, periods or legislative venues?
Learning progress
References
W9 assigned readings
- Bischof, Daniel, and Roman Senninger. 2018. “Simple Politics for the People? Complexity in Campaign Messages and Political Knowledge.” European Journal of Political Research 57(2): 473–495. doi:10.1111/1475-6765.12235
- Rodriguez, Pedro L., and Arthur Spirling. 2022. “Word Embeddings: What Works, What Doesn’t, and How to Tell the Difference for Applied Research.” The Journal of Politics 84(1): 101–115. doi:10.1086/715162
- Rodriguez, Pedro L., Arthur Spirling, and Brandon M. Stewart. 2023. “Embedding Regression: Models for Context-Specific Description and Inference.” American Political Science Review 117(4): 1255–1274. doi:10.1017/S0003055422001228
Cases and further reading
- Rheault, Ludovic, and Christopher Cochrane. 2020. “Word Embeddings for the Analysis of Ideological Placement in Parliamentary Corpora.” Political Analysis 28(1): 112–133. doi:10.1017/pan.2019.26
- Rodman, Emma. 2020. “A Timely Intervention: Tracking the Changing Meanings of Political Concepts with Word Vectors.” Political Analysis 28(1): 87–111. doi:10.1017/pan.2019.23
- Müller, Stefan, and Sven-Oliver Proksch. 2024. “Nostalgia in European Party Politics: A Text-Based Measurement Approach.” British Journal of Political Science 54(3): 993–1005. doi:10.1017/S0007123423000571 (W10 optional reading)
- Wirsching, Elisa M., Pedro L. Rodriguez, Arthur Spirling, and Brandon M. Stewart. 2025. “Multilanguage Word Embeddings for Social Scientists.” Political Analysis 33(2): 156–163. doi:10.1017/pan.2024.17
- Widmann, Tobias, and Maximilian Wich. 2023. “Creating and Comparing Dictionary, Word Embedding, and Transformer-Based Models to Measure Discrete Emotions in German Political Text.” Political Analysis. doi:10.1017/pan.2022.15 (W10 comparison)
- Gonthier (2025) doi:10.1111/spsr.12649; Karell & Sachs (2023) doi:10.1177/23780231231212108; Van Matre et al. (2026) doi:10.1111/psj.70079; Kim & Kesari (2021) doi:10.54501/jots.v1i1.13
Textbook, course materials and software
- Grimmer, J., M. E. Roberts, and B. M. Stewart. 2022. Text as Data. Princeton University Press. Chapter 8 (Chapter 7: similarity and TF–IDF).
- Schoonvelde, Martijn. 2026. Essex Summer School, Introduction to Quantitative Text Analysis, Day 3, “Comparing representations.”
- conText (R) Quick Start: github.com/prodriguezsosa/conText; Flair 0.15.1
WordEmbeddings("glove"); quanteda, quanteda.textstats.