⌂ Course index
🐞 Feedback
中文
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 slide panel need JavaScript; if the in-app preview shows no interactivity, use “Share → Open in Safari” or open the file in a desktop browser.)
00 · Week overview

W4: Dictionaries and Sentiment Analysis

W2 split text into tokens and built a DFM; W4 takes the next step: first define the concept to be measured, then use a “word → category” lookup table (a dictionary) to turn text into scores, and finally use human judgement to validate what the score actually measures.

This week’s learning objectives Slide 2

Slide 2 lists five objectives; the first four correspond to the four main parts of these notes, and the fifth connects to your own final project. Come back and tick them off when you have finished:

  1. Measurement: state clearly what a dictionary score is “intended to measure”. (Chapters 00, 04)
  2. Dictionary construction: build and revise word or phrase lists from political texts. (Chapters 02, 03, 06)
  3. Scoring: turn matches into scores, and explain the denominator and texts with “no matches at all”. (Chapters 04, 05)
  4. Validation: assess validity using published evidence and human judgement. (Chapters 07, 08)
  5. Own project: plan a dictionary measure for your own research. (The plan builder in Chapters 11 and 14)

A political science research question Slide 3

This week’s guiding question: When do MPs describe household economic conditions negatively? The example sentence is “Families cannot afford rent or energy bills.” We could compare speakers, periods, or government vs. opposition.

The key is to read two things at once: rent tells us the issue (household costs), while cannot afford is the evaluation (hardship). The slide’s reminder: mentioning inflation does not tell us how an MP evaluates household conditions. Slide 3

Attention, sentiment, stance: three different questions Slide 4

ConceptQuestion askedExample on the slide
Issue attentionWhat is mentioned?This speech discusses energy bills.
SentimentHow is something evaluated?High energy bills are hurting families.
StanceWhat position is taken towards a target?I support the government’s price cap.
Key point of slide 4

Negative words used to describe a problem may come together with support for a policy. “Negative sentiment” is not the same as “opposition”.

One measurement workflow Slide 5

Click each step below to see the explanation (content taken from slide 5):

1
Find relevant sentences
→
2
Code evaluation and target
→
3
Compare with human judgement
→
4
Compare speakers or periods
  1. Find relevant sentences: household income, cost of living, affordability.
  2. Code the evaluation and its target: how are household conditions described?
  3. Validate against human judgement: include both texts the dictionary matched and texts it did not match.
  4. Compare speakers or periods: relevant sentences judged negative ÷ all relevant sentences.

Slide 5 is also candid: today’s class practises two things separately — counting issue mentions and counting positive and negative words. To really answer the opening question we would still need to link the “evaluation” to its “target”, and that step is not completed today. Slide 5

Construct, indicator, score, claim Slide 6

LevelConcrete example (slide 6)
ConstructHow much MPs talk about household costs
IndicatorCount matches of terms such as rent and energy bills (one phrase match)
ScoreSpeech A: 4 matches / 100 words = 4 per 100 words; Speech B: 4 / 200 = 2 per 100 words
ClaimPer 100 words, A has twice as many household-cost matches as B
🧮Quick calculation: the same 4 matches, different denominatorsNumbers from slide 6
The default values reproduce slide 6: A = 4 per 100, B = 2 per 100.

Note the last sentence of slide 6: this only counts mentions; to measure negative evaluation we also need to recognise language such as cannot afford.

Same corpus, different units of analysis Slide 7

Text unitCorresponding political science question
SentenceWhich statements describe household hardship?
SpeechWhat share of a speech discusses hardship?
Speaker-periodHow does a speaker’s attention change over time?

This week’s practice data: 5,000 UK House of Commons speeches, 1945–2025 (Data/hc_sample_1945_2025.rds). When splitting or combining texts, keep the speaker, date and source ID. Slide 7

Exercise: which concept does this sentence measure?

Choose one for each sentence: issue attention, sentiment or stance. (The sentences are adapted from the concepts on slides 3–4 and 66; the reasoning is shown after you answer.)

🧩Concept sorterExercise
When you have chosen, click “Check”.

How to use these notes

  • Each chapter has a slide panel on the right (wide screens) or behind the bottom-right button (phones); it turns the page automatically when you scroll to a passage marked “Slide N”.
  • R code is taken from W4/classroom/W4_classroom.R (C01–C16) and the after-class W4/lab/Lab_Session_W4.R; all output is from actually running it locally (R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64) and has been checked against the numbers on the slides one by one.
  • There are three kinds of interactive components: real data (exported from this week’s Data/), toy intuition (marked “Supplement (not from the lecture)”), and exercises (answer boxes, flip cards, claim judgements, plan builder).
  • Progress and answers are stored only in this browser; the sidebar shows how much you have completed.
End-of-chapter quiz: “High energy bills are hurting families.” mainly corresponds to which concept?
Slide 4 uses this sentence as the example of sentiment: it evaluates the effect of energy bills but does not take a position for or against any policy. Slide 4
Speech A has 4 matches in 100 words; speech B has 4 matches in 200 words. Which statement is correct?
The score depends on the denominator. The claim on slide 6 is a comparison “per 100 words”. Slide 6
01 · Building intuition first

Bag of words, DFM and dictionaries

Dictionary methods build on W2’s bag of words: documents are split into tokens and counted into a document × feature table (DFM). This chapter first runs C01 to load the data, then uses a small two-sentence example to make DFMs, document length and dictionary matching clear.

C01: set up once, use for the whole class Slide 8

Each document is one parliamentary speech contribution. C01 locates workflow.R, switches the working directory and source()s it; workflow.R prepares in one go the objects used later: speeches, discovery_tokens, comparison, check_scores, policy_scores, validation, etc. After that, keep the same R session.

R · C01 (W4/classroom/W4_classroom.R)
# C01: Setup
# First use: uncomment the next line to install.
# install.packages(c("quanteda", "quanteda.textstats"))
library(quanteda)
library(quanteda.textstats)
paths <- c("workflow.R", "W4/classroom/workflow.R",
           "classroom/workflow.R", "../classroom/workflow.R")
found <- paths[file.exists(paths)]
if (length(found) == 0) found <- file.choose()
setwd(dirname(normalizePath(found[1])))
source("workflow.R")
R console output (run locally, W4_classroom.R: R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64)
> library(quanteda)
Package version: 4.5.1
Unicode version: 17.0
ICU version: 78.3
Parallel computing: 2 of 2 threads used.
See https://quanteda.io for tutorials and examples.

> library(quanteda.textstats)

> paths <- c("workflow.R", "W4/classroom/workflow.R",
+            "classroom/workflow.R", "../classroom/workflow.R")

> found <- paths[file.exists(paths)]

> if (length(found) == 0) found <- file.choose()

> setwd(dirname(normalizePath(found[1])))

> source("workflow.R")
What workflow.R does for you (summarised from the source code)
  • Reads hc_sample_1945_2025.rds (checks 5,000 rows with no missing text) and gives each speech an ID speech_0001….
  • toks: punctuation removed, lowercased; lengths_original = the number of tokens per speech, and every later “per 100 words” or “per 1,000 words” denominator uses it.
  • policy_tokens: a second token stream that keeps punctuation, used specifically for phrase matching so that phrases do not run across full stops.
  • With a fixed seed set.seed(719104) it draws 80 speeches as the hand-coding sample (30 development + 50 test); discovery_tokens = the 4,950 speeches left after removing the 50 test speeches. Use only discovery to find terms; keep test for testing (end of Chapter 02, Chapter 07).

C02: counts and document length Slides 9–10

Predict first: what will prices be in row A?

R · C02 (W4/classroom/W4_classroom.R)
# C02: Counts and document length
library(quanteda)
demo <- c(A = "Prices rise. Prices worry voters.",
          B = "Prices fall.")
demo_tokens <- tokens(demo, remove_punct = TRUE)
demo_dfm <- dfm(demo_tokens)
selected <- dfm_match(demo_dfm, c("prices", "rise", "fall"))
as.matrix(selected)
ntoken(demo_tokens)
R console output (run locally, W4_classroom.R: R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64)
> library(quanteda)

> demo <- c(A = "Prices rise. Prices worry voters.",
+           B = "Prices fall.")

> demo_tokens <- tokens(demo, remove_punct = TRUE)

> demo_dfm <- dfm(demo_tokens)

> selected <- dfm_match(demo_dfm, c("prices", "rise", "fall"))

> as.matrix(selected)
    features
docs prices rise fall
   A      2    1    0
   B      1    0    1

> ntoken(demo_tokens)
A B 
5 2 
  • Rows = documents; columns = the selected words; each cell is a count. Row A: prices 2, rise 1, fall 0. Slide 10
  • Length is different: A has 5 tokens, but the table only shows 3 counts — worry and voters were not selected. This foreshadows why the denominator later has to use all tokens.
  • dfm() lowercases by default, so Prices and prices are the same column.

Interactive: build your own DFM

🧱Mini tokens → DFMToy intuition · defaults = the C02 example on slide 9

Supplement (not from the lecture): the tokenisation rule here is simplified (split on spaces and punctuation). For short English sentences it agrees with quanteda, but it does not handle details such as hyphens or contractions.

What a word-count table throws away Slide 11

The government does not support the opposition.

The opposition does not support the government.

The same bag of words, but who does what to whom is completely reversed. This is also why, after this point, W4 discusses phrases (Chapter 03), negation (Chapter 05) and “sentiment ≠ stance” (Chapter 08). Paste the two sentences into A and B in the interactive component above and clear the features box, and you will see two identical rows.

What is a dictionary? Slide 12

A dictionary maps “expressions” to categories defined in advance. In quanteda:

R · Slide 12
library(quanteda)
dic <- dictionary(list(
  household_costs = c("inflation", "rent", "energy bills"),
  employment = c("unemployment", "job security")
))

Slide 12: mentioning household costs does not, by itself, prove economic hardship.

Applying our dictionary Slide 13

The instructor combined slides 12–13 into one self-contained file, examples/W4_dictionary_simple.R. Local output:

R console output (run locally, examples/W4_dictionary_simple.R)
> library(quanteda)

> dic <- dictionary(list(
+   household_costs = c("inflation", "rent", "energy bills"),
+   employment = c("unemployment", "job security")
+ ))

> texts <- c("Rent and energy bills are rising.",
+            "We need job security.")

> example_tokens <- tokens(texts, remove_punct = FALSE)

> matched <- tokens_lookup(example_tokens, dic, capkeys = FALSE)

> counts <- dfm(matched)

> as.matrix(counts)
       features
docs    household_costs employment
  text1               2          0
  text2               0          1

rent + energy bills give 2 matches; job security gives 1. Note that energy bills is a phrase: tokens_lookup() looks for the two consecutive words in the token sequence and counts them once. This agrees with the table on slide 13. Slide 13

In C02 the counts shown in row A add up to 3, but ntoken() is 5. Why?
Slide 10: Length is different… worry and voters are not shown. Slide 10
With the dictionary on slide 12, how many times does household_costs match in “Rent and energy bills are rising.”?
A phrase counts as one match as a whole. Slide 13
02 · Building the dictionary

Finding candidate terms: frequency, KWIC, collocations, keyness

A dictionary can be reused, adapted or built from scratch, but “available” does not mean “suitable”. This chapter runs C03–C06, using four tools to find candidate terms in the 4,950 discovery speeches, and goes back to read the context at every step.

Reuse, adapt, or build? Slide 14

ChoiceMain question
Existing dictionaryDoes its original domain fit this corpus?
Adapted dictionaryWhich changes improve performance here?
New dictionaryCan we document the coverage and the exclusion rules?
Use another methodIs the category so context-dependent that word rules cannot hold up?

Slide 14: Availability is not evidence of suitability. Grimmer & Stewart (2013, pp. 274–275) cite the example from Loughran & McDonald (2011): tax, cost, crude (oil) and cancer carry negative connotations in other contexts, but in company financial reports they may carry positive connotations (see the Chapter 12 reading guide).

Four steps to building or adapting a word list Slide 15

  1. Write down what should count, with one example of what should not count.
  2. Read passages that do and do not discuss the issue.
  3. List the words and phrases that represent the issue.
  4. Check for false matches and for relevant passages the list misses.

Taking household costs as the example: we need to distinguish energy bills (invoices) from a parliamentary bill (legislation). Slide 15

C03: frequency — occurrences vs. number of speeches Slides 16–17

R · C03 (W4/classroom/W4_classroom.R)
# C03: Frequency in real speeches (run C01 first)
recap_dfm <- dfm(discovery_tokens)
recap_dfm <- dfm_remove(recap_dfm, stopwords("en"))
# Keep words made of English letters only.
recap_dfm <- dfm_select(recap_dfm, "^[a-z]+$", valuetype = "regex")
freq <- textstat_frequency(recap_dfm)
head(freq, 6)
R console output (run locally, W4_classroom.R: R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64)
> recap_dfm <- dfm(discovery_tokens)

> recap_dfm <- dfm_remove(recap_dfm, stopwords("en"))

> # Keep words made of English letters only.
> recap_dfm <- dfm_select(recap_dfm, "^[a-z]+$", valuetype = "regex")

> freq <- textstat_frequency(recap_dfm)

> head(freq, 6)
     feature frequency rank docfreq group
1        hon      6514    1    2826   all
2 government      3190    2    1320   all
3      right      2762    3    1470   all
4     member      2395    4    1129   all
5        can      2391    5    1221   all
6     people      2273    6     995   all
  • frequency: total occurrences; docfreq: number of speeches in which the word occurs; rank is ordered by frequency; group = all means all speeches are counted together. Slide 17
  • The local result is identical to slide 17: hon occurs 6,514 times, in 2,826 speeches.
  • Exercise: change 6 to 12. Which words describe parliamentary procedure rather than policy? (hon, right and member come from forms of address such as “the right hon. Member”.)
📊Frequency table browserReal data · top 60 of recap_dfm
Click a word to mark it as “procedural language” (click again to undo):

C04: KWIC — putting words back into context Slides 18–19

KWIC = keyword in context. Does security always mean defence?

R · C04 (W4/classroom/W4_classroom.R)
# C04: Context in real speeches (run C01 first)
live_contexts <- kwic(discovery_tokens, "security", window = 5)
context_table <- as.data.frame(live_contexts)
columns <- c("docname", "pre", "keyword", "post")
head(context_table[, columns], 2)
R console output (run locally, W4_classroom.R: R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64)
> live_contexts <- kwic(discovery_tokens, "security", window = 5)

> context_table <- as.data.frame(live_contexts)

> columns <- c("docname", "pre", "keyword", "post")

> head(context_table[, columns], 2)
      docname                         pre  keyword                    post
1 speech_0024 as a basis of international security   , is essential to the
2 speech_0246   raise the question in the security council . we advanced £

Each row is one match; read across from pre → keyword → post, with at most 5 tokens on each side. Row 1 is international security, row 2 is security council — the same word, two meanings. Slide 19

🔎KWIC reading exerciseReal data · discovery_tokens, window = 8

Mark each row as “relevant” or “false match”, and your judgements are tallied below. Define “relevant” yourself here (e.g. security = defence / security policy).

About the data: exported locally with kwic(discovery_tokens, pattern, window = 8); for words with more than 150 matches, 150 rows were sampled at random (set.seed(4)).

C05: collocations — candidate phrases Slides 20–21

Collocation: two adjacent words that are strongly associated statistically. Sorted by lambda from largest to smallest.

R · C05 (W4/classroom/W4_classroom.R)
# C05: Phrases in real speeches (run C01 first)
coll <- textstat_collocations(discovery_tokens, size = 2, min_count = 20)
row_order <- order(coll$lambda, decreasing = TRUE)
coll <- coll[row_order, ]
head(coll, 6)
first_phrase <- phrase(coll$collocation[1])
phrase_context <- kwic(discovery_tokens, first_phrase, window = 5)
head(phrase_context, 2)
R console output (run locally, W4_classroom.R: R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64)
> coll <- textstat_collocations(discovery_tokens, size = 2, min_count = 20)

> row_order <- order(coll$lambda, decreasing = TRUE)

> coll <- coll[row_order, ]

> head(coll, 6)
           collocation count count_nested length   lambda        z
2809         sri lanka    23            0      2 15.65685 10.56449
2692          per cent   718            0      2 15.64201 11.04304
1743      dispatch box    23            0      2 13.23135 15.27786
1283 liberal democrats    37            0      2 12.40680 18.59108
113   northern ireland   334            0      2 12.22301 51.32513
452     united kingdom   300            0      2 11.97618 29.83622

> first_phrase <- phrase(coll$collocation[1])

> phrase_context <- kwic(discovery_tokens, first_phrase, window = 5)

> head(phrase_context, 2)
Keyword-in-context with 2 matches.
                                                                                                     
 [speech_1885, 29:30] the british-owned tea estates in | sri lanka | . there has been considerable   
 [speech_1885, 80:81]            to extend its stay in | sri lanka | to investigate the conditions of
  • The top one is sri lanka; both matches come from the same speech, speech_1885. Slide 21
  • A strong collocation is only a candidate: a place name by itself cannot measure household costs.
🔗Collocation table: min_count 20 vs 50Real data
The exercise on slide 20: raise min_count to 50 — are the top phrases about household costs? (The count ≥ 50 table is filtered to count ≥ 50 from the same min_count = 20 run; λ comes from that same estimation.)

C06: keyness — comparing two groups Slides 22–23

R · C06 (W4/classroom/W4_classroom.R)
# C06: Relative word use (run C01 and C03 first)
party_dfm <- dfm_subset(recap_dfm,
  party %in% c("Conservative", "Labour"))
party_dfm <- dfm_group(party_dfm, groups = party)
party_dfm <- dfm_trim(party_dfm, min_termfreq = 1)
keys_con <- textstat_keyness(party_dfm, target = "Conservative")
keys_lab <- textstat_keyness(party_dfm, target = "Labour")
head(keys_con, 3)
head(keys_lab, 3)
R console output (run locally, W4_classroom.R: R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64)
> party_dfm <- dfm_subset(recap_dfm,
+   party %in% c("Conservative", "Labour"))

> party_dfm <- dfm_group(party_dfm, groups = party)

> party_dfm <- dfm_trim(party_dfm, min_termfreq = 1)

> keys_con <- textstat_keyness(party_dfm, target = "Conservative")

> keys_lab <- textstat_keyness(party_dfm, target = "Labour")

> head(keys_con, 3)
        feature     chi2            p n_target n_reference
1      aircraft 44.37288 2.714218e-11      116          31
2 cyberstalking 39.62479 3.077519e-10       42           0
3      stalking 33.96359 5.615304e-09       36           0

> head(keys_lab, 3)
      feature     chi2            p n_target n_reference
1       waste 61.43017 4.551914e-15      124          31
2        tory 49.50067 1.983080e-12       73          11
3 advertising 38.71565 4.902623e-10       64          12
Target: Conservative (slide 23)Target: Labour
Wordchi2Con.Lab.Wordchi2Con.Lab.
aircraft44.3711631waste61.4331124
cyberstalking39.62420tory49.501173
stalking33.96360advertising38.721264
  • Each target is run once; each table shows that party’s top three positive keyness scores.
  • Keyness takes into account each group’s total number of tokens — raw counts alone cannot decide it.
  • These words are distinctive of this sample; they are not necessarily the most frequent, and they have nothing to do with positive or negative sentiment. Slide 23
⚖️Keyness top 15Real data · chi2
Bar = chi2; the numbers in brackets are the target / reference counts. Supplement (not from the lecture): cyberstalking and stalking occur 0 times in Labour — this may just be a few Conservative speeches concentrating on the same issue; a feature of the sample is not a feature of the party.

Keep “finding terms” and “evaluation” separate Slide 24

A
Discovery texts
→
B
Candidate terms → human review
→
C
Freeze the dictionary
→
D
Held-out texts + independent human labels
→
E
Error analysis
  • Record the dictionary version and the inclusion rules.
  • Do not keep tuning on the final evaluation sample.
  • Recheck performance when the language or period changes. Slide 24

In the code: workflow.R removes the 50 test speeches from discovery_tokens, so C03–C06 never see them while finding terms.

In C03, hon has frequency = 6,514 and docfreq = 2,826. What does docfreq mean?
frequency counts occurrences; docfreq counts speeches with a match. Slides 16–17
In C05 the top collocation by lambda is sri lanka. What does this mean?
Both matches come from the same speech; a place name by itself does not measure household costs. Slide 21
Why are the 50 test speeches excluded from discovery?
Do not keep tuning on the final evaluation sample. Slide 24
03 · Matching rules

Matching rules: phrases and wildcards

The same concept can be written as many different rules: a broad bill*, exact bill/bills, or the phrase energy bills. The broader the rule, the more false matches; the narrower the rule, the more it misses.

A small example you can calculate by hand Slide 25

TextBroad rule bill*Phrase energy bills
Energy bills are rising.11
This bill reforms parliament.10
Families cannot afford heating.00

Switching to the phrase removes one false positive (legislation), but still misses one relevant passage (cannot afford heating). Slide 25

C07: phrase matching with quanteda Slide 26

R · C07 (W4/classroom/W4_classroom.R)
# C07: A complete phrase-lookup example
library(quanteda)
examples <- c("Energy bills are rising.",
              "This bill reforms parliament.",
              "Families cannot afford heating.")
example_tokens <- tokens(examples, remove_punct = FALSE)
cost_dict <- dictionary(list(costs = "energy bills"))
matched <- tokens_lookup(example_tokens, cost_dict)
cost_counts <- dfm(matched)
as.matrix(cost_counts)
R console output (run locally, W4_classroom.R: R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64)
> library(quanteda)

> examples <- c("Energy bills are rising.",
+               "This bill reforms parliament.",
+               "Families cannot afford heating.")

> example_tokens <- tokens(examples, remove_punct = FALSE)

> cost_dict <- dictionary(list(costs = "energy bills"))

> matched <- tokens_lookup(example_tokens, cost_dict)

> cost_counts <- dfm(matched)

> as.matrix(cost_counts)
       features
docs    costs
  text1     1
  text2     0
  text3     0

Was your prediction right? Only the first sentence is matched (1, 0, 0). The exercise on the slide: add "cannot afford heating" to the dictionary — which error changes? (The false negative in the third sentence is fixed, but the phrase is very specific, and a different wording will be missed again.) You can try it directly in the test bench below.

C08: wildcard vs. exact matching Slides 27–28

R · C08 (W4/classroom/W4_classroom.R)
# C08: Wildcards in real speeches (run C01 first)
wild <- kwic(discovery_tokens, "bill*", window = 0)
exact <- kwic(discovery_tokens, c("bill", "bills"),
              valuetype = "fixed", window = 0)
c(wildcard = nrow(wild), exact = nrow(exact))
word_counts <- table(wild$keyword)
word_counts <- sort(word_counts, decreasing = TRUE)
head(word_counts, 8)
R console output (run locally, W4_classroom.R: R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64)
> wild <- kwic(discovery_tokens, "bill*", window = 0)

> exact <- kwic(discovery_tokens, c("bill", "bills"),
+               valuetype = "fixed", window = 0)

> c(wildcard = nrow(wild), exact = nrow(exact))
wildcard    exact 
    1774     1539 

> word_counts <- table(wild$keyword)

> word_counts <- sort(word_counts, decreasing = TRUE)

> head(word_counts, 8)

      bill    billion      bills     bill's   billions billericay     bill’s      billâ 
      1470        157         69         24         18          5          3          3 
  • bill* matches bill followed by any suffix, including billion and billericay (a place name).
  • Exact bill/bills: 1,470 + 69 = 1,539.
  • Exact matching still mixes “legislation” and “household bills” — it cannot resolve semantic ambiguity.
  • The output shows different apostrophes (bill's and bill’s) as well as what looks like encoding residue (billâ). These are match counts, not numbers of speeches. Slide 28
✱Which words did bill* catch?Real data · table(wild$keyword)

Interactive: rule test bench

🧪Write a rule and see how three sentences are matchedToy intuition · defaults = slides 25–26

Supplement (not from the lecture): the matching logic imitates the glob rules of tokens_lookup() (case-insensitive, * stands for any suffix, phrases must occur consecutively, and with punctuation kept a phrase cannot run across a full stop).

Phrase rules keep useful context Slide 29

  • Phrases can separate energy bills from legislative bills.
  • Longer n-grams carry more local context.
  • But more specific expressions are also rarer.
  • Match phrases first, then remove stop words — otherwise phrases such as cannot afford may be broken first.

The figure on slide 29 (Hvitfeldt & Silge 2022): each point is the number of distinct n-grams in one Andersen fairy tale at a given n-gram length; the larger n is, the lower the count of the most frequent n-gram (the more purple the colour).

In C08 the wildcard has 1,774 matches and the exact rule has 1,539. Where does most of the difference come from?
bill* matches any suffix after bill, including billion. Slide 28
What does switching to exact matching of bill/bills solve?
Exact matching still mixes legislation and household bills. Slide 28
04 · Scoring

Denominators, sentiment scores and “zero”

After matching, the results have to become numbers. This chapter covers three things: what to divide by (C09), two sentiment summaries (net tone and coverage), and why a score of zero is not necessarily neutral (C10).

C09: document length and the denominator Slides 30–31

Predict: will the top entries be the same when ranked by “count” and by “rate”?

R · C09 (W4/classroom/W4_classroom.R)
# C09: Rankings on real speeches (run C01 first)
discovery_ids <- docnames(discovery_tokens)
rates <- subset(comparison, doc_id %in% discovery_ids)
rates <- subset(rates, tokens >= 50)
cols <- c("doc_id", "broad", "tokens", "broad_per100")
raw_order <- order(rates$broad, decreasing = TRUE)
rate_order <- order(rates$broad_per100, decreasing = TRUE)
head(rates[raw_order, cols], 3)
head(rates[rate_order, cols], 3)
R console output (run locally, W4_classroom.R: R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64)
> discovery_ids <- docnames(discovery_tokens)

> rates <- subset(comparison, doc_id %in% discovery_ids)

> rates <- subset(rates, tokens >= 50)

> cols <- c("doc_id", "broad", "tokens", "broad_per100")

> raw_order <- order(rates$broad, decreasing = TRUE)

> rate_order <- order(rates$broad_per100, decreasing = TRUE)

> head(rates[raw_order, cols], 3)
                 doc_id broad tokens broad_per100
speech_2792 speech_2792    20   1349    1.4825797
speech_1673 speech_1673    19   2655    0.7156309
speech_0743 speech_0743    18   1599    1.1257036

> head(rates[rate_order, cols], 3)
                 doc_id broad tokens broad_per100
speech_4435 speech_4435     4     69     5.797101
speech_1551 speech_1551     4     78     5.128205
speech_4917 speech_4917     3     59     5.084746
  • Rate = 100 × broad / tokens; broad is the number of bill* matches.
  • 20 / 1,349 → 1.48 per 100 words; 4 / 69 → 5.80 per 100 words. More matches does not mean higher density. Slide 31
  • The six rows of local output are identical to slide 31.
📏Ranking by count vs. ranking by rateReal data · bill* matches in the 4,950 discovery speeches
Sorted by count (top 5)
Sorted by rate per 100 words (top 5)

Two simple sentiment summaries Slide 32

Let P = number of positive matches, N = number of negative matches, L = number of original tokens.

SummaryDefinitionInterpretation
Net tone100 × (P − N) / LNet matches per 100 tokens
Match coverage100 × (P + N) / LMatched sentiment tokens per 100 tokens

P = 3, N = 1, L = 100: net tone = 2, coverage = 4%. The slide also flags that the Proksch et al. case later uses a different scoring rule (Chapter 08). Slide 32

C10: zero is not necessarily neutral Slides 33–34

check_texts are five teaching examples built by workflow.R; the sentiment dictionary is the ten-word Dictionaries/teaching_affect.dic (positive: good, excellent, success, successful, improve; negative: bad, failure, crisis, harm, harmful).

R · C10 (W4/classroom/W4_classroom.R)
# C10: Zero, balance and missing matches
check_texts
check_scores[, c("doc_id", "positive", "negative",
                 "net_per100", "coverage_per100", "balance")]
R console output (run locally, W4_classroom.R: R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64)
> check_texts
                             good                           negated                         unmatched 
            "The policy is good."         "The policy is not good."       "The minister spoke today." 
                         balanced                             empty 
"A good plan with a bad outcome."                                "" 

> check_scores[, c("doc_id", "positive", "negative",
+                  "net_per100", "coverage_per100", "balance")]
     doc_id positive negative net_per100 coverage_per100 balance
1      good        1        0         25        25.00000       1
2   negated        1        0         20        20.00000       1
3 unmatched        0        0          0         0.00000      NA
4  balanced        1        1          0        28.57143       0
5     empty        0        0         NA              NA      NA
doc_idWhat happens (slide 34)
good1 positive match / 4 words → 25 per 100 words; all matches are positive, balance = 1.
negated1 positive match / 5 words → 20. The rule ignores not.
unmatchedHas words but P = N = 0; the denominator of balance is 0 → NA.
balancedP = N = 1, 7 words in total: net = 0, coverage = 100 × 2 / 7 = 28.57%.
emptyL = 0 and P + N = 0: all three scores are undefined (NA).
Conclusion of slide 34

Zero can mean “no matches” or “positives and negatives cancel out”; neither proves neutrality.

🎚Sentiment scorer (teaching_affect.dic)Toy intuition · default five sentences = check_texts

When unticked, the calculation is the same as score_sentiment() in workflow.R (punctuation removed, lowercased, the denominator is all tokens; NA when the denominator is 0). The blank last line corresponds to empty. The negation rule you can tick is a supplement (not from the lecture), included for comparison with “the limits of a fixed negation window” in Chapter 05.

With P = 3, N = 1, L = 100, what are net tone and coverage?
100 × (3 − 1) / 100 = 2; 100 × (3 + 1) / 100 = 4. Slide 32
unmatched and balanced both have a net tone of 0. What is the difference?
Zero can mean no matches or cancellation; neither proves neutrality. Slide 34
05 · Scoring

Negation, preprocessing and Denny & Spirling

A bag-of-words dictionary does not understand “not good”. Keeping not is only the first step; we also need a rule that uses it. And every preprocessing choice (stop words, word forms) can change the results — the Denny & Spirling manifesto case shows that 128 preprocessing combinations produce 12 different orderings.

C11: a deliberate sentiment failure Slides 35–36

Predict: will keeping not make the second sentence negative?

R · C11 (W4/classroom/W4_classroom.R)
# C11: A deliberate sentiment failure (run C01 first)
negation_tokens <- check_tokens[c("good", "negated")]
as.list(negation_tokens)
negation_dfm <- dfm(negation_tokens)
negation_counts <- dfm_lookup(negation_dfm, toy_sentiment)
as.matrix(negation_counts)
without_stopwords <- tokens_remove(negation_tokens, stopwords("en"))
as.list(without_stopwords)
R console output (run locally, W4_classroom.R: R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64)
> negation_tokens <- check_tokens[c("good", "negated")]

> as.list(negation_tokens)
$good
[1] "the"    "policy" "is"     "good"  

$negated
[1] "the"    "policy" "is"     "not"    "good"  


> negation_dfm <- dfm(negation_tokens)

> negation_counts <- dfm_lookup(negation_dfm, toy_sentiment)

> as.matrix(negation_counts)
         features
docs      positive negative
  good           1        0
  negated        1        0

> without_stopwords <- tokens_remove(negation_tokens, stopwords("en"))

> as.list(without_stopwords)
$good
[1] "policy" "good"  

$negated
[1] "policy" "good"  
  1. Dictionary matching: both sentences match good (positive = 1, negative = 0). The rule does not use not to reverse anything.
  2. After removing stop words: not is in stopwords("en") and gets deleted; the two sentences’ tokens become identical: "policy" "good".
Conclusion of slide 36

Keep negation words, then add a rule that handles them.

Interactive: how far can a fixed negation window go?

🚫Negation window ruleSupplement (not from the lecture) · toy intuition

The sentences are the four difficult cases on slide 37 plus the two sentences from C11. Dictionary = teaching_affect.dic plus reject (negative; added to demonstrate the second sentence, not part of the course dictionary). Rauh (2018) uses “a direct two-word negation rule” (slide 57); a window of 1 here is the closest to it.

Limits of a fixed negation window Slide 37

  • “Not good” differs from “not only good but excellent”.
  • “I reject the claim that this is a failure” contains a negative word.
  • Quoting someone else’s criticism is not necessarily the speaker’s own view.
  • Long-distance negation may fall outside a simple word window.

Rules can improve a baseline, but they cannot solve every sentence. Slide 37

Preprocessing must fit the dictionary Slide 38

  • Different stop-word lists remove different shares of the words in a text.
  • Keep negation words when they matter.
  • Dictionary entries must match the word forms you choose (e.g. with or without stemming/lemmatisation).
  • Check what each preprocessing choice throws away.

The figure on slide 38 (Hvitfeldt & Silge 2022): three points per story, one for each of three stop-word lists; X = total number of words, Y = percentage of words removed. For the same text, different lists remove different shares.

🧹Which words does quanteda’s stopwords("en") delete?Real data · stop-word list exported locally

Case: positioning parties from manifestos (Denny & Spirling 2018) Slides 39–41

  • Question: can manifesto language place parties on a left–right scale? Data: 8 UK party manifestos, 1983–1997; model: Wordfish (estimates positions from word counts). Slide 39
  • The same 8 manifestos and the same Wordfish model, 128 preprocessing specifications, produce 12 different document orderings; black cells = disagreement with the authors’ prior ordering. Slide 40
Research claimWhat this case can show (slide 41)
Vocabulary can place parties on a scaleWordfish estimates relative positions from word counts
The ordering is robust to reasonable choicesMust be checked: this example produced 12 orderings
The model explains why parties changeThat is a causal question and needs a different research design

Back to dictionaries: do substantive comparisons survive reasonable scoring choices? (That is exactly what C12/C15 in the next chapter do.) Slide 41

In C11, what happens after applying tokens_remove(stopwords("en")) to the two sentences?
not is deleted. The two token lists are now identical. Slide 36
What does the Denny & Spirling manifesto case mainly tell us?
Do substantive comparisons survive reasonable scoring choices? Slides 40–41
06 · Scoring

Dictionary revision and sensitivity (C12, C15)

In this chapter the construct switches to energy policy attention (not sentiment). Dictionaries/energy_policy.csv has two versions: v1 is broad and v2 is narrow. Changing the dictionary changes the scores — but whether the change is better can only be answered by human judgement.

C12: did revising the dictionary improve measurement? Slide 42

Predict first: which version will flag more speeches?

R · C12 (W4/classroom/W4_classroom.R)
# C12: Dictionary revisions (run C01 first)
policy_entries[, c("version", "category", "pattern")]
dev <- subset(policy_scores,
  doc_id %in% docnames(discovery_tokens))
c(v1 = sum(dev$v1 > 0), v2 = sum(dev$v2 > 0))
energy_context <- kwic(discovery_tokens, "energy", window = 5)
head(energy_context, 3)
R console output (run locally, W4_classroom.R: R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64)
> policy_entries[, c("version", "category", "pattern")]
   version category      pattern
1       v1   energy       energy
2       v1   energy        power
3       v1   energy    electric*
4       v1   energy          gas
5       v1   energy        bill*
6       v2   energy       energy
7       v2   energy    electric*
8       v2   energy    gas bill*
9       v2   energy     renewab*
10      v2   energy       solar*
11      v2   energy   wind farm*
12      v2   energy fossil fuel*

> dev <- subset(policy_scores,
+   doc_id %in% docnames(discovery_tokens))

> c(v1 = sum(dev$v1 > 0), v2 = sum(dev$v2 > 0))
 v1  v2 
899 139 

> energy_context <- kwic(discovery_tokens, "energy", window = 5)

> head(energy_context, 3)
Keyword-in-context with 3 matches.
                                                                                    
  [speech_0103, 105] production and use of atomic | energy | , clause 10 enables him
  [speech_0103, 134]           , 521 or of atomic | energy | plant. it is thought   
 [speech_0105, 2610]           , the will and the | energy | to push it through,    
v1 (broad)v2 (narrow)
energy, power, electric*, gas, bill*energy, electric*, gas bill*, renewab*, solar*, wind farm*, fossil fuel*
  • v2 drops the most ambiguous terms, power (political power), gas (tear gas) and bill* (legislation), narrows gas to the phrase gas bill*, and adds renewable-energy terms.
  • The result is in the output below: v1 = 899 speeches, v2 = 139 speeches (at least one match among the 4,950). The scores changed — but is this closer to human judgement? That is the discussion question on slide 42.
  • The first 3 rows of the KWIC show directly that energy can also mean “vigour”.

Interactive: compare the v1 and v2 highlighters on real speeches

🖍Speech browser + dictionary highlighterReal data · 335 discovery speeches
Your judgement (using the labelling rule in the Lab handout):

Sample: 300 discovery speeches (60–700 tokens) drawn locally with set.seed(719), plus the 40 speeches with the highest v2 matches per 1,000 words (≤ 900 tokens) to make sure there are energy-related speeches; 335 after de-duplication — not a random sample, and it cannot be used to estimate precision for the whole corpus. The matching logic is the same as the Chapter 07 validation bench (JS imitating tokens_lookup()); the denominator of the per-1,000-word rate uses the JS token count, which may differ slightly from R’s tokens column, so R’s token count is also shown below.

C15: visualising dictionary sensitivity Slides 43–44

dev is the table built in C12: one row per speech, 4,950 speeches in all; v1_per1000 and v2_per1000 are each version’s matches per 1,000 words.

R · C15 (W4/classroom/W4_classroom.R)
# C15: Visualizing dictionary sensitivity (run C12 first)
# install.packages("ggplot2")  # run once
library(ggplot2)
ggplot(dev, aes(x = v1_per1000, y = v2_per1000)) +
  geom_point(size = 1, alpha = 0.4, colour = "#314f4f") +
  geom_abline(intercept = 0, slope = 1,
              colour = "firebrick", linetype = "dashed") +
  labs(x = "v1 matches per 1,000 tokens",
       y = "v2 matches per 1,000 tokens") +
  theme_minimal()
C15 redrawn locally: v1 vs v2 matches per 1,000 words
Figure produced by running C15 locally (ggplot2 4.0.3). One point = one speech; on the dashed line = unchanged; below the line = fewer v2 matches; above the line = more v2 matches. Local counts: of 4,950 speeches, 4,096 are on the dashed line (4,046 of them are 0 in both versions, all stacked at the origin), 841 are below the line and 13 above it. Slide 44
🎯Interactive scatterplot: v1 vs v2Real data · 4,950 speeches
Conclusion of slide 44

Overlapping points can hide many speeches. Changed scores show sensitivity, not which dictionary is more valid.

Extension: comparing parties with v1/v2 (optional Lab section)

workflow.R also computes party-level rates: sum first, then divide (ratio of group totals), not the average of per-speech rates. Note that party_rates uses all 5,000 speeches (policy_scores), not just the 4,950 discovery speeches.

🏛Energy matches per 1,000 words by partyReal data · party_rates
Sorted by total tokens, largest first. Is the party ordering the same under v1 and v2? If not, this is exactly the question slide 41 asks: “do substantive comparisons survive reasonable choices?” Small parties have very few tokens, so their rates are unstable.
In the C15 scatterplot, most speeches with matches fall below the dashed line (locally: 841 below, 13 above). What is the most reasonable interpretation?
Changed scores show sensitivity, not which dictionary is more valid. Slide 44
07 · Validation

Human benchmark, kappa, precision/recall

Validation needs human judgement as a benchmark. This chapter first asks whether humans agree with each other (C13, kappa), then whether the dictionary agrees with humans (C14, precision/recall/F1), and finally uses 24 teaching sentences to practise “develop → freeze → test”.

Human benchmark Slide 45

  • Write a codebook with positive, negative and ambiguous examples.
  • Where feasible, keep coders blind to the dictionary’s predictions.
  • Record disagreements and the adjudication procedure.
  • The coding unit should match how the score will be used.

Human labels are evidence to be examined, not unquestionable truth. Slide 45

Which texts should be validated? Slide 46

  • Include both matched and unmatched passages.
  • Cover important dates, groups and documents of different lengths.
  • Use an untouched sample for the final performance estimate.
  • Check rare or ambiguous cases separately, for diagnosis.

A pile of easy examples cannot establish performance on the whole corpus. Slide 46

C13: agreement between two human coders Slide 47

R · C13 (W4/classroom/W4_classroom.R)
# C13: Human agreement, not model accuracy
# install.packages("irr")  # run once
library(irr)
ratings <- data.frame(
  coder_A = c(1, 1, 1, 1, 1, 0, 0, 0, 0, 0),
  coder_B = c(1, 1, 1, 1, 0, 1, 0, 0, 0, 0))
table(ratings$coder_A, ratings$coder_B)
mean(ratings$coder_A == ratings$coder_B)
agreement <- kappa2(ratings, weight = "unweighted")
agreement$value
R console output (run locally, W4_classroom.R: R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64)
> library(irr)
Loading required package: lpSolve

> ratings <- data.frame(
+   coder_A = c(1, 1, 1, 1, 1, 0, 0, 0, 0, 0),
+   coder_B = c(1, 1, 1, 1, 0, 1, 0, 0, 0, 0))

> table(ratings$coder_A, ratings$coder_B)
   
    0 1
  0 4 1
  1 1 4

> mean(ratings$coder_A == ratings$coder_B)
[1] 0.8

> agreement <- kappa2(ratings, weight = "unweighted")

> agreement$value
[1] 0.6

Raw agreement is 80% (8 out of 10 the same), and Cohen’s kappa = 0.60. Kappa subtracts the probability that “the two would agree even if both guessed at random”: here each coder labelled 5 1s and 5 0s, so the expected chance agreement is 0.5, and κ = (0.8 − 0.5) / (1 − 0.5) = 0.6.

🤝Kappa calculatorToy intuition · defaults = C13
B = 1
B = 0
A = 1
A = 0

Supplement (not from the lecture): try making both coders label almost every text 0 (e.g. 0, 1, 1, 18) — agreement is very high, but kappa drops a lot.

Confusion matrix for issue detection Slide 48

20 demonstration passagesHuman: relevantHuman: not relevant
Dictionary: matched6 true positives2 false positives
Dictionary: not matched4 false negatives8 true negatives

The unit is the passage, not the words in the dictionary.

C14: precision and recall Slides 49–50

Calculate by hand from the table above before running the code.

R · C14 (W4/classroom/W4_classroom.R)
# C14: Checking validation arithmetic (run C01 first)
predicted <- validation$predicted
human <- validation$human
TP <- sum(predicted == 1 & human == 1)
FP <- sum(predicted == 1 & human == 0)
FN <- sum(predicted == 0 & human == 1)
precision <- TP / (TP + FP)
recall <- TP / (TP + FN)
F1 <- 2 * TP / (2 * TP + FP + FN)
c(precision = precision, recall = recall, F1 = F1)
R console output (run locally, W4_classroom.R: R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64)
> predicted <- validation$predicted

> human <- validation$human

> TP <- sum(predicted == 1 & human == 1)

> FP <- sum(predicted == 1 & human == 0)

> FN <- sum(predicted == 0 & human == 1)

> precision <- TP / (TP + FP)

> recall <- TP / (TP + FN)

> F1 <- 2 * TP / (2 * TP + FP + FN)

> c(precision = precision, recall = recall, F1 = F1)
precision    recall        F1 
0.7500000 0.6000000 0.6666667 
  • Precision = 0.75: of the 8 passages the dictionary flagged, 6 are relevant (6 / 8).
  • Recall = 0.60: of the 10 relevant passages, the dictionary found 6 (6 / 10).
  • F1 ≈ 0.667: 2 × 6 / (2 × 6 + 2 + 4).
Slide 50

Missed cases matter: reading only the passages the dictionary matched cannot tell us recall.

🎛Precision/Recall calculatorToy intuition · defaults = slide 48

Try the question on slide 49: if you read only the TP + FP passages that the dictionary matched, can you work out FN?

Interactive: develop → freeze → test (24 teaching sentences) Slide 95

Data/synthetic_validation.csv contains 24 teaching sentences written by the instructor with labels (12 development, 12 test; 1 = relevant to energy policy). These are not real parliamentary speeches, nor independently observed human labels (per the comments in workflow.R). The steps on slide 95:

  • Develop: use the 12 development sentences to see where v1 and v2 go wrong.
  • Freeze: keep v2 unchanged on the next 12 sentences.
  • Test: compare predictions with labels, including the sentences with no match.
  • Result: precision 0.80, recall 0.667, F1 0.727. This is only demonstration arithmetic, not a performance estimate on the parliamentary corpus. Slide 95
R console output (run locally, print(synthetic_results): results of the same v1/v2 on development and test from workflow.R)
   n tp fp fn tn precision    recall        f1  accuracy       split version
1 12  3  4  3  2 0.4285714 0.5000000 0.4615385 0.4166667 development      v1
2 12  6  1  0  5 0.8571429 1.0000000 0.9230769 0.9166667 development      v2
3 12  4  4  2  2 0.5000000 0.6666667 0.5714286 0.5000000        test      v1
4 12  4  1  2  5 0.8000000 0.6666667 0.7272727 0.7500000        test      v2
🧪Dictionary validation benchReal data (course Data/) + exercise
or edit the dictionary entries yourself (one per line; * and phrases allowed):
Rule: tune using development only; when you are satisfied, click “Freeze”, then switch to test. You can peek at test before freezing, but it will be recorded here.

Matching logic: punctuation kept, case-insensitive, glob wildcards, phrases must be consecutive (imitating policy_counts()); when v1/v2 is loaded, each sentence’s prediction is checked against the actual R run, and the rightmost column of the table shows the “R” prediction.

Evaluating continuous sentiment scores Slide 51

  • Plot scores against human ratings.
  • Check group means and individual disagreements.
  • Check unmatched texts, compressed ranges and extreme values.
  • Compare performance across groups and genres.
📈Correlation ≠ agreementToy intuition · the example on slide 51

Validation must match the level of the claim Slide 52

ClaimEvidence needed
This sentence is negativeSentence-level agreement
This group is relatively more positiveGroup-level measurement validity
Sentiment changes over timeMeasurement that is stable across periods
Countries differ in level of conflictComparable measurement and institutional context
⚖️Claim judgement: is this evidence enough to support this claim?Exercise
The two coders in C13 agree 80% of the time, yet kappa is only 0.60, because?
(0.8 − 0.5) / (1 − 0.5) = 0.6. Slide 47
If you read only the passages the dictionary matched, which can you estimate?
Missed cases matter: reading only matched passages cannot tell us recall. Slide 50
Scores 1, 2, 3 and 11, 12, 13 have a correlation of 1. This means?
Two scores can rise together but still disagree. Slide 51
08 · Research cases

Cases: Boyle, Rauh, Proksch

Three published studies, each illustrating one step of dictionary measurement: a custom dictionary + held-out testing (Boyle et al. 2025), an adapted dictionary + human validation (Rauh 2018), and a translated dictionary + group-level validation + substantive analysis (Proksch et al. 2019). Everything below is based on the slides (the full texts of the three papers are not in the repo; see Chapter 12).

Policy relevance in energy research (Boyle et al. 2025) Slides 53–55

  • Question: which abstracts communicate policy relevance? Data: 270,537 abstracts, 100 journals, 2010–2023; a custom dictionary identifies relevance statements. Expressed relevance ≠ actual policy uptake. Slide 53
  • Unit: one abstract (does it contain a policy-relevance statement?). Development: start from policy terms and read 400 double-coded abstracts to find more terms; refinement: keep only added terms that improve positive-class F1 on the development set; test: evaluate on another 200 human-coded abstracts kept out of tuning.
  • Reported average F1: development 0.90 / held-out 0.86. The instructor’s research-process note: fine-tuning transformers was tried first and did not work well. Slide 54
  • About 15% of abstracts are classified as policy-relevant; only 8% explicitly mention policy/policies. Journals whose aims explicitly mention policy: 26.7%; those that do not: 3.7%. This is a descriptive textual pattern, not evidence of policy uptake. Slide 55

Compare with slide 24 in Chapter 02: this is the real-research version of “discovery → freeze → held-out”. A development-set F1 higher than the held-out F1 is expected.

A sentiment dictionary for German political language (Rauh 2018) Slides 56–60

StepWhat the study did (slide 57)
DictionaryCombined SentiWS and GermanPolarityClues; manually reviewed the entries
ContextAdded a direct two-word negation rule
ScorePositive minus negative matches, divided by retained terms
ValidationThree coders coded 1,500 sampled Bundestag sentences
  • Coder agreement: 3 coders, 1,500 sentences; exact agreement 59.1%; ordinal alpha .675. Agreement is not validity. Slide 58
  • The scores of three dictionaries are compared across human-rated categories; the positive category separates better. The intervals show uncertainty in group means, not classification accuracy. Slide 59
  • Result: positive evaluations are easier to recover than negative ones. Use: a tested measure for comparing evaluative language in political texts. Limitation: scores cluster near 0 and have no self-evident numeric unit. The study validates the measurement; it does not explain why politicians became more positive. Slide 60

Sentiment and legislative consensus (Proksch et al. 2019) Slides 61–65

Question: does opposition tone reflect cross-party consensus? Is more positive opposition language associated with bills passing unanimously? Slides 61–62

  1. Collect about 26,000 speeches on 871 German government bills, 2005–2017.
  2. Match positive and negative words with a translated Lexicoder sentiment dictionary.
  3. Aggregate by party and bill: log((P + 0.5) / (N + 0.5)).
  4. Put bill-level sentiment into a logistic regression of unanimous passage.
  • Human validation: 300 passages, two human ratings each; standardized scores are compared by speaker group; the reported group-level correlation is about 0.9 — this is not 90% classification accuracy. Slide 63
  • Translation is itself a measurement decision: translated words may be used differently in politics, may have several equivalents, and word forms and tokenization affect matching; each language must be validated separately. The same category name does not guarantee comparable numeric scales. Slide 64
  • Regression: 814 bills; the coefficients are positive in all three models, but only model (3) is significant. This is an association, not a causal effect of tone. Slide 65
➗log ratio vs net toneToy intuition · formulas from slides 32 and 62

Supplement (not from the lecture): the +0.5 keeps the logarithm defined when P or N is 0; the log ratio does not use L as a denominator, so when “length doubles and matches double too” the score is unchanged, and so is net tone; but when only length grows without more matches, net tone shrinks while the log ratio stays the same. Try it.

Sentiment, stance and conflict Slide 66

ConceptWhat the evidence must establish
SentimentEvaluative language in a defined unit
StanceSupport for or opposition to a specific target
ConflictA substantive relation between actors or positions

Negative words can describe a social problem rather than attack another party.

Flip cards: key numbers from the three cases

🃏Think of the answer first, then click to flip the cardExercise
Proksch et al. report a group-level correlation of about 0.9 between human and automated scores. The correct reading?
This is not 90% classification accuracy. Slide 63
Boyle et al. report F1 0.90 on the development set and 0.86 on the held-out set. Why report both?
Test: evaluate on 200 other human-coded abstracts, kept out of tuning. Slide 54
09 · Extensions

LIWC, custom dictionaries and campaign promises

LIWC is the most common “category percentage” tool, but the software, its official dictionary and our own quanteda dictionary are three different things. Next, we use the concepts of Eichorst & Lin (2019) for a two-sentence “specific vs vague” example, and finally look at two Chinese LIWC studies.

LIWC: what does it measure? Slide 67

  • LIWC = Linguistic Inquiry and Word Count: maps language to predefined dictionary categories.
  • Categories include pronouns, emotion, social processes, etc.; most category scores are percentages of total words. Example: 4 category matches in 100 words = 4%.
  • Category percentages measure word use; interpretation still requires validation.

LIWC and quanteda: separate roles Slide 68

ResourceRoleAccess
LIWC applicationRuns built-in or custom dictionariesLicensed software
Official LIWC dictionaryProprietary word–category resourceRestricted by license terms
quanteda + our dictionaryMatching with our own rules in RNo LIWC purchase needed

Importing a file does not grant a license to use its dictionary. This week’s teaching_affect.dic only borrows LIWC’s file format (category numbers enclosed by %, followed by one “word + category number” per line).

C16: applying our dictionary with quanteda Slide 69

R · C16 (W4/classroom/W4_classroom.R)
# C16: Custom dictionary (run C01; stay in W4/classroom)
library(quanteda)
own <- dictionary(file = "Dictionaries/teaching_affect.dic", format = "LIWC")
mini <- tokens(c("Good policy.", "A bad crisis."), remove_punct = TRUE)
matched <- tokens_lookup(mini, own, capkeys = FALSE)
hits <- dfm(matched)
counts <- as.matrix(hits)
counts
word_count <- ntoken(mini)
100 * counts / word_count
R console output (run locally, W4_classroom.R: R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64)
> library(quanteda)

> own <- dictionary(file = "Dictionaries/teaching_affect.dic", format = "LIWC")

> mini <- tokens(c("Good policy.", "A bad crisis."), remove_punct = TRUE)

> matched <- tokens_lookup(mini, own, capkeys = FALSE)

> hits <- dfm(matched)

> counts <- as.matrix(hits)

> counts
       features
docs    positive negative
  text1        1        0
  text2        0        2

> word_count <- ntoken(mini)

> 100 * counts / word_count
       features
docs    positive negative
  text1       50  0.00000
  text2        0 66.66667

“Good policy.”: 1 of 2 words is positive → 50%; “A bad crisis.”: 2 of 3 words are negative → 66.67%. Discussion: why divide by all tokens rather than only by the number of matches? (Dividing by matches would only give 0 or 100% and lose the information about “how many emotion words were used”; this is also the difference between coverage and balance in Chapter 04.)

Campaign statements: vague or specific? (Eichorst & Lin 2019) Slides 70–71

  • Question: when do parties make specific campaign statements? Texts: English party manifestos; compares incumbency status and economic performance.
  • Word-density plot: each column is a party manifesto, each row a dictionary term; darker colour = larger log count, white = 0. Slide 71

A two-sentence dictionary example Slides 72–74

The instructor’s examples/W4_campaign_simple.R, run locally:

R console output (run locally, examples/W4_campaign_simple.R)
> library(quanteda)

> text <- c("We may improve public services.",
+           "We guarantee better public services.")

> dict <- dictionary(list(vague = "may", concrete = "guarantee"))

> toks <- tokens(text, remove_punct = TRUE)

> counts <- dfm(toks)

> hits <- dfm_lookup(counts, dictionary = dict)

> as.matrix(hits)
       features
docs    vague concrete
  text1     1        0
  text2     0        1

> m <- as.matrix(hits)

> 100 * (m[, "concrete"] - m[, "vague"]) / ntoken(toks)
text1 text2 
  -20    20 
  • text1: may matches vague once; text2: guarantee matches concrete once.
  • Teaching score = 100 × (C − V) / L, i.e. “concrete percentage − vague percentage”, in percentage points: text1 = 100 × (0 − 1) / 5 = −20; text2 = +20. Slide 74
  • Adapted from Eichorst & Lin (2019): the original paper’s denominator excludes stop words and the difference is rescaled to 0–1; this example does neither.
📣Concrete vs vague scorerToy intuition · defaults = slide 72

The third sentence corresponds to “Try: Add not before guarantee” on slide 73: the count is unchanged (still concrete 1), but L becomes 7.

Chinese LIWC: two studies Slides 75–76

  • Lin (2023): a review article in Chinese that introduces dictionary categories and word-use rates and reviews studies of sports injury, self-efficacy and sports communication. Discussion: what can language reveal about a team? Slide 75
  • Lin et al. (2020): can categories distinguish emotional contexts? Data: 50 Hate and 50 Sad posts from PTT; anger words 2.00% vs 0.88%, Cohen’s d = 0.61. A group difference is not an individual diagnosis. Slide 76
Reading a .dic file in quanteda with format = "LIWC" means?
Importing a file does not grant a license to use its dictionary. Slides 68–69
“We will not guarantee better public services.” With the dictionary on slide 72, what is the teaching score?
The dictionary has no negation rule; 100 × (1 − 0) / 7 ≈ 14.29. Slides 73–74
10 · Extensions

Beyond dictionaries: POS, TextRank, NER, LLMs

These tools help us find candidate terms or find names, but none of them validates a dictionary automatically. The optional extensions (O01, TextRank, Flair) require downloading models; where they ran locally the output is shown as is, and where they could not run we say so.

POS tagging (UDPipe) Slides 77–80

Optional extension: back to “finding candidate terms”, now as POS → candidate terms → human review.

R · examples/W4_pos_simple.R
# Standalone POS example. No C01 or workflow.R required.
# The model is saved in udpipe_models under your current working directory.
# O01: POS candidates (model download on first run)
# install.packages("udpipe")  # run once before class
library(udpipe)
dir.create("udpipe_models", showWarnings = FALSE)
info <- udpipe_download_model("english-ewt",
  model_dir = "udpipe_models", overwrite = FALSE)
model <- udpipe_load_model(info$file_model)
text <- "Housing costs are unaffordable."
annotation <- udpipe_annotate(model, x = text, parser = "none")
ann <- as.data.frame(annotation)
ann[, c("token", "lemma", "upos")]

# Optional: retain candidate nouns, adjectives and verbs.
candidates <- subset(ann, upos %in% c("NOUN", "ADJ", "VERB"))
candidates[, c("token", "lemma", "upos")]
R console output (run locally; udpipe english-ewt model)
> library(udpipe)

> dir.create("udpipe_models", showWarnings = FALSE)

> info <- udpipe_download_model("english-ewt",
+   model_dir = "udpipe_models", overwrite = FALSE)
Downloading udpipe model from https://raw.githubusercontent.com/jwijffels/udpipe.models.ud.2.5/master/inst/udpipe-ud-2.5-191206/english-ewt-ud-2.5-191206.udpipe to udpipe_models/english-ewt-ud-2.5-191206.udpipe
 - This model has been trained on version 2.5 of data from https://universaldependencies.org
 - The model is distributed under the CC-BY-SA-NC license: https://creativecommons.org/licenses/by-nc-sa/4.0
 - Visit https://github.com/jwijffels/udpipe.models.ud.2.5 for model license details.
 - For a list of all models and their licenses (most models you can download with this package have either a CC-BY-SA or a CC-BY-SA-NC license) read the documentation at ?udpipe_download_model. For building your own models: visit the documentation by typing vignette('udpipe-train', package = 'udpipe')
trying URL 'https://raw.githubusercontent.com/jwijffels/udpipe.models.ud.2.5/master/inst/udpipe-ud-2.5-191206/english-ewt-ud-2.5-191206.udpipe'
Content type 'application/octet-stream' length 16309608 bytes (15.6 MB)
==================================================
downloaded 15.6 MB

Downloading finished, model stored at 'udpipe_models/english-ewt-ud-2.5-191206.udpipe'

> model <- udpipe_load_model(info$file_model)

> text <- "Housing costs are unaffordable."

> annotation <- udpipe_annotate(model, x = text, parser = "none")

> ann <- as.data.frame(annotation)

> ann[, c("token", "lemma", "upos")]
         token        lemma  upos
1      Housing      housing   ADJ
2        costs         cost  NOUN
3          are           be   AUX
4 unaffordable unaffordable   ADJ
5            .            . PUNCT

> candidates <- subset(ann, upos %in% c("NOUN", "ADJ", "VERB"))

> candidates[, c("token", "lemma", "upos")]
         token        lemma upos
1      Housing      housing  ADJ
2        costs         cost NOUN
4 unaffordable unaffordable  ADJ
CodeWhat it does (slide 78)
library(udpipe)Loads the installed R package
dir.create(...)Creates a folder for the model file
udpipe_download_modelDownloads the model; keeps an existing file
udpipe_load_modelReads the model into memory
udpipe_annotateApplies the model to our sentence
as.data.frame(annotation)Converts the result into a table

Output on slide 79: Housing → ADJ, costs → NOUN (lemma cost), are → AUX, unaffordable → ADJ. The token is the observed form, the lemma is the predicted base form, and upos is the predicted part of speech. The local O01 output matches this exactly. Discussion: do you accept Housing → ADJ?

MethodRole of POS and token relations (slide 80)
Candidate filteringKeep nouns or adjectives for human review
TextRankFilter candidates by POS; rank them in a co-occurrence network
Dependency extractionFind words along grammatical links (e.g. a noun and its modifiers); requires turning on the parser

TextRank: ranking candidate terms Slides 81–83

Data: Obama’s 2013 inaugural address, built into quanteda (examples/W4_keywords_real.R, no C01 needed). Nodes = candidate lemmas; edges = adjacent noun/adjective pairs; PageRank uses pair counts and neighbour scores. Actual output on slide 82: new 0.0161, same 0.0096, endure 0.0095, nation 0.0094, common 0.0092, hard 0.0083; with the caveat that new is generic and some endure tokens are tagged as nouns.

R · examples/W4_keywords_real.R
# Real political speech: Obama 2013 inaugural address. No C01 required.
# Source: https://quanteda.io/reference/data_corpus_inaugural.html
# install.packages(c("quanteda", "udpipe", "textrank", "igraph"))
# The model is saved in udpipe_models under your current working directory.
# O01: POS candidates (model download on first run)
# install.packages("udpipe")  # run once before class
library(udpipe)
dir.create("udpipe_models", showWarnings = FALSE)
info <- udpipe_download_model("english-ewt",
  model_dir = "udpipe_models", overwrite = FALSE)
model <- udpipe_load_model(info$file_model)
library(quanteda)
library(textrank)
speech <- corpus_subset(data_corpus_inaugural, Year == 2013)
text <- as.character(speech)
ann <- as.data.frame(udpipe_annotate(model, x = text,
                                  parser = "none"))
# Mark candidates, retaining punctuation and other tokens as separators.
keep <- ann$upos %in% c("NOUN", "ADJ")
# This implementation connects immediately adjacent eligible tokens.
# ngram_max controls output phrase length, not the co-occurrence window.
result <- textrank_keywords(ann$lemma, relevant = keep,
                           ngram_max = 2, sep = " ")
scores <- sort(result$pagerank$vector, decreasing = TRUE)
print(round(head(scores, 6), 4))

# Inspect observed adjacent pairs. cooc is the pair occurrence count.
pairs <- cooccurrence(ann$lemma, relevant = keep)
print(head(pairs, 3))
print(pairs[pairs$term1 == "new" | pairs$term2 == "new", ])

# TextRank (3/3): print the top five and draw their neighbours.
# Scores come from the full TextRank network; we show a smaller part here.
print(round(head(scores, 5), 4))
library(igraph)
top5 <- names(head(scores, 5))
links <- subset(pairs,
  term1 %in% top5 | term2 %in% top5)
g <- graph_from_data_frame(links, directed = FALSE)
set.seed(4)
plot(g, layout = layout_with_fr(g),
     vertex.size = 6, vertex.color = "#7cae96",
     vertex.label.color = "#314f4f",
     vertex.label.cex = 1.5,
     edge.width = E(g)$cooc)
# Each line is an observed adjacent noun/adjective pair.
# A thicker line means that pair occurs more often.
# Try head(scores, 10), rerun from top5 onwards, and compare the network.
# We do not recompute PageRank on this smaller graph.

# Inspect model predictions before accepting a candidate.
print(ann[ann$lemma == "endure", c("token", "lemma", "upos")])
# Phrase output: freq counts occurrences; it is NOT the PageRank score.
print(head(result$keywords))
# High centrality does not establish relevance or negative evaluation.
R console output (run locally)
> library(udpipe)

> dir.create("udpipe_models", showWarnings = FALSE)

> info <- udpipe_download_model("english-ewt",
+   model_dir = "udpipe_models", overwrite = FALSE)

> model <- udpipe_load_model(info$file_model)

> library(quanteda)
Package version: 4.5.1
Unicode version: 17.0
ICU version: 78.3
Parallel computing: 2 of 2 threads used.
See https://quanteda.io for tutorials and examples.

> library(textrank)

> speech <- corpus_subset(data_corpus_inaugural, Year == 2013)

> text <- as.character(speech)

> ann <- as.data.frame(udpipe_annotate(model, x = text,
+                                   parser = "none"))

> keep <- ann$upos %in% c("NOUN", "ADJ")

> result <- textrank_keywords(ann$lemma, relevant = keep,
+                            ngram_max = 2, sep = " ")

> scores <- sort(result$pagerank$vector, decreasing = TRUE)

> print(round(head(scores, 6), 4))
    new      we require  nation  common   these 
 0.0125  0.0122  0.0112  0.0090  0.0089  0.0083 

> pairs <- cooccurrence(ann$lemma, relevant = keep)

> print(head(pairs, 3))
       term1   term2 cooc
1 individual freedom    2
2        new     job    2
3     fellow citizen    1

> print(pairs[pairs$term1 == "new" | pairs$term2 == "new", ])
     term1      term2 cooc
2      new        job    2
30 require        new    1
31     new   response    1
57     new       idea    1
79     new industries    1

> print(round(head(scores, 5), 4))
    new      we require  nation  common 
 0.0125  0.0122  0.0112  0.0090  0.0089 

> library(igraph)

Attaching package: ‘igraph’

The following objects are masked from ‘package:stats’:

    decompose, spectrum

The following object is masked from ‘package:base’:

    union


> top5 <- names(head(scores, 5))

> links <- subset(pairs,
+   term1 %in% top5 | term2 %in% top5)

> g <- graph_from_data_frame(links, directed = FALSE)

> set.seed(4)

> plot(g, layout = layout_with_fr(g),
+      vertex.size = 6, vertex.color = "#7cae96",
+      vertex.label.color = "#314f4f",
+      vertex.label.cex = 1.5,
+      edge.width = E(g)$cooc)

> 
> print(ann[ann$lemma == "endure", c("token", "lemma", "upos")])
        token  lemma upos
872   endures endure VERB
1303 enduring endure VERB
2281 enduring endure VERB

> print(head(result$keywords))
  keyword ngram freq
1      we     1  148
2      be     1   57
3  nation     1    8
4   these     1    8
5 citizen     1    7
6   we be     2    6
Local TextRank does not match slides 82–83 (side by side)
RankSlide 82 (instructor’s run)Local (udpipe 0.8.16, textrank 0.3.1, english-ewt 2.5)
1new 0.0161new 0.0125
2same 0.0096we 0.0122
3endure 0.0095require 0.0112
4nation 0.0094nation 0.0090
5common 0.0092common 0.0089
6hard 0.0083these 0.0083

The first two co-occurrence pairs (individual–freedom 2, new–job 2) match the slides; the third differs (slides: other–nation 2; local: fellow–citizen 1). The local POS tagging looks faulty: diagnostics showed the pronoun we tagged as NOUN 5 times and as NUM 8 times, so it was treated as a candidate; all three forms of endure were tagged as VERB (the slides say some were tagged as nouns). Possible causes (unverified): on this aarch64 machine the first udpipe compilation was aborted for lack of memory and it was recompiled with -O0; or the package/model versions differ from the instructor’s. The same model gives exactly the slide-79 result for the single O01 sentence (Housing costs are unaffordable.). Please treat the numbers on slides 82–83 as authoritative; the local output only illustrates that “POS-tagging errors directly change the TextRank candidates” — which is exactly why slide 82 asks you to review them by hand.

Named entities (Flair, optional Python) Slides 84–86

POS tags word classes; NER finds names and their types. Result on slide 85: Barack Obama → PER, United Nations → ORG, New York → LOC; United Nations is one entity span.

Not run locally

examples/W4_flair_ner.py requires pip install flair (including PyTorch) and downloads the ner-fast model on first run; Flair is not installed on this build machine, so these notes did not rerun it, and the results above are quoted from slide 85.

Slide 86: “The minister praised the NHS but criticized its funding.” — mentioning an organization does not mean the speaker supports it; an entity mention is not a stance.

Embeddings and LLMs can propose candidate terms Slide 87

Seed concept → suggested terms → examples in the corpus → researcher review. Embeddings can suggest related expressions; LLMs can propose variants or organize candidate lists; but antonyms and unrelated associations may also appear. Keep an independent human benchmark: these tools assist dictionary development; they cannot certify validity.

Extending to Chinese text Slide 88

ChoiceExample
SegmentationAre relevant expressions split incorrectly?
Character normalizationAre traditional/simplified and variant characters merged appropriately?
Entity aliasesDo abbreviations link to the correct institution?
Negation and contextDoes the phrase express support, criticism or a quotation?

Validate within the language and political domain of the project. Supplement (not from the lecture): for example, 「不」, 「沒有」 and 「未必」 (not / not have / not necessarily) often sit right before the evaluative word in Chinese; whether the segmenter cuts 「不好」 (not good) into one word or two directly determines whether the dictionary can match 「好」 (good).

Five sentences, three labelling methods Slides 89–90

Label them yourself first, then see how the dictionary labels them:

✍️You vs the dictionaryExercise · dictionary results = local run of five_sentence_sentiment.R
R console output (run locally, examples/five_sentence_sentiment.R)
> library(quanteda)

> dictionary_path <- "Dictionaries/teaching_affect.dic"

> sentences <- c(
+   "This policy is good.",
+   "This policy is bad.",
+   "This policy is not good.",
+   "Excellent, another tax increase.",
+   "The committee met on Tuesday."
+ )

> own_dictionary <- dictionary(file = dictionary_path, format = "LIWC")

> sentence_tokens <- tokens(sentences, remove_punct = TRUE)

> matched_tokens <- tokens_lookup(sentence_tokens, own_dictionary, capkeys = FALSE)

> matched_dfm <- dfm(matched_tokens)

> matched <- as.matrix(matched_dfm)

> net <- matched[, "positive"] - matched[, "negative"]

> total_matches <- rowSums(matched)

> status <- rep("balanced", length(sentences))

> status[net > 0] <- "positive"

> status[net < 0] <- "negative"

> status[total_matches == 0] <- "unmatched"

> dictionary_result <- data.frame(
+   id = seq_along(sentences), sentence = sentences,
+   positive = matched[, "positive"], negative = matched[, "negative"],
+   dictionary_status = status, row.names = NULL
+ )

> print(dictionary_result, row.names = FALSE)
 id                         sentence positive negative dictionary_status
  1             This policy is good.        1        0          positive
  2              This policy is bad.        0        1          negative
  3         This policy is not good.        1        0          positive
  4 Excellent, another tax increase.        1        0          positive
  5    The committee met on Tuesday.        0        0         unmatched

> assumed_latency <- data.frame(
+   method = c("Dictionary", "Transformer classifier", "Prompted LLM"),
+   sentences_per_batch = 5L,
+   assumed_seconds = c(0.02, 0.30, 3.00)
+ )

> cat("\nFICTIONAL batch times, not measurements. No Transformer or LLM was run.\n")

FICTIONAL batch times, not measurements. No Transformer or LLM was run.

> print(assumed_latency, row.names = FALSE)
                 method sentences_per_batch assumed_seconds
             Dictionary                   5            0.02
 Transformer classifier                   5            0.30
           Prompted LLM                   5            3.00

> cat("\nCheck negation and possible irony; unmatched does not establish neutral sentiment.\n")

Check negation and possible irony; unmatched does not establish neutral sentiment.

The timing comparison on slide 90 is hypothetical (dictionary 0.02 s, transformer 0.30 s, LLM 3.00 s), and the instructor’s script says so explicitly: “FICTIONAL batch times, not measurements. No Transformer or LLM was run.” Can faster labelling answer the research question? What validation is still needed?

TextRank ranks new first. The most reasonable next step?
High centrality does not establish relevance. Slide 82
“Excellent, another tax increase.” is labelled positive by the dictionary. What is the problem?
Check negation and possible irony. Slide 89
11 · Practice

Back to your project + the four after-class Lab tasks

The final part of the slides brings all the concepts back to “writing the methods section” and “your own project”. Then come the four tasks of the after-class Lab (45–60 minutes, ungraded, no submission); all output below is from local runs of W4/lab/Lab_Session_W4.R and answers/Lab_Session_W4_Answers.R.

What the methods section should report Slide 91

  • Corpus scope, source and unit of analysis.
  • Dictionary source, version, language and modifications.
  • Rules for matching, preprocessing, the denominator and zeros.
  • Design and results of human validation, and the remaining errors.
  • Code and access information sufficient to audit the whole workflow.

Applying the concepts to your project Slides 92–93

Sentence frames on slide 92: I want to measure …, not just count …; my unit of analysis is …; one possible false positive is …; one possible false negative is …; I will validate this measure with …. Extending the opening question: what further rules are needed to identify negative evaluations of household conditions? Slide 93: is a dictionary right for your project? List two strengths and two limitations; how do you trade off speed, transparency and context sensitivity?

Chapter 14 has a research plan builder that turns these sentence frames into Markdown.

O02: your own policy dictionary (optional challenge) Slide 94

Add one justified energy-policy term, then work in pairs: find one passage that supports it and one possible false positive.

R · O02 (slide 94; not in W4_classroom.R, not run separately here)
my_dict <- dictionary(list(energy = c("energy", "gas bills")))
matched <- tokens_lookup(discovery_tokens, my_dict)
my_dfm <- dfm(matched)
my_counts <- as.numeric(my_dfm[, "energy"])
sum(my_counts > 0)
my_context <- kwic(discovery_tokens, "energy", window = 6)
head(my_context, 3)

The KWIC reading exercise in Chapter 02 and the dictionary validation bench in Chapter 07 can serve as an online version of O02.

Lab task 1: read the dictionary, inspect the matches Slide 97

After the Setup block (same as C01; it runs source("workflow.R")), first read the raw .dic file:

R console output (run locally, W4/lab/Lab_Session_W4.R, code chunk 2)
> readLines("Dictionaries/teaching_affect.dic")
 [1] "%"            "1 positive"   "2 negative"   "%"            "good 1"       "excellent 1"  "success 1"   
 [8] "successful 1" "improve 1"    "bad 2"        "failure 2"    "crisis 2"     "harm 2"       "harmful 2"   

> toy_sentiment <- dictionary(file = "Dictionaries/teaching_affect.dic",
+                             format = "LIWC")

> toy_sentiment
Dictionary object with 2 key entries.
- [positive]:
  - excellent, good, improve, success, successful
- [negative]:
  - bad, crisis, failure, harm, harmful
R console output (run locally, W4/lab/Lab_Session_W4.R, code chunk 3)
> texts <- c("The policy is good.", "The policy is not good.")

> example_tokens <- tokens(texts, remove_punct = TRUE)

> example_dfm <- dfm(example_tokens)

> example_hits <- dfm_lookup(example_dfm, toy_sentiment)

> counts <- convert(example_hits, to = "data.frame")

> counts
  doc_id positive negative
1  text1        1        0
2  text2        1        0
R console output (run locally, W4/lab/Lab_Session_W4.R, code chunk 4)
> word_count <- ntoken(example_tokens)

> positive <- counts$positive

> negative <- counts$negative

> net_score <- 100 * (positive - negative) / word_count

> net_score
text1 text2 
   25    20 

25 and 20: one positive match divided by 4 words and by 5 words. The second sentence scores lower because not adds to the denominator, not because the rule recognized the negation.

R console output (run locally, W4/lab/Lab_Session_W4.R, code chunk 5)
> # The setup above created these five named examples.
> check_texts
                             good                           negated                         unmatched 
            "The policy is good."         "The policy is not good."       "The minister spoke today." 
                         balanced                             empty 
"A good plan with a bad outcome."                                "" 

> check_tokens <- tokens(check_texts, remove_punct = TRUE)

> check_dfm <- dfm(check_tokens)

> check_hits <- dfm_lookup(check_dfm, toy_sentiment)

> convert(check_hits, to = "data.frame")
     doc_id positive negative
1      good        1        0
2   negated        1        0
3 unmatched        0        0
4  balanced        1        1
5     empty        0        0

> # Prepared by workflow.R using the three formulas in the table above.
> check_scores
     doc_id tokens positive negative net_per100 coverage_per100 balance no_match
1      good      4        1        0         25        25.00000       1    FALSE
2   negated      5        1        0         20        20.00000       1    FALSE
3 unmatched      4        0        0          0         0.00000      NA     TRUE
4  balanced      7        1        1          0        28.57143       0    FALSE
5     empty      0        0        0         NA              NA      NA     TRUE

Lab task 2: change one energy-policy rule

Coding rules (Lab handout, section 2)
  • 1 — relevant: discusses energy production, supply, prices, affordability or transition (e.g. electricity bills, heating costs, renewables, coal-mine closures). One substantive passage is enough; the speaker need not support the policy.
  • 0 — not relevant: political power, an unrelated legislative bill, personal energy and tear gas do not count. General climate discussion counts only when it is linked to energy.
  • Unsure: leave blank, write down why, and discuss before scoring. Do not treat unsure as 0.
R console output (run locally, W4/lab/Lab_Session_W4.R, code chunk 6)
> policy_entries <- read.csv("Dictionaries/energy_policy.csv")

> head(policy_entries)
  version category   pattern
1      v1   energy    energy
2      v1   energy     power
3      v1   energy electric*
4      v1   energy       gas
5      v1   energy     bill*
6      v2   energy    energy

> # Read the v1 patterns, then put them in a dictionary category.
> v1_entries <- subset(policy_entries, version == "v1")

> energy_v1 <- dictionary(list(energy = v1_entries$pattern))

> v2_entries <- subset(policy_entries, version == "v2")

> energy_v2 <- dictionary(list(energy = v2_entries$pattern))

> energy_v1
Dictionary object with 1 key entry.
- [energy]:
  - energy, power, electric*, gas, bill*

> energy_v2
Dictionary object with 1 key entry.
- [energy]:
  - energy, electric*, gas bill*, renewab*, solar*, wind farm*, fossil fuel*

> contexts <- kwic(discovery_tokens, pattern = c("power", "gas", "bill*"),
+                  valuetype = "glob", window = 8)

> head(contexts, 10)
Keyword-in-context with 10 matches.
                                                                                 
  [speech_0006, 32]     opinion. on the question whether any additional | power |
  [speech_0006, 37]        whether any additional power is given by the | bill  |
 [speech_0006, 233]                   the case. the third object of the | bill  |
 [speech_0006, 254]         acquired for public purposes. in effect the | bill  |
  [speech_0008, 24] special act undertakers will be over-ridden by this | bill  |
  [speech_0019, 38]          were very widely published and there was a | power |
 [speech_0019, 165]   considered these proposals very carefully. he had | power |
  [speech_0021, 36]     it would facilitate the further progress of the | bill  |
  [speech_0021, 61]      to avoid lengthening the committee stage. this | bill  |
 [speech_0021, 426]                    to remove them. there are in the | bill  |
                                                               
 is given by the bill to local authorities                     
 to local authorities in blighted areas—not war-damaged areas—i
 is to regulate the compensation payable in respect            
 provides that where land is compulsorily acquired for         
 , particularly as regards special provisions which may        
 , which we can be quite certain was                           
 under the act to submit them to the                           
 if we were to have a reply to                                 
 is a very drastic measure. the housing                        
 at present no default powers. if a                            
R console output (run locally, W4/lab/Lab_Session_W4.R, code chunk 7)
> first_id <- contexts$docname[1]

> original <- subset(speeches, doc_id == first_id)

> original$text
[1] "I will try again, but I repudiate the idea that I had any irritation at all: that is a matter of opinion. On the question whether any additional power is given by the Bill to local authorities in blighted areas—not war-damaged areas—I say the answer is, \"Yes.\" To start with, it affords greater expedition in acquisition. It absolves them from personal notifications and allows them to give bl … [truncated]
R console output (run locally, W4/lab/Lab_Session_W4.R, code chunk 8)
> energy_revised <- dictionary(list(
+   energy = c("energy", "wind farm*", "electric*", "gas", "bill*")
+ ))

> revision_texts <- c(
+   wind = "The government should approve new wind farms.",
+   authority = "Parliament must retain the power to question ministers."
+ )

> revision_tokens <- tokens(revision_texts, remove_punct = FALSE)

> before_tokens <- tokens_lookup(revision_tokens, energy_v1, capkeys = FALSE)

> before_counts <- convert(dfm(before_tokens), to = "data.frame")

> after_tokens <- tokens_lookup(revision_tokens, energy_revised, capkeys = FALSE)

> after_counts <- convert(dfm(after_tokens), to = "data.frame")

> data.frame(sentence = before_counts$doc_id,
+            before = before_counts$energy,
+            after = after_counts$energy)
   sentence before after
1      wind      0     1
2 authority      1     0

The answers’ reading: wind goes from 0 to 1 and authority from 1 to 0 — this change fixes two examples. Next, check which errors remain in the other sentences.

R console output (run locally, W4/lab/Lab_Session_W4.R, code chunk 9)
> matched_tokens <- tokens_lookup(discovery_tokens, energy_v2, capkeys = FALSE)

> match_dfm <- dfm(matched_tokens)

> head(match_dfm, 6)
dfm of 6 documents x 1 feature (0 occurrences, 100.00% sparsity) and 12 docvars.
             features
docs          energy
  speech_0001      0
  speech_0002      0
  speech_0003      0
  speech_0004      0
  speech_0005      0
  speech_0006      0

Lab task 3: inspect development-set errors

R console output (run locally, W4/lab/Lab_Session_W4.R, code chunk 10)
> # Read the labelled teaching examples and generate predictions explicitly.
> synthetic <- read.csv("Data/synthetic_validation.csv")

> example_corpus <- corpus(synthetic, text_field = "text", docid_field = "doc_id")

> example_tokens <- tokens(example_corpus, remove_punct = FALSE)

> # Apply v1, then v2. Each matched phrase counts once.
> v1_matches <- tokens_lookup(example_tokens, energy_v1, capkeys = FALSE)

> v1_dfm <- dfm(v1_matches)

> v1_binary <- dfm_weight(v1_dfm, scheme = "boolean")

> v1_predictions <- convert(v1_binary, to = "data.frame")

> synthetic$v1 <- v1_predictions$energy

> v2_matches <- tokens_lookup(example_tokens, energy_v2, capkeys = FALSE)

> v2_dfm <- dfm(v2_matches)

> v2_binary <- dfm_weight(v2_dfm, scheme = "boolean")

> v2_predictions <- convert(v2_binary, to = "data.frame")

> synthetic$v2 <- v2_predictions$energy
R console output (run locally, W4/lab/Lab_Session_W4.R, code chunk 11)
> dev <- subset(synthetic, split == "development")

> dev[, c("doc_id", "text", "human", "v1", "v2")]
   doc_id                                                    text human v1 v2
1   dev01                   We must address rising energy prices.     1  1  1
2   dev02             Electricity supply needs public investment.     1  1  1
3   dev03                 Families cannot afford their gas bills.     1  1  1
4   dev04                  Subsidies should support solar panels.     1  0  1
5   dev05           The government should approve new wind farms.     1  0  1
6   dev06                   We should reduce fossil fuel imports.     1  0  1
7   dev07 Parliament must retain the power to question ministers.     0  1  0
8   dev08                  This bill reforms criminal sentencing.     0  1  0
9   dev09                    Police used tear gas at the protest.     0  1  0
10  dev10              The minister brought energy to the debate.     0  1  1
11  dev11                           Schools need a larger budget.     0  0  0
12  dev12               The committee discussed train timetables.     0  0  0

The worked answers list only the development sentences that v1 gets wrong:

R console output (run locally, answers/Lab_Session_W4_Answers.R)
> errors <- subset(dev, v1 != human)

> errors[, c("doc_id", "text", "human", "v1", "v2")]
   doc_id                                                    text human v1 v2
4   dev04                  Subsidies should support solar panels.     1  0  1
5   dev05           The government should approve new wind farms.     1  0  1
6   dev06                   We should reduce fossil fuel imports.     1  0  1
7   dev07 Parliament must retain the power to question ministers.     0  1  0
8   dev08                  This bill reforms criminal sentencing.     0  1  0
9   dev09                    Police used tear gas at the protest.     0  1  0
10  dev10              The minister brought energy to the debate.     0  1  1

The answers’ explanation: the development sentences show why one might drop bare power, gas and bill* and add expressions for renewables, solar panels, wind farms and fossil fuels. The “dictionary validation bench” in Chapter 07 lets you do this step interactively.

Lab task 4: freeze v2 and compute precision/recall/F1 on the test sentences

R console output (run locally, W4/lab/Lab_Session_W4.R, code chunk 13)
> test <- subset(synthetic, split == "test")

> # 0 = not relevant; 1 = relevant. Keep both categories in the table.
> predicted <- factor(test$v2, levels = c(0, 1))

> human <- factor(test$human, levels = c(0, 1))

> table(predicted, human)
         human
predicted 0 1
        0 5 2
        1 1 4
R console output (run locally, W4/lab/Lab_Session_W4.R, code chunk 14)
> # Compare each dictionary prediction with its teaching label.
> TP <- sum(test$v2 == 1 & test$human == 1)

> FP <- sum(test$v2 == 1 & test$human == 0)

> FN <- sum(test$v2 == 0 & test$human == 1)

> TN <- sum(test$v2 == 0 & test$human == 0)

> precision <- TP / (TP + FP)

> recall <- TP / (TP + FN)

> F1 <- 2 * TP / (2 * TP + FP + FN)

> c(TP = TP, FP = FP, FN = FN, TN = TN)
TP FP FN TN 
 4  1  2  5 

> c(precision = precision, recall = recall, F1 = F1)
precision    recall        F1 
0.8000000 0.6666667 0.7272727 
R console output (run locally, answers/Lab_Session_W4_Answers.R)
> errors <- subset(test, v2 != human)

> errors[, c("doc_id", "text", "human", "v2")]
   doc_id                                                  text human v2
17 test05 The closure of coal mines requires a transition plan.     1  0
18 test06               Heating tariffs must remain affordable.     1  0
22 test10                 Her energy transformed the committee.     0  1
  • v2: TP = 4, FP = 1, FN = 2, TN = 5; precision 0.80, recall 0.667, F1 0.727, matching slide 95.
  • answers: v1 finds the same 4 relevant sentences but also flags 4 irrelevant ones.
  • Adding coal or heating now would be revising the dictionary with information from the test sentences; evaluating the new version needs a new test set.
  • These results describe only the 12 test sentences; evaluating parliamentary speeches requires human labels for those speeches.

W6 preview: five texts, one hard decision Slide 96

W5 (October 9) is a holiday; W6 (October 16) covers human coding and classification. For now, label five texts with a short codebook, explain one uncertain decision, and keep the dictionary predictions separate; about 10 minutes, no model training and no upload.

R console output (run locally, W4/lab/Lab_Session_W4.R, code chunk 15)
> development_texts <- subset(coding_template, split == "development")

> preview <- head(development_texts, 5)

> preview[, c("doc_id", "text")]
       doc_id
1 speech_3484
2 speech_0299
3 speech_3560
4 speech_1238
5 speech_0963
                                                                                                                                                                                                                                                                                                                                                                                                                 … [truncated]
1 That is why I have appealed to the Disraeli wing of the Conservative party, which formed a radical, reforming Government who addressed some of the abuses of power of previous Governments. In appealing to Conservative Members to support the amendments, I draw their attention to the congruity between the intent and content of the amendments and the policies set out in their party's manifesto at th … [truncated]
2                                                                                                                                                                                                                                                                                                                                                                                                                … [truncated]
3                                                                                                                                                                                                                                                                                                                                                                                This petition is signed by more … [truncated]
4                                                                                                                                                                                                                                                                                                                                                                                                                … [truncated]
5                                                                                                                                                                                                                                                                                                                                                                                                                … [truncated]
🏷Labelling sheet for five development speechesExercise · texts = first five of coding_template (run locally, set.seed(719104))

Optional: party comparison

R console output (run locally, W4/lab/Lab_Session_W4.R, code chunk 16)
> # quanteda adds counts within each party.
> party_matches <- tokens_lookup(policy_tokens, energy_v2, capkeys = FALSE)

> party_dfm <- dfm(party_matches)

> party_dfm <- dfm_group(party_dfm, groups = party)

> # Group original word counts separately to preserve the denominator.
> party_words <- dfm(toks)

> party_words <- dfm_group(party_words, groups = party)

> party_summary <- convert(party_dfm, to = "data.frame")

> party_summary$tokens <- ntoken(party_words)

> party_summary$per1000 <- 1000 * party_summary$energy / party_summary$tokens

> head(party_summary, 6)
                              doc_id energy tokens    per1000
1 Alliance Party of Northern Ireland      0     44 0.00000000
2   Communist Party of Great Britain      0     36 0.00000000
3                       Conservative    151 447158 0.33768824
4          Democratic Unionist Party      1  11814 0.08464534
5   Green Party of England and Wales      2    217 9.21658986
6                        Independent      1   1394 0.71736011

Note that the Lab version aggregates with dfm_group(); the result should match v2 in party_rates from Chapter 06 (likewise aggregating first, then dividing).

Run checklist

✅Class C01–C16 + Lab tasksTick the ones you have run on your own computer
In Lab task 4 you see that v2 misses two sentences and want to add coal. The correct approach?
Using test information to revise the dictionary needs a fresh test set (answers). Slide 95
12 · Reading guide

Reading guide

Three required readings (slide 98). None of their full texts is in the course repo, so the cards below only summarize what the slides say (with slide numbers) and do not cite paper pages. The only relevant full text legitimately in the repo is Grimmer & Stewart (2013) from W1; its dictionary passages are cited with paper page numbers.

Denny & Spirling (2018) Slides 39–41, 98

Reference“Text Preprocessing for Unsupervised Learning: Why It Matters, When It Misleads, and What to Do about It.” Political Analysis 26(2): 168–189.
Argument used this weekThe same 8 UK manifestos (1983–1997), the same Wordfish model: 128 preprocessing specifications yield 12 different orderings (slide 40).
Back to dictionariesDoes the substantive comparison hold up under reasonable scoring choices? (Slide 41; Chapters 05–06 of these notes)
Full textNot in the repo. Without the full text, paper page numbers cannot be given.

Rauh (2018) Slides 56–60, 98

Reference“Validating a Sentiment Dictionary for German Political Language: A Workbench Note.” Journal of Information Technology & Politics 15(4): 319–343.
DesignCombined SentiWS and GermanPolarityClues, manual review, a two-word negation rule; (positive − negative) / retained terms; 3 coders, 1,500 Bundestag sentences (slide 57).
Key numbersExact agreement 59.1%, ordinal alpha .675 (slide 58); positive evaluations are easier to recover than negative ones; scores cluster near 0 (slide 60).
Full textNot in the repo. Without the full text, paper page numbers cannot be given.

Proksch, Lowe, Wäckerle & Soroka (2019) Slides 61–66, 98

Reference“Multilingual Sentiment Analysis: A New Approach to Measuring Conflict in Legislative Speeches.” Legislative Studies Quarterly 44(1): 97–131.
DesignAbout 26,000 speeches, 871 German government bills (2005–2017); translated Lexicoder; log((P + 0.5) / (N + 0.5)); logistic regression (814 bills) (slides 62, 65).
Validation300 passages, two human ratings each; group-level correlation about 0.9, not 90% accuracy (slide 63). Translation is a measurement decision (slide 64).
Full textNot in the repo. Without the full text, paper page numbers cannot be given.

Grimmer & Stewart (2013) (repo: W1/papers/Grimmer2013.pdf)

Reference“Text as Data: The Promise and Pitfalls of Automatic Content Analysis Methods for Political Texts.” Political Analysis 21(3): 267–297. Cited on slides 7, 9 and 11.
Definition of dictionaries (p. 274)Dictionaries use the rate at which keywords appear to classify documents or to measure the extent to which documents belong to a category; the simplest tone measure gives each word +1/−1 and divides by the document’s word count Ni — the form of net tone in Chapter 04 (apart from the multiplication by 100).
Domain specificity (pp. 274–275)Dictionary scores must closely match how words are used in that context; the authors cite Loughran & McDonald (2011): tax, cost, crude (oil) and cancer carry negative connotations in other contexts but may carry positive ones in corporate financial reports; applying a dictionary built for one domain to another can produce serious errors.
Validation (p. 275; principle 4 on p. 271)The authors note that dictionary measures are “rarely validated” and recommend either reducing the problem to a binary classification validated against a human gold standard, or validating along several dimensions as with unsupervised methods. Principle 4: “Validate, Validate, Validate”.

Further reading and software (slide 99)

  • Grimmer, Roberts & Stewart (2022). Text as Data. Chapters 5 and 16.
  • Hvitfeldt & Silge. Supervised Machine Learning for Text Analysis in R. Chapters on tokenization and stopwords (online).
  • Eichorst & Lin (2019). “Resist to Commit.” The Journal of Politics 81(1): 15–32.
  • Boyle et al. (2025). “Catalysts for progress? Mapping policy insights from energy research.” Energy Research & Social Science 121: 103955.
  • Software: quanteda (dictionaries, KWIC, matching), quanteda.textstats (frequencies, collocations, keyness), UDPipe/TextRank, ggplot2, Flair (Python NER), irr (coder agreement), LIWC.

The full texts of the further readings above are not in the repo either; for close reading, they are available through the NTU Library or the university VPN.

13 · Wrap-up

Common pitfalls and glossary

Ten common pitfalls

Treating a “mention” as an “evaluation”

Mentioning inflation is not a negative evaluation of household conditions (slide 3). Topic words measure attention, evaluative words measure sentiment, and the two must be tied to the same target.

Treating sentiment as stance

Negative language can describe a problem while supporting a policy (slides 4, 66).

Comparing counts without dividing by length

speech_2792 has 20 bill* matches but 1.48 per 100 words; speech_4435 has only 4 but scores 5.80 (slide 31).

Treating 0 as neutral

No matches and offsetting positives and negatives both give 0; an empty text is NA (slide 34).

Removing stop words before matching negation or phrases

not is in stopwords("en") and gets deleted (slide 36); phrases must be matched before stop words are removed (slide 29).

Wildcards that are too broad

bill* catches billion and billericay (slide 28).

Claiming recall after reading only matched passages

False negatives can only be found among unmatched passages (slide 50).

Continuing to tune the dictionary on the test set

Test only after freezing; once test information is used, a new test set is needed (slides 24, 95; Lab answers).

Treating a group-level correlation as classification accuracy

The 0.9 in Proksch et al. is a group-level correlation (slide 63).

Assuming an off-the-shelf dictionary is suitable / licensed

Availability is not evidence of suitability (slide 14); importing a file is not obtaining a license (slide 68).

Flip cards: formulas and definitions

🃏Click a card to flip itExercise

Glossary

14 · Wrap-up

Final review, research plan and references

My progress

Final review (20 questions)

Research plan builder Slides 91–93

📝My dictionary measurement planExercise · exports Markdown for your final project
Markdown

References (per slides 98–99 and citations on individual slides)

  • Boyle et al. (2025). “Catalysts for progress? Mapping policy insights from energy research.” Energy Research & Social Science 121: 103955.
  • Denny, M. J., and A. Spirling (2018). Political Analysis 26(2): 168–189.
  • Eichorst, J., and N. C. N. Lin (2019). “Resist to Commit.” The Journal of Politics 81(1): 15–32.
  • Grimmer, J., M. E. Roberts, and B. M. Stewart (2022). Text as Data. Princeton University Press. Chapters 5 and 16.
  • Grimmer, J., and B. M. Stewart (2013). “Text as Data.” Political Analysis 21(3): 267–297.
  • Hvitfeldt, E., and J. Silge (2022). Supervised Machine Learning for Text Analysis in R.
  • Lin, W.-F. (2023). “Linguistic inquiry and word count in sport and exercise.” Physical Education Journal 56(1): 1–16. doi:10.6222/pej.202303_56(1).0001 (slide 75)
  • Lin, W.-F., C.-L. Huang, Y.-C. Lin, C.-L. Lee, and J. W. Pennebaker (2020). “The Revision of the Chinese Linguistic Inquiry and Word Count Dictionary 2015.” Survey Research – Method and Application 45: 73–118. doi:10.7014/SRMA.2020100004 (slide 76)
  • Proksch, S.-O., W. Lowe, J. Wäckerle, and S. Soroka (2019). Legislative Studies Quarterly 44(1): 97–131.
  • Rauh, C. (2018). Journal of Information Technology & Politics 15(4): 319–343.
These notes are based on the NTLDEV 7191 W4 slides (Yen-Chieh Liao, 2026-10-02; 99-page PDF, Last compiled 2026-10-08), W4/classroom/W4_classroom.R, workflow.R, examples/, W4/lab/Lab_Session_W4.R and answers/. R output is from a local rerun (R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64). The full texts of the three required readings are not in the repo; the reading cards are based on the slides. Passages and toy demos marked “Supplement (not from the lecture)” are additional explanation. Prepared 2026-11-06.
NTLDEV 7191 Text as Data · W4 interactive self-study notes · based on the 2026-10-02 lecture slides (2026-11-06)