# Package loading check
library(quanteda); library(quanteda.textmodels)
library(mlr3); library(mlr3learners)
library(e1071); library(stringi)
lrn("classif.svm")$id[1] "classif.svm"
Naive Bayes with quanteda.textmodels and linear SVM with mlr3
Let’s work through the same four sections and checkpoints as the student handout. Compare your output with the results here, then read how we interpret them. Return to the student handout.
Download and extract the lab ZIP for the handouts, R scripts and Data/ folder. Allow 60–90 minutes for the core practice. Open Lab_Session_W6_Answers.R in RStudio and set the working directory to the lab folder containing Data/ (one level above answers/). Run section 1 once, then sections 2–4 in order in the same R session. The source QMD does not need to be rendered.
We’ll use quanteda, quanteda.textmodels, mlr3, mlr3learners, e1071 and stringi. Let’s complete the package check in section 1 before C01, then read the CSVs directly.
We’ll work from top to bottom in the same R session. In RStudio, select a line or block and use Ctrl+Enter (Windows) or Cmd+Enter (Mac). Pause at the printed output before moving on: what changed, and which object now holds the result?
| Syntax | Meaning | Example |
|---|---|---|
<- |
Save a result under a name | hs_dfm <- dfm(hs_tokens) |
$ with a data frame |
Select a column | hate$label |
$ with an mlr3 object |
Access a field or call a method | gs_result$response, gs_result$score(measures) |
[rows, columns] |
Select rows or columns | hs_dfm[hs_split$train, ] |
c(...) |
Combine values | c("NonHateSpeech", "HateSpeech") |
==, != |
Equal to, different from | nb_prediction != parts$test$label |
which(...) |
Find row positions where a condition is TRUE | which(nb_prediction != parts$test$label) |
table(...) |
Count categories | table(hate$label) |
The C and G checkpoint names match the W6 slides, so we can move between the slides and this handout. Run the lettered and numbered substeps in order; each builds on objects created earlier. We’ll call the package functions directly.
| Step | Existing functions | Package |
|---|---|---|
| Read a CSV | read.csv(), factor() |
base R |
| Reserve test data | as_task_classif(), partition() |
mlr3 |
| Count text features | corpus(), tokens(), dfm() |
quanteda |
| Keep training vocabulary | dfm_trim(), dfm_match() |
quanteda |
| Fit hate-speech NB | textmodel_nb(), predict() |
quanteda.textmodels |
| Fit grandstanding SVM | lrn(), $train(), $predict_newdata() |
mlr3 + mlr3learners |
| Check predictions | PredictionClassif$new(), $score(), msrs() |
mlr3 |
We’ll use mlr3 to calculate classification accuracy, precision, recall and F1. lmtest supplies tests for regression models.
| Exercise | Data | Classifier | Main interface |
|---|---|---|---|
| Hate speech | Wang, Day & Wu (2022) | Multinomial Naive Bayes | quanteda.textmodels |
| Grandstanding | Park (2021) | Linear SVM | mlr3 + mlr3learners |
In both exercises, we’ll count text features with quanteda and use mlr3 to reserve test rows and evaluate predictions. We are reanalysing the data for class; the results below come from our classroom models rather than the papers’ reported models.
| Data | Original field | Practice CSV field |
|---|---|---|
| Wang, Day & Wu (2022) | text |
text |
| Wang, Day & Wu (2022) | hate_speech (0/1) |
label (NonHateSpeech/HateSpeech) |
| Park (2021) | speech |
text |
| Park (2021) | rescaled_gs (0/1) |
label (NonGrandstanding/Grandstanding) |
We’ll use doc_id to identify rows and key to check text overlap, and keep both outside the predictors. We’ll also keep the source data’s binary labels without applying a new cutoff.
Before we read classification errors, let’s agree on what to look for in the texts. The summaries below guide our discussion; they do not reproduce the full annotation instructions or replace the supplied labels.
Hate speech: Wang, Day & Wu define attribute-directed abuse of an individual or group, including attacks based on political beliefs or party affiliation. Their scheme excludes satire and humour and distinguishes offensive speech from hate speech. When reading a comment, identify the target, the attribute attacked and the context indicating abuse. See Wang, Day & Wu (2022), §III-A(2), p. 44342 (full article text).
Grandstanding: Park’s rating instructions cover praise or denigration of people or institutions, policy positions or subjective assessments, and questions intended to embarrass or attack witnesses. Factual descriptions and requests for facts or expert advice form the other end of the scale. A question can still grandstand; self-reference alone does not settle the category. See Park (2021), author manuscript, “Data and Methods,” p. 14 and Table 1, p. 16. The original ratings measure relative intensity. The supplied CSV does not document the cutoff for its binary rescaled_gs categories; keep those existing categories.
5–10 minutes. Let’s check the packages and locate Data/ before we load the texts. We should see "classif.svm" from the SVM check and TRUE from the C01 data check. Keep this R session open for both cases.
If these packages are not installed yet, run this command once before we begin.
install.packages(c("quanteda", "quanteda.textmodels",
"mlr3", "mlr3learners", "e1071", "stringi"),
repos = "https://cloud.r-project.org")Each new R session needs to load the packages again. Let’s run this check before C01.
# Package loading check
library(quanteda); library(quanteda.textmodels)
library(mlr3); library(mlr3learners)
library(e1071); library(stringi)
lrn("classif.svm")$id[1] "classif.svm"
Once all six packages load without errors and the last line returns "classif.svm", we’re ready for C01.
Let’s set up the data path and the measures we’ll use later. As we read the code, which package supplies each function?
# 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"))[1] TRUE
measures <- msrs(c("classif.acc", "classif.precision",
"classif.recall", "classif.fbeta"))Look at the file check. If it returns FALSE, where would we look for a problem in the data path?
If the file check returns FALSE, we’ll need to check the working directory and make sure the extracted Data/ folder is beside the lab script. We’ll build features with quanteda and fit hate-speech NB with quanteda.textmodels. For grandstanding, we’ll use the mlr3/ mlr3learners SVM interface; mlr3 also handles our splits and evaluation. The package check has already loaded mlr3learners and its e1071 backend for us.
25–30 minutes. We’ll start with the data from Wang, Day & Wu (2022). First we’ll reserve test comments, then count Chinese characters and use only the training rows to select our vocabulary and fit Naive Bayes. After checking the held-out comments, we’ll apply that fitted model to the separate human-reference sample.
Let’s load the comments and count the two labels.
# 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)
NonHateSpeech HateSpeech
1622 2378
nrow(hate)[1] 4000
Which class appears more often? If we predicted that class for every comment, what accuracy would we get?
We have 2,378 HateSpeech and 1,622 NonHateSpeech comments, so HateSpeech is the majority class. If we always predicted that class, we’d get 2,378 / 4,000 = 59.45% accuracy on the full sample. That gives us a majority-class baseline. When we evaluate a model, we’ll calculate its baseline on the same evaluation rows. The labels come from Wang, Day & Wu (2022).
Before we count features, let’s set aside the comments we’ll use to evaluate the model.
# 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)
NonHateSpeech HateSpeech
1298 1902
table(parts$test$label)
NonHateSpeech HateSpeech
324 476
Why do we reserve the test rows now? What information would reach our vocabulary selection if we used those rows too?
We now have 3,200 training and 800 test comments. By using the label as the stratum, we keep approximately 80/20 of each class in the two sets. At this point, the task just holds the labels and row IDs we need for splitting; we haven’t fitted a classifier yet.
| 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. |
# 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)[1] "tokens"
Look at what = "character". What have we asked R to count, and how would the result differ if we wanted Chinese words?
We get a tokens object with one sequence per comment. Because we chose character tokenization, these sequences contain characters rather than segmented Chinese words. We’ve removed punctuation, symbols and numeric tokens from this working copy; the raw text in hate$text stays available for us to read.
| Function / object | What it does here |
|---|---|
tokens_select() |
Retain tokens matching the Han-character pattern. |
dfm() |
Count features in a sparse document-feature matrix. |
# 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)[1] 4000 2916
We now have 4,000 rows and 2,916 columns. Which represents comments, which represents characters, and what does one cell count?
Each row is a comment, each column is a retained character, and each cell counts that character in that comment. We have all comments in this DFM for now. In the next step, we’ll use only the training rows to choose the vocabulary cutoff.
| 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. |
# 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)[1] 3200 603
With min_docfreq = .01, are we counting the documents that contain a character or all occurrences of that character?
We keep 603 features across the 3,200 training comments. The 1% threshold asks how many documents contain a character, so repeating it many times in one comment does not make it appear in more documents. Only the training rows contribute to this choice.
| 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. |
# C04b_2: Match test features to training columns
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
The test set has 800 rows, and the training vocabulary has 603 columns. Why do we need those same columns in the same order when we predict?
Our test matrix is 800 by 603, and the name/order check returns TRUE. We can now give the model the columns it expects: dfm_match() aligns them with the training vocabulary without selecting a new vocabulary from the test texts.
Let’s fit Naive Bayes using the training counts and their labels.
# C05: Fit Naive Bayes
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"
Which argument gives the model its training labels, and which object now holds the fitted model?
The fitted multinomial NB model is now stored in nb. We supplied its labels through y, so their order must match the rows of the training matrix.
Now we can predict the held-out comments. Let’s use the confusion matrix to see where the predictions agree with the labels and where they differ.
# 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 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
Read the predictions down the rows and the reference labels across the columns. Which cells contain false positives and false negatives?
We keep the reference labels and predictions together in PredictionClassif, then use $score(measures) to calculate the measures from C01. When we read precision, recall and F1, we need to check which class the task sets as positive.
Reading predictions down the rows and reference labels across the columns, we find TP371, FP140, FN105 and TN184. Our accuracy is .694, precision .726, recall .779 and F1 .752. For comparison, always predicting HateSpeech on these same 800 test comments gives 476 / 800 = 59.5% accuracy. We’re treating HateSpeech as positive, and classif.fbeta uses beta=1, which gives us F1.
Let’s put the scores aside for a moment and read one held-out comment. Does its prediction agree with the provided label?
# C07: Inspect one held-out comment
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
Which words in this comment express group-based degradation or exclusion? How do they relate to the category definition above?
For hs_26234, we predict HateSpeech with model probability .999, matching the provided label. We can see the group-directed degradation in “垃圾” and the demands for exclusion in “滾回去中國” and “永不得進來台灣”. Those phrases help us connect the prediction to the coding definition above.
Next we’ll read hate_speech_reference.csv and evaluate the same fitted NB model on these separate comments. The source column tells us whether a comment came from the BERT file, the Lexicon file or both. Our reference is label, the final 是否仇恨 (Hate speech: Yes/No) category. The original model-prediction columns are excluded, and we will not train a BERT model here.
Before we predict, let’s give these comments the vocabulary we selected from the training data.
# 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)[1] 1968 603
[1] 17
We find 17 rows with no features. Are those comments empty, or do they contain no characters from our retained vocabulary?
These 1,968 reference comments have no matching texts in our training sample. We apply the fitted training vocabulary with dfm_match(). A row with no retained features may still contain text; it just has none of our selected characters. We keep all comments in the evaluation, including those 17 rows.
Let’s score these predictions and compare them with our first test results.
# 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)[1] 1968
classif.acc classif.precision classif.recall classif.fbeta
0.514 0.165 0.880 0.278
We get recall of .880 and precision of .165. What does that combination tell us about the comments predicted as HateSpeech?
We use the same measures from C01 again, with HateSpeech as the task’s positive class. Keeping that definition fixed helps us compare precision, recall and F1 across the two evaluations.
Here we get precision .165, recall .880 and F1 .278. We’re finding most reference HateSpeech comments, but many comments we predict as HateSpeech are false positives. Sampling and label construction differ across the two evaluations, so this comparison alone cannot tell us why the scores changed.
20–30 minutes. Now we’ll follow the same steps with Park (2021) data, using English word features and an mlr3 learner. We’ll predict the supplied binary rescaled_gs category. As we read the results, remember that the SVM probability and the original research score describe different quantities.
Let’s load the hearing excerpts. Which original field gives us the grandstanding target?
# 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)
NonGrandstanding Grandstanding
1846 1653
Look at the label counts. Which class is more common in this sample?
We have 3,499 distinct excerpts with the supplied rescaled_gs categories, Grandstanding and NonGrandstanding, from Park (2021). We’ll keep these categories because the file does not document the original binary conversion cutoff. We also keep the score fields outside the predictors.
We’ll reserve test excerpts as before. Check which category we set as the positive class.
# 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)
NonGrandstanding Grandstanding
1477 1322
table(gs_parts$test$label)
NonGrandstanding Grandstanding
369 331
Compare the training and test counts. How does stratification keep both categories represented?
We have 2,799 training and 700 test excerpts. We’ve set Grandstanding as positive in the task, so that is the class we’ll use when we read precision and recall.
| 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. |
# 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)[1] 3499
In the corpus() call, which column do we read as text and which do we use for document IDs?
Our corpus contains 3,499 documents. We use text_field to select text and docid_field to select doc_id. The remaining columns stay as document metadata, so we don’t count them as words in the text.
| 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. |
# 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)[1] 3499 14123
What does one column count here? Compare these English word features with the Chinese character features we used earlier.
We now have a sparse DFM of word counts, ready for trimming with the training rows. Here we count English words rather than Chinese characters. We’ve chosen to remove English stopwords for this exercise; for another research question, we’d first ask whether those words carry meaning we need.
| Function / object | What it does here |
|---|---|
dfm_trim() |
Choose words using training document frequencies. |
dfm_match() |
Give test documents the same feature columns. |
# 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)[1] 2799 629
[1] 700 629
Both matrices have 629 columns even though they contain different excerpts. Where did we choose those columns, and why do we keep them the same?
We choose 629 features from the 2,799 training rows, then give the 700 test rows those same columns. This is the same rule we used for hate speech: the training texts choose the vocabulary, and the test texts use it.
| 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. |
# 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)[1] 2799 629
[1] 700 629
We’ve removed the document ID from the feature table. What should the model learn from, and why would an ID be an unsuitable predictor?
After removing doc_id, we have 629 numeric feature columns. These are the text counts we’ll pass to the learner. A dense table is manageable for this dataset; with a larger text matrix, we’d look for a learner or backend that can use sparse features.
| Function / object | What it does here |
|---|---|
make.names() |
Create valid, unique feature names. |
label |
Add the target after the 629 feature columns. |
# 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)[1] 2799 630
[1] 700 630
We now have 630 columns. Which one is the target, leaving 629 predictors?
The extra column is label, giving us 629 features plus the target. We’ve kept the feature names and order the same in both tables. We also put Grandstanding first in the test label factor to match the mlr3 task’s positive-class order, so the binary measures refer to the intended class.
| 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. |
# G02c_1: Define the grandstanding task
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
Check target_names and feature_names. Why do we keep the target column outside the predictors?
We can see label listed as the target and 629 names listed as features. This task holds the text counts we’ll train on; our earlier label-only tasks helped us split the rows. Setting the positive class tells mlr3 how to calculate binary precision, recall and F1.
| 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. |
# 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[1] "classif.svm"
gs_learner$predict_type[1] "prob"
We’ve chosen the learner and its settings. Has lrn() seen any training rows yet?
We’ve created a classif.svm learner with predict_type set to prob. The interface comes from mlr3learners and uses e1071 underneath. So far we’ve chosen kernel, cost and scale; we’ll give the learner its training rows in the next step.
| 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. |
# 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)[1] 700
colnames(gs_result$prob)[1] "Grandstanding" "NonGrandstanding"
We now have a fitted model and 700 test predictions. Which object holds each, and where can we find the class probabilities?
Our fitted model is in gs_learner, and its 700 predictions are in gs_result. For each test row, we can read the predicted category and a probability for each class. We’ll use the test labels to evaluate these predictions; they were kept outside training.
# G02d: Evaluate the mlr3 predictions
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
Find the 74 false positives and 155 false negatives in the table. Which kind of error is more common?
With Grandstanding as positive, we count TP176, FP74, FN155 and TN295. Our accuracy is .673, precision .704, recall .532 and F1 .606. We miss more reference Grandstanding excerpts than we incorrectly predict as Grandstanding, which helps explain the lower recall.
Here gs_result is our PredictionClassif object, holding the reference labels and predictions. We call $score(measures) with the measures from C01 and read precision, recall and F1 for the task’s positive class, Grandstanding.
Let’s read one excerpt alongside its prediction and the supplied rescaled_gs category.
# G03: Inspect one grandstanding prediction
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
Which words suggest self-promotion or position-taking? Keep them in mind as we read the full statement next.
For gs_01045, we predict Grandstanding with linear SVM probability .637, matching the provided label. Let’s look at what the speaker says: “I am not intimidated by anybody” and “I am going to do whatever I have to do” emphasize personal resolve, while the tax statements take a public political position. We can discuss these as self-promotion and position-taking, but the model probability cannot establish whether the classification is substantively correct. The original grandstanding score is 2.003; we have kept it outside the predictors.
10–15 minutes. Let’s read one full text from each case. We’ll first identify the type of error, then explain what the category boundary means for that text.
We’ll use which() to find the held-out rows where prediction and reference differ. Let’s select the first error, compare its categories and probability, and print the complete statement. This is the same block we used on the Read performance with the text slide.
# 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) 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 others along the coast.
Is this a false positive or a false negative, and which metric does it lower? As we read, consider whether describing a district’s needs is enough to count as self-promotion.
Our first SVM error is gs_00013: we predict Grandstanding, while the reference is NonGrandstanding. That makes it a false positive and lowers precision. The speaker repeatedly mentions the district and asks how a program will address local needs. We might read those phrases as self-promotion, or read the full statement as a request for policy information. What hearing context would help us decide? The disagreement gives us a case to examine; it does not by itself establish that either the model or the reference is substantively correct.
hate_errors <- which(nb_prediction != parts$test$label)
cat(parts$test$text[hate_errors[1]], "\n")這隻河童來台灣亂更恐怖。
Now compare the two full texts with their category definitions. Where can we explain the boundary clearly, and where would we need more context to judge the label?
Which case has higher precision, and which has higher recall? We used different labels, languages and class frequencies, so the scores alone cannot tell us which algorithm caused the difference. If we change a model after examining these test errors, we’ll need a fresh evaluation sample.
After finishing the core practice, we can try another classifier. The blocks below are for reference and do not run in the main R script; run one separately when you’re ready to try it.
Let’s keep our training and held-out test matrices and fit logistic regression. textmodel_lr() selects its penalty by cross-validation within the training data. Complete C01–C08 before trying this block.
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)We can also reuse mlr3learners and e1071 from the grandstanding exercise to fit an SVM for hate speech. We’ll keep the small classroom vocabulary because converting it to a data frame creates a dense matrix. For a large text dataset, we’d need to consider learners or backends that support sparse features.
# 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)Here we fit the classifier with $train(), obtain a prediction object with $predict(), and compare predictions with the held-out labels using $score(). Keeping the NB split and training-derived vocabulary lets us compare the two models on the same comments.
We read three prepared CSVs: hate_speech_practice.csv (4,000 comments), hate_speech_reference.csv (1,968 human references), and grandstanding_practice.csv (3,499 excerpts). Preparation keeps the existing labels, removes duplicate texts and texts with conflicting labels, and excludes every raw human-reference text from the hate-speech practice pool before sampling. We choose the vocabulary and fit the models later in the lab.
For both classifiers, we use only text counts as predictors. The grandstanding exercise converts its 629-word vocabulary into a dense data frame, which is manageable for this example. With larger text matrices, we’d look for learners or backends that support sparse features.
The original source CSVs are in Data. We can reproduce the cleaned CSVs with prepare_practice_data.R, using base R and stringi, but we don’t need to run it for the core exercise. Data/README.md and practice_manifest.json record the cleaning rules and counts. Throughout the lab, we keep label and score fields outside X.
We split the data with mlr3 partition(), seed 7192 and label stratification. For hate speech, we fit multinomial NB through quanteda.textmodels; for grandstanding, we fit a linear SVM through mlr3. Our SVM uses type C-classification, a linear kernel, cost 1 and scale FALSE, with seed 7193 for reproducible probability fitting. These results describe our classroom model rather than a reproduction of Park’s original research model. We separate texts across the split, but authors, hearings, threads or time periods may still overlap.