Text as Data

W10 · Transformers: Architecture and Applications

Yen-Chieh Liao

Fall 2026 (115-1) · National Taiwan University (GIND)
NTLDEV 7191 · Fri. 16:30–18:20 · GIND 204Last compiled: 2026-11-06 16:22:26 (Asia/Taipei)

Course route

Concepts → Applications → Lab
1Transformer basicsTokens → Attention → Representations → Fine-tuning
2ClassificationThree studies: oversight, issue attention and stance
3NLI applicationsText + hypothesis → Relation scores → Task labels
LabPolicy fine-tuning → NLI stance example

One framework, two ways to turn text into research labels.

Vaswani et al. (2017) · Devlin et al. (2019) · Lab: Liao & Müller (2024), supplied Week 12 notebooks.

← / → Follow the course route

Transformer basics

How does a Transformer turn a token sequence into contextual representations?

1Build the inputToken IDs → vectors + position information
2Process the contextSelf-attention + feed-forward layers
3Reuse the outputContextual representations learned through pretraining

These representations can support a task classifier.

← / → Follow the architecture

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.
We interpret the original text. Token IDs index a model’s vocabulary.

Token IDs → embedding lookup → input vectors.

Keep the tokenizer matched to the trained model.

← / → Follow the tokens

Word order is part of the input

My dog is cute. He likes playing.

Position 0 1 2 3 4 5 6 7 8 9 10
Token [CLS] my dog is cute . he likes playing . [SEP]

The bert-base-uncased tokenizer lowercases this input and adds [CLS] and [SEP].

Token vectors + position information → input to the encoder.

← / → Follow the positions

Self-attention mixes information across positions

Actual BertViz head view for My dog is cute. He likes playing. One selected BERT head shows attention from dog to positions in this same input.

My dog is cute.
He likes playing.

Update dog using information from other input positions.

Weighted values → contextual representation.

BertViz · bert-base-uncased, layer 5 / head 5 (zero-based) · Vaswani et al. (2017), §3.2.

← / → Follow the attention links

Read the connections at dog

BERT can use every input position.
Learned matching scores set the mixing weights.

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.

These weights alone do not prove that he refers to dog.

BertViz · bert-base-uncased, layer 5 / head 5 (zero-based), updating dog · rounded weights from the same model run · Vaswani et al. (2017), §3.2.

← / → Read the attention connections

Queries, keys and values make attention concrete

One selected BERT head · update the representation at dog.

Actual BertViz neuron view for My dog is cute. He likes playing. The selected dog query is compared with key vectors at every position, followed by dot-product scores and softmax weights. Value vectors are not displayed in this figure.

Attention weights → weighted sum of V → updated vector at dog.

BertViz neuron view · bert-base-uncased, layer 5 / head 5 (zero-based) · Vaswani et al. (2017), §3.2.

← / → Follow self-attention

An encoder repeats this processing

Start with token and position representations.

1Mix positionsMulti-head self-attention → residual addition → LayerNorm
2Transform each positionFeed-forward network → residual addition → LayerNorm
3Pass to the next layerRepeat with that layer’s learned parameters

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

The residual path adds the sublayer’s input back to its output.

Vaswani et al. (2017), §3.1, Figure 1 and §3.3. Normalization order varies across Transformer architectures.

← / → Follow the encoder layer

Pretraining learns reusable representations

The government announced a [MASK] policy.

Masked language modeling: predict selected hidden tokens from context.

The original text supplies the answers.

The model still needs a connection to our research labels.

Grimmer, Roberts & Stewart (2022), Text as Data, §8.5, p. 88 · BERT, §3.1. Masked-policy sentence: teaching example.

← / → Follow the pretraining example

Fine-tuning connects representations to labels

Full fine-tuning updates the pretrained encoder and the task head using prediction errors on labeled examples.

At inference, the trained model predicts labels for new texts.

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.

← / → Follow the data splits

Application 1 · Transformer classification

Case Application Journal
Case 1 · Liao & Tang Legislative oversight and electoral reform Electoral Studies
Case 2 · Schöll et al. Citizen feedback and gender-issue attention American Journal of Political Science
Case 3 · Bestvater & Monroe Sentiment versus target-specific stance Political Analysis

Case 1 · Targeted oversight

Case 1

Original article opening of Liao and Tang on electoral systems and geographically targeted oversight.

  • Background
    Did Taiwan’s electoral reform change legislators’ local oversight?
  • Classification
    Chinese BERT identifies geographically targeted questions (GTQs). Validate on human-coded questions.
  • Research use
    Aggregate GTQ shares by legislator-year to study change after reform.

Liao & Tang (2026), Electoral Studies 99:103026, §§4–5. Article. Original first-page excerpt.

← / → Background → Classification → Research use

Case 1 · Build the oversight measure

Case 1

Learn the label from legislation

7,216 human-labeled proposals and amendments → Chinese BERT

Check the new text genre

About 400 human-coded written questions · GTQ F1 .88

Turn question labels into a research outcome

63,748 questions · 402 district legislators · 1999–2019

GTQ percentage = 100 × targeted questions / all questions, within each legislator-year.

← / → Labels → Validation → Research outcome

Case 1 · Read the reform comparison

Case 1

Original Figure 3 from Liao and Tang: observed geographically targeted question shares and Model 4 fitted trends before and after the 2008 electoral reform, with 95 percent confidence bands.

The initial GTQ share is lower after reform; the negative difference weakens over time.

Liao & Tang (2026), Figure 3, p. 7; Table 1, p. 6. Original figure; Model 4 fitted trends and 95% confidence intervals. Interpret with the time comparison and controls.

← / → Axes → Reform boundary → Later trend

Case 2 · Feedback and issue attention

Case 2

Original article opening of Schöll, Gallego and Le Mens on politicians' responses to citizens' feedback.

  • Background
    Do politicians give more attention to issues that received positive feedback?
  • Classification
    Fine-tune BERT to identify gender-related tweets. Check precision and recall.
  • Research use
    Relate earlier retweet feedback to later shares of gender-related tweets.

Schöll, Gallego & Le Mens (2024), AJPS 68(2):557–574, “Measuring Attention to Gender Issues” and Table 4. Article. Original first-page excerpt.

← / → Background → Classification → Research use

Case 2 · Build the issue-attention measure

Case 2
Stage What enters the research measure?
Human labels and BERT About 20,000 tweets coded as 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

Schöll, Gallego & Le Mens (2024), “Measuring Attention to Gender Issues,” p. 562; research variables, pp. 564–565. Scores are reported for validation data; no separate untouched test set is established in the main-text description.

← / → Human labels → Validation → Panel measure

Case 2 · Read the feedback estimates

Case 2

Original Table 4 excerpt from Schöll and colleagues. Model 2 reports positive logit coefficients for prior relative feedback: .11 for female politicians and .07 for male politicians, with clustered standard errors in parentheses.

Both coefficients are positive: .11 for women and .07 for men.

Their response difference is not statistically clear.

Panel association; retweet feedback does not represent all voters’ preferences.

Schöll et al. (2024), Table 4, p. 567; interpretation, p. 568. Original table excerpt; logit coefficients, not percentage-point effects. SE clustered by politician.

← / → Estimates → Comparison → Inference limit

Case 3 · Sentiment is Not Stance

Case 3

Original first page of Bestvater and Monroe's Sentiment is Not Stance article.

  • Background
    A positive tone and support for a specified target are different labels.
  • Classification
    Compare a sentiment dictionary, fine-tuned BERT stance and human coding.
  • Research use
    Compare their Women’s March approval measures against political ideology.

Bestvater & Monroe (2023), Political Analysis 31(2):235–256, Table 2 and Figure 3. Article. Original first-page excerpt.

← / → Background → Classification → Research use

Three ways to measure approval

Case 3

Target: approval of the 2017 Women’s March

Regress each approval measure 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

A more negative slope means a sharper decline with conservatism.

Logit coefficients, not percentage-point changes. Estimation samples differ.

Bestvater & Monroe (2023), pp. 238–242; Table 2, p. 241. Article. Published observational results; human coding is the reference measure.

← / → Dictionary → Fine-tuned BERT → Human reference

Approval and political ideology

Case 3
Original Figure 3: estimated Women’s March approval declines with conservatism. Human-coded stance is solid black, VADER sentiment is dotted light blue, and fine-tuned BERT stance is dashed blue. The human curve is steepest; the VADER curve is flattest.

Bestvater & Monroe (2023), Table 2, p. 241; original Figure 3, p. 242 (CC BY 4.0). Article. Regression-estimated approval probabilities, not classifier confidence or causal effects.

← / → Human reference → Fine-tuned BERT → Dictionary

Application 2 · NLI with Transformers

Text + full hypothesis → Transformer NLI model → Relation scores

Paired input Teaching example
Text “The council discussed the housing bill today.”
Hypothesis “The council approved the housing bill today.”

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.

Constructed teaching pair, not a model prediction. Bowman et al. (2015), §2.1 · Laurer et al. (2024).

← / → Follow the paired input

Three NLI relations

Hypothesis: “The council approved the housing bill today.”

Relation Text What follows?
Entailment “Today, the council voted to approve the housing bill.” The hypothesis is supported.
Contradiction “The council did not approve the housing bill today.” The text conflicts with the hypothesis.
Neutral “The council discussed the housing bill today.” Approval remains unresolved.

NLI neutral means insufficient evidence about this hypothesis.

Constructed teaching examples, not model predictions. Relation definitions: Bowman et al. (2015), §2.1 and Figure 1.

← / → Compare the three relations

From NLI relations to stance labels

Candidate stance Full hypothesis
Support “The author supports this bill.”
Oppose “The author opposes this bill.”

Text + each hypothesis → Relation scores → Decision rule → Stance label

Define how to compare scores and handle uncertain cases.

  • Not entailed does not establish opposition.
  • NLI neutral is not automatically neutral stance.
  • Validate the rule against human labels.

Constructed stance hypotheses, not model predictions. Burnham (2025), §§3.2.1–3.2.3, pp. 619–620.

← / → Build the classification rule

Task-specific classification and NLI

Same text: “I oppose Trump’s policies.”

Task-specific classifier

Input: the tweet.

Fine-tune on human stance labels for this task.

Predict a class from the trained label set.

Existing NLI classifier

Input: the tweet + a stance hypothesis.

Reuse a model trained on NLI relations.

Compare hypotheses to select a stance.

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

Constructed tweet. Zero-shot route follows Burnham’s official NLI tutorial and its Hugging Face model.

← / → Compare the two inputs

Stance hypotheses for one tweet

Text: “I oppose Trump’s policies.”

Template: The author of this tweet {} Trump.

Candidate text Complete hypothesis
supports The author of this tweet supports Trump.
opposes The author of this tweet opposes Trump.
does not express an opinion about The author of this tweet does not express an opinion about Trump.

Compare the hypotheses, then check the text. “No opinion” is a stance candidate; NLI neutral is a relation.

Constructed tweet; no model prediction shown. Template and candidates from Burnham’s official NLI tutorial. Hugging Face model card.

← / → Read the complete hypotheses

NLI for political text classification

Application 2 · NLI · Study 1 / 2

Original first-page excerpt with title and authors from 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.

Laurer et al. (2024), “Less Annotating, More Classifying,” Political Analysis 32:84–100. Eight tasks from five datasets; original first-page excerpt.

← / → Follow the study

Read a stance classification

Application 2 · NLI · Study 1 / 2

Text in the paper’s Figure 1: “Our armed forces keep us safe”

Shown candidate hypothesis Entailment score in Figure 1
“The Military is good” .83
“The Military is bad” .07

Selected label in the figure: Military: Positive

Compare the candidate hypotheses, then use the selected stance label.

Laurer et al. (2024), Figure 1, p. 89. Paper illustration of the NLI workflow, not a new classroom prediction or accuracy estimate.

← / → Text → Hypotheses → Stance label

Evaluate labeling efficiency

Application 2 · NLI · Study 1 / 2
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.

These labeled-data gains include target-task fine-tuning.

Required annotation still depends on the task. Evaluate on held-out human labels.

← / → Read the evidence and its limits

NLI for stance detection

Application 2 · NLI · Study 2 / 2

Original first-page excerpt with title, author and abstract from Burnham (2025), Stance Detection: A Practical Guide to Classifying Political Beliefs in Text.

  • 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.
← / → Follow the study

Classify and validate COVID-19 tweets

Application 2 · NLI · Study 2 / 2

862,923 COVID-19 tweets · 23,476 users

September 2020–February 2021

Tweet + topic-matched hypotheses → DeBERTaV3 NLI

Flag threat minimization when a matched threat-minimizing hypothesis is entailed.

Check 300 human-labeled tweets

Hypothesis set MCC Accuracy
Set 1 .67 87%
Set 2 .74 90%

The references came from the original training pool.

Burnham (2025), §§4.1–4.2, pp. 624–625. Published hypothesis checks; these are not new W10 predictions.

← / → Data → NLI rule → Human check

Use stance labels in political analysis

Application 2 · NLI · Study 2 / 2

Original Figure 3 from Burnham: coefficient estimates for ideology, county deaths per 100 and their interaction, comparing supervised labels with two NLI hypothesis sets.

Tweet labels → User counts → Negative-binomial regression

Similar associations across label sets do not replace human validation.

Burnham (2025), Figure 3, p. 624 and §4.2, pp. 624–625. Original figure excerpt, CC BY 4.0; published observational associations, not new or causal W10 estimates.

← / → Labels → Research variable → Analysis

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.

Laurer et al. (2024), pp. 90–94 · Burnham (2025), §§4.1–4.2, pp. 624–625. These are different tasks, not a model ranking.

← / → Compare the design choices

Lab

LAB · Supplied notebooks

First: fine-tune policy classifiers. Then: reuse NLI for stance.

Policy labels → Fine-tuning → Evaluation → NLI stance exercise

Start with the supplied Flair and Transformers workflows. Finish with the NLI demonstration.

Open the notebooks/ folder with the data directory beside both files.

Two APIs, one classification task

LAB · Flair and Transformers
Open Main objects Encoder in the original file
Flair notebook Sentence → Corpus → TextClassifier Multilingual DistilUSE
Transformers notebook Tokenizer → DistilBERT → Trainer English DistilBERT

Same supplied data: 1,880 train · 627 validation · 627 test.

Read the text and label columns. Keep the existing split.

Different encoders and training recipes. Record both before comparing scores.

Liao & Müller (2024), supplied notebook files. Flair · Transformers · Data and labels · Before running.

← / → Follow the notebook route

Follow labels through fitting and evaluation

LAB · Shared workflow

1. Read and attach the supplied labels

Flair adds a label to each Sentence; Transformers maps class names to IDs.

2. Build the classifier and fit it on train

Flair uses ModelTrainer; Transformers uses Trainer. Validation guides model selection.

3. Evaluate after fixing the training procedure

Read the final test report and return to the full text of one error.

← / → Follow the classification workflow

Read class-specific performance

LAB · Results and interpretation

Only 44 of 627 test excerpts are labeled environmental policy.

Accuracy alone can hide a model that misses this class.

Read precision, recall and F1 by class.

Compare them with macro-F1 and accuracy where reported.

Explain one prediction with its full text.

Report the reference label, prediction and evidence for your interpretation.

Read the results and exit questions · Supplied split counts. Original notebook output cells are historical records.

← / → Read the evidence

Packages and shared imports

LAB · Shared setup
python -m pip install \
  torch datasets numpy pandas scikit-learn \
  flair transformers accelerate sentencepiece
from importlib.metadata import version
from collections import Counter

import pandas as pd
import torch
from datasets import DatasetDict
from sklearn.metrics import classification_report

1. Install once

Use the prepared environment. In a notebook, install with %pip, then restart the kernel.

2. Load the shared tools

DatasetDict loads data. Counter counts labels. classification_report reads performance by class.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Versions and available devices

LAB · Shared setup
packages = [
    "torch", "datasets", "numpy", "pandas",
    "scikit-learn", "flair",
    "transformers", "accelerate",
]
for package in packages:
    print(f"{package}: {version(package)}")
if torch.cuda.is_available():
    device = torch.device("cuda")
elif torch.backends.mps.is_available():
    device = torch.device("mps")
else:
    device = torch.device("cpu")
print("Available device:", device)

1. Record the environment

Keep these package versions with your model settings and results.

2. Inspect the device

Choose CUDA, Apple MPS or CPU. Check the device reported by each training log.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Read the current preparation check

LAB · Printed results
torch: 2.2.2
datasets: 2.19.0
numpy: 1.26.2
pandas: 2.2.1
scikit-learn: 1.3.2
flair: 0.13.1
transformers: 4.54.0
accelerate: 1.9.0
Available device: cpu

Preparation check: 27 November 2026.

1. Record the versions

These versions describe the prepared environment.

2. Read the device

This check reports CPU availability. Check the trainer log when training.

3. Keep the date with the output

This preparation check does not report a trained model’s performance.

Current preparation output, 27 November 2026: environment.txt. This is not the environment record of the original 2024 model run.

← / → Read the printed output

The shared dataset and label IDs

LAB · Shared setup
dataset = DatasetDict.load_from_disk(
    "irish_environmental_policies"
)
train = dataset["train"]
validation = dataset["validation"]
test = 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()
}

1. Load the existing split

Run from notebooks/. Keep train, validation and test in their supplied roles.

2. Read the stored mapping

0 means other policy. 1 means environmental policy. Preserve this order.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Class counts and a full training text

LAB · Shared setup
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"]])

1. Inspect class balance

Split sizes: 1,880 / 627 / 627. Test has 44 environmental-policy texts.

2. Read before fitting

The first text discusses community policing and has reference label 0.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Printed data and labels

LAB · Printed results

Printed from the supplied data · 27 November 2026

Split Rows Other policy (0) Environmental policy (1)
Train 1,880 1,772 108
Validation 627 582 45
Test 627 583 44

0 → None Environment Policy
1 → Environment Policy

Only 44 of 627 test excerpts have the environmental-policy label.

Executed data printout · Supplied dataset counts; original Transformers notebook, zero-based cell 8 (mapping); Flair notebook, cells 12 and 19 (training and test labels).

← / → Counts → Labels → Class balance

Flair objects and device

LAB · Flair
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

1. Load the Flair interface

Sentence holds one text. Corpus holds the split. The classifier and trainer have separate jobs.

2. Configure the run

Set a seed and assign the device to Flair explicitly.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Texts become labeled Sentences

LAB · Flair
def as_sentences(split):
    sentences = []
    for row in split:
        sentence = Sentence(row["text"])
        sentence.add_label(
            "label", str(row["label"])
        )
        sentences.append(sentence)
    return sentences
flair_train = as_sentences(train)
flair_dev = as_sentences(validation)
flair_test = as_sentences(test)

print(flair_train[0].to_plain_string())
print(flair_train[0].get_label("label").value)

1. Attach the supplied label

Sentence stores text. add_label stores the gold value in the label layer.

2. Preserve each split

Convert train, validation and test separately, then inspect the first training example.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Corpus and training-label dictionary

LAB · Flair
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(label_dict.get_items())

1. Keep the split together

Corpus holds train, dev and test. Their roles remain distinct.

2. Build classes from train

add_dev_test=False excludes held-out labels. The dictionary contains strings "0" and "1".

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

The Flair encoder and task head

LAB · Flair
flair_checkpoint = (
    "sentence-transformers/"
    "distiluse-base-multilingual-cased-v2"
)
flair_embeddings = TransformerDocumentEmbeddings(
    flair_checkpoint,
    fine_tune=True,
)
flair_classifier = TextClassifier(
    flair_embeddings,
    label_dictionary=label_dict,
    label_type="label",
    multi_label=False,
)

1. Load the pretrained encoder

fine_tune=True allows encoder weights to change when training runs.

2. Add a classification head

Use the class dictionary and gold label layer. Each text receives one category.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Flair training and the saved checkpoint

LAB · Flair
flair_trainer = ModelTrainer(
    flair_classifier, corpus
)
flair_trainer.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,
)
flair_model = TextClassifier.load(
    "qta_flair_python_model/best-model.pt"
)

1. Run the original training recipe

SGD, rate .02, three epochs. Dev selects the checkpoint. Test runs at the end.

2. Reload the selected model

best-model.pt contains the checkpoint selected using validation.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Read the original Flair training history

LAB · 2024 notebook record
Epoch Train loss Dev loss Dev micro-F1
1 0.2199 0.1576 0.9522
2 0.1360 0.1586 0.9522
3 0.0888 0.1616 0.9522

Values displayed to four decimal places.

Best checkpoint saved after epoch 1.

Historical training log: 19 April 2024 · CPU.

1. Read the training loss

Loss falls as the model fits the training data.

2. Check validation performance

Dev micro-F1 stays at 0.9522; dev loss rises slightly.

3. Identify the saved checkpoint

The log saves epoch 1. Later epochs do not improve the recorded selection score.

Historical output from the supplied 2024 Flair notebook, stored training log. These are original model records, not results from a new W10 training run.

← / → Read the printed output

Flair predictions and class-specific results

LAB · Flair
flair_model.predict(
    flair_test,
    mini_batch_size=16,
    label_name="predicted",
)
flair_predictions = [
    int(sentence.get_label("predicted").value)
    for sentence in flair_test
]
print(classification_report(
    test["label"],
    flair_predictions,
    labels=[0, 1],
    target_names=labels,
    zero_division=0,
))

1. Keep gold and predictions separate

Write predictions to predicted, then convert their strings back to category IDs.

2. Read the environmental-policy row

Compare precision, recall and F1. Use the shared class names and order.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Printed Flair test report

LAB · 2024 notebook record

2024 notebook record · not a new run of revised code

Class Precision Recall F1 Support
Other policy (0) .9507 .9914 .9706 583
Environmental policy (1) .7368 .3182 .4444 44

Accuracy: .9442 · Macro-F1: .7075 · Test rows: 627

High accuracy can coexist with low environmental-policy recall.

Original Flair notebook, zero-based cell 19, final “Results / By class” output. Stored training recipe: rate .02, batch 16, three epochs.

← / → Larger class → Environmental class → Summary

Transformers tools and tokenizer

LAB · Transformers
from transformers import (
    AutoTokenizer,
    AutoModelForSequenceClassification,
    TrainingArguments,
    Trainer,
    pipeline,
    set_seed,
)
from sklearn.metrics import (
    accuracy_score,
    f1_score,
)

set_seed(42)
hf_checkpoint = "distilbert-base-uncased"
hf_tokenizer = AutoTokenizer.from_pretrained(
    hf_checkpoint
)

1. Make the training components explicit

Load the tokenizer, model, settings and trainer. Set the seed before model creation.

2. Match tokenizer and checkpoint

Use distilbert-base-uncased for both the tokenizer and model.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Tokenized data and the DistilBERT head

LAB · Transformers
def tokenize_batch(batch):
    return hf_tokenizer(
        batch["text"],
        padding="max_length",
        truncation=True,
    )

hf_data = dataset.map(tokenize_batch, batched=True)
print(hf_data["train"].column_names)
print(len(hf_data["train"][0]["input_ids"]))
hf_model = (
    AutoModelForSequenceClassification
    .from_pretrained(
        hf_checkpoint,
        num_labels=len(labels),
        id2label=id2label,
        label2id=label2id,
    )
)

1. Encode without replacing raw data

hf_data adds input IDs and attention masks. Padding gives 512 positions; truncation limits length.

2. Use the shared two-class mapping

Load the pretrained encoder with a new policy-classification head.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Accuracy and macro-F1

LAB · Transformers
def compute_metrics(prediction):
    reference = prediction.label_ids
    predicted = prediction.predictions.argmax(-1)
    return {
        "accuracy": accuracy_score(
            reference, predicted
        ),
        "macro_f1": f1_score(
            reference,
            predicted,
            average="macro",
            zero_division=0,
        ),
    }

1. Define what evaluation reports

Choose the largest logit for each prediction. Macro-F1 weights the two classes equally.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Training and checkpoint settings

LAB · Transformers
hf_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,
)

1. Select using validation macro-F1

Evaluate and save each epoch. Reload the checkpoint with the highest validation macro-F1.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Trainer connects the model and data

LAB · Transformers
hf_trainer = Trainer(
    model=hf_model,
    args=hf_args,
    train_dataset=hf_data["train"],
    eval_dataset=hf_data["validation"],
    processing_class=hf_tokenizer,
    compute_metrics=compute_metrics,
)
hf_trainer.train()

1. Configure first, then train

Train updates weights. Validation selects the checkpoint. The test split is absent.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Transformers predictions on the test split

LAB · Transformers
hf_result = hf_trainer.predict(hf_data["test"])
hf_predictions = hf_result.predictions.argmax(-1)
print(classification_report(
    hf_result.label_ids,
    hf_predictions,
    labels=[0, 1],
    target_names=labels,
    zero_division=0,
))

1. Evaluate the fixed procedure

Predict test once the procedure is fixed. Read the same class report as for Flair.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Printed Transformers test report

LAB · 2024 notebook record

2024 notebook record · not a new run of revised code

Stored test metric Value
Accuracy .9298245614
Macro-F1 .4818181818
Macro-precision .4649122807
Macro-recall .5000000000
Test rows 627

The stored cell reports macro averages, not a per-class report.

Original learning rate: 0.3. Revised code needs its own run and results.

Original Transformers notebook, zero-based cells 17, 19 and 25. Cells 33–34 use a different model path; the example is not validated by this test report.

← / → Accuracy → Macro averages → Run provenance

Save and reload the same model directory

LAB · Transformers
model_save_path = "qta_hf_python_model"
hf_trainer.save_model(model_save_path)
hf_tokenizer.save_pretrained(model_save_path)
policy_classifier = pipeline(
    "text-classification",
    model=model_save_path,
    tokenizer=model_save_path,
    device=-1,
)

1. Save both model and tokenizer

Store the selected checkpoint and its matching tokenizer together.

2. Reload from that path

The pipeline reads the saved model and tokenizer. device=-1 runs this demonstration on CPU.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

A new policy excerpt

LAB · Transformers
policy_text = (
    "Reducing our carbon footprint through "
    "renewable energy sources and enhanced "
    "energy efficiency is crucial."
)
print(
    policy_classifier(policy_text, truncation=True)
)

1. Read the category and model score

Use policy text for this policy classifier. The score does not establish correctness.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Align both predictions with the same texts

LAB · Flair and Transformers
comparison = pd.DataFrame({
    "text": test["text"],
    "reference_id": test["label"],
    "flair_id": flair_predictions,
    "transformers_id": hf_predictions,
})
for column in [
    "reference_id",
    "flair_id",
    "transformers_id",
]:
    comparison[column.replace("_id", "")] = (
        comparison[column].map(id2label)
    )

1. Join by the unchanged test order

Keep full text, reference ID and both prediction IDs in one table.

2. Translate IDs into class names

Apply the same id2label mapping to the reference and both models.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Read a full-text error

LAB · Flair and Transformers
needs_reading = (
    (
        comparison["flair_id"]
        != comparison["reference_id"]
    )
    | (
        comparison["transformers_id"]
        != comparison["reference_id"]
    )
)
candidates = comparison.loc[needs_reading]
row = (
    candidates if len(candidates) else comparison
).iloc[0]
print(row["text"])
for name in ["reference", "flair", "transformers"]:
    print(f"{name}: {row[name]}")

1. Choose a text for inspection

Select a row where either model disagrees with the reference. If none do, use the first text.

2. Explain the evidence

Read the full text, reference, Flair prediction and Transformers prediction in that order.

Unified Lab guide. Code follows the supplied notebook workflows.

← / → Follow the code and explanation

Reuse an existing NLI classifier

LAB · NLI stance demonstration
import torch
from transformers import pipeline

nli_model_id = (
    "MoritzLaurer/DeBERTa-v3-large-"
    "mnli-fever-anli-ling-wanli"
)
nli_revision = (
    "b3546ea6b0346eb6f8d5d68b13c7dc6d0376b3d7"
)
nli_classifier = pipeline(
    "zero-shot-classification",
    model=nli_model_id,
    revision=nli_revision,
    device=-1,
    torch_dtype=torch.float32,
    batch_size=1,
)

1. Load an NLI model

Its existing head predicts relations between two texts.

2. Reuse its weights

device=-1 selects CPU. There is no train() call.

← / → Follow the NLI code

Write the stance hypotheses

LAB · NLI stance demonstration
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))

1. Define the target

The template names Trump. Candidate phrases specify the stance.

2. Read complete statements

The model pairs each statement with the same input text.

← / → Follow the NLI code

Classify three short texts

LAB · NLI stance demonstration
nli_texts = [
    "I support Trump's policies.",
    "I oppose Trump's policies.",
    "The committee meets on Tuesday.",
]
nli_results = nli_classifier(
    nli_texts,
    candidate_labels=nli_labels,
    hypothesis_template=nli_template,
    multi_label=False,
)

1. Read texts A, B and C

These are constructed teaching inputs, not a research test set.

2. Compare candidate scores

False selects one stance. It normalizes across candidate hypotheses.

← / → Follow the NLI code

Read the executed NLI output

LAB · Executed NLI demonstration · 27 November 2026

A: I support Trump’s policies.

B: I oppose Trump’s policies.

C: The committee meets on Tuesday.

Text Support Oppose No opinion
A 0.9918 0.0044 0.0038
B 0.0086 0.9843 0.0071
C 0.2063 0.1967 0.5970

Candidate scores with multi_label=False; short column names.

1. A ranks support first

Read the text and all three scores together.

2. B ranks opposition first

Check that the target matches the research definition.

3. C is less decisive

No opinion leads at .5970. Set review rules with validation data.

Actual CPU output and pinned revision · Constructed inputs; no fine-tuning, COVID-19 replication or accuracy estimate.

← / → Read text A, then B, then C

Selected application readings

Architecture: Vaswani et al. (2017) · Devlin et al. (2019). Lab: Liao & Müller (2024), supplied Week 12 notebooks.