W6: Human Coding and Document Classification
In W4 we used dictionaries: the researcher picks the words and writes the rules. W6 takes another route: first have people label a set of texts, then let a machine-learning classifier learn from those labels to classify new texts. This week's two labs: political hate speech in Taiwan (Naive Bayes) and grandstanding in US congressional hearings (linear SVM).
From dictionaries to classifiers
Slide 2 puts W4 and W6 side by side. The four rows are the same tasks, done differently:
| Task | W4: dictionary | W6: classification |
|---|---|---|
| Build a measure | Select words and rules | Learn from labelled comments |
| Use human evidence | Validate dictionary output | Train and evaluate the classifier |
| Develop the method | Read KWIC, revise rules | Fit an ML algorithm and predict new texts |
| Evaluate results | Read errors and sensitivity | Held-out test set + human benchmark |
A dictionary is like a "checklist" you write by hand: if 「滾」 (get lost) or 「垃圾」 (trash) appears, count it as hate. A classifier is more like asking a new assistant to look through a few thousand comments that people have already judged and work out for themselves "which characters tend to show up in hateful comments". So the key in W6 is not how clever the algorithm is, but where those few thousand human labels came from and whether they can be trusted—which is the focus of the "human coding" half of this week.
What you should be able to explain this week
Compiled from the learning goals on slide 2 and the in-class exercise requirements on slide 94. After finishing a chapter, come back and tick the ones you can now do:
- Labels before algorithms: explain what a codebook must define (coding unit, boundaries, admissible evidence), and why "high agreement" does not mean "measuring the concept you want".
- Split and vocabulary (C03–C04, G01b–G02a): explain why the test set is held out first, the vocabulary is chosen from training data only, and the test matrix is aligned to the same columns.
- Read evaluation metrics (C06, C08, G02d): read false positives and false negatives off a confusion matrix, and explain what accuracy, precision, recall and F1 each say.
- Read misclassified texts (C07, G03, error reading): pick one misclassified text and use the category definition to explain where the boundary lies and what context is missing.
One workflow: load → split → features → fit → predict → check
Slide 31 says both cases follow the same steps. Click each step to see where it sits in this week's R script:
Static summary: 1 get labelled data with one row per text (code it yourself or use found labels, and audit the labels) → 2 hold out a 20% test set before choosing the vocabulary or fitting the model → 3 choose the vocabulary from training texts only (characters for Chinese, words for English) → 4 fit the classifier on the training matrix and labels → 5 align the test texts to the same vocabulary, predict, read the confusion matrix and F1, and read the misclassified texts.
Six research cases
| Study | Venue | Teaching link this week | Chapter in these notes |
|---|---|---|---|
| Wang, Day & Wu (2022) | IEEE Access | Hate speech: Chinese character counts | 06–08 |
| Gillion (2016) | Governing with Words | Coding rules and agreement | 02 |
| Benoit et al. (2016) | APSR | Crowd coding and reproducibility | 02 |
| Boydstun (2013) | Making the News | Codebooks and rare categories | 03 |
| Nielsen (2017) | Deadly Clerics | Found labels and validation | 03 |
| Park (2021) | JOP | Grandstanding: mlr3 linear SVM | 04, 09–10 |
The classification exercises use only the Wang, Day & Wu (2022) and Park (2021) data; the other four studies are for discussing "how human labels are produced and how they are checked".
Two practice datasets
| Hate speech (Wang, Day & Wu 2022) | Grandstanding (Park 2021) | |
|---|---|---|
| One row = | One Chinese comment on political news | One English excerpt of congressional hearing speech |
| Rows | Original 31,071 → 4,000 for practice | Original 3,500 → 3,499 after de-duplication |
| Text → target | text → hate_speech (0/1) | speech → rescaled_gs (0/1) |
| Positive class | HateSpeech | Grandstanding |
| Features | Chinese character counts | English word counts |
| Classifier / interface | Multinomial NB / quanteda.textmodels | Linear SVM / mlr3 + mlr3learners |
| Unused columns | label (class name) | sentimentit_score (original grandstanding score; not used as a predictor) |
Slide 32 also shows the first three rows of both raw CSVs; for example, row 3 of merged-hate-speeches.csv, 「智X總統 畜X官員 無誤 ?!」, is labelled 1. The cleaned practice CSVs were prepared in advance by the instructor with prepare_practice_data.R (removing label conflicts and duplicates, excluding texts in the human benchmark, and drawing 4,000 comments with seed 7191); students just call read.csv().
- Hate speech: 31,071 rows → remove 1,275 rows with label conflicts and 5,811 duplicate rows → 23,985 comments → exclude a further 370 that overlap with the benchmark → 23,615 usable → draw 4,000 (2,378 HateSpeech, 1,622 NonHateSpeech).
- Human benchmark: two validation sheets of 1,000 comments each → remove 8 conflicting rows and 24 duplicate rows → 1,968 comments (209 HateSpeech, 1,759 NonHateSpeech).
- Grandstanding: 3,500 rows → remove 1 duplicate row with the same label → 3,499 rows (1,846 NonGrandstanding, 1,653 Grandstanding).
How to use these notes
- On the right (on narrow screens, the button at the bottom right) is the slide panel; clicking any "Slide N" badge jumps to that page.
- Every R output block is the result of actually running the instructor's
W6/classroom/W6_classification.Rlocally (R 4.5.3 (aarch64-conda-linux-gnu), quanteda 4.5.1, quanteda.textmodels 0.9.10, mlr3 1.8.0, mlr3learners 0.16.0, e1071 1.7.17, stringi 1.8.9, glmnet 5.0), checked number by number against the slides. - The interactive labs come in three kinds: real-data (predictions, probabilities and model parameters exported after running this week's Data/), toy intuition (marked "Supplement (not from the lecture)") and practice (coding exercises, answer boxes, flip cards, plan builder).
- Progress, answers and notes are stored only in this browser (localStorage) and are never uploaded.
In-class exercise and deadlines
In class, run C01–C08 in order in the same R session, then G01–G03 (including all sub-steps). For hate speech, look at both the test-set and the independent benchmark results; for grandstanding, fit an mlr3 linear SVM on rescaled_gs; for each case, read one error and explain the category boundary. Week 7: research proposal due 2026-10-23 23:59. This exercise does not need to be submitted.
A different wording: the syllabus (NTLDEV_7191_1151.pdf) lists 23 October as "Individual research abstract due"; follow the instructor's announcement.
Self-check
sentimentit_score in the grandstanding exercise?What does supervised document classification do? Four steps
"Supervised" means we have a set of texts whose answers are already known (the labels); the model learns from them and is then used to judge texts it has never seen. Slides 23–26 break this into four steps.
Step 1: Get labelled data
Workflow: define the concept → label it yourself or find existing labels → audit the labels → one row per text.
- Make your own labels: write a codebook, collect independent judgements, and adjudicate disagreements.
- Use found labels: check the source, coding unit, definition, and how scores were converted into categories.
- This week: the hate-speech labels come from Wang, Day & Wu (2022); grandstanding uses the
rescaled_gscategory in the Park (2021) data.
Step 2: Split the labelled documents
Split before vocabulary selection or model fitting; use a fixed stratified 80/20 split; test-set labels take no part in fitting. Both cases use the same procedure.
If you first pick the "common characters" from all 4,000 comments, the choice of those characters has already peeked at the test set. This is called data leakage: the test score becomes optimistic because the test set is no longer truly "unseen" data. That is why this week's C04b applies dfm_trim() to the training rows only, and the test rows are then aligned with dfm_match().
Step 3: Fit an ML classifier
Training texts → text features → fitted classifier. Chinese comments use character counts and English excerpts use word counts; the vocabulary is chosen from training texts only; the classifier is fitted on the training feature matrix and the matching labels. Classroom example: textmodel_nb() fits a multinomial Naive Bayes.
Step 4: Predict and check the labels
Test texts → align the vocabulary (same order) → predict() → compare with the labels. Read the predicted classes, the confusion matrix and F1; for hate speech, also check against independent human benchmark comments.
Labels before algorithms
Hate speech uses the labels in the Wang, Day & Wu (2022) data; grandstanding uses rescaled_gs—but this CSV does not record the cut-point originally used to turn the score into binary categories.
The intuition behind Naive Bayes
Slide 36 only asks you to "be able to use" it: NB is fitted with a document-feature matrix and one label per row; it combines the counted features into "evidence for each class"; predict() returns classes and type = "probability" returns model probabilities. The toy below lets you see how "combining evidence" is calculated.
Training data (fictional, only to demonstrate the calculation): class H = 「滾 回去」 (get lost, go back), 「垃圾 滾」 (trash, get lost), 「垃圾 官員」 (trash official); class N = 「支持 政策」 (support the policy), 「官員 回應 政策」 (official responds to policy), 「支持 回應」 (support the response). Click the words below to build a new comment (you can click repeatedly) and see how multinomial NB computes it.
Static explanation: P(class | text) ∝ P(class) × Π P(word | class)count. prior = "docfreq" means P(class) is the share of training documents in each class (here 3/6); smooth = 1 means 1 is added to every word count first, so an unseen word cannot drive the probability to 0.
Self-check
Gillion and Benoit: coding rules, agreement and crowd coding
A classifier learns "how people assign labels". So the first questions are: by what rules were the human labels assigned? Were they assigned consistently? And if they were consistent, what did they actually measure?
Gillion (2016): how politicians talk about race
- Question: how do politicians discuss race and minority concerns?
- Texts: presidential public statements and congressional floor speech.
- Application: humans label paragraphs, then a classifier extends the coding to the whole corpus.
- Research use: compare political attention across politicians and periods.
Coding boundaries and agreement
| Design | Gillion's approach (Appendix A, pp. 163–166) |
|---|---|
| Coding unit | Paragraph; written bills and procedural content excluded |
| Training labels | Two assistants coded random samples: 300 paragraphs per presidential term and 1,000 per congressional session |
| Rule | Must contain an explicit reference to race: racial groups, race-specific policies, minority figures or race-specific issues |
| Boundary | General discussion of crime, education or health counts only when it carries such an explicit reference |
| Agreement | Reported intercoder reliability of 97%; disagreements adjudicated by Gillion |
The footnote on slide 6: the 97% concerns coders, not classifier accuracy.
What does this measure miss?
- Missed content: coded racial messages without an explicit racial reference.
- Example: "inner city" may carry racial meaning in context, but the phrase alone is not enough to infer a racial appeal (White 2007).
- Lesson: 97% agreement means the coding is consistent; but we still need to ask whether the rule captures implicit appeals.
Agreement calculator: why also look at κ?
The slides only report Gillion's 97%; Cohen's κ is a common supplementary measure that removes "agreement by chance". Enter the two coders' judgement counts (fictional) in the table below, or press a preset scenario.
Static explanation: κ = (Po − Pe) / (1 − Pe). When "yes" is very rare (say only 3 of 100 paragraphs discuss race), two coders who both carelessly answer "no" will still have very high percent agreement; κ is what exposes the problem. This is also why we need to be careful with Boydstun's rare categories in chapter 03 and with hate speech in chapter 08, where only about 10.6% are positive.
Benoit et al. (2016): crowd coding political texts
- Texts: sentences from party manifestos. Coding: repeated crowd judgments. Validation: comparison with experts.
- A simple coding scheme (Figure 1, p. 281): classify the topic first, then rate the position; keep the task simple.
- Replicating judgements (Table 4, p. 291, replication of immigration coding): two waves of coding, party scores correlate .93; the scope is reproducibility at the aggregate level.
.93 is the correlation of "party scores" between the two waves, not the share of individual sentences that received the same label in both waves. Many noisy judgements can average out to something very stable—this is the core idea of crowd coding—but what it guarantees is reproducibility at the party level.
The coal subsidy case: checking scores against votes
36 European Parliament (EP) speeches; the figure shows 31 votes in six languages; crowd-coded scores are compared with votes (Figure 7, p. 292). This is an example of checking what a score means using behaviour outside the text, in the same spirit as Nielsen's external validation in chapter 03.
Self-check
Boydstun and Nielsen: codebooks, rare categories and found labels
Boydstun shows how a good codebook limits "what coders may look at"; Nielsen shows how, when the labels are not coded by you but "found" (found labels), you use evidence outside the text to check what the scores mean.
Boydstun (2013): measuring the news agenda
- Question: how is news attention distributed across policy issues over time?
- Data: New York Times front-page stories, 1996–2006.
- Application: human coders assign policy topics; counts track media attention.
- First step: before comparing issues, make sure topic labels are applied consistently.
Codebook: first define the evidence coders may use
| Codebook element | Boydstun's rule (original coding manual, pp. 1–5) |
|---|---|
| Evidence | Headline and first three paragraphs |
| Label | One primary topic + a short summary |
| Consistency | Align labels within the same storyline; clarify unclear cases |
| Lesson | Define which evidence coders may use |
What is the "evidence" for hate speech? Only that one comment? Or also the news headline it responds to? Data/README says this dataset provides no user, news story, thread or time identifiers. So our classifier can only look at the characters of a single comment—that is its "scope of evidence".
Labels reveal uneven attention
Selected rows from Boydstun (2013) Table A.1 (full corpus of 31,034 stories). Press the button to see the proportion bars:
| Topic | Stories | Share of all stories |
|---|---|---|
| International affairs and foreign aid | 6,354 | 20.5% |
| Defense | 4,479 | 14.4% |
| Health | 1,799 | 5.8% |
| Energy | 299 | 1.0% |
Nielsen: from reference texts to scores
- Texts: Arabic writings by Islamic clerics. Measure: a language-based jihad score, used to study networks, careers and ideological differences.
- Supervision: 765 jihadist-curated texts vs. 1,951 sampled cleric texts (a mixed baseline).
- NB weights: words more common in the jihadist references raise the score; words more common in the baseline lower it.
- Aggregation: pool each cleric's writings and sum these word weights. Interpretation: the higher the score, the more the language resembles the jihadist references; the measure is continuous. (Nielsen 2014 working paper §4.1, pp. 13–14)
Nielsen uses exactly NB's "word weight" idea: log P(word | jihadist) − log P(word | baseline). The live NB scorer in chapter 07 uses this week's fitted model to plot the same kind of weight for every Chinese character.
External checks and their limits
- The paper's claim: combine "understanding the meaning for actors" with "quantitative tests of causes". Treating clerics as scholars, it tests whether blocked careers predict jihadist rhetoric.
- Language check: explain why "apostasy" in context points to jihadist ideology.
- External checks: compare the scores with biographies and scholarly classifications (2014), and with a jihadist infographic criticising non-jihadist preachers (2017).
- Our check: use evidence outside the training texts to see what the score represents.
If a biography does not mention ideology, you cannot therefore label the person "non-jihadist"—silence cannot establish non-jihadist status. Class discussion: could a text that criticises jihadism receive a high score because it uses the same vocabulary? For our hate-speech task: check comments that quote abuse in order to reject it.
Claim-judging exercise
For each statement below, decide from the slides whether "you can say this" or "you cannot say this".
Self-check
Park (2021): measuring grandstanding, and four coding design choices
Grandstanding refers to members of Congress speaking at hearings not to obtain information but to take a position, praise or attack. Park used crowd ratings to produce labels and then a model to predict scores. At the end of this chapter you will act as a coder yourself.
Park (2021): measuring political grandstanding
- Texts: US House hearing speech. Study: crowd coding and grandstanding scores.
- Our exercise: use the
rescaled_gslabels in the Park (2021) data; mlr3 linear SVM.
Grandstanding: predicted scores
Original study (manuscript Figure 1, pp. 16–18): 3,000 crowd-rated paragraphs as labels; 300 held out for testing; RMSE 0.613 (original units). Note: the original study predicts a continuous score, while our classroom exercise does binary classification instead, so the two sets of evaluation numbers cannot be compared directly.
Using the measure for research
Manuscript Figure 3 (p. 20): the horizontal axis is "Republican mean − Democratic mean"; the pattern is that the minority party scores higher; interpretation: messaging and power.
Category boundaries: what counts as grandstanding?
Park's rating instructions as summarised in the lab handout (Lab_Session_W6.R, "Reading the category boundaries"):
- One end: praising or disparaging people or institutions; policy positions or subjective evaluations; questions meant to embarrass or attack the witness.
- The other end: factual descriptions, requests for facts or expert opinion.
- Questions can also be grandstanding; merely referring to oneself does not decide the category.
- The original ratings measure relative intensity; the CSV does not record the cut-point for the binary
rescaled_gs, so we keep the existing classes.
Hate speech (same handout): Wang, Day & Wu define it as abuse targeting attributes of an individual or group, including attacks on political beliefs or parties; satire and humour are excluded, and offensive speech is distinguished from hate speech. When reading a comment, identify the target, the attribute attacked, and the context that shows abuse. (The handout cites Wang, Day & Wu 2022, §III-A(2), p. 44342; the full text was not available for these notes.)
Four choices in coding and measurement
| Design choice | The W6 question |
|---|---|
| Coding unit | Does one sentence contain enough evidence to judge our category? |
| Repeated judgements | Which disagreements should trigger human review? |
| Aggregation | Do we need comment-level labels, hate-speech shares, or a continuous score? |
| Validation | What independent evidence can test our intended interpretation? |
Exercise: you are the coder (real data)
The 8 passages below come from the 700-passage test set run locally (2 from each cell of the confusion matrix, in shuffled order). First judge them yourself using the boundary definitions above; after answering all of them, press "Reveal" to compare with the rescaled_gs reference labels and the SVM probabilities. Your judgements are stored only in this browser.
Static note: this exercise needs JavaScript. Without JS, you can read the two full texts in chapter 10 (gs_01045 and gs_00013).
Self-check
R tools: quanteda, quanteda.textmodels, mlr3 and Naive Bayes
This week three groups of packages share the work: quanteda turns text into features, quanteda.textmodels fits simple text classifiers directly, and mlr3 handles data splitting and evaluation (plus the SVM for grandstanding).
R tools for document classification
| We need to | R tool |
|---|---|
| Turn text into features | quanteda |
| Fit text classifiers directly | quanteda.textmodels |
| Organise models and evaluation | mlr3 |
| Chain preprocessing steps | mlr3pipelines |
| Search model settings | mlr3tuning |
Use mlr3 when you need resampling, model comparison, pipelines or tuning; for this week's NB exercise we fit the model directly with quanteda.textmodels.
mlr3: a machine-learning framework for R
- Framework: different learners share one interface.
- Task + learner:
as_task_classif()defines the target;lrn()creates the model;$train()fits it. - Evaluation: resampling, measures (
msrs()) and extension packages.
$ of R6 objects (supplement)mlr3 objects are R6 classes: what follows $ may be a field (gs_result$response) or a method (gs_result$score(measures), with parentheses). The syntax table in the lab handout also explicitly distinguishes "the $ of a data frame" from "the $ of an mlr3 object".
mlr3 vs. the Python ecosystem
Click a card to flip it. The front shows a need; the back shows the R (mlr3 ecosystem) and Python (scikit-learn ecosystem) equivalents.
| Need | R: mlr3 ecosystem | Python: scikit-learn |
|---|---|---|
| Model interface | Task + learner | Estimator |
| Fit / predict | $train() / $predict() | .fit() / .predict() |
| Text features | quanteda counts / TF-IDF | CountVectorizer / TfidfVectorizer |
| Preprocessing + model | mlr3pipelines | Pipeline |
| Cross-validation | resample() | cross_validate() |
| Parameter search | mlr3tuning | GridSearchCV |
Same workflow: define the target, separate training and test data, evaluate predictions.
Simple models in quanteda.textmodels
| Model | Function | This week |
|---|---|---|
| Naive Bayes | textmodel_nb() | Main hate-speech model (C05) |
| Regularized logistic regression | textmodel_lr() | Optional (Chapter 11, run locally) |
| Linear SVM | textmodel_svmlin() | Experimental, two classes only; this week we use mlr3's classif.svm instead |
Slide 36: fit with a DFM and one label per row; NB combines counted features into evidence for each class; predict() returns classes, and type = "probability" returns model probabilities. The focus is on fit → predict → inspect.
Package check
# Install once
install.packages(c("quanteda", "quanteda.textmodels",
"mlr3", "mlr3learners", "e1071", "stringi"),
repos = "https://cloud.r-project.org")
# Load and check before the exercise
library(quanteda); library(quanteda.textmodels)
library(mlr3); library(mlr3learners)
library(e1071); library(stringi)
lrn("classif.svm")$idReady when: all six packages load and the last line returns "classif.svm".
The R output in these notes was run on Linux aarch64: R 4.5.3 (aarch64-conda-linux-gnu), quanteda 4.5.1, quanteda.textmodels 0.9.10, mlr3 1.8.0, mlr3learners 0.16.0, e1071 1.7.17, stringi 1.8.9, glmnet 5.0. quanteda.textmodels, mlr3, mlr3learners and e1071 were installed from CRAN source for this run.
Self-check
GridSearchCV corresponds to what in the mlr3 ecosystem?textmodel_svmlin() for grandstanding this week? What clue does the slide give?C01–C04: setup, reading data, splitting, Chinese-character features and the training vocabulary
From 4,000 comments to a 3,200 × 603 training matrix. Every step comes with the code from the instructor's script and the output of a local run.
C01: set up both cases at once
# C01: Setup
# install.packages(c("quanteda", "quanteda.textmodels",
# "mlr3", "mlr3learners", "e1071", "stringi"))
library(quanteda); library(quanteda.textmodels)
library(mlr3)
quanteda_options(threads = 1)
data_dirs <- c("Data", "W6/lab/Data",
"W6/classroom/Data", "../Data")
data_dir <- data_dirs[dir.exists(data_dirs)][1]
file.exists(file.path(data_dir, "hate_speech_practice.csv"))
measures <- msrs(c("classif.acc", "classif.precision",
"classif.recall", "classif.fbeta"))> library(quanteda); library(quanteda.textmodels)
Package version: 4.5.1
Unicode version: 17.0
ICU version: 78.3
Parallel computing: 2 of 2 threads used.
See https://quanteda.io for tutorials and examples.
> library(mlr3)
> quanteda_options(threads = 1)
> data_dirs <- c("Data", "W6/lab/Data",
+ "W6/classroom/Data", "../Data")
> data_dir <- data_dirs[dir.exists(data_dirs)][1]
> file.exists(file.path(data_dir, "hate_speech_practice.csv"))
[1] TRUE
> measures <- msrs(c("classif.acc", "classif.precision",
+ "classif.recall", "classif.fbeta"))| Function | Purpose |
|---|---|
quanteda_options() | Sets text-processing options for this session (here threads = 1) |
msrs() | Creates four measure objects: accuracy, precision, recall, F1 (classif.fbeta defaults to β = 1, i.e. F1) |
data_dirs looks in Data, W6/lab/Data, W6/classroom/Data, ../Data, in that order. FALSE means R's working directory is not the unzipped folder, or Data/ is not next to the R file — check with getwd() first rather than changing the code.
C02: read the Wang, Day & Wu (2022) data
# C02: Load the Wang, Day & Wu (2022) data
hate <- read.csv(file.path(data_dir,
"hate_speech_practice.csv"), stringsAsFactors = FALSE)
hate$label <- factor(hate$label,
levels = c("NonHateSpeech", "HateSpeech"))
table(hate$label)
nrow(hate)> hate <- read.csv(file.path(data_dir,
+ "hate_speech_practice.csv"), stringsAsFactors = FALSE)
> hate$label <- factor(hate$label,
+ levels = c("NonHateSpeech", "HateSpeech"))
> table(hate$label)
NonHateSpeech HateSpeech
1622 2378
> nrow(hate)
[1] 4000HateSpeech, with 2,378 comments, is the larger class. If a classifier always guesses HateSpeech, accuracy = 2,378 / 4,000 = 59.5% (test set 476 / 800 = 59.5%), recall = 1, precision = .595. This is the baseline every model should beat (supplementary calculation).
C03: hold out test comments with mlr3
# C03: Reserve test comments with mlr3
hs_task <- as_task_classif(hate["label"],
target = "label", positive = "HateSpeech")
hs_task$col_roles$stratum <- "label"
set.seed(7192)
hs_split <- partition(hs_task, ratio = .8)
parts <- list(train = hate[hs_split$train, ],
test = hate[hs_split$test, ])
table(parts$train$label)
table(parts$test$label)> hs_task <- as_task_classif(hate["label"],
+ target = "label", positive = "HateSpeech")
> hs_task$col_roles$stratum <- "label"
> set.seed(7192)
> hs_split <- partition(hs_task, ratio = .8)
> parts <- list(train = hate[hs_split$train, ],
+ test = hate[hs_split$test, ])
> table(parts$train$label)
NonHateSpeech HateSpeech
1298 1902
> table(parts$test$label)
NonHateSpeech HateSpeech
324 476 Discussion: why hold out the test rows before choosing the vocabulary? — See "data leakage" in Chapter 01.
C04a: Chinese character tokenization and the DFM
# C04a_1: Normalize and tokenize Chinese comments hs_text <- stringi::stri_trans_nfkc(hate$text) names(hs_text) <- hate$doc_id hs_tokens <- tokens(hs_text, what = "character", remove_punct = TRUE, remove_symbols = TRUE, remove_numbers = TRUE) class(hs_tokens)
> hs_text <- stringi::stri_trans_nfkc(hate$text) > names(hs_text) <- hate$doc_id > hs_tokens <- tokens(hs_text, what = "character", + remove_punct = TRUE, remove_symbols = TRUE, + remove_numbers = TRUE) > class(hs_tokens) [1] "tokens"
# C04a_2: Select Han characters and count features
hs_tokens <- tokens_select(hs_tokens,
pattern = "^\\p{Han}$", valuetype = "regex")
hs_dfm <- dfm(hs_tokens)
dim(hs_dfm)> hs_tokens <- tokens_select(hs_tokens,
+ pattern = "^\\p{Han}$", valuetype = "regex")
> hs_dfm <- dfm(hs_tokens)
> dim(hs_dfm)
[1] 4000 2916| Function | What it does here |
|---|---|
stri_trans_nfkc() | stringi: Unicode NFKC normalization on a working copy of the text (e.g. full-width letters and digits become half-width) |
tokens(what = "character") | Splits each comment into single characters and removes punctuation, symbols and numbers |
tokens_select("^\\p{Han}$", valuetype = "regex") | Keeps only Han (Chinese) characters (remaining Latin letters, emoji, etc. are dropped) |
dfm() | Counts in a sparse document-feature matrix |
Why characters? Chinese has no spaces, so segmenting "words" needs an extra segmenter and dictionary; single characters are the simplest and most reproducible. What is lost? The meaning of words and phrases (「台灣」 is split into 「台」 and 「灣」), character order and negation (「不是」), homophones and variants (such as 「畜X」 on slide 32). 4,000 × 2,916: 4,000 comments × 2,916 distinct Han characters.
Tokenization lab: what does a comment become?
Type or paste a comment. Green box = in the C04b training vocabulary (603 characters); the small number below is its document frequency in the 3,200 training comments. Grey box = a Han character not in the vocabulary (dfm_match drops it). Strikethrough = not a Han character (removed in C04a). The tokenization rule approximates quanteda in the browser (character by character + Han regular expression); NFKC normalization uses the browser's normalize("NFKC").
C04b: choose the vocabulary from training rows only, then align the test rows
# C04b_1: Trim training features train_dfm <- dfm_trim(hs_dfm[hs_split$train, ], min_docfreq = .01, docfreq_type = "prop") train_label <- parts$train$label dim(train_dfm)
> train_dfm <- dfm_trim(hs_dfm[hs_split$train, ], + min_docfreq = .01, docfreq_type = "prop") > train_label <- parts$train$label > dim(train_dfm) [1] 3200 603
# C04b_2: Match test features to training columns test_dfm <- dfm_match(hs_dfm[hs_split$test, ], features = featnames(train_dfm)) dim(test_dfm) identical(featnames(train_dfm), featnames(test_dfm))
> test_dfm <- dfm_match(hs_dfm[hs_split$test, ], + features = featnames(train_dfm)) > dim(test_dfm) [1] 800 603 > identical(featnames(train_dfm), featnames(test_dfm)) [1] TRUE
Does min_docfreq count documents or tokens? Documents. docfreq_type = "prop" with .01 means "appears in at least 1% of training comments", 3,200 × 1% = 32 comments; repeats within one comment count once. Why must the 800 test rows use the same 603 columns in the same order? The model's parameters are probabilities for "the character in column j"; a different column order would apply the evidence for character A to character B. dfm_match() orders columns as in training, drops extra characters, and fills missing ones with 0.
Trimming-threshold lab: how does 1% become 603?
Static note: for hate speech, the 1% threshold (≥ 32 comments) keeps 603 characters; for grandstanding, 1% (≥ 27.99, i.e. ≥ 28 paragraphs) keeps 629 terms. Data exported from the locally run docfreq(hs_dfm[hs_split$train, ]) and docfreq(gs_dfm[gs_split$train, ]).
Self-check
dim(hs_dfm) is 4000 × 2916, while dim(train_dfm) is 3200 × 603. Where did the missing 2,313 columns go?dfm_trim() on all 4,000 comments before splitting, what would be the problem?identical(featnames(train_dfm), featnames(test_dfm)) being TRUE guarantee?C05–C07: fit Naive Bayes, read the confusion matrix, inspect one comment
Fitting NB takes a single line. The real skill is reading the output: the rows of the confusion matrix are predictions and the columns are truth; 0.999 is a model probability, not accuracy.
C05: fit Naive Bayes
# C05: Fit Naive Bayes nb <- textmodel_nb(train_dfm, y = train_label, distribution = "multinomial", smooth = 1, prior = "docfreq") class(nb) nb$distribution
> nb <- textmodel_nb(train_dfm, y = train_label, + distribution = "multinomial", smooth = 1, + prior = "docfreq") > class(nb) [1] "textmodel_nb" "textmodel" "list" > nb$distribution [1] "multinomial"
| Argument | What we supply |
|---|---|
x | Training feature counts (train_dfm) |
y | Labels in the same row order (train_label) — this is the answer to the discussion question |
smooth = 1 | Smoothing of counts (Laplace) |
prior = "docfreq" | Uses training label frequencies as the prior |
Priors from the local export: HateSpeech 0.5944, NonHateSpeech 0.4056 (= 1,902 / 3,200 and 1,298 / 3,200).
C06: predict and evaluate with mlr3
# C06: Predict and evaluate with mlr3 nb_prediction <- predict(nb, newdata = test_dfm) nb_check <- PredictionClassif$new(task = hs_task, row_ids = hs_split$test, truth = hs_task$truth(hs_split$test), response = as.character(nb_prediction)) nb_check$confusion nb_scores <- nb_check$score(measures) round(nb_scores, 3)
> nb_prediction <- predict(nb, newdata = test_dfm)
> nb_check <- PredictionClassif$new(task = hs_task,
+ row_ids = hs_split$test,
+ truth = hs_task$truth(hs_split$test),
+ response = as.character(nb_prediction))
> nb_check$confusion
truth
response HateSpeech NonHateSpeech
HateSpeech 371 140
NonHateSpeech 105 184
> nb_scores <- nb_check$score(measures)
> round(nb_scores, 3)
classif.acc classif.precision classif.recall classif.fbeta
0.694 0.726 0.779 0.752 Rows (response) are predictions; columns (truth) are the true labels. False positives FP = 140: predicted HateSpeech, actually NonHateSpeech. False negatives FN = 105: predicted NonHateSpeech, actually HateSpeech. TP = 371, TN = 184.
What each of the four measures says
| Measure | Formula | Calculation for C06 | In plain words |
|---|---|---|---|
| accuracy | (TP+TN) / N | (371+184)/800 = .694 | Share of all predictions that are correct |
| precision | TP / (TP+FP) | 371/511 = .726 | Among comments predicted as hate, the share that really are hate |
| recall | TP / (TP+FN) | 371/476 = .779 | Among true hate comments, the share that are caught |
| F1 (classif.fbeta, β=1) | 2PR / (P+R) | 2(.726)(.779)/(.726+.779) = .752 | Harmonic mean of precision and recall |
Reminder: accuracy .694 is only about 10 percentage points above the .595 of "always guess HateSpeech" (supplementary calculation).
Confusion-matrix lab: move the threshold
predict() picks the class with the highest probability by default, which equals a threshold of 0.5. Drag the threshold to see how FP and FN trade off; click any cell to list its comments (up to 40, sorted by probability). Threshold adjustment is a supplement; the class script does not do it.
Static note: at threshold 0.5 this reproduces the 371 / 140 / 105 / 184 on slide 54.
C07: predict one real comment
# C07: Inspect one held-out comment
i <- match("hs_26234", parts$test$doc_id)
cat(parts$test$text[i], "\n")
predict(nb, newdata = test_dfm[i, ])
round(predict(nb, newdata = test_dfm[i, ],
type = "probability"), 3)
parts$test$label[i]> i <- match("hs_26234", parts$test$doc_id)
> cat(parts$test$text[i], "\n")
垃圾426,滾回去中國,永不得進來台灣
> predict(nb, newdata = test_dfm[i, ])
hs_26234
HateSpeech
Levels: NonHateSpeech HateSpeech
> round(predict(nb, newdata = test_dfm[i, ],
+ type = "probability"), 3)
docs NonHateSpeech HateSpeech
hs_26234 0.001 0.999
> parts$test$label[i]
[1] HateSpeech
Levels: NonHateSpeech HateSpeech「垃圾426,滾回去中國,永不得進來台灣」 (slide translation: You mainland Chinese scum, get back to China and never set foot in Taiwan.) The model predicts HateSpeech, P(HateSpeech) = 0.999; the reference label is HateSpeech. Discussion: which characters express derogation or exclusion targeting a group?
Levelslists the two possible classes.- 0.999 is a model probability, not overall accuracy. NB's "naive" assumption (characters independent of each other) pushes probabilities to extremes near 0 or 1, so 0.999 does not mean "99.9% sure" either (supplement).
Live NB scorer: using the model fitted this week
Recomputes P(HateSpeech) in the browser from the locally fitted nb$param and nb$priors. Each character's colour = log P(char|Hate) − log P(char|Non): orange = supports HateSpeech, blue = supports NonHateSpeech; grey = not in the 603-character vocabulary. Try editing the text (e.g. delete 「垃圾」).
Overall: the characters NB "trusts" most (real parameters)
Values are log P(char|Hate) − log P(char|Non). Only the 603 characters appearing in ≥ 32 training comments are listed. A high-weight character is not necessarily a hateful word in itself — it simply appears more often in one class in this set of labels (supplement).
Static note: the formula is log posterior ratio = log(prior ratio) + Σ count × [log P(char|Hate) − log P(char|Non)], then converted back to a probability. During export, R checked that this formula agrees with predict(type = "probability") (max absolute difference 5.638268e-13).
Self-check
C08: an independent human reference set — recall is high, so why does precision collapse?
The internal test set comes from the same pool as the training set. The real test is to have the model judge a batch of comments that were collected and human-labelled separately, with the model kept unchanged.
An independent human reference check
- Combined file:
hate_speech_reference.csvcombines two validation files of 1,000 comments each. - BERT / Lexicon: the original file names, recorded in the
sourcecolumn (15 comments appear in both, recorded as BERT+Lexicon). - Reference label:
labelcomes from the "是否仇恨" (is it hate) column, not the original model-prediction columns. - After deduplication and conflict checks, 1,968 comments remain, all excluded from training. They are checked only after fitting; the model stays fixed.
Data/README: the original coder1/coder2/coder3 values are kept as metadata, but the "score-to-category" aggregation was not reconstructed; these notes therefore display the values as they are, without interpreting their codes.
C08a: align the reference comments to the training vocabulary
# C08a: Match human-reference texts to the vocabulary
benchmark <- read.csv(file.path(data_dir,
"hate_speech_reference.csv"), stringsAsFactors = FALSE)
benchmark$label <- factor(benchmark$label,
levels = c("NonHateSpeech", "HateSpeech"))
ref_text <- stringi::stri_trans_nfkc(benchmark$text)
names(ref_text) <- benchmark$doc_id
ref_tokens <- tokens(ref_text, what = "character",
remove_punct = TRUE, remove_symbols = TRUE,
remove_numbers = TRUE)
ref_dfm <- dfm_match(dfm(ref_tokens),
features = featnames(train_dfm))
dim(ref_dfm); sum(ntoken(ref_dfm) == 0)> benchmark <- read.csv(file.path(data_dir,
+ "hate_speech_reference.csv"), stringsAsFactors = FALSE)
> benchmark$label <- factor(benchmark$label,
+ levels = c("NonHateSpeech", "HateSpeech"))
> ref_text <- stringi::stri_trans_nfkc(benchmark$text)
> names(ref_text) <- benchmark$doc_id
> ref_tokens <- tokens(ref_text, what = "character",
+ remove_punct = TRUE, remove_symbols = TRUE,
+ remove_numbers = TRUE)
> ref_dfm <- dfm_match(dfm(ref_tokens),
+ features = featnames(train_dfm))
> dim(ref_dfm); sum(ntoken(ref_dfm) == 0)
[1] 1968 603
[1] 17No. They contain none of the 603 retained characters (e.g. only rare characters, English, numbers or emoji). Data/README says zero-feature reference comments remain in the evaluation; NB can only judge them by the prior — and the prior leans towards HateSpeech (.594). The local export confirms it: all 17 have P(HateSpeech) = 0.5944 and are all predicted HateSpeech, while only 1 of them has the reference label HateSpeech (supplement; you can verify by ticking "zero-feature only" in the lab below).
C08b: evaluate the independent human reference
# C08b: Evaluate the separate human references ref_task <- as_task_classif(benchmark["label"], target = "label", positive = "HateSpeech") benchmark$prediction <- predict(nb, newdata = ref_dfm) ref_check <- PredictionClassif$new(task = ref_task, row_ids = ref_task$row_ids, response = as.character(benchmark$prediction)) benchmark_scores <- ref_check$score(measures) nrow(benchmark); round(benchmark_scores, 3)
> ref_task <- as_task_classif(benchmark["label"],
+ target = "label", positive = "HateSpeech")
> benchmark$prediction <- predict(nb, newdata = ref_dfm)
> ref_check <- PredictionClassif$new(task = ref_task,
+ row_ids = ref_task$row_ids,
+ response = as.character(benchmark$prediction))
> benchmark_scores <- ref_check$score(measures)
> nrow(benchmark); round(benchmark_scores, 3)
[1] 1968
classif.acc classif.precision classif.recall classif.fbeta
0.514 0.165 0.880 0.278 Comparing the two evaluation samples
| Check | Internal test set | Human reference set |
|---|---|---|
| Comments | 800 | 1,968 |
| HateSpeech share (supplementary calculation) | 476 / 800 = 59.5% | 209 / 1,968 = 10.6% |
| HateSpeech precision | .726 | .165 |
| HateSpeech recall | .779 | .880 |
| HateSpeech F1 | .752 | .278 |
Discussion (slide 62): what kind of error do recall .880 and precision .165 indicate? — Of the 209 true hate comments, 184 are caught, but the model labels 1,115 comments as hate in total, of which 931 are false positives: only about 1 in 6 is really hate (confusion matrix computed from the local output; see the lab below).
Why? A base-rate experiment
Precision depends not only on the model but also on how many positives the sample contains. Fix the model's recall (TPR) and false-positive rate (FPR), change only the positive-class share, and watch precision change. The two presets are computed from the local confusion matrices.
Static note: precision = TPR·π / (TPR·π + FPR·(1−π)), where π is the positive-class share. Internal test π = .595; reference set π = .106. When π drops from six in ten to one in ten, even with an unchanged FPR the same false-positive rate produces far more FP than TP: applying the internal test's TPR .779 and FPR .432 to π = .106 leaves precision at only about .176. The actual FPR on the reference set is .529 (the model misjudges comments from a different source more often), pushing precision further down to .165. So most of the gap can be explained by the base rate — this is a supplementary interpretation; the slides only state the result.
Reference-set confusion matrix and comment browser
The "coders" value next to each comment is the raw values of the three original annotators (e.g. 000), shown only as metadata.
Self-check
label come from?G01–G02b: English word features and the mlr3 data table
The second case switches to English, to SVM, and to mlr3's full task/learner interface. The preprocessing logic is the same as for hate speech: split first, choose the vocabulary from training rows only, align the test rows.
Source and lab columns
Source gscore_julia_park.csv → the lab uses grandstanding_practice.csv:
speechbecomestext: English hearing excerpts.rescaled_gsbecomeslabel: a ready-made binary class (0 = NonGrandstanding, 1 = Grandstanding).sentimentit_scorestays outside the predictors.
G01: read the data and hold out test excerpts
# G01a: Load the Park (2021) data
grandstanding <- read.csv(file.path(data_dir,
"grandstanding_practice.csv"), stringsAsFactors = FALSE)
grandstanding$label <- factor(grandstanding$label,
levels = c("NonGrandstanding", "Grandstanding"))
table(grandstanding$label)> grandstanding <- read.csv(file.path(data_dir,
+ "grandstanding_practice.csv"), stringsAsFactors = FALSE)
> grandstanding$label <- factor(grandstanding$label,
+ levels = c("NonGrandstanding", "Grandstanding"))
> table(grandstanding$label)
NonGrandstanding Grandstanding
1846 1653 # G01b: Reserve test excerpts with mlr3
gs_task <- as_task_classif(grandstanding["label"],
target = "label", positive = "Grandstanding")
gs_task$col_roles$stratum <- "label"
set.seed(7192)
gs_split <- partition(gs_task, ratio = .8)
gs_parts <- list(train = grandstanding[gs_split$train, ],
test = grandstanding[gs_split$test, ])
table(gs_parts$train$label)
table(gs_parts$test$label)> gs_task <- as_task_classif(grandstanding["label"],
+ target = "label", positive = "Grandstanding")
> gs_task$col_roles$stratum <- "label"
> set.seed(7192)
> gs_split <- partition(gs_task, ratio = .8)
> gs_parts <- list(train = grandstanding[gs_split$train, ],
+ test = grandstanding[gs_split$test, ])
> table(gs_parts$train$label)
NonGrandstanding Grandstanding
1477 1322
> table(gs_parts$test$label)
NonGrandstanding Grandstanding
369 331 NonGrandstanding is the larger class (1,846 vs. 1,653). How does stratification keep both classes? stratum = "label" makes partition split about 80/20 within each class: the test set has 369 + 331, a ratio (52.7% / 47.3%) almost identical to the full data (52.8% / 47.2%) (supplementary calculation).
G02a: corpus, tokens, DFM, trimming and alignment
# G02a_1: Build an English corpus and tokens gs_corpus <- corpus(grandstanding, text_field = "text", docid_field = "doc_id") gs_tokens <- tokens(gs_corpus, remove_punct = TRUE, remove_symbols = TRUE, remove_numbers = TRUE, remove_url = TRUE) ndoc(gs_corpus)
> gs_corpus <- corpus(grandstanding, + text_field = "text", docid_field = "doc_id") > gs_tokens <- tokens(gs_corpus, remove_punct = TRUE, + remove_symbols = TRUE, remove_numbers = TRUE, + remove_url = TRUE) > ndoc(gs_corpus) [1] 3499
# G02a_2: Normalize English tokens and build a DFM
gs_tokens <- tokens_tolower(gs_tokens)
gs_tokens <- tokens_remove(gs_tokens,
pattern = stopwords("en"))
gs_dfm <- dfm(gs_tokens)
dim(gs_dfm)> gs_tokens <- tokens_tolower(gs_tokens)
> gs_tokens <- tokens_remove(gs_tokens,
+ pattern = stopwords("en"))
> gs_dfm <- dfm(gs_tokens)
> dim(gs_dfm)
[1] 3499 14123# G02a_3: Select training words and match test columns gs_train_dfm <- dfm_trim(gs_dfm[gs_split$train, ], min_docfreq = .01, docfreq_type = "prop") gs_test_dfm <- dfm_match(gs_dfm[gs_split$test, ], features = featnames(gs_train_dfm)) dim(gs_train_dfm); dim(gs_test_dfm)
> gs_train_dfm <- dfm_trim(gs_dfm[gs_split$train, ], + min_docfreq = .01, docfreq_type = "prop") > gs_test_dfm <- dfm_match(gs_dfm[gs_split$test, ], + features = featnames(gs_train_dfm)) > dim(gs_train_dfm); dim(gs_test_dfm) [1] 2799 629 [1] 700 629
| Function | What it does here |
|---|---|
corpus(text_field = "text", docid_field = "doc_id") | Reads text and document IDs from the data frame (discussion question: the text column supplies the text, the doc_id column supplies the IDs) |
tokens(remove_punct, remove_symbols, remove_numbers, remove_url) | Splits into words and removes the specified types |
tokens_tolower() | Merges upper and lower case |
tokens_remove(stopwords("en")) | Removes the English stopword list |
dfm_trim() / dfm_match() | Chooses words by training document frequency; gives test documents the same columns |
English has spaces, so one feature is one word, and the vocabulary is much larger (3,499 × 14,123, versus 4,000 × 2,916 characters for Chinese); stopwords are removed (not done for Chinese). After trimming the two sizes are actually close (629 vs. 603), because both use the same 1% document-frequency threshold. Both matrices have 629 columns because the test matrix is aligned to the training vocabulary with dfm_match(), rather than choosing its own words.
English tokenization lab
Type an English sentence. Strikethrough = stopword (stopwords("en"), 175 in the local export); green box = among the 629 training words; grey box = not in the vocabulary. The browser tokenizes with simplified rules (lower case, remove punctuation and numbers), not exactly the same as quanteda's tokenizer.
Note that "not" and "I" are both stopwords: "I have not signed" leaves only signed. Negation and the first person are discarded, which may be a loss for a concept like grandstanding that centres on self-presentation (supplement).
G02b: convert the DFM into a data table for mlr3
# G02b_1: Convert text counts to feature tables gs_train_data <- convert(gs_train_dfm, to = "data.frame") gs_test_data <- convert(gs_test_dfm, to = "data.frame") gs_train_data$doc_id <- NULL; gs_test_data$doc_id <- NULL dim(gs_train_data); dim(gs_test_data)
> gs_train_data <- convert(gs_train_dfm, to = "data.frame") > gs_test_data <- convert(gs_test_dfm, to = "data.frame") > gs_train_data$doc_id <- NULL; gs_test_data$doc_id <- NULL > dim(gs_train_data); dim(gs_test_data) [1] 2799 629 [1] 700 629
# G02b_2: Name feature columns and add labels
names(gs_train_data) <- make.names(featnames(gs_train_dfm),
unique = TRUE)
names(gs_test_data) <- names(gs_train_data)
gs_train_data$label <- gs_parts$train$label
gs_test_data$label <- factor(gs_parts$test$label,
levels = c("Grandstanding", "NonGrandstanding"))
dim(gs_train_data); dim(gs_test_data)> names(gs_train_data) <- make.names(featnames(gs_train_dfm),
+ unique = TRUE)
> names(gs_test_data) <- names(gs_train_data)
> gs_train_data$label <- gs_parts$train$label
> gs_test_data$label <- factor(gs_parts$test$label,
+ levels = c("Grandstanding", "NonGrandstanding"))
> dim(gs_train_data); dim(gs_test_data)
[1] 2799 630
[1] 700 630quanteda::convert(to = "data.frame")turns the small sparse DFM into a dense data frame;doc_id <- NULLremoves the identifier, leaving 629 numeric feature columns.- Why can't the ID be a predictor? The ID is unrelated to the text content but may correlate with data order or source batch, letting the model learn "who is who" instead of "what was said"; it is also meaningless for new texts.
make.names(unique = TRUE)produces valid, unique column names (e.g. for words starting with a digit or clashing with R reserved words).- 630 columns = 629 text features + 1 label column. The target column
labelis not a predictor.
Converting 629 words into a dense data frame is fine in this example; as text matrices grow larger, look for learners or backends that support sparse features.
Self-check
dim(gs_dfm)?gs_test_dfm also have 629 columns?G02c–G03: define the task, train the SVM, evaluate and read the errors
mlr3 separates "data and roles" (task) from "algorithm and settings" (learner). lrn() is only a specification; $train() is what learns. Finally we return to the original text: one correctly classified excerpt and one misclassified.
G02c_1: define the classification task
# G02c_1: Define the grandstanding task gs_model_task <- as_task_classif(gs_train_data, target = "label", positive = "Grandstanding") gs_model_task$target_names length(gs_model_task$feature_names)
> gs_model_task <- as_task_classif(gs_train_data, + target = "label", positive = "Grandstanding") > gs_model_task$target_names [1] "label" > length(gs_model_task$feature_names) [1] 629
as_task_classif() describes the training data, the target column and the positive class; TaskClassif stores data and roles — creating a task does not train a model. The target column label is not in feature_names because it is what we want to predict.
G02c_2: specify a linear SVM learner
# G02c_2: Configure the linear SVM learner
library(mlr3learners)
gs_learner <- lrn("classif.svm", type = "C-classification",
kernel = "linear", cost = 1, scale = FALSE,
predict_type = "prob")
gs_learner$id
gs_learner$predict_type> library(mlr3learners)
> gs_learner <- lrn("classif.svm", type = "C-classification",
+ kernel = "linear", cost = 1, scale = FALSE,
+ predict_type = "prob")
> gs_learner$id
[1] "classif.svm"
> gs_learner$predict_type
[1] "prob"Discussion: has lrn() already learned anything from the training rows? — No. It is just "an unfitted learner and its settings".
G02c_3: train and predict the held-out texts
# G02c_3: Train the learner and predict held-out texts set.seed(7193) gs_learner$train(gs_model_task) gs_result <- gs_learner$predict_newdata(gs_test_data) gs_prediction <- gs_result$response length(gs_prediction) colnames(gs_result$prob)
> set.seed(7193) > gs_learner$train(gs_model_task) > gs_result <- gs_learner$predict_newdata(gs_test_data) > gs_prediction <- gs_result$response > length(gs_prediction) [1] 700 > colnames(gs_result$prob) [1] "Grandstanding" "NonGrandstanding"
gs_learner stores the fitted learner ($model); gs_result is a PredictionClassif of 700 test predictions; read classes with $response and the probability matrix with $prob.
G02d: evaluate the mlr3 predictions
# G02d: Evaluate the mlr3 predictions gs_result$confusion gs_scores <- gs_result$score(measures) round(gs_scores, 3)
> gs_result$confusion
truth
response Grandstanding NonGrandstanding
Grandstanding 176 74
NonGrandstanding 155 295
> gs_scores <- gs_result$score(measures)
> round(gs_scores, 3)
classif.acc classif.precision classif.recall classif.fbeta
0.673 0.704 0.532 0.606 The 74 with response = Grandstanding and truth = NonGrandstanding are FP; the 155 with response = NonGrandstanding and truth = Grandstanding are FN. FN far outnumber FP, so recall is only .532: the SVM is rather "conservative" and misses nearly half of the grandstanding. Note that the column order here is the same as in hate-speech C06: the positive class comes first.
Confusion-matrix lab: SVM test set
Threshold 0.5 reproduces slide 86. Lower the threshold to see recall recover and precision fall (supplement). Click a cell to read its excerpts.
Which words did the linear SVM learn?
The linear SVM weight is w = Σ αi yi xi (t(model$coefs) %*% model$SV). Positive values push towards Grandstanding, negative values towards NonGrandstanding. A weight is a contribution "holding other words constant", not the meaning of the word itself (supplement).
G03: predict one real excerpt
# G03: Inspect one grandstanding prediction
j <- match("gs_01045", gs_parts$test$doc_id)
cat(gs_parts$test$text[j], "\n")
gs_result$response[j]
round(gs_result$prob[j, ], 3)
gs_result$truth[j]> j <- match("gs_01045", gs_parts$test$doc_id)
> cat(gs_parts$test$text[j], "\n")
Also I have not signed the no tax pledge. I am not intimidated by anybody. I am going to do whatever I have to do. I do not like to raise taxes. I do not want to raise taxes. I want to see how we can cut first. But, I also want to deal with the entitlements. The Simpson Bowles Commission is sort of a grand compromise. A grand compromise that not everyone really feels totally comfortable with. But you know that they are kind of moving in the right direction. So we really are going to have to get it out of this administration to participate with us.
> gs_result$response[j]
[1] Grandstanding
Levels: Grandstanding NonGrandstanding
> round(gs_result$prob[j, ], 3)
Grandstanding NonGrandstanding
0.637 0.363
> gs_result$truth[j]
[1] Grandstanding
Levels: Grandstanding NonGrandstanding“Also I have not signed the no tax pledge. I am not intimidated by anybody. I am going to do whatever I have to do. I do not like to raise taxes. I do not want to raise taxes. I want to see how we can cut first. But, I also want to deal with the entitlements. The Simpson Bowles Commission is sort of a grand compromise. A grand compromise that not everyone really feels totally comfortable with. But you know that they are kind of moving in the right direction. So we really are going to have to get it out of this administration to participate with us.”
Prediction / reference: Grandstanding; SVM probability .637; original score 2.003. Lab solution: "I am not intimidated by anybody" and "I am going to do whatever I have to do" emphasize personal resolve, and the statements on taxes are public political position-taking — this can be discussed as self-promotion and position-taking; but the model probability cannot prove that the classification is substantively correct, and the original score was kept out of the predictors throughout.
Reading performance: a false positive
# Run after W6_classification.R in the same R session. # Read one grandstanding prediction error error_rows <- which(gs_result$response != gs_result$truth) k <- error_rows[1] data.frame( doc_id = gs_parts$test$doc_id[k], reference = gs_result$truth[k], prediction = gs_result$response[k], prob = round(gs_result$prob[k, "Grandstanding"], 3), row.names = NULL) cat(gs_parts$test$text[k], "\n")
> error_rows <- which(gs_result$response != gs_result$truth)
> k <- error_rows[1]
> data.frame(
+ doc_id = gs_parts$test$doc_id[k],
+ reference = gs_result$truth[k],
+ prediction = gs_result$response[k],
+ prob = round(gs_result$prob[k, "Grandstanding"], 3),
+ row.names = NULL)
doc_id reference prediction prob
1 gs_00013 NonGrandstanding Grandstanding 0.609
> cat(gs_parts$test$text[k], "\n")
I know that Ms. Pingree mentioned the Coastal Climate Resilience Fund. So the district I represent includes a whole bunch of rural communities that lie in the tsunami zone. Coastal communities like Westport and Ocean Shores are seeing much more severe storm events and flooding and there are four coastal tribes in the district that I represent that are in the process of trying to move to higher ground. I was hoping you could provide a roadmap for what this program is going to look like if it is funded, and how the program is going to address the specific needs of the communities I represent and … [truncated; full output in tad/labs/W6/run_output.txt]This is a false positive, which lowers precision. The speaker repeatedly mentions "the district I represent" and asks how a programme will respond to local needs. We can read these phrases as self-promotion, or read the whole passage as a question requesting policy information. Discussion: does describing constituency needs count as self-promotion? What context is missing (the hearing topic, surrounding statements, who the witness is)? The lab solution stresses: this disagreement gives us a case to read closely; it does not by itself establish whether the model or the reference label is right.
Lab Section 4: reading a hate-speech error in the same way
# Lab section 4 (Lab_Session_W6.R): Repeat with the hate-speech model hate_errors <- which(nb_prediction != parts$test$label) cat(parts$test$text[hate_errors[1]], "\n")
> hate_errors <- which(nb_prediction != parts$test$label) > cat(parts$test$text[hate_errors[1]], "\n") 這隻河童來台灣亂更恐怖。
This is hs_00453: reference NonHateSpeech, NB's P(HateSpeech) = 0.791, predicted HateSpeech — a false positive (confirmed from the locally exported predictions; the lab solution only prints the full text). Think with Wang, Day & Wu's definition: who is the target? Which attribute is attacked? What context is needed to judge? Press "First NB error" in the Chapter 07 scorer to see its character evidence.
Error reader: pick one to read yourself
Highlighting: orange = weight pushes towards Grandstanding, blue = pushes towards NonGrandstanding; only words in the 629-word vocabulary are marked; colour intensity follows the weight's size.
Comparing the two cases
| Hate-speech NB (internal test) | Grandstanding SVM | |
|---|---|---|
| accuracy | .694 | .673 |
| precision | .726 | .704 |
| recall | .779 | .532 |
| F1 | .752 | .606 |
Which case has higher precision, which has higher recall? We used different labels, languages and class frequencies, so the scores alone cannot tell us whether the difference is due to the algorithm. To compare algorithms, compare at least on the same data, the same split and the same features — which is exactly what the optional exercise in Chapter 11 does.
Self-check
gs_learner <- lrn("classif.svm", ...), what has the model learned?Extensions: other classifiers on the same features, LLM coding, and the after-class checklist
The optional script optional_classifiers.R keeps the hate-speech split and the 603-character vocabulary and swaps in logistic regression and an mlr3 SVM. The instructor's lab solution does not include output for these two parts; these notes ran them once locally.
Optional: reuse the features, change the classifier
| Model | Package interface | Prediction |
|---|---|---|
| Logistic regression | quanteda.textmodels textmodel_lr() | predict() |
| Linear SVM | mlr3 lrn("classif.svm", kernel = "linear") | $train() then $predict() |
Keep the same training split and vocabulary. textmodel_lr() chooses the penalty by cross-validation within the training data (lab handout).
# Optional models; run W6_classification.R first.
set.seed(7193)
lr <- textmodel_lr(train_dfm, y = train_label)
lr_prediction <- predict(lr, newdata = test_dfm)
lr_check <- PredictionClassif$new(task = hs_task,
row_ids = hs_split$test, truth = hs_task$truth(hs_split$test),
response = as.character(lr_prediction))
lr_check$score(measures)
# install.packages(c("mlr3learners", "e1071"))
library(mlr3learners)
svm_data <- rbind(convert(train_dfm, to = "data.frame"),
convert(test_dfm, to = "data.frame"))
svm_data$doc_id <- NULL
names(svm_data) <- make.names(names(svm_data), unique = TRUE)
svm_data$label <- factor(c(as.character(parts$train$label),
as.character(parts$test$label)))
svm_task <- as_task_classif(svm_data, target = "label",
positive = "HateSpeech")
svm_train <- seq_len(nrow(parts$train))
svm_test <- seq.int(nrow(parts$train) + 1L, nrow(svm_data))
svm <- lrn("classif.svm", type = "C-classification",
kernel = "linear", cost = 1, scale = FALSE)
svm$train(svm_task, row_ids = svm_train)
svm_result <- svm$predict(svm_task, row_ids = svm_test)
svm_result$score(measures)> set.seed(7193)
> lr <- textmodel_lr(train_dfm, y = train_label)
Warning in .resolve_control(control = control, nvars = nvars, deprecated = list(thresh = if (!missing(thresh)) thresh, :
Passing 'maxit' to glmnet() is deprecated. Use control = list(maxit = ...) instead.
> lr_prediction <- predict(lr, newdata = test_dfm)
> lr_check <- PredictionClassif$new(task = hs_task,
+ row_ids = hs_split$test, truth = hs_task$truth(hs_split$test),
+ response = as.character(lr_prediction))
> lr_check$score(measures)
classif.acc classif.precision classif.recall classif.fbeta
0.7375000 0.7955556 0.7521008 0.7732181
> library(mlr3learners)
> svm_data <- rbind(convert(train_dfm, to = "data.frame"),
+ convert(test_dfm, to = "data.frame"))
> svm_data$doc_id <- NULL
> names(svm_data) <- make.names(names(svm_data), unique = TRUE)
> svm_data$label <- factor(c(as.character(parts$train$label),
+ as.character(parts$test$label)))
> svm_task <- as_task_classif(svm_data, target = "label",
+ positive = "HateSpeech")
> svm_train <- seq_len(nrow(parts$train))
> svm_test <- seq.int(nrow(parts$train) + 1L, nrow(svm_data))
> svm <- lrn("classif.svm", type = "C-classification",
+ kernel = "linear", cost = 1, scale = FALSE)
> svm$train(svm_task, row_ids = svm_train)
> svm_result <- svm$predict(svm_task, row_ids = svm_test)
> svm_result$score(measures)
classif.acc classif.precision classif.recall classif.fbeta
0.7212500 0.7651992 0.7668067 0.7660021
optional runtime (s): 4 Local results: same split, same 603 characters
| Model (hate-speech internal test, 800 comments) | accuracy | precision | recall | F1 | Source |
|---|---|---|---|---|---|
| Multinomial NB (C06) | .694 | .726 | .779 | .752 | Slide 54; identical locally |
Logistic regression (textmodel_lr) | 0.738 | 0.796 | 0.752 | 0.773 | Run locally (no numbers in slides/solution) |
Linear SVM (mlr3 classif.svm) | 0.721 | 0.765 | 0.767 | 0.766 | Run locally (no numbers in slides/solution) |
In this local run, logistic regression beats NB on all four measures (e.g. F1 .773 vs. .752), and the linear SVM falls in between. Because the three models are compared on the same data, the same 800 test comments and the same features, the differences can more plausibly be attributed to the algorithms. But all of them only look at single-character counts, so they all face the same problem as in Chapter 08: how they perform on the independent reference set is not checked here. These numbers come from one local run; the cross-validation in textmodel_lr() is random, so small differences may appear on other platforms; neither the slides nor the lab solution provide numbers for comparison.
Later weeks: LLM coding and classification
- Classification: prompts and codebooks can guide category labels.
- AJPS example: Benoit et al. (2026) use LLMs to produce summaries and policy-position scores.
- Later LLM week: methods and validation.
Connection (supplement): the role of the codebook does not disappear with LLMs — a prompt is a codebook written for the model; this week's principles of "labels before algorithms" and "validate with independent evidence" apply just the same.
Answer area: two paragraphs on reading errors
Suggested reasoning (based on the lab solution and slides)
1. FP (predicted Grandstanding, reference NonGrandstanding); it lowers precision.
2. Two readings are possible: self-promotion, or a question requesting policy information; you need the hearing topic, who is being asked, and the surrounding context. The disagreement itself does not prove who is right.
3. Open question; judge by Wang, Day & Wu's definition (abuse targeting attributes of individuals or groups, excluding satire and humour, distinguishing offence from hate).
4. Hate-speech NB: precision .726, recall .779; grandstanding SVM: precision .704, recall .532. The two cases differ in labels, language and class proportions, so the score differences cannot be attributed to the algorithm (lab handout, Section 4).
R run checklist (class + lab)
Run in order in the same R session. Ticks are saved in this browser.
Static list: C01, C02, C03, C04a_1, C04a_2, C04b_1, C04b_2, C05, C06, C07, C08a, C08b, G01a, G01b, G02a_1, G02a_2, G02a_3, G02b_1, G02b_2, G02c_1, G02c_2, G02c_3, G02d, G03 (24 checkpoints) + error_reading.R + Lab §4 hate-speech error.
Self-check
convert() into a dense data frame. What does the lab handout warn about this?Reading guide: six research cases and the textbook
Each card summarizes "research question, data, where the labels come from, validation, and the connection to this week".
The W6 folder of the course repo contains no full-text PDF of any of the studies (only screenshots of book covers, first pages and figures in the slides, W6/assets/cases/). The cards below are therefore based only on the slides, and page numbers refer to slide pages; original source pages noted on the slides (e.g. Gillion Appendix A, pp. 163–166) are transcribed from the slides and have not been checked against the originals in these notes. For in-depth reading, the full texts can be obtained from the publishers through the NTU Library or the university VPN. The lab handout also provides public links to the Park (2021) author manuscript (Essex repository) and to Wang, Day & Wu (2022); these notes did not download or check them.
Wang, Day & Wu (2022). Political Hate Speech Detection and Lexicon Building: A Study in Taiwan. IEEE Access 10: 44337–44346.
merged-hate-speeches.csv (31,071 rows; 17,548 positive, 13,523 negative) and two human validation sheets of 1,000 comments each (BERT/Lexicon).Sources: slides 4, 32, 58, 96; W6/classroom/Data/README.md. Full text not in the repo.
Gillion (2016). Governing with Words: The Political Dialogue on Race, Public Policy, and Inequality in America. Cambridge UP.
Cited on the slides: Appendix A, pp. 163–166; Appendix B; textbook §17.1.
Benoit, Conway, Lauderdale, Laver & Mikhaylov (2016). Crowd-sourced Text Analysis: Reproducible and Agile Production of Political Data. APSR 110(2): 278–295.
Slides 8–11 (including screenshots of the first page, Figure 1, Table 4 and Figure 7).
Boydstun (2013). Making the News: Politics, the Media, and Agenda Setting. U. of Chicago Press.
Cited on the slides: §18.2.7; book supplements.
Nielsen (2017). Deadly Clerics: Blocked Ambition and the Paths to Jihad. Cambridge UP. (and Nielsen's 2013 dissertation, 2014 working paper; English & Nielsen 2024)
Slide 16 notes that the 2014 working paper and the 2017 book are separate sources.
Park (2021). When Do Politicians Grandstand? Measuring Message Politics in Committee Hearings. Journal of Politics 83(1): 214–228.
rescaled_gs is not documented, and the CSV has no individual coder votes.Slides 19–21; Data/README (replication: doi:10.7910/DVN/GSMBFX).
Grimmer, Roberts & Stewart (2022). Text as Data, Part IV (Chapters 17–20)
| Chapter | Read first | Teaching link |
|---|---|---|
| 17 An Overview of Supervised Classification | 17.2–17.5 | Connects the research steps |
| 18 Coding a Training Set | Core 18.1–18.2 | Codebooks and human labels |
| 19 Classifying Documents with Supervised Learning | Model details 19.1–19.2 | NB and learned classifiers |
| 20 Checking Performance | Core 20.1 | Validation and prediction errors |
Further: §19.2.3 aggregate-level measurement; §20.2 indirect validation; Chapter 15 as optional measurement background.
Comparing cases: where do the labels come from?
For each row, choose the study that fits best.
Common pitfalls and glossary
Ten common pitfalls
The vocabulary choice peeks at the test set. Correct: partition() first, dfm_trim() on training rows only, dfm_match() for test rows.
With a different column order, the model parameters are applied to the wrong characters. Check identical(featnames(train_dfm), featnames(test_dfm)).
doc_id, key, sentimentit_score, original model predictions and coder values must not be used as predictors.
mlr3's $confusion: rows = response (prediction), columns = truth.
The majority-class baseline (59.5% for hate speech) is already not low; look at precision and recall together.
0.999 is the model probability for one comment.
The independent reference set has a different positive-class share and distribution; precision drops from .726 to .165.
Gillion's 97% is agreement; rules may consistently miss implicit appeals.
The cut-point of rescaled_gs is undocumented; keep the existing classes and do not re-dichotomize yourself.
A fresh evaluation sample is needed (lab handout, Section 4).
Glossary
Final review, research design and references
Final review quiz
Classification research-design planner
Apply the four design choices on slide 22 and the four steps on slides 23–26 to your own topic (useful for the methods section of the Week 7 research proposal). Markdown is generated automatically.
Learning progress
References
Practice data
- Wang, Chih-Chien, Min-Yuh Day, and Chun-Lian Wu. 2022. “Political Hate Speech Detection and Lexicon Building: A Study in Taiwan.” IEEE Access 10: 44337–44346. doi:10.1109/ACCESS.2022.3160712
- Park, Ju Yeon. 2021. “When Do Politicians Grandstand? Measuring Message Politics in Committee Hearings.” The Journal of Politics 83(1): 214–228. doi:10.1086/709147; replication doi:10.7910/DVN/GSMBFX
Empirical studies
- Gillion, Daniel Q. 2016. Governing with Words: The Political Dialogue on Race, Public Policy, and Inequality in America. Cambridge University Press. Appendix A.
- Boydstun, Amber E. 2013. Making the News: Politics, the Media, and Agenda Setting. University of Chicago Press.
- Nielsen, Richard A. 2017. Deadly Clerics: Blocked Ambition and the Paths to Jihad. Cambridge University Press. Methods supplement: Nielsen (2014); English & Nielsen (2024).
- Benoit, Kenneth, Drew Conway, Benjamin E. Lauderdale, Michael Laver, and Slava Mikhaylov. 2016. “Crowd-sourced Text Analysis: Reproducible and Agile Production of Political Data.” APSR 110(2): 278–295.
- Benoit, Kenneth, Scott De Marchi, Conor Laver, Michael Laver, and Jinshuai Ma. 2026. “Using large language models to analyze political texts through natural language understanding.” AJPS 70(4): 1589–1605.
Textbook and software
- Grimmer, J., M. E. Roberts, and B. M. Stewart. 2022. Text as Data: A New Framework for Machine Learning and the Social Sciences. Princeton University Press. Chapters 17–20, with Chapter 15 as background.
- quanteda (text features); quanteda.textmodels (
textmodel_nb(), optionaltextmodel_lr()); mlr3classif.svm(mlr3learners, e1071); stringi.