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 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
Come back and tick each goal after reading:
- How a Transformer processes input: token IDs → vectors + positions → self-attention (Q/K/V) → stacked encoder layers → contextual representations.
- 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.
- Classification cases: name each case's text unit, human label, classifier output and the research measure built from the labels.
- NLI: separate the three relations (entailment/contradiction/neutral) from the final stance label; know that NLI is not automatically zero-shot.
- Lab results: read imbalanced data with per-class precision/recall/F1; explain why accuracy .93 can mean “predict 0 for everything”.
The two routes
| Task-specific classifier (Application 1) | Existing NLI classifier (Application 2) | |
|---|---|---|
| Input | The text | The text + a complete hypothesis |
| Training | Fine-tune encoder + head on this task's human labels | Reuse a model trained on NLI relations; target-task fine-tuning optional (none in Burnham, yes in Laurer) |
| Output | One class from a fixed label set | Relation scores per hypothesis → decision rule → stance label |
| Shared | Both 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 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
Tokens, IDs and word order
Build the input → process the context → reuse the output
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
| Text we read | Transformer input |
|---|---|
| A word may be the unit of analysis | A word may be split into several tokens |
| A passage contains words and punctuation | Special tokens mark boundaries or tasks (e.g. [CLS], [SEP]) |
| We interpret the original text | Token IDs index a model's vocabulary; ID → embedding lookup → input vectors |
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:
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 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).
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.
Chapter quiz
bert-base-uncased tokenizer give slide 5's example?Self-attention and Q/K/V
Self-attention mixes information across positions
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
BERT can use every input position; learned matching scores set the mixing weights. Slide 7 lists rounded weights from the same model run:
| Position | Approx. weight | What is being mixed |
|---|---|---|
| he | 0.69 | Information from the position at he |
| [SEP] | 0.26 | Information from this input's final marker |
| Other 9 positions | 0.05 total | Information from the remaining positions |
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 is the neuron view of the same head, following the update at dog: Attention weights → weighted sum of V → updated vector at dog.
- Create Q, K and V: each position's current vector goes through three learned projections.
- Match Q with K: dog's query meets every key → scale → softmax weights.
- Combine the V vectors: the weighted sum of values is this head's output vector at dog.
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.
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
Encoder layers
An encoder repeats this processing
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.
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).
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
Pretraining, fine-tuning and data splits
Pretraining learns reusable representations
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
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
| Split | Purpose | Example decision |
|---|---|---|
| Training | Fit model parameters | Learn from human labels |
| Validation | Choose settings | Select a checkpoint or threshold |
| Test | Estimate performance after choices are fixed | Report 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.
Chapter quiz
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
| Case | Application | Journal |
|---|---|---|
| 1 · Liao & Tang (2026) | Legislative oversight and electoral reform | Electoral Studies |
| 2 · Schöll et al. (2024) | Citizen feedback and gender-issue attention | American Journal of Political Science |
| 3 · Bestvater & Monroe (2023) | Sentiment versus target-specific stance | Political 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
- 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.
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
| Stage | What enters the research measure? |
|---|---|
| Human labels and BERT | About 20,000 tweets coded gender issue / other |
| Validation | Precision .90 · recall .79 |
| Aggregation | Gender-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).
(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
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 measure | Label source | Ideology slope | N |
|---|---|---|---|
| VADER | Sentiment dictionary + rules | −0.35 | 928 |
| BERT | Fine-tuned on human stance labels | −0.76 | 1,501 |
| Human coding | Manual approval / opposition labels | −1.87 | 1,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 labels | SVM: stance F1 | BERT: 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:
Chapter quiz
Application 2: NLI — from three relations to stance labels
Paired input: text + full hypothesis
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'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):
{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}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
(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
| Same text: “I oppose Trump’s policies.” | Task-specific classifier | Existing NLI classifier |
|---|---|---|
| Input | The tweet | The tweet + a stance hypothesis |
| Training | Fine-tune on human stance labels for this task | Reuse a model trained on NLI relations |
| Output | A class from the trained label set | Compare 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
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.
Chapter quiz
NLI applications: Laurer et al. (2024) and Burnham (2025)
Study 1 · Laurer et al. (2024) “Less Annotating, More Classifying”
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 paper | Reported evidence |
|---|---|
| 100–2,500 target-task labels | BERT-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 methods | Similar 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”
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).
| Data | 862,923 COVID-19 tweets · 23,476 users · September 2020–February 2021 | |
|---|---|---|
| Hypothesis set | MCC | Accuracy |
| Set 1 | .67 | 87% |
| Set 2 | .74 | 90% |
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
| Design choice | Laurer · Political Analysis | Burnham · PSRM |
|---|---|---|
| Research output | Political text categories | COVID-19 threat-minimization labels |
| Target-task fine-tuning | Yes | No in this application |
| Human check | Held-out target-task labels | 300 tweets from the original training pool |
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
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
| Source | Content | Label in these notes |
|---|---|---|
| 2024 notebook records | Stored 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-27 | Versions, split counts, first training text; NLI on three teaching texts | “course repo output” |
| Local rerun | The revised code from the slides, actually trained and run on this CPU | “run locally” |
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
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):
| Package | Course 2026-11-27 | Run locally |
|---|---|---|
torch | 2.2.2 | 2.5.1 |
datasets | 2.19.0 | 3.6.0 |
numpy | 1.26.2 | 1.26.4 |
pandas | 2.2.1 | 2.2.3 |
scikit-learn | 1.3.2 | 1.9.1 |
flair | 0.13.1 | 0.15.1 |
transformers | 4.54.0 | 4.57.6 |
accelerate | 1.9.0 | 1.15.0 |
| Available device | cpu | cpu |
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
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())) 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 PolicyIdentical 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):
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:
Class imbalance: accuracy can mislead
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.
Chapter quiz
Lab A/B: fine-tuning with Flair and Transformers (run locally)
Approach A: Flair
- Texts become labeled Sentences:
Sentence(row["text"]),add_label("label", str(row["label"]))(slide 46). - 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). - Encoder + head:
TransformerDocumentEmbeddings("sentence-transformers/distiluse-base-multilingual-cased-v2", fine_tune=True)+TextClassifier(..., multi_label=False)(slide 48). - Training: SGD, rate .02, batch 16, three epochs; dev selects the checkpoint, test runs at the end; reload
best-model.pt(slide 49).
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))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
| Epoch | 2024 train loss | 2024 dev loss | 2024 dev micro-F1 | Local train loss | Local dev loss | Local dev micro-F1 |
|---|---|---|---|---|---|---|
| 1 | 0.2199 | 0.1576 | 0.9522 | 0.2080 | 0.1496 | 0.9633 |
| 2 | 0.1360 | 0.1586 | 0.9522 | 0.1374 | 0.1532 | 0.9633 |
| 3 | 0.0888 | 0.1616 | 0.9522 | 0.0835 | 0.1560 | 0.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).
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| Class | 2024 P | 2024 R | 2024 F1 | Local P | Local R | Local F1 | support |
|---|---|---|---|---|---|---|---|
| Other policy (0) | .9507 | .9914 | .9706 | .9646 | .9828 | .9737 | 583 |
| Environmental policy (1) | .7368 | .3182 | .4444 | .6970 | .5227 | .5974 | 44 |
| accuracy | .9442 | .9506 | 627 | ||||
| macro-F1 | .7075 | .7855 | 627 | ||||
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
- Match tokenizer and checkpoint: both
distilbert-base-uncased;set_seed(42)before model creation (slide 53). - Encode:
dataset.map(tokenize_batch, batched=True)addsinput_idsandattention_mask;AutoModelForSequenceClassificationadds a new head with the sharedid2label/label2id(slide 54). - Metrics: largest logit; macro-F1 weights the two classes equally (slide 55).
- 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).
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))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.
{'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
| Stored test metric | 2024 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 rows | 627 | 627 |
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 6272024 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.
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.
Save, reload and a new policy excerpt
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:
[{'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
add_dev_test=False is for…load_best_model_at_end=True and metric_for_best_model="macro_f1", which split selects the checkpoint?Lab C: both models on the same text + the NLI stance demo
Align both predictions with the same texts
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.
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
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
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
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):
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| Text | Course supports | Local supports | Course opposes | Local opposes | Course no opinion | Local no opinion |
|---|---|---|---|---|---|---|
| A | 0.991822 | 0.991822 | 0.004377 | 0.004377 | 0.003801 | 0.003801 |
| B | 0.008588 | 0.008588 | 0.984321 | 0.984321 | 0.007091 | 0.007091 |
| C | 0.206294 | 0.206293 | 0.196707 | 0.196706 | 0.597000 | 0.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).
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:
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
“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):
Answer box
Chapter quiz
train() call in the NLI demo?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
Full text: Cambridge open access (CC BY 4.0), doi:10.1017/pan.2022.10.
| Item | Content | Pages |
|---|---|---|
| Question | Political 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) |
| Data | Three 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 |
| Method | Human 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 |
| Findings | Women’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 week | Case 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
Full text: Cambridge open access (CC BY 4.0), doi:10.1017/pan.2023.20.
| Item | Content | Pages |
|---|---|---|
| Question | Supervised learning needs thousands of annotations; can deep transfer learning with BERT-NLI reduce that need? | p. 84 (abstract) |
| Data | Five 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 |
| Method | BERT-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 |
| Findings | With 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 |
| Limitations | Slow, 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 week | NLI 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
Full text: Cambridge open access (CC BY 4.0), doi:10.1017/psrm.2024.35 (published online 2024).
| Item | Content | Pages |
|---|---|---|
| Question | Define 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) |
| Data | Trump-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 |
| Method | Two 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 |
| Findings | Table 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 advice | When 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 week | NLI 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
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.
| Item | From the slides |
|---|---|
| Question | Did Taiwan's electoral reform change legislators' geographically targeted oversight? |
| Data and classification | Chinese 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 measure | 63,748 questions, 402 district legislators, 1999–2019; legislator-year GTQ percentage (§§5.1–5.2, pp. 6–7). |
| Findings | Lower 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
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.
| Item | From the slides |
|---|---|
| Question | Do politicians give more attention to issues that received positive feedback? |
| Data and classification | BERT fine-tuned on about 20,000 human-coded tweets; validation precision .90, recall .79 (p. 562). |
| Research measure | Politician-month share of gender-related tweets; retweets as feedback (pp. 564–565). |
| Findings | Positive logit coefficients .11 (women) and .07 (men); the difference is not statistically clear; a panel association (Table 4 p. 567; p. 568). |
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.
Common pitfalls and glossary
Ten common pitfalls
Token IDs index each model's own vocabulary; DistilBERT and DistilUSE give the same sentence completely different IDs.
MLM learns representations, not your labels; fine-tune or define an NLI decision rule.
The local DistilBERT: validation macro-F1 0.9107, test only .7636.
“Predict 0 for everything” already scores .9298. Report per-class P/R/F1.
Slides 52 and 59 say “not a new run of revised code”.
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).
Define a decision rule and validate it with human labels.
Neutral is a text–hypothesis relation; “does not express an opinion about” is a stance candidate.
Laurer fine-tunes on the target task; Burnham's application does not.
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.
Glossary
Review, research design and references
Final quiz (20 questions)
Design a study with Transformer classification
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).
Progress
References
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.