# install.packages(c("tidyverse", "quanteda", "quanteda.textmodels", "glmnet", "Matrix"))
library(tidyverse)
library(quanteda)
library(quanteda.textmodels)
library(glmnet)
library(Matrix)
set.seed(607)Project 4: Document Classification — Code Base
Introduction
Email spam filtering is a practical application of document classification in which previously labeled messages are used to predict the class of new messages. For this project, I plan to use the SpamAssassin public corpus to develop a classification model that distinguishes spam from legitimate email (ham). My primary question is: How accurately can the textual content of an email be used to predict whether it is spam, and which classification method provides the best balance between detecting spam and avoiding the misclassification of legitimate messages?
Data Collection and Preparation
I use the February 2003 easy-ham, hard-ham and spam archives. Including hard ham makes the task more realistic than comparing spam only with easily recognized legitimate messages. The archives are downloaded into a temporary directory, so no local data files are required. Install the packages listed below once if they are not already available.
Anticipated Data Challenges
One challenge is that the emails are unstructured text files rather than a conventional rectangular dataset. Differences in encoding, MIME formatting, HTML content, and message structure may make extracting readable text difficult. I will inspect problematic files and document any exclusions or cleaning decisions.
Another concern is class imbalance. If one class is substantially larger than the other, a model may achieve high accuracy simply by favoring the majority class. Stratified sampling and class-specific evaluation metrics will help address this issue. If needed, I will investigate class weighting or resampling within the training data only.
Data leakage is another important consideration. Email headers may contain spam-filter annotations, and duplicate messages may appear across the collections. Including these indicators or allowing duplicate messages into both training and testing datasets could produce unrealistically high performance. I will exclude label-revealing metadata and keep the test data separate from feature selection and model tuning.
Finally, the corpus contains historical emails that may not reflect current spam tactics. Spam messages can also contain deliberately misspelled words, unusual symbols, and misleading language that complicate text preprocessing. Therefore, strong performance on this dataset would not necessarily indicate that the model would perform equally well on modern email traffic.
Import labeled emails
Each message is read as text. I retain the subject and body but discard other headers, including any spam-filter labels. This is a lightweight parser rather than a complete MIME decoder; encoded attachments and HTML may not be fully recovered.
base_url <- "https://spamassassin.apache.org/old/publiccorpus/"
archives <- c(easy_ham = "20030228_easy_ham.tar.bz2",
hard_ham = "20030228_hard_ham.tar.bz2",
spam = "20030228_spam.tar.bz2")
read_email <- function(path) {
x <- tryCatch(readLines(path, warn = FALSE, encoding = "latin1"),
error = function(e) character())
x <- iconv(x, from = "", to = "UTF-8", sub = " ")
x[is.na(x)] <- ""
sep <- which(trimws(x) == "")
if (!length(sep)) return("")
k <- sep[1]
headers <- if (k > 1) x[seq_len(k - 1)] else character()
subject <- sub("^Subject:[[:space:]]*", "", grep("^Subject:", headers,
ignore.case = TRUE, value = TRUE), ignore.case = TRUE)
body <- if (k < length(x)) x[seq.int(k + 1, length(x))] else character()
paste(c(subject, body), collapse = " ")
}
read_archive <- function(group, archive) {
folder <- tempfile(pattern = group)
dir.create(folder)
dest <- file.path(folder, archive)
download.file(paste0(base_url, archive), dest, mode = "wb", quiet = TRUE)
untar(dest, exdir = folder)
paths <- list.files(file.path(folder, group), recursive = TRUE, full.names = TRUE)
paths <- paths[grepl("^[0-9]+\\.", basename(paths))]
stopifnot(length(paths) > 0)
tibble(id = paste(group, basename(paths), sep = "/"),
source = group, label = ifelse(group == "spam", "spam", "ham"),
text = vapply(paths, read_email, character(1)))
}
options(timeout = max(300, getOption("timeout")))
raw <- purrr::imap_dfr(archives, ~ read_archive(.y, .x))
raw |> count(source, label)# A tibble: 3 × 3
source label n
<chr> <chr> <int>
1 easy_ham ham 2500
2 hard_ham ham 250
3 spam spam 500
Clean text and audit exclusions
I replace URLs and currency symbols with meaningful tokens, remove HTML tags and normalize whitespace. Exact duplicates are removed after normalization, including conflicting labels, before splitting. Near-duplicate campaigns may remain and are a limitation.
clean_text <- function(x) {
x |> str_to_lower() |>
str_replace_all("https?://[^[:space:]<>]+|www\\.[^[:space:]<>]+", " urltoken ") |>
str_replace_all("[$€£]", " moneytoken ") |>
str_replace_all("<[^>]+>", " ") |>
str_replace_all("[^[:alnum:] ]", " ") |>
str_squish()
}
cleaned <- raw |> mutate(text = clean_text(text)) |> filter(nchar(text) > 0)
conflicts <- cleaned |> group_by(text) |> summarise(n_labels = n_distinct(label), .groups = "drop") |> filter(n_labels > 1)
emails <- cleaned |> anti_join(conflicts, by = "text") |> distinct(text, .keep_all = TRUE) |>
mutate(label = factor(label, levels = c("ham", "spam")))
tibble(imported = nrow(raw), nonempty = nrow(cleaned), retained = nrow(emails),
excluded = nrow(raw) - nrow(emails), conflicting_texts = nrow(conflicts))# A tibble: 1 × 5
imported nonempty retained excluded conflicting_texts
<int> <int> <int> <int> <int>
1 3250 3250 3201 49 0
emails |> count(label) |> ggplot(aes(label, n, fill = label)) +
geom_col(show.legend = FALSE) + labs(title = "Class distribution after cleaning", x = NULL, y = "Emails") + theme_minimal()Model development
Stratified split and feature construction
I reserve approximately 20% of each class for final testing. Within each training fold, the vocabulary is learned from that fold alone. Words occurring in fewer than five documents are removed. TF-IDF uses smoothed inverse document frequencies learned only from the corresponding training partition.
train_ids <- emails |> group_by(label) |> slice_sample(prop = .8) |> ungroup() |> pull(id)
train <- emails |> filter(id %in% train_ids)
test <- emails |> filter(!id %in% train_ids)
stopifnot(!any(train$text %in% test$text))
bind_rows(train |> count(label) |> mutate(split = "Train"),
test |> count(label) |> mutate(split = "Test"))# A tibble: 4 × 3
label n split
<fct> <int> <chr>
1 ham 2176 Train
2 spam 384 Train
3 ham 545 Test
4 spam 96 Test
make_dfm <- function(d) {
tokens(d$text, remove_punct = TRUE, remove_numbers = TRUE) |>
tokens_remove(stopwords("en")) |> dfm()
}
features <- function(a, b) {
x <- dfm_trim(make_dfm(a), min_docfreq = 5)
z <- dfm_match(make_dfm(b), features = featnames(x))
m <- methods::as(x, "dgCMatrix")
n <- methods::as(z, "dgCMatrix")
idf <- log((1 + nrow(m))/(1 + Matrix::colSums(m > 0))) + 1
weight <- function(v) Matrix::Diagonal(x = 1/pmax(Matrix::rowSums(v), 1)) %*% v %*% Matrix::Diagonal(x = idf)
list(count_train = x, count_test = z, tf_train = weight(m), tf_test = weight(n))
}
metrics <- function(actual, predicted) {
tp <- sum(actual == "spam" & predicted == "spam")
tn <- sum(actual == "ham" & predicted == "ham")
fp <- sum(actual == "ham" & predicted == "spam")
fn <- sum(actual == "spam" & predicted == "ham")
safe <- function(a,b) if (b == 0) 0 else a/b
tibble(accuracy = safe(tp+tn,tp+tn+fp+fn), precision = safe(tp,tp+fp),
recall = safe(tp,tp+fn), specificity = safe(tn,tn+fp),
f1 = safe(2*tp,2*tp+fp+fn), fp = fp, fn = fn)
}Cross-validation and tuning
I use five stratified folds to compare Laplace smoothing values for multinomial Naive Bayes and penalty values for ridge logistic regression. F1 is the selection metric because it balances spam precision and recall. The test set is not used during tuning. A probability threshold of 0.5 is fixed in advance.
train <- train |> group_by(label) |> mutate(fold = sample(rep(1:5, length.out = n()))) |> ungroup()
smooth <- c(0.5, 1, 2)
lambdas <- c(.1, .01, .001, .0001)
cv <- map_dfr(1:5, function(k) {
a <- filter(train, fold != k); b <- filter(train, fold == k)
f <- features(a,b)
nb <- map_dfr(smooth, function(s) {
model <- textmodel_nb(f$count_train, a$label, smooth = s, distribution = "multinomial")
metrics(b$label, predict(model, newdata = f$count_test)) |> mutate(model = "Naive Bayes", parameter = s)
})
lr <- glmnet(f$tf_train, as.integer(a$label == "spam"), family = "binomial", alpha = 0, lambda = lambdas)
lg <- map_dfr(lambdas, function(l) {
prob <- as.numeric(predict(lr, newx = f$tf_test, s = l, type = "response"))
metrics(b$label, ifelse(prob >= .5, "spam", "ham")) |> mutate(model = "Logistic regression", parameter = l)
})
bind_rows(nb, lg) |> mutate(fold = k)
})
cv_summary <- cv |> group_by(model, parameter) |> summarise(mean_f1 = mean(f1), sd_f1 = sd(f1), .groups = "drop")
best <- cv_summary |> group_by(model) |> slice_max(mean_f1, n = 1, with_ties = FALSE) |> ungroup()
cv_summary# A tibble: 7 × 4
model parameter mean_f1 sd_f1
<chr> <dbl> <dbl> <dbl>
1 Logistic regression 0.0001 0.887 0.0261
2 Logistic regression 0.001 0.889 0.0267
3 Logistic regression 0.01 0.886 0.0262
4 Logistic regression 0.1 0.870 0.0331
5 Naive Bayes 0.5 0.927 0.0167
6 Naive Bayes 1 0.925 0.0220
7 Naive Bayes 2 0.919 0.0184
best# A tibble: 2 × 4
model parameter mean_f1 sd_f1
<chr> <dbl> <dbl> <dbl>
1 Logistic regression 0.001 0.889 0.0267
2 Naive Bayes 0.5 0.927 0.0167
cv_summary |> ggplot(aes(factor(parameter), mean_f1, group = 1)) + geom_point() + geom_line() +
facet_wrap(~model, scales = "free_x") + labs(x = "Tuning parameter", y = "Mean validation F1", title = "Training-only cross-validation") + theme_minimal()Held-out evaluation
I refit the two models on all training emails using the selected parameters. A majority-class baseline shows whether the text classifiers improve on simply predicting the most common label. False positives are especially important because legitimate messages could be lost.
f <- features(train,test)
s <- best$parameter[best$model == "Naive Bayes"]
l <- best$parameter[best$model == "Logistic regression"]
nb <- textmodel_nb(f$count_train, train$label, smooth = s, distribution = "multinomial")
lr <- glmnet(f$tf_train, as.integer(train$label == "spam"), family = "binomial", alpha = 0, lambda = lambdas)
majority <- names(which.max(table(train$label)))
predictions <- tibble(actual = test$label,
Baseline = rep(majority, nrow(test)),
`Naive Bayes` = as.character(predict(nb, newdata = f$count_test)),
`Logistic regression` = ifelse(as.numeric(predict(lr, newx = f$tf_test, s = l, type = "response")) >= .5, "spam", "ham")) |>
pivot_longer(-actual, names_to = "model", values_to = "predicted")
results <- predictions |> group_by(model) |> group_modify(~metrics(.x$actual,.x$predicted)) |> ungroup()
knitr::kable(results, digits = 3)| model | accuracy | precision | recall | specificity | f1 | fp | fn |
|---|---|---|---|---|---|---|---|
| Baseline | 0.850 | 0.000 | 0.000 | 1.000 | 0.000 | 0 | 96 |
| Logistic regression | 0.967 | 0.895 | 0.885 | 0.982 | 0.890 | 10 | 11 |
| Naive Bayes | 0.972 | 0.898 | 0.917 | 0.982 | 0.907 | 10 | 8 |
Visual comparison and errors
The confusion matrices show correct and incorrect classifications. The metric plot compares accuracy, precision, recall, specificity and F1 on a common scale. Precision is defined as zero when a classifier predicts no spam.
predictions |> mutate(predicted = factor(predicted, levels = c("ham","spam"))) |>
count(model, actual, predicted, .drop = FALSE) |>
ggplot(aes(predicted, actual, fill = n)) + geom_tile() + geom_text(aes(label = n)) +
facet_wrap(~model) + scale_fill_gradient(low = "white", high = "steelblue") +
labs(title = "Held-out confusion matrices", x = "Predicted", y = "Actual") + theme_minimal()results |> select(-fp,-fn) |> pivot_longer(-model, names_to = "metric", values_to = "value") |>
ggplot(aes(value, metric, color = model)) + geom_point(position = position_dodge(width = .5), size = 3) +
scale_x_continuous(limits = c(0,1), labels = scales::label_percent()) +
labs(title = "Test-set classification performance", x = NULL, y = NULL) + theme_minimal()Inspect influential words
Ridge logistic regression coefficients indicate the direction of association between a feature and predicted spam, conditional on the other features. They do not establish causality.
co <- as.matrix(coef(lr, s = l))
terms <- tibble(word = rownames(co), coefficient = as.numeric(co[,1])) |> filter(word != "(Intercept)")
bind_rows(slice_max(terms, coefficient, n = 10, with_ties = FALSE),
slice_min(terms, coefficient, n = 10, with_ties = FALSE)) |>
ggplot(aes(coefficient, reorder(word, coefficient), fill = coefficient > 0)) +
geom_col(show.legend = FALSE) + labs(title = "Words associated with spam and ham", x = "Logistic regression coefficient", y = NULL) + theme_minimal()Conclusions
The model chosen by training cross-validation is Naive Bayes. On the held-out test set, the classifier with the highest observed F1 is Naive Bayes, with F1 of 0.907. The majority baseline has accuracy of 85.0%. These results are calculated at render time rather than assumed in advance.
For deployment, I would prioritize the training-selected model and consider the cost of false positives before selecting a threshold. A quarantine folder rather than automatic deletion would reduce the consequences of misclassification. The held-out results are descriptive estimates from a single historical corpus, not proof of performance on modern emails. Future work should use MIME-aware parsing, group near-duplicate campaigns before splitting, evaluate newer independent messages and tune thresholds on validation data using business-specific error costs. Comparing word counts and TF-IDF within each algorithm would also help separate the effect of feature representation from model choice.
References
Apache SpamAssassin. (n.d.). Public mail corpus. https://spamassassin.apache.org/old/publiccorpus/
Silge, J., & Robinson, D. (2017). Text mining with R: A tidy approach. O’Reilly Media. https://www.tidytextmining.com/