W6: Human Coding and Document Classification
2026-10-16Fall 2026 (115-1) · National Taiwan University (GIND)
NTLDEV 7191 · Fri. 16:30–18:20 · 國發 204
Last compiled: 2026-10-22 17:07:12 (Asia/Taipei)
| Task | W4: dictionaries | W6: classification |
|---|---|---|
| Build a measure | Select words and rules | Learn from labelled comments |
| Use human evidence | Validate dictionary output | Train and evaluate classifiers |
| Develop the method | Inspect KWIC; revise rules | Fit ML algorithms and predict new texts |
| Assess results | Read errors and sensitivity | Reserved test and human benchmark |
Today, we’ll use machine learning with two real datasets:
Course progression: W4: Dictionaries and Sentiment Analysis to W6.
| Research case | Source | Teaching connection |
|---|---|---|
| Wang, Day & Wu (2022) | IEEE Access | Hate speech: Chinese character counts |
| Gillion (2016) | Governing with Words | Coding rules and agreement |
| Benoit et al. (2016) | APSR | Crowd coding and reproducibility |
| Boydstun (2013) | Making the News | Codebooks and rare categories |
| Nielsen (2017) | Deadly Clerics | Found labels and validation |
| Park (2021) | JOP | Grandstanding: mlr3 linear SVM |
Original-study sources accompany each literature case. Classification practice uses the data from Wang, Day & Wu (2022) and Park (2021).
2022
Cambridge University Press, 2016
§17.1. Gillion (2016), Governing with Words, Appendix A, Appendix B.
Unit: paragraphs; exclude written bills and procedural material.
Training labels: two assistants code random samples: 300 paragraphs per presidential administration and 1,000 per congressional session.
The rule requires an explicit racial reference: a group, race-specific policy, minority figure, or race-specific issue.
General crime, education, or health discussion qualifies only with such a reference.
Reported intercoder reliability: 97%. Gillion adjudicates disagreements.
Discussion: What would this measure miss about implicit racial appeals?
Gillion (2016), Appendix A, pp. 163–166. The 97% concerns coders, not classifier accuracy.
Course interpretation of Gillion (2016), Appendix A · Racial cue example: White (2007).
APSR, 2016 · first-page excerpt
Benoit et al. (2016), APSR · Replication · Connection: §18.3.
Figure 1 · original coding scheme
Benoit et al. (2016), APSR · Figure 1, p. 281.
Table 4 · immigration coding replication
Benoit et al. (2016), APSR · Table 4, p. 291.
Figure 7 · coal-mine aid debate
Benoit et al. (2016), APSR · Figure 7, p. 292.
Book cover · University of Chicago Press, 2013
§18.2.7. Boydstun (2013), book supplements.
Original coding manual · 2013
Book connection: §18.2.7. Boydstun (2013), media codebook, pp. 1–5.
| Topic | Stories | Share of all stories |
|---|---|---|
| International affairs and foreign aid | 6,354 | 20.5% |
| Defense | 4,479 | 14.4% |
| Health | 1,799 | 5.8% |
| Energy | 299 | 1.0% |
Selected rows; full corpus: 31,034 stories.
Boydstun (2013), Table A.1. Selected topic counts from the original study.
Cambridge University Press, 2017
§19.3. Nielsen (2017), Deadly Clerics.
Working paper · July 2014
Method supplement: Nielsen (2014), §4.1, pp. 13–14. Earlier working paper, separate from the 2017 book.
Book connection: §20.3. Nielsen (2017), Ch. 5. Nielsen (2014), pp. 15–17; English & Nielsen (2024), pp. 23–24.
If a biography omits ideology, we cannot label the person non-jihadist on that basis.
Some biographies identify jihadist commitments explicitly. Others omit ideology. Silence cannot establish non-jihadist status.
Course discussion: could a text criticizing jihadism receive a high score because it discusses the same vocabulary?
Let’s read passages in context and compare genres and authors. A separate benchmark checks the scores; close reading helps us understand the language behind them.
For our hate-speech task, let’s check comments that quote abuse in order to reject it.
Nielsen (2013), dissertation, §4.4.1, pp. 121–122; Nielsen (2014), p. 17 n. 16. Discussion and hate-speech application are course extensions.
rescaled_gs labels; mlr3 linear SVM.Figure 1 · author manuscript
Park (2021), manuscript Figure 1 and pp. 16–18.
Ju Yeon Park (2021)
Park (2021), manuscript Figure 3, p. 20.
Let’s use these studies to think through our hate-speech task.
| Design choice | Question for W6 |
|---|---|
| Coding unit | Does one sentence contain enough evidence for our category? |
| Repeated judgments | Which disagreements should trigger human review? |
| Aggregation | Do we need comment labels, hate-speech shares, or a continuous score? |
| Validation | Which independent evidence tests the intended interpretation? |
Before adding raters or models, let’s check that our coding rule fits the question.
Course synthesis from the preceding research cases, including Benoit et al. (2016).
Data: Wang, Day & Wu (2022) · Park (2021) · Classroom ZIP.
We’ll use R to prepare text features, train classifiers and check predictions.
| What we need | R tools |
|---|---|
| Convert text to features | quanteda |
| Fit a text classifier directly | quanteda.textmodels |
| Organize models and evaluation | mlr3 |
| Connect preprocessing steps | mlr3pipelines |
| Search model settings | mlr3tuning |
When we need resampling, model comparison, pipelines or tuning, we can use mlr3.
For our NB exercise, we’ll fit the model directly with quanteda.textmodels.
Official homepage · mlr-org.com · captured 2026-10-15
| Need | R: mlr3 ecosystem | Python: scikit-learn ecosystem |
|---|---|---|
| Model interface | Task + learner | Estimator |
| Fit / predict | $train() / $predict() |
.fit() / .predict() |
| Text features | quanteda counts / TF-IDF |
CountVectorizer / TfidfVectorizer |
| Preprocessing + model | mlr3pipelines |
Pipeline |
| Cross-validation | resample() |
cross_validate() |
| Parameter search | mlr3tuning |
GridSearchCV |
Same workflow: define the target, separate training and test data, then evaluate predictions.
We can train a simple text classifier directly from a DFM and training labels.
| Model | Function |
|---|---|
| Naive Bayes | textmodel_nb() |
| Regularized logistic regression | textmodel_lr() |
| Linear SVM | textmodel_svmlin() |
Linear SVM: experimental, for two classes.
We’ll fit NB with training counts and labels, then predict held-out texts.
| Case | Classifier | Model interface |
|---|---|---|
| Taiwan political hate speech | Multinomial Naive Bayes | quanteda.textmodels |
| Political grandstanding | Linear SVM | mlr3 + mlr3learners |
We will use the data from Wang, Day & Wu (2022) and Park (2021).
We’ll use the same steps: load → split → features → fit classifier → predict → check labels.
speech → rescaled_gs (0/1).sentimentit_score (unused).First 3 rows · gscore_julia_park.csv
| Row | speech (preview) |
rescaled_gs |
|---|---|---|
| 1 | Beautiful, because that brings me to my ne… | 0 |
| 2 | And so, while there may have been an indic… | 1 |
| 3 | Yeah, and I do not think there has been in… | 0 |
text → hate_speech (0/1).label, the category name.First 3 rows · merged-hate-speeches.csv
| Row | text |
hate_speech |
|---|---|---|
| 1 | 係阿6啊~ | 0 |
| 2 | 我媽媽說,學生最好騙, 叫我不要上他的當 | 0 |
| 3 | 智X總統 畜X官員 無誤 ?! | 1 |
Text previews follow the original CSV row order.
# Install once
install.packages(c("quanteda", "quanteda.textmodels",
"mlr3", "mlr3learners", "e1071", "stringi"),
repos = "https://cloud.r-project.org")
# Load and check before the exercise
library(quanteda); library(quanteda.textmodels)
library(mlr3); library(mlr3learners)
library(e1071); library(stringi)
lrn("classif.svm")$idReady: all six packages load without errors; the last line returns "classif.svm".
| Input | Hate speech | Grandstanding |
|---|---|---|
| One row | Chinese comment | English hearing excerpt |
| Label column | hate_speech |
rescaled_gs |
| Positive category | HateSpeech | Grandstanding |
| Features | Chinese character counts | English word counts |
| Classifier | Multinomial NB | Linear SVM |
| Model interface | quanteda.textmodels |
mlr3 + mlr3learners |
We’ll build features from the text. The label is what we’re trying to predict.
Data: Wang, Day & Wu (2022). W6 classroom NB run. Data: Park (2021). W6 classroom linear SVM run.
Hate speech: use the labels in the Wang, Day & Wu (2022) data.
Grandstanding: use rescaled_gs; the CSV does not document its original binary cutoff.
Data: Wang, Day & Wu (2022). W6 classroom NB run. Data: Park (2021). W6 classroom linear SVM run.
We’ll predict a category from text counts.
predict() returns categories; type = "probability" returns model probabilities.Let’s focus on fit → predict → inspect.
Copy and run — C01.
# 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
> file.exists(file.path(data_dir, "hate_speech_practice.csv"))
[1] TRUE
| Function | Purpose |
|---|---|
quanteda_options() |
Set the text-processing options for this session |
msrs() |
Create the accuracy, precision, recall and F1 measure objects |
Discuss: What would FALSE tell us about the data path?
Copy and run — C02.
We’ll use read.csv() to load 4,000 cleaned comments with their existing labels.
Data: Wang, Day & Wu (2022). W6 classroom NB run.
R console output
> table(hate$label)
NonHateSpeech HateSpeech
1622 2378
> nrow(hate)
[1] 4000
Discuss: Which class is more common? What would always predicting that class achieve?
Data: Wang, Day & Wu (2022). W6 classroom NB run.
Copy and run — C03.
# 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)With mlr3, we declare the outcome using as_task_classif(), then get row IDs for our split with partition().
Data: Wang, Day & Wu (2022). W6 classroom NB run.
R console output
> table(parts$train$label)
NonHateSpeech HateSpeech
1298 1902
> table(parts$test$label)
NonHateSpeech HateSpeech
324 476
Discuss: Why do we reserve test rows before selecting the vocabulary?
Data: Wang, Day & Wu (2022). W6 classroom NB run.
Copy and run — C04a_1.
| Function / object | What it does here |
|---|---|
stri_trans_nfkc() |
stringi: normalize Unicode forms in a working text copy. |
quanteda::tokens() |
Turn each comment into character tokens. |
Data: Wang, Day & Wu (2022). W6 classroom NB run. · quanteda tokens
R console output
> class(hs_tokens)
[1] "tokens"
Discuss: Why use character tokens here, and what might we lose?
Data: Wang, Day & Wu (2022). W6 classroom NB run. · quanteda tokens
Copy and run — C04a_2.
| Function / object | What it does here |
|---|---|
tokens_select() |
Retain tokens matching the Han-character pattern. |
dfm() |
Count features in a sparse document-feature matrix. |
Data: Wang, Day & Wu (2022). W6 classroom NB run. · tokens_select · dfm
R console output
> dim(hs_dfm)
[1] 4000 2916
Discuss: What do the 4,000 rows and 2,916 columns represent?
Data: Wang, Day & Wu (2022). W6 classroom NB run. · tokens_select · dfm
Copy and run — C04b_1.
| Function / object | What it does here |
|---|---|
dfm_trim() |
Keep features occurring in at least 1% of training documents. |
train_label |
Keep one label per training row, in the same order. |
Data: Wang, Day & Wu (2022). W6 classroom NB run. · dfm_trim
R console output
> dim(train_dfm)
[1] 3200 603
Discuss: Does min_docfreq count documents or total token occurrences?
Data: Wang, Day & Wu (2022). W6 classroom NB run. · dfm_trim
Copy and run — C04b_2.
| Function / object | What it does here |
|---|---|
featnames() |
Read the training feature names in column order. |
dfm_match() |
Match that order, drop extra features and fill missing ones with zero. |
Data: Wang, Day & Wu (2022). W6 classroom NB run. · dfm_match
R console output
> dim(test_dfm)
[1] 800 603
> identical(featnames(train_dfm), featnames(test_dfm))
[1] TRUE
Discuss: Why must the 800 test rows use the same 603 columns in the same order?
Data: Wang, Day & Wu (2022). W6 classroom NB run. · dfm_match
Copy and run — C05.
We’ll give textmodel_nb() the counts and matching labels. It returns our fitted NB model.
R console output
> class(nb)
[1] "textmodel_nb" "textmodel" "list"
> nb$distribution
[1] "multinomial"
| Argument | What we supply |
|---|---|
x |
Training feature counts |
y |
Labels in the same row order |
smooth = 1 |
Smoothing for counts |
prior = "docfreq" |
Training label frequencies |
Discuss: Which argument supplies the training labels?
Copy and run — C06.
# 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)We’ll predict with the quanteda NB model, pair those predictions with test labels using PredictionClassif$new(), then calculate metrics with $score().
Data: Wang, Day & Wu (2022). W6 classroom NB run.
R console output
> nb_check$confusion
truth
response HateSpeech NonHateSpeech
HateSpeech 371 140
NonHateSpeech 105 184
> round(nb_scores, 3)
classif.acc classif.precision classif.recall classif.fbeta
0.694 0.726 0.779 0.752
Discuss (2 minutes): Rows are predictions. Which cells are false positives and false negatives?
Data: Wang, Day & Wu (2022). W6 classroom NB run.
Copy and run — C07.
We’ll represent the full comment using the same training vocabulary.
Data: Wang, Day & Wu (2022). W6 classroom NB run.
垃圾426,滾回去中國,永不得進來台灣(You mainland Chinese scum, get back to China and never set foot in Taiwan.)
Comment ID: hs_26234
| What to read | Result for this comment |
|---|---|
| Model prediction | HateSpeech |
| Model probability | P(HateSpeech) = 0.999 |
| Reference label | HateSpeech |
Discuss: Which words express group-based degradation or exclusion?
Data: Wang, Day & Wu (2022). W6 classroom NB run.
R console output
> 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
Levels lists the two possible categories.0.999 is a model probability, not overall accuracy.Data: Wang, Day & Wu (2022). W6 classroom NB run.
hate_speech_reference.csv combines two 1,000-comment validation files.source column.label comes from 是否仇恨 (Hate speech: Yes/No), not the original model-prediction columns.We’ll check these comments after fitting and keep the model fixed.
Data: Wang, Day & Wu (2022). W6 classroom NB run.
Copy and run — C08a.
# 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)Data: Wang, Day & Wu (2022). W6 classroom NB run.
R console output
> dim(ref_dfm)
[1] 1968 603
> sum(ntoken(ref_dfm) == 0)
[1] 17
Discuss: Do the 17 zero-feature rows mean empty comments or no retained characters?
Data: Wang, Day & Wu (2022). W6 classroom NB run.
Copy and run — C08b.
# 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)We’ll put the reference labels and predictions together in PredictionClassif$new(), then calculate our selected metrics with $score(measures).
Data: Wang, Day & Wu (2022). W6 classroom NB run.
R console output
> nrow(benchmark)
[1] 1968
> round(benchmark_scores, 3)
classif.acc classif.precision classif.recall classif.fbeta
0.514 0.165 0.880 0.278
Discuss (2 minutes): Recall is .880, but precision is .165. What errors does that imply?
Data: Wang, Day & Wu (2022). W6 classroom NB run.
| Check | Internal test | Human references |
|---|---|---|
| Comments | 800 | 1,968 |
| HateSpeech precision | .726 | .165 |
| HateSpeech recall | .779 | .880 |
| HateSpeech F1 | .752 | .278 |
Let’s read precision alongside recall. This simple NB produces many false positives on the separate sample, despite its high recall.
Data: Wang, Day & Wu (2022). W6 classroom NB run.
Source: gscore_julia_park.csv.
Lab: grandstanding_practice.csv.
speech becomes text: English hearing excerpt.rescaled_gs becomes label: existing binary category.sentimentit_score stays outside the predictors.We’ll count English words with quanteda, then fit a linear SVM with mlr3.
Data: Park (2021). W6 classroom linear SVM run.
Copy and run — G01a.
We’ll use the CSV’s existing rescaled_gs categories. One duplicate was removed before class.
Data: Park (2021). W6 classroom linear SVM run.
R console output
> table(grandstanding$label)
NonGrandstanding Grandstanding
1846 1653
Discuss: Which class is more common in the Park (2021) data?
Data: Park (2021). W6 classroom linear SVM run.
Copy and run — G01b.
# 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)We’ll use the row IDs from partition() to split the data. Setting stratum to the label gives us an approximate 80/20 split within each category.
Data: Park (2021). W6 classroom linear SVM run.
R console output
> table(gs_parts$train$label)
NonGrandstanding Grandstanding
1477 1322
> table(gs_parts$test$label)
NonGrandstanding Grandstanding
369 331
Discuss: How does stratification preserve both categories in the test set?
Data: Park (2021). W6 classroom linear SVM run.
Copy and run — G02a_1.
| Function / object | What it does here |
|---|---|
corpus() |
Read text and document IDs from the data table. |
tokens() |
Split the selected text into words and remove the requested token types. |
Data: Park (2021). W6 classroom linear SVM run. · corpus · tokens
R console output
> ndoc(gs_corpus)
[1] 3499
Discuss: Which column supplies text, and which column supplies document IDs?
Data: Park (2021). W6 classroom linear SVM run. · corpus · tokens
Copy and run — G02a_2.
| Function / object | What it does here |
|---|---|
tokens_tolower() |
Combine upper- and lowercase versions of words. |
tokens_remove() |
Remove the English stopword list from the tokens. |
dfm() |
Count the remaining words for each document. |
Data: Park (2021). W6 classroom linear SVM run. · tokens_tolower · tokens_remove · dfm
R console output
> dim(gs_dfm)
[1] 3499 14123
Discuss: How do these word features differ from the Chinese character features?
Data: Park (2021). W6 classroom linear SVM run. · tokens_tolower · tokens_remove · dfm
Copy and run — G02a_3.
| Function / object | What it does here |
|---|---|
dfm_trim() |
Choose words using training document frequencies. |
dfm_match() |
Give test documents the same feature columns. |
Data: Park (2021). W6 classroom linear SVM run. · dfm_trim · dfm_match
R console output
> dim(gs_train_dfm)
[1] 2799 629
> dim(gs_test_dfm)
[1] 700 629
Discuss: Why do both matrices have 629 columns even though they contain different texts?
Data: Park (2021). W6 classroom linear SVM run. · dfm_trim · dfm_match
Copy and run — G02b_1.
| Function / object | What it does here |
|---|---|
quanteda::convert() |
Turn the small sparse DFM into a dense data frame. |
doc_id <- NULL |
Remove the identifier, leaving 629 numeric feature columns. |
Data: Park (2021). W6 classroom linear SVM run. · quanteda convert
R console output
> dim(gs_train_data)
[1] 2799 629
> dim(gs_test_data)
[1] 700 629
Discuss: Why should a document ID stay outside the predictor columns?
Data: Park (2021). W6 classroom linear SVM run. · quanteda convert
Copy and run — G02b_2.
# 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)| Function / object | What it does here |
|---|---|
make.names() |
Create valid, unique feature names. |
label |
Add the target after the 629 feature columns. |
Data: Park (2021). W6 classroom linear SVM run. · mlr3 PredictionClassif
R console output
> dim(gs_train_data)
[1] 2799 630
> dim(gs_test_data)
[1] 700 630
630 columns = 629 text features + 1 label column.
label (Grandstanding / NonGrandstanding), excluded from predictors.Discuss: Why are there now 630 columns, but only 629 predictors?
Data: Park (2021). W6 classroom linear SVM run. · mlr3 PredictionClassif
Copy and run — G02c_1.
| Function / object | What it does here |
|---|---|
as_task_classif() |
Describe the training data, target column and positive class. |
TaskClassif |
Stores data and roles. Creating the task does not train a model. |
Data: Park (2021). W6 classroom linear SVM run. · as_task_classif
R console output
> gs_model_task$target_names
[1] "label"
> length(gs_model_task$feature_names)
[1] 629
Discuss: Which column is the target, and why is it excluded from feature_names?
Data: Park (2021). W6 classroom linear SVM run. · as_task_classif
Copy and run — G02c_2.
| Function / object | What it does here |
|---|---|
lrn() |
Create an unfitted learner and set its options. |
predict_type = "prob" |
Request class probabilities as well as predicted categories. |
Data: Park (2021). W6 classroom linear SVM run. · mlr3 SVM
R console output
> gs_learner$id
[1] "classif.svm"
> gs_learner$predict_type
[1] "prob"
Discuss: Has lrn() already learned from any training rows?
Data: Park (2021). W6 classroom linear SVM run. · mlr3 SVM
Copy and run — G02c_3.
| Function / object | What it does here |
|---|---|
$train(task) |
Fit the learner using the training task. |
$predict_newdata() |
Return predictions for the held-out feature table. |
$response / $prob |
Read category labels / the matrix of class probabilities. |
Data: Park (2021). W6 classroom linear SVM run. · mlr3 Learner · PredictionClassif
R console output
> length(gs_prediction)
[1] 700
> colnames(gs_result$prob)
[1] "Grandstanding" "NonGrandstanding"
Discuss: Which object stores the fitted learner, and which stores the 700 test predictions?
Data: Park (2021). W6 classroom linear SVM run. · mlr3 Learner · PredictionClassif
Copy and run — G02d.
We’ll read the confusion table with $confusion and calculate the evaluation scores with $score(measures).
Data: Park (2021). W6 classroom linear SVM run.
R console output
> gs_result$confusion
truth
response Grandstanding NonGrandstanding
Grandstanding 176 74
NonGrandstanding 155 295
> round(gs_scores, 3)
classif.acc classif.precision classif.recall classif.fbeta
0.673 0.704 0.532 0.606
Discuss: Locate the 74 false positives and 155 false negatives.
Data: Park (2021). W6 classroom linear SVM run.
Copy and run — G03.
We’ll read an excerpt that we kept out of training.
Data: Park (2021). W6 classroom linear SVM run.
R console output
> 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
Discuss: Which words suggest self-promotion? Read the full statement next.
Data: Park (2021). W6 classroom linear SVM run.
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
Let’s look for self-promotion and a stance on taxes. Original score: 2.003.
Data: Park (2021). W6 classroom linear SVM run.
Let’s run this after G03 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")We’ll find mismatches with which(), select one with k, and print its full text with cat().
Data: Park (2021). W6 classroom linear SVM run.
R console output
doc_id reference prediction prob
1 gs_00013 NonGrandstanding Grandstanding 0.609
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 others along the coast.
Discuss: Does describing district needs count as self-promotion? What context is missing?
Data: Park (2021). W6 classroom linear SVM run.
Let’s keep the same training split and vocabulary as we try another classifier.
| Model | Package interface | Prediction |
|---|---|---|
| Logistic regression | quanteda.textmodelstextmodel_lr() |
predict() |
| Linear SVM | mlr3 lrn("classif.svm", kernel = "linear") |
$train() then $predict() |
We can use the package functions directly; the lab shows the complete calls.
In class, we’ll run C01–C08, then G01–G03 (including all substeps), in order in one R session.
rescaled_gs.Classroom code + data · Lab · Worked answers
Week 7: proposal due 2026-10-23, before 23:59. No separate submission for this practice.
| Text as Data chapter | Sections to prioritize | Teaching connection |
|---|---|---|
| 17: An Overview of Supervised Classification | Overview: 17.2–17.5 | Connect the research steps |
| 18: Coding a Training Set | Core: 18.1–18.2 | Codebooks and human labels |
| 19: Classifying Documents with Supervised Learning | Model detail: 19.1–19.2 | NB and learned classifiers |
| 20: Checking Performance | Core: 20.1 | Validation and prediction errors |
Extensions: §19.2.3 for aggregate measures; §20.2 for indirect validation.
Chapter 15 provides optional measurement context.
Grimmer, Roberts & Stewart (2022), Text as Data, Part IV.
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.
Hate-speech data: Wang, Day & Wu (2022), merged-hate-speeches.csv.
Grandstanding data: Park (2021), gscore_julia_park.csv, target rescaled_gs.
Manual benchmark: the supplied BERT and Lexicon 1,000-comment validation sheets.
W6 results are new classroom runs, separate from the paper’s BERT and lexicon results.
Source files and hashes: data notes.
Methods supplements: Nielsen (2014); English & Nielsen (2024).
Park, Ju Yeon. 2021. “When Do Politicians Grandstand? Measuring Message Politics in Committee Hearings.” The Journal of Politics 83(1): 214–228. Article · Author manuscript.
Benoit, Kenneth, Drew Conway, Benjamin E. Lauderdale, Michael Laver, and Slava Mikhaylov. 2016. “Crowd-sourced Text Analysis: Reproducible and Agile Production of Political Data.” American Political Science Review 110(2): 278–295. Article · Replication.
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.” American Journal of Political Science 70(4): 1589–1605. Article · Replication.
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. Book and contents.
Software: quanteda for text features, quanteda.textmodels::textmodel_nb() for Naive Bayes, quanteda.textmodels::textmodel_lr() for optional logistic regression, and mlr3 classif.svm (with mlr3learners and e1071) for the grandstanding linear SVM.
Further tools: quanteda.textmodels for text classifiers; mlr3 for splitting and evaluation; Transformers for the fine-tuning extension.
R workflow references: tidyverse, tidymodels, and the mlr3 feature-selection chapter.
Evaluation references: scikit-learn documentation on cross-validation and classification metrics.
Our hate-speech NB exercise uses Wang, Day & Wu (2022); our grandstanding linear SVM uses Park (2021). We’ve run predictions for both exercises. Results from the original studies are cited separately.