⌂ Course index
🐞 Feedback
中文
Interactive features failed to start, so all chapters are shown in order as a static page. (Interactive labs, quiz scoring, progress and the slide panel need JavaScript; if an in-app preview shows no interaction, open the page in a desktop browser or Safari.)
00 · Overview

W10: Transformers: Architecture and Applications

W9's word embeddings gave one vector per word (or per occurrence). W10 goes one step further: a Transformer lets every token's vector take the whole passage into account, and these contextual representations are then connected to research labels. The lecture's thread is one sentence: one framework, two ways to turn text into research labels — fine-tune a classifier with human labels, or pair the text with a complete hypothesis and let an NLI model judge the relation.

Course route Slide 2

Slide 2 splits the week into four parts: 1 Transformer basics (tokens → attention → representations → fine-tuning), 2 Classification (three studies: oversight, issue attention, stance), 3 NLI (text + hypothesis → relation scores → stance), and the Lab (policy fine-tuning → evaluation → an NLI stance example). Click each step:

→ → → →

The slide PDF has 68 pages (page 1: Last compiled 2026-11-06 16:22:26; the materials were uploaded to the course repo on 2026-11-27). The README schedule lists W10 on Nov 13, but the materials arrived on Nov 27. These notes follow upstream commit 7c3a741. The instructor updated the W10 slides several times on 2026-11-27 (still 68 pages, same compile stamp); this version follows the 16:17 revision: slides 5–9 now use BERT's dog example and the mask slide is gone, and slides 13 and 20–22 now use the Women's March case.

Learning goals Slides 3, 13, 23, 38

Come back and tick each goal after reading:

  1. How a Transformer processes input: token IDs → vectors + positions → self-attention (Q/K/V) → stacked encoder layers → contextual representations.
  2. Pretraining vs. fine-tuning: MLM learns reusable representations, but research labels need a classification head and human labels; train/validation/test each have a job.
  3. Classification cases: name each case's text unit, human label, classifier output and the research measure built from the labels.
  4. NLI: separate the three relations (entailment/contradiction/neutral) from the final stance label; know that NLI is not automatically zero-shot.
  5. Lab results: read imbalanced data with per-class precision/recall/F1; explain why accuracy .93 can mean “predict 0 for everything”.

The two routes Slides 11, 23, 26

Task-specific classifier (Application 1)Existing NLI classifier (Application 2)
InputThe textThe text + a complete hypothesis
TrainingFine-tune encoder + head on this task's human labelsReuse a model trained on NLI relations; target-task fine-tuning optional (none in Burnham, yes in Laurer)
OutputOne class from a fixed label setRelation scores per hypothesis → decision rule → stance label
SharedBoth use Transformers; both need human validation (slide 26).

How to use these notes

  • The slide panel on the right follows the paragraph you are reading; every Slide n badge is clickable.
  • Lab numbers come from three sources, always labelled: stored 2024 notebook records, the course's 2026-11-27 preparation checks and NLI run, and a local rerun (Python 3.11, torch 2.5.1, transformers 4.57.6, flair 0.15.1, datasets 3.6.0, CPU).
  • Sections marked “Supplement (not from the lecture)” are extra explanations or toy demos, not slide content.

Chapter quiz

1. What are the two ways in slide 2's “one framework, two ways”?
Slides 2, 26
01 · Tokens and order

Tokens, IDs and word order

Build the input → process the context → reuse the output Slide 3

Slide 3 asks: how does a Transformer turn a token sequence into contextual representations? (1) Token IDs → vectors, plus position information; (2) self-attention + feed-forward layers process the context; (3) contextual representations learned through pretraining can support a task classifier (Vaswani et al. 2017 §§3.1–3.5; Devlin et al. 2019 §3).

A token is a model input unit Slide 4

Text we readTransformer input
A word may be the unit of analysisA word may be split into several tokens
A passage contains words and punctuationSpecial tokens mark boundaries or tasks (e.g. [CLS], [SEP])
We interpret the original textToken IDs index a model's vocabulary; ID → embedding lookup → input vectors
Slide 4's warning

Keep the tokenizer matched to the trained model. The Lab's Transformers route loads both tokenizer and model from distilbert-base-uncased (slide 53).

Real tokenizer output (run locally)

These are the actual outputs of the two Lab tokenizers on this machine (tad/labs/W10/tok_export.py). Switch sentence and model:

Interactive: pick a sentence and tokenizer; see tokens and IDs
What the real output shows (Supplement)

distilbert-base-uncased lowercases first (The → the) and splits Gardai into ga ##rda ##i; the multilingual cased model keeps case and splits it into Garda ##i. ## marks a subword attached to the previous token. The two models' IDs are completely different — which is why tokenizers cannot be mixed.

Word order is part of the input Slide 5

Slide 5 uses BERT's example “My dog is cute. He likes playing.” The bert-base-uncased tokenizer lowercases it and adds [CLS] and [SEP]: 11 tokens at positions 0–10. The encoder's input is token vectors + position information (Vaswani et al. 2017 §3.5; BERT Figure 2).

Interactive: click a token to see its position and vocabulary ID (real tokenizer run)
What the real run shows

The two periods sit at different positions (5 and 9) but share ID 1012: an ID points to a vocabulary entry; position information is added separately. This is what the Lab's optional warmup (lecture-warmup in the Lab handout) prints; run locally with Transformers 4.57.6, the tokens and IDs match the Lab handout's record (Transformers 4.54.0).

Supplement: why a bag of words cannot see word order (not slide content)

“The minister criticized the journalist.” and “The journalist criticized the minister.” have identical word counts but swapped actors and targets. A DFM (the bag of words from W2–W3) cannot tell them apart; position information can. This contrast is written for these notes; it is not on the slides.

Interactive: bag of words vs. sequence (using the real tokens above)

Chapter quiz

1. Why load the tokenizer and model from the same checkpoint name?
Slides 4, 53
2. How many tokens (including [CLS] and [SEP]) does the bert-base-uncased tokenizer give slide 5's example?
Slide 5
02 · Self-attention

Self-attention and Q/K/V

Self-attention mixes information across positions Slide 6

Slide 6 uses BertViz to show bert-base-uncased, layer 5, head 5 (zero-based): to update dog, take information from the other input positions; the value vectors are combined by weight into dog's contextual representation (Vaswani et al. 2017 §3.2).

Read the connections at dog Slide 7

BERT can use every input position; learned matching scores set the mixing weights. Slide 7 lists rounded weights from the same model run:

Interactive: click a row to see how much of dog's update comes from that position (weights from slide 7)
PositionApprox. weightWhat is being mixed
he0.69Information from the position at he
[SEP]0.26Information from this input's final marker
Other 9 positions0.05 totalInformation from the remaining positions
Slide 7's caution

Darker line → larger mixing weight. But these weights alone do not prove that he refers to dog: attention weights are internal mixing proportions, not a linguistic coreference judgment.

Queries, keys and values Slide 8

Slide 8 is the neuron view of the same head, following the update at dog: Attention weights → weighted sum of V → updated vector at dog.

  1. Create Q, K and V: each position's current vector goes through three learned projections.
  2. Match Q with K: dog's query meets every key → scale → softmax weights.
  3. Combine the V vectors: the weighted sum of values is this head's output vector at dog.
Attention(Q, K, V) = softmax(QKᵀ / √dk) V

The formula is from Vaswani et al. (2017) §§3.2.1–3.2.3. The current slide 8 shows only the neuron view and does not print it (an earlier version on 2026-11-27 did), so this line is a supplement. Several heads run in parallel and their outputs are combined.

Attention calculator (Supplement: toy numbers, not from the lecture)

A 2-D toy Q, K, V to show how the formula works. The numbers are invented, not learned parameters; the goal is to see where the softmax weights come from and what √dk does.

Interactive: choose the query position, rotate the query and scale it; watch the softmax weights
How to read it (Supplement)

With a larger scale the gaps between dot products grow and softmax puts nearly all weight on one position. That is why the formula divides by √dk: in high dimensions dot products grow naturally, and without scaling softmax becomes too peaked and gradients small (the explanation in Vaswani et al. 2017 §3.2.1).

Chapter quiz

1. What decides how much information dog takes from he?
Slides 7–8
2. “Multi-head” means…
Slides 6–8
3. Slide 7 shows a weight of about 0.69 on he when updating dog. The most reasonable reading?
Slide 7 (the other 9 positions still total 0.05)
03 · Encoder layers

Encoder layers

An encoder repeats this processing Slide 9

Starting from token + position representations, each layer: ① mixes positions: multi-head self-attention → residual addition → LayerNorm; ② transforms each position: feed-forward network → residual addition → LayerNorm; ③ passes to the next layer, which repeats with its own learned parameters.

Each sublayer: LayerNorm(x + Sublayer(x))

The residual path adds the sublayer's input back to its output. The slide also notes that normalization order varies across Transformer architectures (Vaswani et al. 2017 §3.1, Figure 1, §3.3).

Supplement (not slide content): encoders vs. decoders

This week's Lab models (DistilBERT, DistilUSE, DeBERTa-v3) are all encoders: each position can use both left and right context, which suits representations and classification. A GPT-style causal decoder can use only earlier positions and is used for next-token generation (W12's LLMs). An earlier version of slide 9 on 2026-11-27 compared the two masks; the instructor later removed that slide, so only this note remains.

Chapter quiz

1. What is the order of the three steps in slide 9's encoder layer?
Slide 9
2. What does residual addition do?
Slide 9
04 · Pretraining and fine-tuning

Pretraining, fine-tuning and data splits

Pretraining learns reusable representations Slide 10

Example: “The government announced a [MASK] policy.” Masked language modeling predicts hidden tokens from context; the original text supplies the answers, so no human labels are needed. But the slide stresses that the model still needs a connection to our research labels (Grimmer, Roberts & Stewart 2022, Text as Data §8.5, p. 88; BERT §3.1). In the local tokenizer run in chapter 01, [MASK] is ID 103 in DistilBERT.

Fine-tuning connects representations to labels Slide 11

1Labeled texts→2Pretrained encoder→3Classification head→4Predicted labels

Prediction error updates both the encoder and the head; at inference, the trained model predicts labels for new texts (BERT Figure 1, §3.2). In the Lab, Flair's fine_tune=True and Transformers' AutoModelForSequenceClassification are this step (slides 48, 54).

Separate fitting, model choice and evaluation Slide 12

SplitPurposeExample decision
TrainingFit model parametersLearn from human labels
ValidationChoose settingsSelect a checkpoint or threshold
TestEstimate performance after choices are fixedReport held-out results

Split by speaker, document or time when the research setting requires it. The Lab's DATA.md notes that the original row split shares 2 distinct texts between train/validation, 4 between train/test and 2 between validation/test (after whitespace and case normalization), so it does not establish independence by document, source or time.

Practice: which split does each decision belong to?

Chapter quiz

1. Why does MLM pretraining need no human labels?
Slide 10
2. You select a checkpoint by validation macro-F1 and then report that validation score as final. The problem?
Slides 12, 56–58
05 · Classification

Application 1: three Transformer classification cases

Slide 13 lists the three cases with their applications and journals. The reading README asks the same questions of every case: What is the text unit? What does the human label mean? What does the classifier output? How does the research measure come from the labels?

Three cases at a glance Slide 13

Interactive: flip cards — answer the four questions first, then reveal
CaseApplicationJournal
1 · Liao & Tang (2026)Legislative oversight and electoral reformElectoral Studies
2 · Schöll et al. (2024)Citizen feedback and gender-issue attentionAmerican Journal of Political Science
3 · Bestvater & Monroe (2023)Sentiment versus target-specific stancePolitical Analysis

“Define the label, validate it, then use it in the analysis” was the conclusion line of the earlier slide 13; the current slides no longer carry it, but it is still a good frame for reading these three cases.

Case 1 · Liao & Tang (2026): targeted oversight Slides 14–16

  • Question: did Taiwan's electoral reform change legislators' local oversight?
  • Classification: fine-tune Chinese BERT on 7,216 human-labeled proposals and amendments (learn the label from legislation) → check the new text genre (written questions) with about 400 human-coded questions: GTQ F1 = .88 (§4.1 and footnote 9, pp. 4–5).
  • Research measure: 63,748 questions, 402 district legislators, 1999–2019; GTQ percentage = 100 × targeted questions / all questions within each legislator-year (§§5.1–5.2, pp. 6–7).
  • Reading the result: the initial GTQ share is lower after reform; the negative difference weakens over time (Figure 3, p. 7; Table 1, p. 6; Model 4 fitted trends with 95% CIs). Interpret with the time comparison and controls.
Why it matters (Supplement)

The training genre differs from the application genre: labels are learned from bills but applied to questions. So the authors validate separately on the new genre — slide 15's middle box, “Check the new text genre”.

Case 2 · Schöll, Gallego & Le Mens (2024): feedback and issue attention Slides 17–19

StageWhat enters the research measure?
Human labels and BERTAbout 20,000 tweets coded gender issue / other
ValidationPrecision .90 · recall .79
AggregationGender-related tweets / all tweets, for each politician-month

BERT supplies the topic label; retweets supply the feedback measure. Earlier relative feedback → later issue-attention share (p. 562; research variables pp. 564–565). Result: .11 for women and .07 for men — both positive, but their difference is not statistically clear (Table 4, p. 567; interpretation p. 568).

Three footnotes on slides 18–19

(1) Scores are reported on validation data; no separate untouched test set is established in the main text. (2) The coefficients are logit coefficients, not percentage-point effects; SEs are clustered by politician. (3) It is a panel association; retweet feedback does not represent all voters' preferences.

Case 3 · Bestvater & Monroe (2023): Sentiment is Not Stance Slides 20–22

A positive tone and support for a specified target are different labels. Slides 20–21 compare three measures of Women’s March approval: VADER (sentiment dictionary + rules), BERT fine-tuned on human stance labels, and human coding (the reference), each regressed on the author's political ideology.

Approval measureLabel sourceIdeology slopeN
VADERSentiment dictionary + rules−0.35928
BERTFine-tuned on human stance labels−0.761,501
Human codingManual approval / opposition labels−1.871,501

Target: approval of the 2017 Women's March. Logit coefficients, not percentage-point changes; estimation samples differ. A more negative slope means a sharper decline in approval with conservatism. Source: slide 21; Bestvater & Monroe (2023) Table 2, p. 241 (author ideology runs from −2.5 to 2.5, p. 241).

All three point the same way, but VADER's slope (−0.35) is far smaller than BERT's (−0.76) and human coding's (−1.87). The paper's reading: VADER weakens the apparent link between ideology and opinion — in particular it underrates how liberal authors approve and overrates how conservative authors oppose — which could make the movement look more widely supported across ideology than it was (pp. 241–242; Figure 3, p. 242). Slide 22 is Figure 3's curves: regression-estimated approval probabilities, not classifier confidence and not causal effects.

Supplementary observation (not slide content): BERT and human coding share N = 1,501, yet BERT's slope is only about 0.41 of the human one (−0.76 ÷ −1.87); the table does not explain the gap, so none is inferred here.

Supplement (not on the current slides): the paper's later Kavanaugh case

Slides 21–22 of an earlier version on 2026-11-27 used the paper's §5 case on Kavanaugh's confirmation: SVM and BERT trained on sentiment or stance labels, both evaluated on the same stance task. The current slides use the Women's March above instead; this is paper content I kept for comparison.

Training labelsSVM: stance F1BERT: stance F1
Sentiment.514.582
Stance.935.938

Mean F1 across fivefold cross-validation; §3.2 p. 244, §§5–5.1 pp. 249–251, Table 7 p. 251.

The training label determines which opinion the classifier learns. Switching method (SVM → BERT) adds .003–.07; switching labels (sentiment → stance) adds more than .35. One step further: on 2,785 held-out tweets, human labels and BERT stance both show approval rising with conservatism; a sentiment proxy gives a nearly flat curve that masks the association (§5.2 pp. 251–253; Table 8 p. 252; Figure 5 p. 253).

Practice: sentiment and stance of each sentence (Supplement: constructed examples, using the paper's Kavanaugh case)

The target is approval of Kavanaugh's confirmation (the paper's §5 case, not the current slides' Women's March). These sentences are written for these notes, modelled on the four cells of Bestvater & Monroe's Table 6 (p. 250); they are not data from the paper:

Interactive: choose sentiment (positive/negative) and stance (approve/oppose) for each sentence

Chapter quiz

1. Why does Case 1 validate on about 400 questions?
Slide 15
2. How should Schöll et al.'s .11 and .07 be read?
Slide 19
3. Women's March, Table 2: VADER slope −0.35, BERT −0.76, human coding −1.87. The most reasonable reading?
Slide 21
06 · NLI

Application 2: NLI — from three relations to stance labels

Paired input: text + full hypothesis Slide 23

Natural language inference (NLI) predicts whether the text entails, contradicts or leaves the hypothesis unresolved. The hypothesis is part of the input; the model still uses a Transformer (Bowman et al. 2015 §2.1; Laurer et al. 2024).

Text“The council discussed the housing bill today.”
Hypothesis“The council approved the housing bill today.”

Three NLI relations Slide 24

Slide 24's three examples are constructed teaching examples, not model predictions. These notes ran them through the Lab's NLI model (MoritzLaurer/DeBERTa-v3-large-mnli-fever-anli-ling-wanli, revision b3546ea, CPU) and read the full three-relation probabilities (softmax over entailment / neutral / contradiction):

Python output (run locally: Python 3.11, torch 2.5.1, transformers 4.57.6, flair 0.15.1, datasets 3.6.0)
{0: 'entailment', 1: 'neutral', 2: 'contradiction'}
The council discussed the housing bill today. || The council approved the housing bill today. -> {'entailment': 0.003, 'neutral': 0.9876, 'contradiction': 0.0094}
Today, the council voted to approve the housing bill. || The council approved the housing bill today. -> {'entailment': 0.9919, 'neutral': 0.0073, 'contradiction': 0.0008}
The council did not approve the housing bill today. || The council approved the housing bill today. -> {'entailment': 0.0006, 'neutral': 0.0003, 'contradiction': 0.9992}
Interactive: pick a premise; see the model's three relation probabilities (run locally)
Compared with the slide (Supplement)

The model's top relation matches the slide's teaching answer for all three: discussed → neutral (.9876), voted to approve → entailment (.9919), did not approve → contradiction (.9992). The slide's point: NLI neutral means insufficient evidence about this hypothesis.

From NLI relations to stance labels Slide 25

Text + each hypothesis→Relation scores→Decision rule→Stance label
Slide 25's three warnings

(1) Not entailed does not establish opposition. (2) NLI neutral is not automatically neutral stance. (3) Define how to compare scores and handle uncertain cases, and validate the rule against human labels (Burnham 2025 §§3.2.1–3.2.3, pp. 619–620).

Task-specific classifier vs. existing NLI classifier Slide 26

Same text: “I oppose Trump’s policies.”Task-specific classifierExisting NLI classifier
InputThe tweetThe tweet + a stance hypothesis
TrainingFine-tune on human stance labels for this taskReuse a model trained on NLI relations
OutputA class from the trained label setCompare hypotheses to select a stance

Both use Transformers. This NLI example skips target-task fitting; both approaches still need human validation.

Stance hypotheses for one tweet Slide 27

Burnham's official tutorial uses the template The author of this tweet {} Trump. with candidates supports, opposes and does not express an opinion about, producing three complete hypotheses. The slide stresses: “no opinion” is a stance candidate; NLI neutral is a relation — not the same thing.

Interactive: hypothesis builder — edit the template or candidates and see the full sentences sent to the model

Chapter quiz

1. “The council discussed the housing bill today.” vs. hypothesis “The council approved the housing bill today.” — which relation?
Local run: neutral = .9876. Slide 24
2. A tweet does not entail “The author supports this bill.” Can you label it as opposing?
Slide 25
3. How does the stance candidate “does not express an opinion about” relate to NLI neutral?
Slide 27
07 · NLI applications

NLI applications: Laurer et al. (2024) and Burnham (2025)

Study 1 · Laurer et al. (2024) “Less Annotating, More Classifying” Slides 28–30

Background: codebooks define categories, but labeled training data are limited. NLI application: pair texts with category statements; add NLI training, then target-task fine-tuning. Research use: classify new political texts and evaluate against held-out human labels (Political Analysis 32:84–100; eight tasks from five datasets).

Text in the paper's Figure 1: “Our armed forces keep us safe”Entailment score in Figure 1
“The Military is good”.83
“The Military is bad”.07

Selected label in the figure: Military: Positive (Figure 1, p. 89). A paper illustration of the workflow, not a new classroom prediction or accuracy estimate.

Comparison in the paperReported evidence
100–2,500 target-task labelsBERT-NLI gains 10.7–18.3 macro-F1 points over TF-IDF classifiers, averaged across 8 tasks
500 labels for BERT-NLI vs. ~5,000 for classical methodsSimilar average macro-F1; the larger samples are available for 4 datasets

Figure 2 p. 93; Figure 3 p. 94; comparison and footnote 13 p. 95. Slide 30: these labeled-data gains include target-task fine-tuning; required annotation still depends on the task; evaluate on held-out human labels.

Study 2 · Burnham (2025) “Stance detection: a practical guide” Slides 31–33

Background: stance depends on a target, a proposition and context. NLI application: pair COVID-19 tweets with topic-matched hypotheses; use an existing DeBERTaV3 NLI model. Research use: aggregate threat-minimizing tweets per user and compare political associations (PSRM 13:611–628; published online in 2024).

Data862,923 COVID-19 tweets · 23,476 users · September 2020–February 2021
Hypothesis setMCCAccuracy
Set 1.6787%
Set 2.7490%

Checked on 300 human-labeled tweets; the references came from the original training pool. A tweet is flagged as threat-minimizing when a matched threat-minimizing hypothesis is entailed (§§4.1–4.2, pp. 624–625). Then: tweet labels → user counts → negative-binomial regression (Figure 3, p. 624). Slide 33: similar associations across label sets do not replace human validation; these are published observational associations, not causal estimates.

NLI training and validation choices Slide 34

Design choiceLaurer · Political AnalysisBurnham · PSRM
Research outputPolitical text categoriesCOVID-19 threat-minimization labels
Target-task fine-tuningYesNo in this application
Human checkHeld-out target-task labels300 tweets from the original training pool
Slide 34's conclusion

NLI does not automatically mean zero-shot. Both applications require explicit category definitions and a validated decision rule. These are different tasks, not a model ranking.

Chapter quiz

1. In Laurer et al.'s “500 labels ≈ classical 5,000”, is BERT-NLI fine-tuned on the target task?
Slides 30, 34
2. How does Burnham's COVID-19 application decide that a tweet minimizes the threat?
Slide 32
08 · Lab setup

Lab setup: environment, data and class imbalance

The Lab first fine-tunes policy classifiers (Irish policy excerpts: environmental vs. other policy), then reuses NLI for stance (slide 35). The two 2024 notebooks (Liao & Müller 2024) share the data but use different APIs: Flair (Sentence → Corpus → TextClassifier, multilingual DistilUSE) and Transformers (Tokenizer → DistilBERT → Trainer) (slide 36).

Three sources of numbers Slides 41, 50, 52, 59, 67

SourceContentLabel in these notes
2024 notebook recordsStored training logs and test reports in the original notebooks (Flair 2024-04-19; Transformers with original learning rate 0.3)“2024 record”
Course preparation checks and NLI run, 2026-11-27Versions, split counts, first training text; NLI on three teaching texts“course repo output”
Local rerunThe revised code from the slides, actually trained and run on this CPU“run locally”
The course's reminder

Slides 52 and 59 both say “2024 notebook record · not a new run of revised code”. The revised code needs its own run — chapter 09's local rerun does exactly that.

Install and versions Slides 39–41

shell (slide 39)
python -m pip install \
  torch datasets numpy pandas scikit-learn \
  flair transformers accelerate sentencepiece

In a notebook, install with %pip and then restart the kernel. Versions and device (slide 41's course check vs. this machine):

PackageCourse 2026-11-27Run locally
torch2.2.22.5.1
datasets2.19.03.6.0
numpy1.26.21.26.4
pandas2.2.12.2.3
scikit-learn1.3.21.9.1
flair0.13.10.15.1
transformers4.54.04.57.6
accelerate1.9.01.15.0
Available devicecpucpu
Python output (run locally: Python 3.11, torch 2.5.1, transformers 4.57.6, flair 0.15.1, datasets 3.6.0)
torch: 2.5.1
datasets: 3.6.0
numpy: 1.26.4
pandas: 2.2.3
scikit-learn: 1.9.1
flair: 0.15.1
transformers: 4.57.6
accelerate: 1.15.0
Available device: cpu

Versions differ because this machine reuses the Flair environment built for W9 (Python 3.11, Linux aarch64). The course check also reports only the available device; the device actually used appears in the trainer log (slides 40–41).

The shared dataset and label IDs Slides 42–44

Python · tad/labs/W10/w10_lab.py (follows slides p42–43)
device = torch.device('cuda') if torch.cuda.is_available() else (torch.device('mps') if torch.backends.mps.is_available() else torch.device('cpu'))
dataset = DatasetDict.load_from_disk('irish_environmental_policies')
train, validation, test = dataset['train'], dataset['validation'], dataset['test']
labels = train.features['label'].names
id2label = {i: name for i, name in enumerate(labels)}
label2id = {name: i for i, name in id2label.items()}

rows = []
for split_name, split in dataset.items():
    counts = Counter(split['label'])
    rows.append({'split': split_name, 'rows': len(split), 'other_policy': counts[0], 'environmental_policy': counts[1]})
print(pd.DataFrame(rows).to_string(index=False))
print(id2label)
example = train[0]
print(example['text'])
print('Reference:', id2label[example['label']])
print('# ==== P3 text length (supplement)')
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained('distilbert-base-uncased')
for n, s in dataset.items():
    L = pd.Series([len(tok(t)['input_ids']) for t in s['text']])
    print(n, 'tokens median %d p90 %d max %d ; >512: %d' % (L.median(), L.quantile(.9), L.max(), (L > 512).sum()))
Python output (run locally: Python 3.11, torch 2.5.1, transformers 4.57.6, flair 0.15.1, datasets 3.6.0)
     split  rows  other_policy  environmental_policy
     train  1880          1772                   108
validation   627           582                    45
      test   627           583                    44
{0: 'None Environment Policy', 1: 'Environment Policy'}
  More Community Policing  Garda community outreach activities should be enhanced and we  want to see, in particular, a significant increase in the number of  Gardai assigned to Community Policing and a heightened  awareness of this service within the Gardai and communities  throughout the country
Reference: None Environment Policy

Identical to slide 44: train 1,880 (1,772 / 108), validation 627 (582 / 45), test 627 (583 / 44); 0 → None Environment Policy, 1 → Environment Policy (original wording kept). The first training text is about community policing, reference label 0.

Token lengths, computed locally (Supplement):

Python output (run locally: Python 3.11, torch 2.5.1, transformers 4.57.6, flair 0.15.1, datasets 3.6.0)
train tokens median 22 p90 40 max 117 ; >512: 0
validation tokens median 22 p90 39 max 81 ; >512: 0
test tokens median 22 p90 39 max 78 ; >512: 0

Every text is far shorter than 512, so slide 54's padding="max_length" (pad every text to 512 positions) mostly adds padding here; chapter 09's local run pads per batch instead, as explained there.

Data browser: read the test texts (real data)

DATA.md asks you to read one training text, discuss why its label fits and record uncertainty about the topic boundary. All 627 test texts:

Interactive: filter by label, search a keyword

Class imbalance: accuracy can mislead Slide 38

Only 44 of 627 test excerpts are environmental policy. Slide 38: accuracy alone can hide a model that misses this class; read per-class precision, recall and F1, and compare with macro-F1 and accuracy.

Interactive: what if the model predicts 0 for everything?

Chapter quiz

1. Test has 583 zeros and 44 ones. Accuracy of a model that always predicts 0?
583 / 627 = .9298 — exactly the accuracy stored in the 2024 Transformers notebook. Slides 38, 59
2. Can a “2024 notebook record” stand in for the revised code's result?
Slides 52, 59
09 · Lab A/B

Lab A/B: fine-tuning with Flair and Transformers (run locally)

Approach A: Flair Slides 45–49, 51

  1. Texts become labeled Sentences: Sentence(row["text"]), add_label("label", str(row["label"])) (slide 46).
  2. Corpus and label dictionary: make_label_dictionary(..., add_dev_test=False, min_count=-1, add_unk=False) builds classes from train only; the dictionary holds the strings "0" and "1" (slide 47).
  3. Encoder + head: TransformerDocumentEmbeddings("sentence-transformers/distiluse-base-multilingual-cased-v2", fine_tune=True) + TextClassifier(..., multi_label=False) (slide 48).
  4. Training: SGD, rate .02, batch 16, three epochs; dev selects the checkpoint, test runs at the end; reload best-model.pt (slide 49).
Python · tad/labs/W10/w10_lab.py (follows slides p45–51)
import flair
from flair.data import Sentence, Corpus
from flair.embeddings import TransformerDocumentEmbeddings
from flair.models import TextClassifier
from flair.trainers import ModelTrainer
flair.set_seed(42)
flair.device = device
def as_sentences(split):
    out = []
    for row in split:
        s = Sentence(row['text']); s.add_label('label', str(row['label'])); out.append(s)
    return out
flair_train, flair_dev, flair_test = as_sentences(train), as_sentences(validation), as_sentences(test)
print('# ==== F1 sentences (slide p46)')
print(flair_train[0].to_plain_string())
print(flair_train[0].get_label('label').value)
corpus = Corpus(train=flair_train, dev=flair_dev, test=flair_test)
label_dict = corpus.make_label_dictionary(label_type='label', add_dev_test=False, min_count=-1, add_unk=False)
print('# ==== F2 label dictionary (slide p47)')
print(label_dict.get_items())
emb = TransformerDocumentEmbeddings('sentence-transformers/distiluse-base-multilingual-cased-v2', fine_tune=True)
clf = TextClassifier(emb, label_dictionary=label_dict, label_type='label', multi_label=False)
print('# ==== F3 train (slide p49)')
ModelTrainer(clf, corpus).train('qta_flair_python_model', shuffle=True, patience=3, learning_rate=0.02, mini_batch_size=16,
    max_epochs=3, write_weights=True, train_with_dev=False, train_with_test=False, monitor_test=False, use_final_model_for_eval=False)
model = TextClassifier.load('qta_flair_python_model/best-model.pt')
model.predict(flair_test, mini_batch_size=16, label_name='predicted')
preds = [int(s.get_label('predicted').value) for s in flair_test]
print('# ==== F4 test report (slide p51-52)')
print(classification_report(test['label'], preds, labels=[0, 1], target_names=labels, zero_division=0, digits=4))
Python output (run locally: Python 3.11, torch 2.5.1, transformers 4.57.6, flair 0.15.1, datasets 3.6.0)
More Community Policing  Garda community outreach activities should be enhanced and we  want to see, in particular, a significant increase in the number of  Gardai assigned to Community Policing and a heightened  awareness of this service within the Gardai and communities  throughout the country
0
2026-11-27 10:09:28,438 Dictionary created for label 'label' with 2 values: 0 (seen 1772 times), 1 (seen 108 times)

Flair: 2024 record vs. local run Slides 50, 52

Epoch2024 train loss2024 dev loss2024 dev micro-F1Local train lossLocal dev lossLocal dev micro-F1
10.21990.15760.95220.20800.14960.9633
20.13600.15860.95220.13740.15320.9633
30.08880.16160.95220.08350.15600.9633

2024 columns from slide 50 (log of 2024-04-19; epoch 1 saved); local columns from tad/labs/W10/run_flair.txt. Locally, the best model was saved 1 time(s) — after epoch 1 only; dev micro-F1 stayed at 0.9633 in all three epochs, so later epochs did not improve the selection score (the same pattern as 2024).

Python output (run locally: Python 3.11, torch 2.5.1, transformers 4.57.6, flair 0.15.1, datasets 3.6.0)
                         precision    recall  f1-score   support

None Environment Policy     0.9646    0.9828    0.9737       583
     Environment Policy     0.6970    0.5227    0.5974        44

               accuracy                         0.9506       627
              macro avg     0.8308    0.7528    0.7855       627
           weighted avg     0.9459    0.9506    0.9473       627
# peak RSS MB 3285 ; runtime s 278
Class2024 P2024 R2024 F1Local PLocal RLocal F1support
Other policy (0).9507.9914.9706.9646.9828.9737583
Environmental policy (1).7368.3182.4444.6970.5227.597444
accuracy.9442.9506627
macro-F1.7075.7855627
How to read it (Supplement)

The local run reaches environmental-policy recall .5227 (2024: .3182) and F1 .5974 (2024: .4444). Both runs show the slide-52 point: accuracy (.9506 locally) stays high while the minority class is still missed about half the time. Differences can come from library versions (Flair 0.15.1 vs. 0.13.1), hardware and random initialization; this is one local run, not a benchmark.

Approach B: Hugging Face Transformers Slides 53–58

  1. Match tokenizer and checkpoint: both distilbert-base-uncased; set_seed(42) before model creation (slide 53).
  2. Encode: dataset.map(tokenize_batch, batched=True) adds input_ids and attention_mask; AutoModelForSequenceClassification adds a new head with the shared id2label/label2id (slide 54).
  3. Metrics: largest logit; macro-F1 weights the two classes equally (slide 55).
  4. Training settings: 3 epochs, learning rate 5e-5, batch 8, evaluate and save each epoch, reload the checkpoint with the highest validation macro-F1 (slide 56); test is absent from the Trainer (slide 57).
Python · tad/labs/W10/w10_lab.py (follows slides p53–61)
import numpy as np
from transformers import (AutoTokenizer, AutoModelForSequenceClassification, TrainingArguments, Trainer,
                          pipeline, set_seed, DataCollatorWithPadding)
from sklearn.metrics import accuracy_score, f1_score
set_seed(42)
tok = AutoTokenizer.from_pretrained('distilbert-base-uncased')
# NOTE: slide p54 pads every text to 512 positions (padding="max_length"). Here we keep truncation=True (512 max)
# but pad per batch (DataCollatorWithPadding) so CPU training fits the time budget. Attention masks make padding
# positions inert, so this changes speed, not the model definition.
def tokenize_batch(batch):
    return tok(batch['text'], truncation=True)
hf_data = dataset.map(tokenize_batch, batched=True)
print('# ==== H1 tokenized columns (slide p54)')
print(hf_data['train'].column_names)
model = AutoModelForSequenceClassification.from_pretrained('distilbert-base-uncased', num_labels=len(labels), id2label=id2label, label2id=label2id)
def compute_metrics(p):
    ref = p.label_ids; pred = p.predictions.argmax(-1)
    return {'accuracy': accuracy_score(ref, pred), 'macro_f1': f1_score(ref, pred, average='macro', zero_division=0)}
args = TrainingArguments(output_dir='./qta_hf_python_model', num_train_epochs=3, learning_rate=5e-5,
    per_device_train_batch_size=8, per_device_eval_batch_size=8, eval_strategy='epoch', save_strategy='epoch',
    load_best_model_at_end=True, metric_for_best_model='macro_f1', greater_is_better=True, save_total_limit=1,
    report_to='none', seed=42, logging_strategy='epoch', disable_tqdm=True)
trainer = Trainer(model=model, args=args, train_dataset=hf_data['train'], eval_dataset=hf_data['validation'],
                  processing_class=tok, data_collator=DataCollatorWithPadding(tok), compute_metrics=compute_metrics)
print('# ==== H2 train (slide p56-57)')
trainer.train()
for h in trainer.state.log_history:
    print({k: (round(v, 4) if isinstance(v, float) else v) for k, v in h.items()})
print('# ==== H3 test report (slide p58)')
r = trainer.predict(hf_data['test'])
preds = r.predictions.argmax(-1)
print(classification_report(r.label_ids, preds, labels=[0, 1], target_names=labels, zero_division=0, digits=4))
probs = torch.softmax(torch.tensor(r.predictions), -1)[:, 1].tolist()
trainer.save_model('qta_hf_python_model'); tok.save_pretrained('qta_hf_python_model')
print('# ==== H4 pipeline on a new excerpt (slide p60-61)')
pc = pipeline('text-classification', model='qta_hf_python_model', tokenizer='qta_hf_python_model', device=-1)
print(pc('Reducing our carbon footprint through renewable energy sources and enhanced energy efficiency is crucial.', truncation=True))
One difference from the slides in the local run

Slide 54 uses padding="max_length", padding every text to 512 positions. The local run keeps truncation=True but uses DataCollatorWithPadding to pad each batch to its longest text: the longest text here is 117 tokens, so padding to 512 only makes the CPU compute padding. Attention masks keep padded positions out of attention, so this changes speed, not the model definition; floating-point order differs, so numbers are not guaranteed to match a 512-padded run exactly.

Python output (run locally: Python 3.11, torch 2.5.1, transformers 4.57.6, flair 0.15.1, datasets 3.6.0)
{'epoch': 1.0, 'loss': 0.1986}
{'epoch': 1.0, 'eval_loss': 0.0983, 'eval_accuracy': 0.9745, 'eval_macro_f1': 0.9042}
{'epoch': 2.0, 'loss': 0.1008}
{'epoch': 2.0, 'eval_loss': 0.1058, 'eval_accuracy': 0.9777, 'eval_macro_f1': 0.9107}
{'epoch': 3.0, 'loss': 0.0659}
{'epoch': 3.0, 'eval_loss': 0.0977, 'eval_accuracy': 0.9761, 'eval_macro_f1': 0.9074}
{'epoch': 3.0, 'train_runtime': 251.5253}

Transformers: 2024 record vs. local run Slide 59

Stored test metric2024 record (learning rate 0.3)Local run (learning rate 5e-5)
Accuracy.9298245614.9442
Macro-F1.4818181818.7636
Macro-precision.4649122807.7957
Macro-recall.5000000000.7389
Environment Policy recall— (not stored).5000
Test rows627627
Python output (run locally: Python 3.11, torch 2.5.1, transformers 4.57.6, flair 0.15.1, datasets 3.6.0)
                         precision    recall  f1-score   support

None Environment Policy     0.9628    0.9777    0.9702       583
     Environment Policy     0.6286    0.5000    0.5570        44

               accuracy                         0.9442       627
              macro avg     0.7957    0.7389    0.7636       627
           weighted avg     0.9394    0.9442    0.9412       627
The 2024 record is “predict 0 for everything” (Supplement: inferred from the numbers)

2024 accuracy .9298245614 = 583 / 627; macro-recall exactly .5000 = (1 + 0) / 2; macro-precision .4649 = .9298 / 2. All three hold together only if the model predicted 0 for all 627 texts. Slide 59 notes the original learning rate was 0.3 (the revised guide uses 5e-5) — very large for AdamW fine-tuning, so the model likely collapsed to the majority class. Rerun locally at 5e-5, environmental-policy recall is .5000.

Validation and test differ a lot

The local best validation macro-F1 is 0.9107 (epoch 2, selected as the final model), but test macro-F1 is .7636. With only 44/45 environmental texts, a few errors swing F1 widely — one reason slide 12 separates model choice from reporting.

Threshold and confusion matrix (real probabilities from the local DistilBERT)

The Trainer uses argmax (a .5 threshold). Below, move the threshold on the local model's real P(environmental policy) for the 627 test texts. This is a supplementary exercise: in real research, choose thresholds on validation, never by looking at test.

Interactive: decision threshold on P(Environment Policy)
0.50

Save, reload and a new policy excerpt Slides 60–61

save_model and tokenizer.save_pretrained write to the same folder; pipeline("text-classification", model=..., tokenizer=..., device=-1) reads them back. On slide 61's new sentence:

Python output (run locally: Python 3.11, torch 2.5.1, transformers 4.57.6, flair 0.15.1, datasets 3.6.0)
[{'label': 'Environment Policy', 'score': 0.9858415722846985}]

Slide 61: the score does not establish correctness. Slide 59 also notes that cells 33–34 of the original notebook use a different model path; that example is not validated by the test report.

Chapter quiz

1. Flair's add_dev_test=False is for…
Slide 47
2. The 2024 Transformers record has accuracy .9298 and macro-recall .5000. Most likely…
583/627 = .9298; recall (1+0)/2 = .5. Slide 59
3. With load_best_model_at_end=True and metric_for_best_model="macro_f1", which split selects the checkpoint?
Slides 56–57
10 · Lab C

Lab C: both models on the same text + the NLI stance demo

Align both predictions with the same texts Slides 62–63

Using the unchanged test order, put full text, reference ID, Flair ID and Transformers ID in one table and map them with the same id2label. Pick a row where either model disagrees with the reference and read: full text → reference → Flair → Transformers.

Python output (run locally: Python 3.11, torch 2.5.1, transformers 4.57.6, flair 0.15.1, datasets 3.6.0)
transformers             Environment Policy  None Environment Policy
flair                                                               
Environment Policy                       24                        9
None Environment Policy                  11                      583
rows where either model disagrees with reference: 43
 Begin immediate monitoring of air quality in cities
reference: None Environment Policy
flair: None Environment Policy
transformers: Environment Policy
Interactive: step through disagreements (local predictions)

The two models use different encoders and training settings, so score differences do not isolate a software-library effect (lab/results/README).

Read a full-text error Slides 38, 63

Slide 38: explain one prediction with its full text — report the reference label, the prediction and the evidence for your interpretation. Use the browser above, then write it down in the answer box below.

NLI stance: three teaching texts Slides 64–67

Python · tad/labs/W10/w10_lab.py (follows slides p64–66)
from transformers import pipeline
nli_classifier = pipeline('zero-shot-classification', model='MoritzLaurer/DeBERTa-v3-large-mnli-fever-anli-ling-wanli',
                          revision='b3546ea6b0346eb6f8d5d68b13c7dc6d0376b3d7', device=-1, torch_dtype=torch.float32, batch_size=1)
nli_labels = ['supports', 'opposes', 'does not express an opinion about']
nli_template = 'The author of this tweet {} Trump.'
for label in nli_labels:
    print(nli_template.format(label))
nli_texts = ["I support Trump's policies.", "I oppose Trump's policies.", 'The committee meets on Tuesday.']
res = nli_classifier(nli_texts, candidate_labels=nli_labels, hypothesis_template=nli_template, multi_label=False)
rows = []
for ex, text, r in zip('ABC', nli_texts, res):
    sc = dict(zip(r['labels'], r['scores']))
    rows.append({'example': ex, 'text': text, 'predicted_stance': r['labels'][0], **{l: sc[l] for l in nli_labels}})
print(pd.DataFrame(rows).to_string(index=False, float_format=lambda v: f'{v:.6f}'))

Run locally with the same model and revision (b3546ea6…), CPU float32. Compared with the course's burnham-nli-demo.txt (slide 67):

Python output (run locally: Python 3.11, torch 2.5.1, transformers 4.57.6, flair 0.15.1, datasets 3.6.0)
example                            text                  predicted_stance  supports  opposes  does not express an opinion about
      A     I support Trump's policies.                          supports  0.991822 0.004377                           0.003801
      B      I oppose Trump's policies.                           opposes  0.008588 0.984321                           0.007091
      C The committee meets on Tuesday. does not express an opinion about  0.206293 0.196706                           0.597000
TextCourse supportsLocal supportsCourse opposesLocal opposesCourse no opinionLocal no opinion
A0.9918220.9918220.0043770.0043770.0038010.003801
B0.0085880.0085880.9843210.9843210.0070910.007091
C0.2062940.2062930.1967070.1967060.5970000.597000

All top-ranked stances match. Differences at the sixth decimal: C supports 0.206294 vs. 0.206293; C opposes 0.196707 vs. 0.196706. These come from CPU/library differences (local torch 2.5.1, transformers 4.57.6 vs. the course run with torch 2.2.2, transformers 4.54.0).

Interactive: the three candidate scores (run locally)
Reading slide 67

A ranks support first and B opposition; C is less decisive, with no opinion leading at only .5970. Scores with multi_label=False are candidate scores normalized across the three hypotheses — not accuracy and not the full three-relation NLI distribution. Three constructed examples do not establish research performance; set review rules for uncertain cases and validate them on human-labeled target texts.

A few more texts (Supplement: run locally, not from the lecture)

Same model, template and candidates, four more constructed sentences testing negation, factual reports and sarcasm:

Python output (run locally: Python 3.11, torch 2.5.1, transformers 4.57.6, flair 0.15.1, datasets 3.6.0)
                                 text                  predicted_stance  supports  opposes  does not express an opinion about
   Trump's tariffs will hurt farmers.                           opposes  0.144632 0.527101                           0.328267
Trump held a rally in Ohio yesterday. does not express an opinion about  0.405619 0.172463                           0.421917
   I don't support Trump's opponents.                          supports  0.769755 0.140033                           0.090213
Great job, Trump, another bankruptcy!                           opposes  0.083762 0.846498                           0.069740
Observations (Supplement)

“Trump's tariffs will hurt farmers.” → opposes (0.5271): a factual-looking prediction about a policy effect reads as opposition. “Trump held a rally in Ohio yesterday.” → does not express an opinion about, but supports 0.4056 vs. no opinion 0.4219 — nearly a tie for a neutral event report. “I don't support Trump's opponents.” (a double negative) → supports 0.7698: plausible, but it shows the model infers a stance the author never states directly. “Great job, Trump, another bankruptcy!” (sarcasm) → opposes 0.8465. None of these are validated; they show why slide 67 asks you to read every candidate score and validate the rule on human-labeled target texts.

Decision-rule exercise: when should a text go to human review?

Slides 25 and 67 ask for a rule for uncertain cases and its validation. Using the real candidate scores of the seven local texts, set the threshold below which the top score is sent to human review (supplementary exercise; a real threshold must be chosen on human-labeled target texts):

Interactive: review threshold
0.60

Answer box Slides 38, 63, 67

Write: one full-text error explained + your reading of text C

Chapter quiz

1. Is there a train() call in the NLI demo?
Slide 64
2. Text C has no opinion = .5970. The correct reading?
Slide 67
11 · Reading guide

Reading guide: five application papers

Slide 68 lists five application readings. Three (Bestvater & Monroe, Laurer et al., Burnham) have open-access full texts (CC BY 4.0) that were read in full; page numbers are journal pages. The other two follow the slides and the course's reading/applications.html only.

Bestvater & Monroe (2023). Sentiment is Not Stance. Political Analysis 31(2): 235–256 Slides 20–22

Full text: Cambridge open access (CC BY 4.0), doi:10.1017/pan.2022.10.

ItemContentPages
QuestionPolitical science often measures opinions about specific targets with sentiment analysis; the authors argue sentiment and stance need not align, so sentiment adds noise and can lead to faulty conclusions.p. 235 (abstract)
DataThree examples: tweets about the 2017 Women’s March; open-ended Mood of the Nation survey answers about Trump (nine waves, 2016-11-16 to 2019-09-26); tweets about the Kavanaugh confirmation hearings.pp. 237, 245, 249–250
MethodHuman coders label sentiment and stance separately; Lexicoder and VADER (dictionaries) and SVM/BERT trained on sentiment or stance labels are evaluated on stance, then used in ideology → approval regressions.pp. 239, 246, 250–251
FindingsWomen’s March (Table 2): ideology slope VADER −0.35, BERT −0.76, human coding −1.87 (N 928 / 1,501 / 1,501); VADER understates the association (slides 21–22). MOTN: sentiment-trained BERT reaches F1 .875 on sentiment but only .724 on stance (Table 4). Kavanaugh: sentiment and stance are essentially uncorrelated (r = 0.03); the sentiment-trained measure makes the ideology–approval relationship disappear (Figure 5).pp. 241–242, 246, 250, 253
Conclusions (four points)(1) Sentiment and stance are distinct; (2) the difficulty is not method complexity — every sentiment-trained classifier did worse on stance and every stance-trained one better; (3) noisy measures bias or attenuate downstream results; (4) the bias depends on the correlation between sentiment and stance in the corpus.pp. 253–254
Link to this weekCase 3 (ch05); “the training label decides what the model learns” also motivates reading class-specific Lab results.—

Laurer, van Atteveldt, Casas & Welbers (2024). Less Annotating, More Classifying. Political Analysis 32: 84–100 Slides 28–30, 34

Full text: Cambridge open access (CC BY 4.0), doi:10.1017/pan.2023.20.

ItemContentPages
QuestionSupervised learning needs thousands of annotations; can deep transfer learning with BERT-NLI reduce that need?p. 84 (abstract)
DataFive datasets, eight tasks: Manifesto Corpus (8 topics), Sentiment Economy News, US State of the Union (22 classes), US Supreme Court Cases (20 classes), CoronaNet (20 classes), plus Manifesto stance subtasks on military, protectionism and morality (Table 2).p. 91
MethodBERT-NLI: fine-tune DeBERTaV3-base on 1,279,665 hypothesis–context pairs from eight existing NLI datasets, convert political tasks to NLI format (category statements) and fine-tune on the target task; compare with TF-IDF / embedding classical classifiers.pp. 88–92
FindingsWith 500 data points BERT-NLI reaches average F1 Macro similar to classical models trained on about 5,000; transfer learning helps particularly with imbalanced data.pp. 84, 93–95
LimitationsSlow, GPU-hungry; new software to learn; NLI depends on human-annotated NLI data (abundant in English, less in other languages; multilingual model expected to be weaker); pretraining can introduce biases (e.g. “The US is trustworthy” vs. “China is trustworthy” on semantically equivalent texts).pp. 96–97
Link to this weekNLI Study 1 (ch07); the authors' NLI models are the MoritzLaurer/… family used in the Lab.p. 96 fn. 15

Burnham (2025). Stance detection: a practical guide to classifying political beliefs in text. PSRM 13: 611–628 Slides 31–33, 34

Full text: Cambridge open access (CC BY 4.0), doi:10.1017/psrm.2024.35 (published online 2024).

ItemContentPages
QuestionDefine stance detection (beliefs expressed in a document) precisely and outline three approaches — supervised classification, NLI and in-context learning — with guidance on choice and validation.p. 611 (abstract)
DataTrump-support tweets for demonstration (Table 3); a replication with 862,923 COVID-19 tweets (2020-09-01 to 2021-02-28, 23,476 users) including 2,000 hand-labeled training tweets and coding rules; ideology from tweetscores.pp. 618, 624
MethodTwo sets of synonymous entailment hypotheses (compliant / non-compliant / neutral) from the coding rules; keywords match hypotheses to tweets; a DeBERTaV3 NLI classifier labels them; entailing any threat-minimizing hypothesis flags the tweet. 300 randomly sampled training tweets test the hypotheses.p. 624
FindingsTable 2: NLI needs no training, little compute and is highly reproducible — a good starting point. Table 3: on Trump support, language models (PoliBERTweet MCC .68) beat bag-of-words classifiers (logistic regression .51) at higher compute cost. COVID-19: Set 1 MCC .67 / accuracy 87%, Set 2 .74 / 90%, replicating the supervised results.pp. 616, 618, 624–625
Limitations and adviceWhen documents contain sufficient information, NLI performs comparably to supervised classifiers; when outside context is needed, supervised or in-context classifiers are better. There are no NLI datasets or benchmarks specific to stance; future work could build political-communication data and models and scale stance intensity.pp. 625–626
Link to this weekNLI Study 2 (ch07); Lab C's NLI demo adapts the author's official Trump-stance tutorial (ch10).—

Liao & Tang (2026). Electoral Systems and Geographically Targeted Oversight: Evidence from the Taiwan Legislative Yuan. Electoral Studies 99: 103026 Slides 14–16

Full text: not obtained here (Unpaywall lists it as CC BY open access, but no direct PDF link). The table follows the slides and reading/applications.html; page numbers are those cited on the slides.

ItemFrom the slides
QuestionDid Taiwan's electoral reform change legislators' geographically targeted oversight?
Data and classificationChinese BERT fine-tuned on 7,216 human-labeled proposals/amendments; validated on about 400 human-coded questions, GTQ F1 .88 (§4.1, fn. 9, pp. 4–5).
Research measure63,748 questions, 402 district legislators, 1999–2019; legislator-year GTQ percentage (§§5.1–5.2, pp. 6–7).
FindingsLower initial GTQ share after reform; the negative difference weakens over time (Figure 3 p. 7; Table 1 p. 6).

Schöll, Gallego & Le Mens (2024). How Politicians Learn from Citizens’ Feedback: The Case of Gender on Twitter. AJPS 68(2): 557–574 Slides 17–19

Full text: the Wiley link returned a web page rather than a PDF (Unpaywall lists CC BY-NC). The table follows the slides only; page numbers are those cited on the slides.

ItemFrom the slides
QuestionDo politicians give more attention to issues that received positive feedback?
Data and classificationBERT fine-tuned on about 20,000 human-coded tweets; validation precision .90, recall .79 (p. 562).
Research measurePolitician-month share of gender-related tweets; retweets as feedback (pp. 564–565).
FindingsPositive logit coefficients .11 (women) and .07 (men); the difference is not statistically clear; a panel association (Table 4 p. 567; p. 568).
Getting the remaining full texts

Liao & Tang (2026): doi:10.1016/j.electstud.2025.103026; Schöll et al. (2024): doi:10.1111/ajps.12772 (or the UPF / UB repositories). With the full texts, complete reading cards with page numbers can be added later.

12 · Pitfalls and glossary

Common pitfalls and glossary

Ten common pitfalls

1. Mixing tokenizer and model

Token IDs index each model's own vocabulary; DistilBERT and DistilUSE give the same sentence completely different IDs. Slides 4, 53

2. Expecting pretraining to produce research labels

MLM learns representations, not your labels; fine-tune or define an NLI decision rule. Slides 10–11

3. Reporting the validation score as final

The local DistilBERT: validation macro-F1 0.9107, test only .7636. Slide 12

4. Reporting accuracy only

“Predict 0 for everything” already scores .9298. Report per-class P/R/F1. Slides 38, 59

5. Treating 2024 records as revised-code results

Slides 52 and 59 say “not a new run of revised code”. Slides 52, 59

6. Using sentiment as a stance proxy

Women’s March: VADER's ideology slope is −0.35 versus −1.87 for human coding (slide 21, Table 2); in the paper's later Kavanaugh case, sentiment-trained stance F1 is only .514/.582 (Table 7, supplement). Slides 21–22

7. “Not entailed” = opposition

Define a decision rule and validate it with human labels. Slide 25

8. NLI neutral = neutral stance

Neutral is a text–hypothesis relation; “does not express an opinion about” is a stance candidate. Slides 24, 27

9. NLI = zero-shot

Laurer fine-tunes on the target task; Burnham's application does not. Slide 34

10. Candidate scores = accuracy

With multi_label=False the scores are only normalized across candidates; three constructed texts prove nothing about research performance, and the local supplementary texts show that a high score can still be wrong. Slide 67

Glossary

13 · Review

Review, research design and references

Final quiz (20 questions)

Not answered yet

Design a study with Transformer classification Slides 25, 34

Principle (conclusion line of the earlier slide 13): define the label, validate it, then use it in the analysis. Slides 25 and 34: for NLI, define the decision rule, state whether target-task fine-tuning is used and how it is validated. Copy the result as Markdown for a research design or poster (Supplement).

Planner (exports Markdown)
Markdown

Progress

References Slide 68

Application readings (slide 68)

  • Liao, Yen-Chieh, and Li Tang. 2026. “Electoral Systems and Geographically Targeted Oversight: Evidence from the Taiwan Legislative Yuan.” Electoral Studies 99: 103026. doi:10.1016/j.electstud.2025.103026
  • Schöll, Nikolas, Aina Gallego, and Gaël Le Mens. 2024. “How Politicians Learn from Citizens’ Feedback: The Case of Gender on Twitter.” American Journal of Political Science 68(2): 557–574. doi:10.1111/ajps.12772
  • Bestvater, Samuel E., and Burt L. Monroe. 2023. “Sentiment is Not Stance: Target-Aware Opinion Classification for Political Text Analysis.” Political Analysis 31(2): 235–256. doi:10.1017/pan.2022.10
  • Laurer, Moritz, Wouter van Atteveldt, Andreu Casas, and Kasper Welbers. 2024. “Less Annotating, More Classifying: Addressing the Data Scarcity Issue of Supervised Machine Learning with Deep Transfer Learning and BERT-NLI.” Political Analysis 32(1): 84–100. doi:10.1017/pan.2023.20
  • Burnham, Michael. 2025. “Stance Detection: A Practical Guide to Classifying Political Beliefs in Text.” Political Science Research and Methods 13: 611–628. doi:10.1017/psrm.2024.35

Architecture and other sources cited on the slides

  • Vaswani, A., et al. 2017. “Attention Is All You Need.” NeurIPS 30.
  • Devlin, J., M.-W. Chang, K. Lee, and K. Toutanova. 2019. “BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.” NAACL-HLT.
  • Bowman, S. R., G. Angeli, C. Potts, and C. D. Manning. 2015. “A Large Annotated Corpus for Learning Natural Language Inference.” EMNLP.
  • Grimmer, J., M. E. Roberts, and B. M. Stewart. 2022. Text as Data. Princeton University Press. §8.5.
  • Liao, Yen-Chieh, and Stefan Müller. 2024. Week 12 Flair and Transformers notebooks (course materials). Burnham's official zero-shot stance tutorial: github.com/MLBurnham/stance_detection_tutorials.
These notes are based on the NTLDEV 7191 W10 slides (Yen-Chieh Liao, 68-page PDF, last compiled 2026-11-06 16:22:26), W10/README.md, W10/lab/README.md, W10/lab/Lab_Session_W10.html, W10/lab/notebooks/, W10/lab/results/ and W10/reading/ (upstream commit 7c3a741). Python output was rerun locally (Python 3.11, torch 2.5.1, transformers 4.57.6, flair 0.15.1, datasets 3.6.0, CPU). Reading cards for Bestvater & Monroe, Laurer et al. and Burnham follow open-access full texts; the other two follow the slides only. Sections marked “Supplement (not from the lecture)” and toy demos are extra explanations. Prepared 2026-11-27.
NTLDEV 7191 Text as Data · W10 interactive self-study notes · based on course materials uploaded 2026-11-27 (prepared 2026-11-27)