⌂ Course index
🐞 Feedback
中文
The interactive features failed to initialise, so the page has switched to a static version with all chapters expanded in order; just scroll down to read. (The interactive labs, quiz grading, progress tracking and the slide panel need JavaScript; if you cannot see the interactive parts in an in-app preview, use "Share → Open in Safari" or open the file in a desktop browser.)
00 · Week overview

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

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.

Plain-language version (Supplement)

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 Slides 77, 92

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:

  1. What vectors represent: distinguish "one vector per word type" (static GloVe) from "one vector per occurrence" (ALC / conText).
  2. How to compare: compute and read cosine; know that distances on a 2D PCA plot are not the same as full-dimensional cosine.
  3. The four cases: for each study, "what gets a vector, what is compared, and what evidence supports the political interpretation".
  4. conText results: explain what party_R compares "holding gender fixed", and support it with one neighbour word and one context.
  5. 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) Slides 16, 77, 80

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:

→ → → → →
SegmentSlidesQuestion (paraphrased from the README)
Concepts and research map1–16What do vectors represent? How are they learned?
Case 1 · Rheault & Cochrane17–26Can parliamentary language position parties?
Case 2 · Rodman27–36Can word associations reveal conceptual change?
Case 3 · Müller & Proksch37–46How do neighbour words help build and validate a nostalgia measure?
Case 4 · Embedding regression47–71How do we compare different groups' use of the same word?
Multilingual resources and applications72–76Where else is this method used?
Lab overview and break77–80What will the Lab compare?
Flair and PCA81–85Load GloVe, get vectors, compare security, read the projection plot
conText86–91Build context vectors, read neighbours and passages, compare parties holding gender fixed
Research design and references92–94What evidence can support our own comparisons?
Supplement95–112Extra concepts, sentiment measurement, evaluation, readability

The four cases at a glance Slides 16, 109

CaseTextWhat gets a vectorHow the question is answered
1 · Rheault & Cochrane (2020)Parliamentary speechesA 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 headlineA word in a historical periodCosine tracks associations; news passages show what changed
3 · Müller & Proksch (2024)European party manifestosSeed words and candidate wordsNeighbours expand the dictionary; scores enter a regression
4 · Rodriguez, Spirling & Stewart (2023)U.S. Congressional RecordEach occurrence of the target wordRegression 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 Slide N 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

1. Compared with the W8 topic models, what core question does W9 answer?
Slide 3: W8 asks “What do actors discuss, and how much?”; W9 asks “How can learned vectors describe and compare political language?” Slide 3
2. In Case 4 (embedding regression), what gets a vector?
Slide 109, row 4: “One use of a target word”. Party-term is Case 1; word × period is Case 2. Slide 109
3. How are this week's 30 Lab minutes divided?
Slide 80: “Our 2024 Flair exercise and plots (15 min) → conText Quick Start (15 min)”. Slide 80
01 · Vector intuition

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

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.

Interactive: one-hot vs embeddings (Supplement (not from the lecture), toy numbers)

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 Slides 7–10

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.

Interactive: drag the window size, click a word as the target (Supplement (not from the lecture))

Cosine calculator Slide 101

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

Interactive: change the numbers and watch cosine (defaults = slide 101)
securityforcesenergy
Defence (a)
Energy (b)
Why cosine rather than distance? (Supplement)

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 Slides 95–99

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

1. With window c = 2, target word cat, and the sentence “The cute cat jumps over …”, what is the context?
c = 1 gives cute, jumps; c = 2 adds The, over. Slide 7
2. What is the difference between CBOW and Skip-gram?
Slides 7, 11: CBOW: context → word; Skip-gram: word → context. Slides 7, 11
3. The cosine of the two speeches on slide 101 is 0.50. If every Defence count is multiplied by 10, what does cosine become?
Cosine looks only at direction. Numerator and denominator are both multiplied by 10, so the ratio is unchanged. (Supplementary reasoning; you can verify it with the calculator above.)
02 · Training choices

Training choices determine what kind of vectors you get

Four methods, two kinds of representation Slides 11–15

Method or interfaceLearning signalRepresentation
Word2VecCBOW: context → word; Skip-gram: word → contextStatic word vectors
GloVe (Global Vectors for Word Representation)Fits co-occurrence statistics of the whole corpusStatic word vectors
fastTextPredicts from context with character n-gramsStatic word vectors
FlairEmbeddingsA character language model uses the surrounding textContextual 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.

Easy to confuse

"Using Flair" ≠ "using contextual vectors". WordEmbeddings("glove") is a lookup table: the same word type always returns the same row. Slides 11, 84

What does each row represent? Slide 100

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

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

Interactive: averaging calculator (defaults = slide 102)

Flip cards: static or contextual?

Chapter quiz

1. In the table on slide 11, which one produces "contextual token vectors"?
Only FlairEmbeddings is labelled Contextual token vector. Slide 11
2. What is the biggest difference between fastText and Word2Vec?
Slide 11: fastText “Predict from context with character n-grams.” Co-occurrence statistics are GloVe. Slide 11
3. A document has 3 tokens: (1,0), (0,2), (1,0). What is the simple average?
(1+0+1)/3 = 0.67, (0+2+0)/3 = 0.67. Repeated tokens contribute repeatedly. Slide 102
03 · Case 1

Case 1 · Rheault & Cochrane (2020): positioning parties from parliamentary speech

Question and data Slide 17

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 Slides 18–20

  1. Predict: the model predicts a word (the example is work) from the context plus a party-term label.
  2. Represent: each party-term gets a vector, e.g. Labour 2005.
  3. 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 Slides 21–23

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 Slides 24–26

U.S. House (1921–2016)Figure
Correlation between speech-based PC1 and Voteview party averages0.918
Agreement rate of pairwise party-term orderings85.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)

Why external validation? (Supplement)

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

1. In Rheault & Cochrane, what gets a vector?
“The model represents each party in each legislative term.” Slide 17
2. What is 0.918?
U.S. House: Speech-based PC1 correlates 0.918 with Voteview party averages (1921–2016). Slide 24
3. Claim check: "PC1 is the direction of greatest variation, so it must be left–right ideology."
Slide 24: “We can read PC1 as a left–right scale in this overlapping period. Agreement varies across benchmarks.” Slide 24
04 · Case 2

Case 2 · Rodman (2020): how the meaning of equality changes

Question and data Slide 27

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 Slides 28–30

Research stepWhat Rodman does
Collect contextsUses the headline, abstract and (if available) first paragraph; splits the articles into seven eras.
Estimate embeddingsCompares four Word2Vec training schemes, each producing word vectors for every era.
Track associationsComputes 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? Slides 31–33

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)

Why this step matters (Supplement)

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

Interactive: read the figure step by step (numbers from slides 34 / 36, author's manuscript Figure 4, p. 29)
Discussion question on slide 34

"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

1. What is Rodman's corpus?
Slide 27
2. How does Rodman choose the chronological model?
Slide 31
3. Claim check: "The social–equality cosine rebounding from .19 to .30 proves that the 19th-century usage has continued to this day."
Slide 36
05 · Case 3

Case 3 · Müller & Proksch (2024): building a nostalgia dictionary from neighbour words

Question and data Slide 37

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

  1. Find candidate words: search for neighbours of the seed words in pretrained GloVe and in vectors trained on the manifestos.
  2. Screen: three coders review the neighbour words; the words that pass form the embeddings-based dictionary.
  3. 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.

Interactive: be a screening coder (Supplement (not from the lecture))

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 Slides 41–43

They compare manifesto scores from dictionaries (M1–M4) and sentence classifiers (M5–M6), checking 50 manifestos against two coders:

MethodAgreement with coders (slide figures)
Base dictionary (base).61
Expanded dictionary (expanded, adding embedding neighbours).54
SVM (sentence classifier).87
DistilBERT (sentence classifier).86
Key point: agreement actually drops after expansion

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 Slides 44–46

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

1. In Müller & Proksch, what role do embeddings play?
Slides 38, 109
2. What does the expanded dictionary (.54) compared with the base dictionary (.61) mean?
Slide 43
3. How should ".07–.10" be read?
Slide 44
06 · Case 4 intuition

Case 4 intuition: same word, different contexts → ALC → regression

chips: British fries, American crisps Slides 47–49

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 Slides 50–53

  1. Look up: look up the vectors of the context words in the same pretrained space.
  2. Average: ui = (1/|Ci|) Σw∈Ci vw (the words around this occurrence).
  3. 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.

Why is A needed? (Supplement, based on RSS 2023 p. 1259)

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

Interactive: pick context words → average → multiply by A → see which meaning it is closer to

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 Slides 54–57

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)

Plain language (Supplement)

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

StepContent
1 · One row per occurrenceKeep the context, party and gender. n uses → an n × D outcome matrix Y.
2 · Build outcome vectorsAverage the context word vectors (excluding the target word), then apply the shared ALC transformation: ui = mean vw, yi = A ui.
3 · Regress on every coordinateyi = α + 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

1. What is the third ALC step, "calibrate"?
Slide 50
2. In yi = β0 + UKiβUK + εi, what is βUK?
“Both coefficients are D-coordinate vectors… we use coefficient length for the size of the difference.” Slide 54
3. Why must E (pretrained vectors) and A (transformation matrix) be matched?
Slide 59: “E and A: a matched pair.” See also the README: the conText example has its own 300-dimensional vectors and a matching ALC transformation. Slides 59, 86
07 · Case 4 results

Case 4 results: immigration, multilingual extensions and other applications

Question and data Slide 58

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

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)

Interactive: paper lengths vs this week's Lab numbers (do not compare them directly)

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 Slides 66–68

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 Slides 69–71

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

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.

Extension tip (Supplement)

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 Slides 73–76

StudyComparison
Gonthier (2025) · SPSRHow different ideological groups use the French word peuple
Van Matre et al. (2026) · PSJClimate frames × party × Congress
Karell & Sachs (2023) · SociusMinority 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

1. In the paper, what is the length of the party difference for immigration (holding gender fixed)?
.175 is from the paper's Figure 5; .087 is gender; 8.668 is this week's Lab bias-corrected squared length, in different units. Slides 63, 91
2. Why look at neighbour words and passages after seeing the length of β?
Slides 54, 66, 69
3. Claim check: "The Democratic passages in Table 5 talk about reform, so most Democratic legislators talk about reform when they discuss immigration."
“These passages illustrate the contrast. To estimate frequency, we need a broader sample.” Slide 69
08 · Lab A: Flair

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

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.

How it was run locally (honestly)

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.

Before-class setup suggestion (Supplement)

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

In class we use the R version flair_steps.R (its three parts map one-to-one to the Python version):

W9/lab/flair/flair_steps.R
# 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 output (run locally: Python 3.11.2, flair 0.15.1, torch 2.5.1, numpy 1.26.4, gensim 4.4.0)
$ 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.]]
CheckpointSlidesLocal
embedding_length100 (Slide 82)100 ✓
Matrix of 11 words11 × 100 (Slide 83)(11, 100) ✓
security in three sentences3 × 100, pairwise cosine 1 (Slide 84)(3, 100), all 1 ✓
Why are the three security vectors identical?

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

11 × 11 full-dimensional cosine (actually run locally with flair_lab.py --run) Slides 83, 85

Interactive: click a cell to see that pair's cosine; click a word name to see its ranking

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

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 output (run locally: Python 3.11.2, flair 0.15.1, torch 2.5.1, numpy 1.26.4, gensim 4.4.0)
$ 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.
Interactive: click a word on the PC1–PC2 plot and compare "nearest on the plot" with "nearest by full-dimensional cosine"
PCA Check: what does the projection leave out?

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.Slides 78, 85

E06 answer box Slide 84

E06: explain the two matrix sizes and why the security vectors are identical; if you ran the code, note your route and versions

Chapter quiz

1. In the 11 × 100 word_vectors, what are the rows and columns?
Slide 83
2. The three security vectors have pairwise cosine = 1 because?
Slide 84
3. "PC1 + PC2 retain 38.24%" means?
Slide 85
09 · Lab B: conText

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

R · C00 (W9/classroom/W9-conText.R)
# ==== 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.
R console output (run locally: conText 3.0.1, quanteda 4.5.1, text2vec 0.6.6)
> 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  300

The 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 Slide 87

R · C01 (W9/classroom/W9-conText.R)
# ==== 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.
R console output (run locally: conText 3.0.1, quanteda 4.5.1, text2vec 0.6.6)
> 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.402

924 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 Slide 88

R · C02 (W9/classroom/W9-conText.R)
# ==== 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.
R console output (run locally: conText 3.0.1, quanteda 4.5.1, text2vec 0.6.6)
> 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  300

DEM 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 Slide 89

R · C03 (W9/classroom/W9-conText.R)
# ==== 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.
R console output (run locally: conText 3.0.1, quanteda 4.5.1, text2vec 0.6.6)
> 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 89Local
D neighboursimmigration (0.848), broken (0.680), comprehensive (0.661)Same ✓
R neighboursimmigration (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 Slide 90

R · C04 (W9/classroom/W9-conText.R)
# ==== 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.
R console output (run locally: conText 3.0.1, quanteda 4.5.1, text2vec 0.6.6)
> 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 means

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

Each row is one use; score = cosine of this ALC vector with the D average and the R average (exported from local C02)

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

R · C05 (W9/classroom/W9-conText.R)
# ==== 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.
R console output (run locally: conText 3.0.1, quanteda 4.5.1, text2vec 0.6.6)
> 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
CoefficientSlide 91: debiased squared normLocal deflatedLocal orig (not debiased)Permutation p
party_R8.6688.66810.1400
gender_M5.1555.1556.9090
Three cautions when reading this table

① 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.Slides 63, 91

E04: connecting one observation, the evidence and the coefficient Slides 79, 91

Paragraph assembler: pick one sentence per slot to build an E04 answer
E04 answer draft

Chapter quiz

1. What does the 924 in C01 refer to?
Slide 87
2. What data does conText() take in C05?
Script comment: “Input is the original processed tokens with metadata, not the DEM.” Slide 91
3. What does “D:” in the C04 output mean?
“D/R label the queried party vector, not the source speaker.” Slide 90
10 · Classroom R: W9.R

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

R · R00 (W9/classroom/W9.R)
# ==== 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.
R console output (run locally: R 4.5.3 (aarch64-conda-linux-gnu), quanteda 4.5.1, quanteda.textstats 0.97.2)
> 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-26

R05: static word vectors and raw contexts

R · R05 (W9/classroom/W9.R)
# ==== 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.
R console output (run locally: R 4.5.3 (aarch64-conda-linux-gnu), quanteda 4.5.1, quanteda.textstats 0.97.2)
> 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 security

Every 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

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

R console output (actually run locally)
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 ✓.

Interactive: PCA map of 1,653 words vs full-dimensional cosine (real 30-dimensional vectors)
Nearest by full 30-dimensional cosine
Nearest on the 2D map (Euclidean distance)

Raw contexts of security (real KWIC, 60 sampled / 144 total)

E04 (W9.R version): pick a neighbour word, find a KWIC line that supports it, then find a different use of security

R06: averaging known word vectors and reporting coverage (after class)

R · R06 (W9/classroom/W9.R)
# ==== 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?
R console output (run locally: R 4.5.3 (aarch64-conda-linux-gnu), quanteda 4.5.1, quanteda.textstats 0.97.2)
> 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) Slides 111–112

R · R01 (W9/classroom/W9.R)
# ==== 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.
R console output (run locally: R 4.5.3 (aarch64-conda-linux-gnu), quanteda 4.5.1, quanteda.textstats 0.97.2)
> 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.75000
Opposite directions

LIX = 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.Slide 112

11 · Supplementary slides

Supplementary Slides 95–112: manufacturing, evaluation, emotion measurement, readability

How do presidents talk about manufacturing? Slides 104–105

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

EvaluationQuestion
IntrinsicDo the vector relationships match external judgments about words?
ExtrinsicDo the vectors help a downstream task, such as predicting labels?
SubstantiveCan 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 Slides 107–108

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:

ModelAngerFear
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 Slide 110

Purpose of the vectorsWhat to check
Features for predictionPerformance on held-out text or a new corpus
Measurement of political languageHuman judgments, raw passages, appropriate baselines
Cross-corpus comparisonDomain, vocabulary coverage, stability across model settings
Social associationsTarget 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

"The 30-dimensional GloVe in W9.R says the word nearest to security is resolution, so British party leaders understand security as UN resolutions."
Data/README.md: “produces visibly noisy neighbours. It is not a validated semantic measure.”
"ELECTRA's Anger F1 of .84 is higher than ed8's .59, so dictionary methods are useless."
Slides 108, 110 (supplementary inference)
"LIX rising from 40 to 45 means this manifesto became easier to read."
Slide 112
12 · Reading guide

Reading guide: the three assigned readings

Rodriguez, Spirling & Stewart (2023). Embedding Regression. APSR 117(4): 1255–1274 Slides 58–71

Full text: Cambridge open-access version (CC BY 4.0), read in full locally; page numbers are journal page numbers.

ItemContentPages
Research questionSocial 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)
DataThe 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
MethodALC: 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
FindingsALC 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 adviceNo 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 methodsThis 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 Slide 110

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.

ItemContent based on the slides
TopicChoosing and evaluating word embeddings for research tasks (README).
ApproachCompares window size, dimensions and multiple training runs, against human judgments of word associations (pp. 105–108, 112–113).
Relation to this weekThe 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 Slides 111–112

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.

ItemContent based on the slides
Research questionThe simpler a party manifesto, the closer are voters' left–right placements of the party to expert placements? (pp. 477–481, 486–490)
Data and measurementGerman and Austrian party manifestos, complexity measured with LIX; voters' and experts' left–right placements compared.
FindingsThe simpler the manifesto, the smaller the placement gap.
Measurement noteHigher LIX is more complex, higher Flesch is easier; splitting sentences changes the scores but not the policy content (p. 479).
Relation to this weekR01 in W9.R (ch10).
To fill in the full texts

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.

13 · Pitfalls and glossary

Common pitfalls and glossary

Ten common pitfalls

1. Assuming Flair is always contextualized

WordEmbeddings("glove") is a static lookup; the three security vectors have cosine = 1.Slides 11, 84

2. Treating distance on a PCA plot as similarity

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.Slides 85, 103

3. Calling PC1 ideology outright

Rheault & Cochrane read it that way only after validating against Voteview (r = 0.918).Slide 24

4. Cosine rising again = the old usage is back

For Rodman's social–equality you need to go back and read the passages.Slide 36

5. Embedding-expanded dictionaries are always better

Müller & Proksch: agreement after expansion .61 → .54.Slide 43

6. Mixing and matching E and A

cr_glove_subset and cr_transform are a pair; if you switch to your own vectors you need your own A.Slides 59, 86

7. One row = one speech

In conText a row is one occurrence (924 contexts, not 400 speeches).Slide 87

8. Treating the C02 averages as an adjusted comparison

Only party_R in C05 holds gender fixed.Slides 89, 91

9. Comparing 8.668 with the paper's .175

Current conText reports the debiased squared norm, the paper the L2 norm; the data also differ.Slides 63, 91

10. Using one hand-picked passage to represent a party

Passages only illustrate a contrast; estimating frequency needs a broader sample. In C04, D/R are the queried average vectors, not the speakers.Slides 69, 90

Glossary

14 · Final review

Final review, research design and references

Final test (20 questions)

Not answered yet

Designing an embedding study in one paragraph Slide 92

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?

Plan builder (exports Markdown, can be used for the assignment)
Markdown

Learning progress

References Slides 93–94

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.
These notes are based on the NTLDEV 7191 W9 slides (Yen-Chieh Liao, slides dated 2026-11-06; PDF, 112 pages), W9/README.md, W9/lab/README.md, W9/reading/README.md, W9/classroom/W9.R, W9-conText.R, W9/classroom/Data/README.md and W9/lab/flair/ (upstream commit 3ffaf9f). R output was re-run locally (R 4.5.3 (aarch64-conda-linux-gnu), quanteda 4.5.1, quanteda.textstats 0.97.2; conText: conText 3.0.1, quanteda 4.5.1, text2vec 0.6.6); Flair was run locally via the Python route (Python 3.11.2, flair 0.15.1, torch 2.5.1, numpy 1.26.4, gensim 4.4.0). The RSS (2023) reading card is based on the open-access full text; the other two are based only on the slides. Sections and toy demos marked "Supplement (not from the lecture)" are additional explanations. Prepared on 2026-11-13.
NTLDEV 7191 Text as Data · W9 interactive self-study notes · based on the 2026-11-06 lecture slides (2026-11-13)