W6 Take-home Lab: Document Classification

Text as Data | National Taiwan University

Before starting

Ungraded take-home practice; no submission. In this lab, we’ll fit Naive Bayes and a linear SVM, compare their predictions with the reference labels, and read the texts they classify incorrectly. Allow 60–90 minutes for sections 1–4, with extra time if you are new to R. We can try the optional models after finishing the core exercises.

Download and extract the lab ZIP, then open Lab_Session_W6.R in RStudio and read this handout alongside it. Set the working directory to the folder containing that R file and keep its Data/ folder beside it. Run section 1 once, then continue in order in the same R session. You do not need to render the source QMD.

Try each exercise before opening the worked answers. After each code block, we’ll read the output and use a question to work out what it tells us. Bring any questions to instructor or TA office hours.

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.

Reading the R code

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.

Functions used in the lab

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.

Datasets and labels

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.

Source columns and lab columns

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.

Reading the category boundaries

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.

1. Set up R

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.

Package check: install and load

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.

C01. Setup

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?

2. Hate speech: Naive Bayes with quanteda.textmodels

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.

C02. Load the Wang, Day & Wu (2022) data

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?

C03. Reserve test comments with mlr3

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?

C04a_1. Hate speech: tokenize Chinese characters

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?

C04a_2. Hate speech: turn tokens into a DFM

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?

C04b_1. Hate speech: select the training vocabulary

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?

C04b_2. Hate speech: match the test columns

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?

C05. Fit Naive Bayes

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?

C06. Predict and evaluate with mlr3

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.

C07. Inspect one held-out comment

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?

C08a. Match human-reference texts to the vocabulary

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?

C08b. Evaluate the separate human references

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.

3. Grandstanding: linear SVM with mlr3

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.

G01a. Load the Park (2021) data

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?

G01b. Reserve test excerpts with mlr3

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?

G02a_1. Grandstanding: build a corpus and tokens

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?

G02a_2. Grandstanding: normalize and count words

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.

G02a_3. Grandstanding: trim and align the vocabulary

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?

G02b_1. Grandstanding: convert the DFM for mlr3

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?

G02b_2. Grandstanding: add the target column

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?

G02c_1. mlr3: define the classification task

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?

G02c_2. mlr3: choose an SVM learner

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?

G02c_3. mlr3: train and predict

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?

G02d. Evaluate the mlr3 predictions

# 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?

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.

G03. Inspect one grandstanding prediction

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.

4. Read and compare prediction errors

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.

Follow the slide demonstration

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.

Repeat with the hate-speech model

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.

Optional: try another classifier

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.

Logistic regression with quanteda.textmodels

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)

Reuse the mlr3 SVM for hate speech

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.

Data notes

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.

Reading connections