⌂ Course index
🐞 Feedback
中文
The interactive features failed to initialise, so the page has switched to a static version with all chapters expanded in order; just scroll down to read. (The interactive labs, quiz grading, progress tracking and the slide panel need JavaScript; if you cannot see the interactive parts in an in-app preview, use "Share → Open in Safari" or open the file in a desktop browser.)
00 · Week overview

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

Slide 2 puts W4 and W6 side by side. The four rows are the same tasks, done differently:

TaskW4: dictionaryW6: classification
Build a measureSelect words and rulesLearn from labelled comments
Use human evidenceValidate dictionary outputTrain and evaluate the classifier
Develop the methodRead KWIC, revise rulesFit an ML algorithm and predict new texts
Evaluate resultsRead errors and sensitivityHeld-out test set + human benchmark
In plain words (supplement)

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 Slides 2, 94

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:

  1. 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".
  2. 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.
  3. 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.
  4. 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 Slides 23–26, 31

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. Slides 23–26

Six research cases Slide 3

StudyVenueTeaching link this weekChapter in these notes
Wang, Day & Wu (2022)IEEE AccessHate speech: Chinese character counts06–08
Gillion (2016)Governing with WordsCoding rules and agreement02
Benoit et al. (2016)APSRCrowd coding and reproducibility02
Boydstun (2013)Making the NewsCodebooks and rare categories03
Nielsen (2017)Deadly ClericsFound labels and validation03
Park (2021)JOPGrandstanding: mlr3 linear SVM04, 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". Slide 3

Two practice datasets Slides 32, 34

Hate speech (Wang, Day & Wu 2022)Grandstanding (Park 2021)
One row =One Chinese comment on political newsOne English excerpt of congressional hearing speech
RowsOriginal 31,071 → 4,000 for practiceOriginal 3,500 → 3,499 after de-duplication
Text → targettext → hate_speech (0/1)speech → rescaled_gs (0/1)
Positive classHateSpeechGrandstanding
FeaturesChinese character countsEnglish word counts
Classifier / interfaceMultinomial NB / quanteda.textmodelsLinear SVM / mlr3 + mlr3learners
Unused columnslabel (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(). Slide 32

Data-cleaning numbers (Data/README.md and practice_manifest.json)
  • 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.R locally (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 Slide 94

Slide 94

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

1. What is the main difference between W6 and W4?
Slide 2: "Select words and rules" vs. "Learn from labelled comments". Human judgement is still central; it just moves from writing rules to assigning labels. Slide 2
2. Which of the following is different between this week's hate-speech and grandstanding exercises?
Slide 34: Chinese character counts vs. English word counts; the classifiers also differ (NB vs. linear SVM). Slide 34
3. What is the role of sentimentit_score in the grandstanding exercise?
Slides 32, 64: the score field is not used; Data/README also says it is the original grandstanding score, not a general sentiment measure. Slides 32, 64
01 · From scratch

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 Slide 23

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_gs category in the Park (2021) data.

Step 2: Split the labelled documents Slide 24

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.

Why split "first"? (supplement)

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 Slide 25

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 Slide 26

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 Slide 35

Labels come before the algorithm. First read the coding definition and confirm what one row represents; keep the supplied labels rather than inventing a new cut-point; when checking errors, read disputed and uncertain texts closely.

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. Slide 35

The intuition behind Naive Bayes Slide 36

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.

🧮Toy NB calculatorSupplement (not from the lecture) · 6 fictional training texts

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.

New comment:(empty)
(0.1–2; class uses 1)
P(H | comment)
–
Prediction
–
Click a few words first.

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

1. Which order meets the requirement on slide 24?
Split the labelled documents before vocabulary selection or model fitting. Slide 24
2. In the toy NB, if you set smooth close to 0 and then enter a word that never appeared in one class, what happens?
Without smoothing P(word | class) = 0, and multiplying makes the whole class 0; smooth = 1 exists precisely to avoid this (supplementary explanation). Slide 52
3. When "using found labels", what does slide 23 ask you to check?
Check the source, coding unit, definition and score-to-category conversion. Slide 23
02 · Human coding I

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 Slide 5

  • 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 Slide 6

DesignGillion's approach (Appendix A, pp. 163–166)
Coding unitParagraph; written bills and procedural content excluded
Training labelsTwo assistants coded random samples: 300 paragraphs per presidential term and 1,000 per congressional session
RuleMust contain an explicit reference to race: racial groups, race-specific policies, minority figures or race-specific issues
BoundaryGeneral discussion of crime, education or health counts only when it carries such an explicit reference
AgreementReported intercoder reliability of 97%; disagreements adjudicated by Gillion
A reminder on reading numbers

The footnote on slide 6: the 97% concerns coders, not classifier accuracy.Slide 6

What does this measure miss? Slide 7

  • 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.
Reliability ≠ validity. Two coders can agree very consistently while both missing implicit appeals. The more explicit the rule, the higher the agreement usually is, but the narrower the concept it may cover.

Agreement calculator: why also look at κ?

🤝Agreement between two coders: percentage vs. Cohen's κSupplement (not from the lecture) · toy numbers

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.

B: yes
B: no
A: yes
A: no
Percent agreement
–
Expected chance agreement
–
Cohen's κ
–

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 Slides 8–10

  • Texts: sentences from party manifestos. Coding: repeated crowd judgments. Validation: comparison with experts. Slide 8
  • A simple coding scheme (Figure 1, p. 281): classify the topic first, then rate the position; keep the task simple. Slide 9
  • 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. Slide 10
What does "aggregate level" mean?

.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. Slide 10

The coal subsidy case: checking scores against votes Slide 11

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

1. What is the 97% reported by Gillion?
The 97% concerns coders, not classifier accuracy. Slide 6
2. Why might Gillion's rule miss expressions such as "inner city"?
The phrase alone is not enough to infer a racial appeal; the rule itself excludes it. Slide 7
3. Which conclusion does the .93 from Benoit et al.'s two waves of crowd coding support?
Party scores correlate .93; Scope: aggregate reproducibility. Slide 10
03 · Human coding II

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 Slide 12

  • 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 Slide 13

Codebook elementBoydstun's rule (original coding manual, pp. 1–5)
EvidenceHeadline and first three paragraphs
LabelOne primary topic + a short summary
ConsistencyAlign labels within the same storyline; clarify unclear cases
LessonDefine which evidence coders may use
Link to this week's exercise (supplement)

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 Slide 14

Selected rows from Boydstun (2013) Table A.1 (full corpus of 31,034 stories). Press the button to see the proportion bars:

📰Boydstun Table A.1 (excerpt)Original numbers from slide 14
Energy has only 299 stories (1.0%). In a random training sample of 300 stories you would expect only about 3 energy stories—a rare category gives the classifier almost nothing to learn from and also makes "percent agreement" look high (see scenario B of the calculator in chapter 02). (The second half of this sentence is a supplementary inference.)
TopicStoriesShare of all stories
International affairs and foreign aid6,35420.5%
Defense4,47914.4%
Health1,7995.8%
Energy2991.0%

Nielsen: from reference texts to scores Slides 15–16

  • Texts: Arabic writings by Islamic clerics. Measure: a language-based jihad score, used to study networks, careers and ideological differences. Slide 15
  • 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) Slide 16
Link to this week (supplement)

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 Slides 17–18

  • 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. Slide 17
Limits of external validation Slide 18

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".

Claim A: "A cleric's biography in Nielsen's data does not mention jihad, so he can be treated as a non-jihadist reference."
Silence cannot establish non-jihadist status. Slide 18
Claim B: "Nielsen's score is continuous; higher means the language is more like the jihadist reference texts."
Higher scores mean language more like the jihadist references; the measure is continuous. Slide 16
Claim C: "A high score means the author personally supports jihad."
The score measures "whether the language resembles the reference texts"; a text criticising jihadism may use the same vocabulary, so close reading of context and external evidence are needed. Slide 18

Self-check

1. What evidence does Boydstun's codebook allow coders to use?
Evidence: headline and first three paragraphs. Slide 13
2. What are Nielsen's supervision data?
765 jihadist-curated texts versus 1,951 sampled cleric texts, a mixed baseline. Slide 16
3. Which comments does slide 18 suggest we check especially in the hate-speech task?
Check comments that quote abuse in order to reject it. Slide 18
04 · Park and design choices

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 Slide 19

  • Texts: US House hearing speech. Study: crowd coding and grandstanding scores.
  • Our exercise: use the rescaled_gs labels in the Park (2021) data; mlr3 linear SVM.

Grandstanding: predicted scores Slide 20

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 Slide 21

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 Slide 22

Design choiceThe W6 question
Coding unitDoes one sentence contain enough evidence to judge our category?
Repeated judgementsWhich disagreements should trigger human review?
AggregationDo we need comment-level labels, hate-speech shares, or a continuous score?
ValidationWhat independent evidence can test our intended interpretation?
Slide 22: before adding more coders or models, first make sure the coding rules fit the research question.

Exercise: you are the coder (real data)

✍️Grandstanding coding exerciseReal data · 8 passages from the Park (2021) test set

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.

No answers yet.

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

1. Can the RMSE of 0.613 reported in Park (2021) be compared directly with our classroom F1?
The original study used a 300-paragraph held-out test and RMSE in original units; the classroom results are reanalyses (Data/README: classroom reanalyses). Slides 20, 99
2. What pattern does Park's Figure 3 show?
Pattern: minority party scores higher. Slide 21
3. What is the "aggregation" choice on slide 22 asking?
Do we need comment labels, hate-speech shares, or a continuous score? Slide 22
05 · R tools

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 Slide 27

We need toR tool
Turn text into featuresquanteda
Fit text classifiers directlyquanteda.textmodels
Organise models and evaluationmlr3
Chain preprocessing stepsmlr3pipelines
Search model settingsmlr3tuning

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. Slide 27

mlr3: a machine-learning framework for R Slide 28

  • 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.
The $ 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 Slide 29

Click a card to flip it. The front shows a need; the back shows the R (mlr3 ecosystem) and Python (scikit-learn ecosystem) equivalents.

NeedR: mlr3 ecosystemPython: scikit-learn
Model interfaceTask + learnerEstimator
Fit / predict$train() / $predict().fit() / .predict()
Text featuresquanteda counts / TF-IDFCountVectorizer / TfidfVectorizer
Preprocessing + modelmlr3pipelinesPipeline
Cross-validationresample()cross_validate()
Parameter searchmlr3tuningGridSearchCV

Same workflow: define the target, separate training and test data, evaluate predictions. Slide 29

Simple models in quanteda.textmodels Slides 30, 36

ModelFunctionThis week
Naive Bayestextmodel_nb()Main hate-speech model (C05)
Regularized logistic regressiontextmodel_lr()Optional (Chapter 11, run locally)
Linear SVMtextmodel_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 Slide 33

R · Slide 33
# 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")$id

Ready when: all six packages load and the last line returns "classif.svm". Slide 33

Local environment record

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

1. Which package fits this week's hate-speech NB?
For our NB exercise, we'll fit the model directly with quanteda.textmodels. Slide 27
2. Python's GridSearchCV corresponds to what in the mlr3 ecosystem?
Parameter search: mlr3tuning ↔ GridSearchCV. Slide 29
3. Why don't we use textmodel_svmlin() for grandstanding this week? What clue does the slide give?
Linear SVM: experimental, for two classes. This week we use classif.svm from mlr3 + mlr3learners instead (e1071 underneath). Slide 30
06 · Hate speech C01–C04

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 Slides 37–38

R · C01 (W6/classroom/W6_classification.R)
# 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"))
R console output (run locally: 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)
> 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"))
FunctionPurpose
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)
Discussion: what if it is FALSE? Slide 38

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 Slides 39–40

R · C02 (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> 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] 4000
Discussion: what do we get by always guessing the majority class? Slide 40

HateSpeech, 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 Slides 41–42

R · C03 (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> 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 
as_task_classif(hate["label"], target = "label", positive = "HateSpeech")
Only the label column goes into the task: this task is used only for splitting and evaluation, not for fitting. The positive class is explicitly set to HateSpeech.
hs_task$col_roles$stratum <- "label"
Stratify by label: each class is split about 80/20 separately.
set.seed(7192); partition(hs_task, ratio = .8)
Fixed seed; returns $train and $test row numbers.
parts <- list(train = hate[hs_split$train, ], test = ...)
Uses the row numbers to split the original data frame, used later when reading the text.

Discussion: why hold out the test rows before choosing the vocabulary? — See "data leakage" in Chapter 01. Slide 42

C04a: Chinese character tokenization and the DFM Slides 43–46

R · C04a_1 (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> 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"
R · C04a_2 (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> hs_tokens <- tokens_select(hs_tokens,
+   pattern = "^\\p{Han}$", valuetype = "regex")

> hs_dfm <- dfm(hs_tokens)

> dim(hs_dfm)
[1] 4000 2916
FunctionWhat 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
Discussion Slides 44, 46

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?

🔤Chinese-character feature viewerReal vocabulary · 603 training characters

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").

Han tokens kept
–
Tokens in the 603-character vocabulary
–
Non-Han characters removed
–

C04b: choose the vocabulary from training rows only, then align the test rows Slides 47–50

R · C04b_1 (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> 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
R · C04b_2 (W6/classroom/W6_classification.R)
# 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))
R console output (run locally: 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)
> 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
Discussion Slides 48, 50

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?

✂️dfm_trim(min_docfreq) thresholdReal data · document frequencies in training rows
Threshold (documents)
–
Features kept
–
Features seen in training rows
–

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

1. dim(hs_dfm) is 4000 × 2916, while dim(train_dfm) is 3200 × 603. Where did the missing 2,313 columns go?
dfm_trim(min_docfreq = .01, docfreq_type = "prop") looks only at training rows: every character with document frequency < 32 is removed. The local export shows that 2,774 of the 2,916 characters appear in training rows; the other 142 appear only in test rows (training document frequency 0) and are removed as well; non-Han characters were already removed in C04a_2. Slides 47–48
2. If C04b were changed to run dfm_trim() on all 4,000 comments before splitting, what would be the problem?
Choose the vocabulary using training texts only. Slides 24–25
3. What does identical(featnames(train_dfm), featnames(test_dfm)) being TRUE guarantee?
Match that order, drop extra features and fill missing ones with zero. Slides 49–50
07 · Hate speech C05–C07

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 Slides 51–52

R · C05 (W6/classroom/W6_classification.R)
# C05: Fit Naive Bayes
nb <- textmodel_nb(train_dfm, y = train_label,
  distribution = "multinomial", smooth = 1,
  prior = "docfreq")
class(nb)
nb$distribution
R console output (run locally: 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)
> 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"
ArgumentWhat we supply
xTraining feature counts (train_dfm)
yLabels in the same row order (train_label) — this is the answer to the discussion question
smooth = 1Smoothing 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 Slides 53–54

R · C06 (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> 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 
Discussion (2 minutes): which cells are false positives and false negatives? Slide 54

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

MeasureFormulaCalculation for C06In plain words
accuracy(TP+TN) / N(371+184)/800 = .694Share of all predictions that are correct
precisionTP / (TP+FP)371/511 = .726Among comments predicted as hate, the share that really are hate
recallTP / (TP+FN)371/476 = .779Among true hate comments, the share that are caught
F1 (classif.fbeta, β=1)2PR / (P+R)2(.726)(.779)/(.726+.779) = .752Harmonic 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

🎯NB test set (800 comments)Real data · P(HateSpeech) from the local run

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 Slides 55–57

R · C07 (W6/classroom/W6_classification.R)
# 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]
R console output (run locally: 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)
> 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
hs_26234 Slide 56

「垃圾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?

  • Levels lists the two possible classes. Slide 57
  • 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

🧪Multinomial NB evidence breakdownReal model parameters · 603 characters × 2 classes

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 「垃圾」).

Log prior ratio
–
Sum of character evidence
–
P(HateSpeech)
–
Overall: the characters NB "trusts" most (real parameters)
Most supportive of HateSpeech
Most supportive of NonHateSpeech

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

1. What is the "140" in the C06 confusion matrix?
Rows are predictions (response), columns are truth; the cell with response = HateSpeech and truth = NonHateSpeech is FP. Slide 54
2. Raising the threshold from 0.5 to 0.9 usually makes
The stricter the threshold, the fewer cases are called positive: FP decreases (precision ↑) and FN increases (recall ↓). You can verify this in the lab above (supplement).
3. How should the 0.999 for hs_26234 be read?
0.999 is a model probability, not overall accuracy. Slide 57
08 · Hate speech C08

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 Slide 58

  • Combined file: hate_speech_reference.csv combines two validation files of 1,000 comments each.
  • BERT / Lexicon: the original file names, recorded in the source column (15 comments appear in both, recorded as BERT+Lexicon).
  • Reference label: label comes 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 Slides 59–60

R · C08a (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> 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] 17
Discussion: do the 17 zero-feature rows mean empty comments? Slide 60

No. 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 Slides 61–62

R · C08b (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> 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 Slide 63

CheckInternal test setHuman reference set
Comments8001,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
Slide 63: Read precision and recall together. This simple NB produces many false positives on the separate sample, despite its high recall.

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

⚖️Same model, different positive-class sharesSupplement (not from the lecture) · starting from the real TPR/FPR

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.

precision
–
F1
–
Per 1,000 comments: TP / FP
–

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

🔎Human reference set (1,968 comments)Real data · model fixed

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

1. Where does the reference set's label come from?
Reference label: label comes from 是否仇恨, not the original model-prediction columns. Slide 58
2. What do recall .880 and precision .165 most directly mean?
This simple NB produces many false positives on the separate sample, despite its high recall. Slides 62–63
3. After seeing the poor reference-set performance, what is wrong with going back to change the model and then reporting scores on the same reference set?
Lab handout, Section 4: If we change a model after examining these test errors, we'll need a fresh evaluation sample.
09 · Grandstanding G01–G02b

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 Slide 64

Source gscore_julia_park.csv → the lab uses grandstanding_practice.csv:

  • speech becomes text: English hearing excerpts.
  • rescaled_gs becomes label: a ready-made binary class (0 = NonGrandstanding, 1 = Grandstanding).
  • sentimentit_score stays outside the predictors.

G01: read the data and hold out test excerpts Slides 65–68

R · G01a (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> 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 
R · G01b (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> 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 
Discussion Slides 66, 68

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 Slides 69–74

R · G02a_1 (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> 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
R · G02a_2 (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> 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
R · G02a_3 (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> 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
FunctionWhat 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
Discussion: how do English word features differ from Chinese character features? Slides 72, 74

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

🔡English word-feature viewerReal vocabulary of 629 words + quanteda English stopwords

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.

Word tokens
–
Stopwords removed
–
In the 629-word vocabulary
–

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 Slides 75–78

R · G02b_1 (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> 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
R · G02b_2 (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> 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 630
  • quanteda::convert(to = "data.frame") turns the small sparse DFM into a dense data frame; doc_id <- NULL removes the identifier, leaving 629 numeric feature columns. Slide 75
  • 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. Slide 76
  • make.names(unique = TRUE) produces valid, unique column names (e.g. for words starting with a digit or clashing with R reserved words). Slide 77
  • 630 columns = 629 text features + 1 label column. The target column label is not a predictor. Slide 78
The cost of a dense matrix (lab handout)

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

1. What is the 14,123 in dim(gs_dfm)?
All features after G02a_2 and before trimming. Slide 72
2. Why does gs_test_dfm also have 629 columns?
dfm_match() gives test documents the same feature columns. Slides 73–74
3. After G02b_2 there are 630 columns but only 629 predictors, because
630 columns = 629 text features + 1 label column. Slide 78
10 · Grandstanding G02c–G03

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 Slides 79–80

R · G02c_1 (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> 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. Slides 79–80

G02c_2: specify a linear SVM learner Slides 81–82

R · G02c_2 (W6/classroom/W6_classification.R)
# 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
R console output (run locally: 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)
> 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"
type = "C-classification"
The classification SVM in e1071.
kernel = "linear"
A linear boundary: one weight per word, score = Σ weight × count − intercept.
cost = 1
How strongly misclassification is penalized (larger = tries harder to classify every training point correctly).
scale = FALSE
Does not standardize each column; uses raw word counts directly.
predict_type = "prob"
Asks for probabilities as well as classes (e1071 estimates them internally with Platt scaling, which needs a random internal cross-validation, hence seed 7193 in G02c_3).

Discussion: has lrn() already learned anything from the training rows? — No. It is just "an unfitted learner and its settings". Slide 82

G02c_3: train and predict the held-out texts Slides 83–84

R · G02c_3 (W6/classroom/W6_classification.R)
# 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)
R console output (run locally: 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)
> 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. Slide 84

G02d: evaluate the mlr3 predictions Slides 85–86

R · G02d (W6/classroom/W6_classification.R)
# G02d: Evaluate the mlr3 predictions
gs_result$confusion
gs_scores <- gs_result$score(measures)
round(gs_scores, 3)
R console output (run locally: 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)
> 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 
Discussion: find the 74 false positives and 155 false negatives Slide 86

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

🎯SVM test set (700 paragraphs)Real data · P(Grandstanding) from the local run

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?

📊SVM word weights (top 15 / bottom 15)Real model · computed from e1071 support vectors

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).

Pushes towards Grandstanding
Pushes towards NonGrandstanding

G03: predict one real excerpt Slides 87–89

R · G03 (W6/classroom/W6_classification.R)
# 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]
R console output (run locally: 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)
> 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
gs_01045: a high-scoring statement Slide 89

“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 Slides 90–91

R · ERR (W6/classroom/error_reading.R)
# 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")
R console output (run locally: 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)
> 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]
gs_00013: predicted Grandstanding, reference NonGrandstanding Slide 91

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

R · LAB4 (W6/lab/Lab_Session_W6.R §4)
# 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")
R console output (run locally: 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)
> 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

📖SVM test-set error readerReal data · full text + word-weight highlighting
Reference
–
Prediction (0.5)
–
P(Grandstanding)
–

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
We cannot simply say "NB is better than SVM" (lab handout, Section 4)

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

1. After running gs_learner <- lrn("classif.svm", ...), what has the model learned?
lrn() creates an unfitted learner and sets its options; only $train() fits it. Slides 81–82
2. What does recall .532 in G02d mean?
recall = 176 / (176 + 155) = .532. Slide 86
3. gs_00013 is predicted Grandstanding but its reference is NonGrandstanding. What is the most appropriate conclusion?
The disagreement gives us a case to examine; it does not by itself establish that either the model or the reference is substantively correct (lab solution). Slide 91
11 · Extensions and after class

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 Slide 92

ModelPackage interfacePrediction
Logistic regressionquanteda.textmodels textmodel_lr()predict()
Linear SVMmlr3 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).

R · OPT (W6/classroom/optional_classifiers.R)
# 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)
R console output (run locally: 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)
> 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 Slide 92

Model (hate-speech internal test, 800 comments)accuracyprecisionrecallF1Source
Multinomial NB (C06).694.726.779.752Slide 54; identical locally
Logistic regression (textmodel_lr)0.7380.7960.7520.773Run locally (no numbers in slides/solution)
Linear SVM (mlr3 classif.svm)0.7210.7650.7670.766Run locally (no numbers in slides/solution)
How to read it (supplement)

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 Slide 93

  • 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

📝Lab Section 4 answer areaPractice · copy as R comments and paste back into Lab_Session_W6.R
Suggested reasoning (based on the lab solution and slides)

1. FP (predicted Grandstanding, reference NonGrandstanding); it lowers precision. Slide 91

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) Slide 94

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

1. Why does the optional script keep the same training split and vocabulary?
Keeping the NB split and training-derived vocabulary lets us compare the two models on the same comments (lab handout). Slide 92
2. The optional hate-speech SVM first needs convert() into a dense data frame. What does the lab handout warn about this?
For a large text dataset, we'd need to consider learners or backends that support sparse features.
3. What does slide 94 say about submitting this week's practice?
No separate submission for this practice. Slide 94
12 · Reading guide

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".

About full-text sources (read first)

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. Slides 4, 32, 58, 96

Research questionDetect hate speech in comments on Taiwanese political news and build a hate-speech lexicon.
DataComments on Chinese-language political news. The class uses the instructor-authorized existing Flair fine-tuning copy 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).
MethodOriginal study: hate-speech lexicon and BERT classifier. Class: multinomial NB + Chinese character counts (a re-analysis, not a replication of the paper).
LabelsThe existing binary labels are kept; they are not recomputed from individual coder ratings or model probabilities. The reference set's label comes from "是否仇恨" (is it hate).
Definition(paraphrased in the lab handout, §III-A(2), p. 44342) Abuse targeting attributes of individuals or groups, including political beliefs and parties; excludes satire and humour; distinguishes offence from hate.
Connection to this weekChapters 06–08; the W6 results are a new class run, separate from the paper's BERT and lexicon results (slide 96).

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. Slides 5–7, 97

Research questionHow do politicians talk about race and minority concerns; comparing attention across politicians and periods.
DataPresidents' public remarks and oral statements in Congress; coding unit = paragraph, excluding written bills and procedural content.
LabelsTwo assistants coded random samples (300 paragraphs per president, 1,000 per Congress); explicit racial reference required; reliability 97%, with Gillion resolving disagreements.
MethodAfter human labelling of paragraphs, a classifier extends the coding to the full corpus.
LimitationCoded racial messages without explicit reference are missed (e.g. "inner city"; White 2007).
Connection to this weekChapter 02: agreement ≠ validity; 97% is coder agreement, not classifier accuracy.

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, 98

Research questionCan crowd coding produce political text data reliably and reproducibly?
DataParty manifesto sentences; also 36 European Parliament speeches from the debate on coal subsidies (31 votes, six languages).
LabelsRepeated crowd judgments; a simple scheme: first classify the topic, then rate the position (Figure 1, p. 281).
ValidationCompared with experts; party scores from two coding waves correlate at .93 (Table 4, p. 291); scores compared with votes (Figure 7, p. 292).
ScopeReproducibility holds at the aggregate level.
Connection to this weekChapter 02; the two design choices "repeated judgments" and "aggregation" (slide 22).

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. Slides 12–14, 97

Research questionHow is news attention allocated across policy issues over time?
DataNew York Times front pages, 1996–2006; full corpus of 31,034 stories.
codebookEvidence = headline and first three paragraphs; one main topic + a summary; align storyline labels (codebook pp. 1–5).
Findings (excerpt)International affairs 20.5%, Defense 14.4%, Health 5.8%, Energy 1.0% (Table A.1).
LessonDefine the evidence coders may use; rare categories.
Connection to this weekChapter 03.

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) Slides 15–18, 97

Research questionDo blocked academic careers predict clerics' jihadist rhetoric?
DataClerics' Arabic writings.
Labels (found labels)765 jihadist-curated texts vs. 1,951 sampled cleric texts (2014 working paper §4.1, pp. 13–14).
MethodNB word weights summed into a continuous jihad score.
ValidationInterpreting the context of "apostasy"; comparison with biographies and academic classifications; jihadist infographics (2017). Limitation: biographical silence does not prove someone is non-jihadist (2013 §4.4.1, pp. 121–122; 2014 p. 17 n. 16).
Connection to this weekChapter 03; NB word weights in Chapter 07.

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. Slides 19–21, 64, 98

Research questionWhen do members of Congress grandstand in committee hearings?
DataUS House hearing statements; class copy of 3,500 rows (3,499 after deduplication).
LabelsCrowd ratings; 3,000 paragraphs labelled, 300 held out for testing; RMSE 0.613 (original units, manuscript Figure 1, pp. 16–18).
FindingsMinority-party members score higher; interpreted as messaging and power (Figure 3, p. 20).
Note on the class dataThe binary cut-point of rescaled_gs is not documented, and the CSV has no individual coder votes.
Connection to this weekChapters 04, 09, 10.

Slides 19–21; Data/README (replication: doi:10.7910/DVN/GSMBFX).

Grimmer, Roberts & Stewart (2022). Text as Data, Part IV (Chapters 17–20) Slides 95, 99

ChapterRead firstTeaching link
17 An Overview of Supervised Classification17.2–17.5Connects the research steps
18 Coding a Training SetCore 18.1–18.2Codebooks and human labels
19 Classifying Documents with Supervised LearningModel details 19.1–19.2NB and learned classifiers
20 Checking PerformanceCore 20.1Validation 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?

🗂Matching exercisePractice · based on the slides

For each row, choose the study that fits best.

Not answered yet.
13 · Pitfalls and glossary

Common pitfalls and glossary

Ten common pitfalls

1. Choosing the vocabulary before splitting

The vocabulary choice peeks at the test set. Correct: partition() first, dfm_trim() on training rows only, dfm_match() for test rows. Slide 24

2. Test-matrix columns not aligned

With a different column order, the model parameters are applied to the wrong characters. Check identical(featnames(train_dfm), featnames(test_dfm)). Slides 49–50

3. Putting IDs, scores or labels into X

doc_id, key, sentimentit_score, original model predictions and coder values must not be used as predictors. Slides 64, 76

4. Reading the confusion matrix the wrong way round

mlr3's $confusion: rows = response (prediction), columns = truth. Slide 54

5. Looking only at accuracy

The majority-class baseline (59.5% for hate speech) is already not low; look at precision and recall together. Slides 40, 63

6. Treating a model probability as accuracy

0.999 is the model probability for one comment. Slide 57

7. Assuming internal test scores generalize

The independent reference set has a different positive-class share and distribution; precision drops from .726 to .165. Slide 63

8. Treating coder agreement as validity

Gillion's 97% is agreement; rules may consistently miss implicit appeals. Slides 6–7

9. Inventing your own cut-point

The cut-point of rescaled_gs is undocumented; keep the existing classes and do not re-dichotomize yourself. Slide 35

10. Changing the model after seeing test errors, but reporting scores on the same test set

A fresh evaluation sample is needed (lab handout, Section 4).

Glossary

14 · Final review

Final review, research design and references

Final review quiz

Not answered yet

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.

🧭Proposal plannerPractice · exports Markdown
Markdown

Learning progress

References Slides 96–99

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(), optional textmodel_lr()); mlr3 classif.svm (mlr3learners, e1071); stringi.
These notes are based on the NTLDEV 7191 W6 slides (Yen-Chieh Liao, class date 2026-10-16; 99-page PDF, compiled 2026-10-22), W6/classroom/W6_classification.R, error_reading.R, optional_classifiers.R, W6/lab/Lab_Session_W6.R and its solution, and Data/README.md. R output is from a local rerun (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). Reading cards are based only on the slides (no full texts in the repo). Passages and toy demos marked "Supplement (not from the lecture)" are additional explanation. Prepared 2026-11-06.
NTLDEV 7191 Text as Data · W6 interactive self-study notes · based on the 2026-10-16 lecture slides (2026-11-06)