Project 4: Document Classification

Training a spam filter on the SpamAssassin corpus and testing it on newer email

Author

Aniss Sahraoui

Published

December 6, 2026

library(tidyverse)
library(tidytext)
library(glmnet)
library(Matrix)
library(knitr)

set.seed(607)

pct <- \(x) scales::percent(x, accuracy = 0.1)

1 Overview

The goal is to classify an email as spam or ham (legitimate mail) using emails that are already labelled, then predict the class of documents the model has never seen.

The models are tested on two kinds of unseen documents:

  1. Held-out emails from the same collection as the training data, a standard 80/20 split.
  2. A later collection from the same corpus, gathered after the training emails. This is the harder and more realistic test, because spam changes over time and a filter has to keep working on messages written after it was trained.

Two models are compared: Naive Bayes, the classic spam-filter algorithm, and lasso logistic regression.

2 Data

The Apache SpamAssassin public corpus is a set of real emails collected around 2002 and released for testing spam filters. Each email is a separate raw text file, and the folder it is in gives its label. The hard_ham folder holds legitimate email that looks like spam, such as newsletters and promotional mail the recipient asked for, which makes it a useful stress test.

The archives are downloaded and unpacked here, so the report reproduces without any manual steps.

base_url <- "https://spamassassin.apache.org/old/publiccorpus/"

archives <- tribble(
  ~archive,                      ~label, ~collection,
  "20030228_easy_ham.tar.bz2",   "ham",  "training period",
  "20030228_hard_ham.tar.bz2",   "ham",  "training period",
  "20030228_spam.tar.bz2",       "spam", "training period",
  "20030228_easy_ham_2.tar.bz2", "ham",  "later",
  "20050311_spam_2.tar.bz2",     "spam", "later"
) |>
  mutate(folder = archive |> str_remove("^\\d+_") |> str_remove("\\.tar\\.bz2$"))

corpus_dir <- file.path(tempdir(), "spamassassin")
dir.create(corpus_dir, showWarnings = FALSE)

for (a in archives$archive) {
  dest <- file.path(corpus_dir, a)
  if (!file.exists(dest)) download.file(paste0(base_url, a), dest, mode = "wb", quiet = TRUE)
  untar(dest, exdir = corpus_dir)
}

Some emails are not valid UTF-8 (older mail often used Latin-1), so each file is read as raw bytes and converted where needed. Each folder also contains a cmds file, which is not an email.

read_email <- function(path) {
  bytes <- readBin(path, "raw", file.info(path)$size)
  txt <- rawToChar(bytes[bytes != as.raw(0)])
  if (!validUTF8(txt)) txt <- iconv(txt, "latin1", "UTF-8")
  txt
}

emails <- archives |>
  mutate(path = map(folder, \(f) list.files(file.path(corpus_dir, f), full.names = TRUE))) |>
  unnest(path) |>
  filter(basename(path) != "cmds") |>
  mutate(raw = map_chr(path, read_email))

emails |>
  count(collection, folder, label, name = "emails")
collection folder label emails
later easy_ham_2 ham 1400
later spam_2 spam 1396
training period easy_ham ham 2500
training period hard_ham ham 250
training period spam spam 500

3 From raw email to text

3.1 Header and body

A raw email is a block of header lines (From:, Subject:, routing information), then a blank line, then the body. Only the subject and body are used for classification.

The other header fields are left out on purpose. They describe how an email was delivered and collected, not what it says, and in this corpus they nearly give the answer away:

emails <- emails |>
  mutate(
    raw      = str_replace_all(raw, "\r\n", "\n"),
    split_at = str_locate(raw, "\n\n")[, "start"],
    header   = if_else(is.na(split_at), raw, str_sub(raw, 1, split_at)),
    body     = if_else(is.na(split_at), "", str_sub(raw, split_at + 2)),
    subject  = str_match(header, "(?im)^subject:[ \\t]*(.*)$")[, 2] |> replace_na("")
  )

emails |>
  filter(collection == "training period") |>
  group_by(label) |>
  summarise(
    `has List-Id`          = mean(str_detect(header, "(?im)^list-id:")),
    `has List-Unsubscribe` = mean(str_detect(header, "(?im)^list-unsubscribe:")),
    `has X-Beenthere`      = mean(str_detect(header, "(?im)^x-beenthere:"))
  ) |>
  mutate(across(-label, scales::percent))
label has List-Id has List-Unsubscribe has X-Beenthere
ham 55% 59% 54%
spam 14% 8% 13%

Most of the ham was collected from mailing lists, so it carries list headers that most spam does not. A model trained on headers would learn “came from a mailing list”, which says nothing about whether a new email in someone’s inbox is spam.

3.2 Cleaning the body

Email bodies are messy. Many are encoded for transport, many are HTML, and many contain MIME section markers. The cleaning has two steps.

Decoding removes transport artefacts: quoted-printable line breaks and escapes (=20, =\n), long base64-encoded lines, MIME boundaries and part headers (Content-Type: ...).

Converting to words removes HTML: <style> and <script> blocks first, since their CSS would otherwise leak words like “font” and “text” into the vocabulary, then tags and entities. URLs, email addresses, dollar amounts and numbers are replaced with placeholder words (urltoken, emailtoken, dollartoken, numtoken). The exact link or number does not generalise, but the fact that one was there might.

decode_body <- function(x) {
  x |>
    str_replace_all("=\\n", "") |>                               # quoted-printable soft breaks
    str_replace_all("=[0-9A-Fa-f]{2}", " ") |>                   # quoted-printable escapes
    str_replace_all("(?m)^[A-Za-z0-9+/=]{60,}$", " ") |>         # base64-encoded lines
    str_replace_all("(?im)^(--.*|content-[a-z-]+:.*)$", " ")     # MIME boundaries and part headers
}

to_words <- function(x) {
  x |>
    str_replace_all("(?is)<(style|script)\\b.*?</\\1>", " ") |>
    str_replace_all("(?i)(https?://|www\\.)[^\\s\"'<>]+", " urltoken ") |>
    str_replace_all("(?i)<a\\b[^>]*urltoken[^>]*>", " urltoken ") |>  # keep links inside <a> tags
    str_replace_all("<[^>]*>", " ") |>
    str_replace_all("&[A-Za-z]+;|&#\\d+;", " ") |>
    str_replace_all("[\\w.+-]+@[\\w-]+\\.[\\w.-]+", " emailtoken ") |>
    str_replace_all("\\$\\s?\\d", " dollartoken ") |>
    str_replace_all("\\d+", " numtoken ")
}

emails <- emails |>
  mutate(
    body_decoded = decode_body(body),
    text         = str_squish(paste(subject, to_words(body_decoded))),
    # A few features that are not single words
    is_html      = str_detect(body_decoded, "(?i)<(html|body|table|font|div|p|br)\\b"),
    n_urls       = str_count(body_decoded, "(?i)https?://|www\\."),
    n_exclaim    = str_count(text, "!"),
    cap_share    = str_count(text, "[A-Z]") / pmax(str_count(text, "[A-Za-z]"), 1)
  )

The same email can appear more than once, for example when a message was sent to several lists. Duplicates are removed within each collection. Any email in the later collection that also appears in the training period is dropped, so that every “new” document really is new.

main <- emails |>
  filter(collection == "training period") |>
  distinct(text, .keep_all = TRUE) |>
  mutate(id = row_number())

later <- emails |>
  filter(collection == "later") |>
  distinct(text, .keep_all = TRUE) |>
  anti_join(main, by = "text") |>
  mutate(id = row_number())

bind_rows(main, later) |>
  count(collection, folder, label, name = "emails after removing duplicates")
collection folder label emails after removing duplicates
later easy_ham_2 ham 1387
later spam_2 spam 1317
training period easy_ham ham 2465
training period hard_ham ham 250
training period spam spam 477

4 Training and test sets

The training-period emails are split 80/20. The split is stratified by folder, so the test set has the same mix of easy ham, hard ham and spam as the training set.

train <- main |>
  group_by(folder) |>
  slice_sample(prop = 0.8) |>
  ungroup()

test <- main |>
  anti_join(train, by = "id")

tibble(set = c("train", "test", "later collection"),
       emails = c(nrow(train), nrow(test), nrow(later)),
       spam_share = pct(c(mean(train$label == "spam"),
                                      mean(test$label == "spam"),
                                      mean(later$label == "spam"))))
set emails spam_share
train 2553 14.9%
test 639 15.0%
later collection 2704 48.7%

The training data is about 15% spam. The later collection is roughly half spam, which matters when reading precision later on.

4.1 Document-term matrix

Each email is split into words with tidytext. Stop words, and anything that is not 2 to 20 letters long, are removed. The vocabulary is built from the training set only, keeping words that appear in at least 10 training emails. Building it from all emails would let information from the test set leak into the model.

tokenize <- function(df) {
  df |>
    select(id, text) |>
    unnest_tokens(word, text) |>
    anti_join(stop_words, by = "word") |>
    filter(str_detect(word, "^[a-z]{2,20}$"))
}

train_tokens <- tokenize(train)

vocab <- train_tokens |>
  distinct(id, word) |>
  count(word) |>
  filter(n >= 10) |>
  pull(word) |>
  sort()

# Sparse matrix: one row per email, one column per vocabulary word, cells are word counts
build_dtm <- function(df, vocab) {
  counts <- tokenize(df) |>
    filter(word %in% vocab) |>
    count(id, word)
  sparseMatrix(i = match(counts$id, df$id), j = match(counts$word, vocab), x = counts$n,
               dims = c(nrow(df), length(vocab)), dimnames = list(NULL, vocab))
}

X_train <- build_dtm(train, vocab)
X_test  <- build_dtm(test, vocab)
X_later <- build_dtm(later, vocab)

dim(X_train)
[1] 2553 4159

The matrix has 4,159 columns and is 98.5% zeros, which is why it is stored as a sparse matrix.

5 Models

5.1 Naive Bayes

Multinomial Naive Bayes is the classic spam filter. For each class it estimates how likely each word is, then scores a new email by adding up the log-probabilities of its words. It assumes words are independent of each other, which is false, but it works well in practice. It is short enough to write out directly. Laplace smoothing (alpha = 1) stops a word that never appeared in one class from making that class impossible.

nb_fit <- function(X, y, alpha = 1) {
  classes <- c("ham", "spam")
  prior <- as.numeric(table(factor(y, classes))) / length(y)
  word_counts <- sapply(classes, \(k) colSums(X[y == k, , drop = FALSE]))
  log_lik <- log(sweep(word_counts + alpha, 2, colSums(word_counts) + alpha * nrow(word_counts), "/"))
  list(log_prior = setNames(log(prior), classes), log_lik = log_lik)
}

nb_predict <- function(model, X) {
  scores <- as.matrix(X %*% model$log_lik)
  log_odds <- (scores[, "spam"] + model$log_prior["spam"]) -
              (scores[, "ham"]  + model$log_prior["ham"])
  plogis(log_odds)   # probability of spam
}

nb <- nb_fit(X_train, train$label)

5.2 Lasso logistic regression

Logistic regression models the log-odds of spam as a weighted sum of features. With thousands of word columns it would overfit, so the lasso penalty shrinks most weights to exactly zero and keeps only the useful words. The penalty strength is chosen by 5-fold cross-validation using the lambda.1se rule (the simplest model within one standard error of the best).

Here words are coded as present/absent rather than counted, and the four extra features from section 3.2 are added.

lasso_matrix <- function(X, df) {
  extras <- df |>
    transmute(cap_share,
              log_urls    = log1p(n_urls),
              log_exclaim = log1p(n_exclaim),
              is_html     = as.numeric(is_html)) |>
    as.matrix()
  cbind((X > 0) * 1, Matrix(extras, sparse = TRUE))
}

cv_lasso <- cv.glmnet(lasso_matrix(X_train, train), factor(train$label, c("ham", "spam")),
                      family = "binomial", alpha = 1, nfolds = 5)

lasso_predict <- function(X, df) {
  as.numeric(predict(cv_lasso, lasso_matrix(X, df), s = "lambda.1se", type = "response"))
}

n_kept <- sum(coef(cv_lasso, s = "lambda.1se")[-1] != 0)

The lasso keeps 185 of the 4,163 available features.

6 Results

6.1 Evaluation measures

An email is predicted as spam when its predicted probability is at least 0.5. Treating spam as the “positive” class:

  • Precision: of the emails flagged as spam, the share that really were spam.
  • Recall: of the real spam, the share that was caught.
  • False positive rate: of the real ham, the share wrongly flagged. For a user this is the costliest mistake, because it means real email goes missing.
evaluate <- function(truth, prob, threshold = 0.5) {
  pred <- if_else(prob >= threshold, "spam", "ham")
  tp <- sum(pred == "spam" & truth == "spam")
  fp <- sum(pred == "spam" & truth == "ham")
  fn <- sum(pred == "ham"  & truth == "spam")
  tn <- sum(pred == "ham"  & truth == "ham")
  tibble(accuracy = (tp + tn) / length(truth),
         precision = tp / (tp + fp),
         recall = tp / (tp + fn),
         f1 = 2 * tp / (2 * tp + fp + fn),
         false_pos_rate = fp / (fp + tn),
         ham_flagged = fp,
         spam_missed = fn)
}

predictions <- bind_rows(
  test  |> mutate(set = "held-out test",    nb = nb_predict(nb, X_test),  lasso = lasso_predict(X_test, test)),
  later |> mutate(set = "later collection", nb = nb_predict(nb, X_later), lasso = lasso_predict(X_later, later))
) |>
  pivot_longer(c(nb, lasso), names_to = "model", values_to = "prob") |>
  mutate(model = recode(model, nb = "Naive Bayes", lasso = "Lasso logistic"))

results <- predictions |>
  group_by(set, model) |>
  summarise(evaluate(label, prob), .groups = "drop")

results |>
  mutate(across(accuracy:false_pos_rate, pct))
set model accuracy precision recall f1 false_pos_rate ham_flagged spam_missed
held-out test Lasso logistic 96.7% 91.2% 86.5% 88.8% 1.5% 8 13
held-out test Naive Bayes 95.9% 86.5% 86.5% 86.5% 2.4% 13 13
later collection Lasso logistic 89.6% 99.5% 79.1% 88.2% 0.4% 5 275
later collection Naive Bayes 90.9% 99.0% 82.2% 89.8% 0.8% 11 234

6.2 Held-out test

On held-out emails from the same period, both models do well. Naive Bayes is 95.9% accurate and lasso logistic regression 96.7%. The lasso flags fewer real emails (8 against 13) while catching the same share of spam.

Accuracy alone flatters both models, because 85% of the test set is ham: a “model” that called everything ham would score about 85%. Recall is the more telling figure. Both models catch about 86.5% of spam.

6.3 Where the false positives come from

predictions |>
  filter(set == "held-out test") |>
  group_by(model, folder) |>
  summarise(emails = n(),
            flagged_as_spam = sum(prob >= 0.5),
            share_flagged = pct(mean(prob >= 0.5)),
            .groups = "drop") |>
  arrange(model, folder)
model folder emails flagged_as_spam share_flagged
Lasso logistic easy_ham 493 0 0.0%
Lasso logistic hard_ham 50 8 16.0%
Lasso logistic spam 96 83 86.5%
Naive Bayes easy_ham 493 5 1.0%
Naive Bayes hard_ham 50 8 16.0%
Naive Bayes spam 96 83 86.5%

The lasso’s mistakes on real email are all in hard_ham: it flags 8 of the 50 hard-ham test emails and 0 of the 493 easy-ham emails. Naive Bayes flags the same number of hard-ham emails and also a handful of ordinary ones, which is why its false positive rate is higher. That is expected: hard ham is commercial mail the recipient signed up for, and it uses the same words as spam (“offer”, “click”, “free”). A word-based filter has no way to know the recipient wanted it.

6.4 The later collection

This is the more important test, because the documents come from a different, later period.

results |>
  select(set, model, precision, recall, false_pos_rate) |>
  pivot_longer(c(precision, recall, false_pos_rate), names_to = "measure") |>
  mutate(measure = recode(measure, precision = "Precision", recall = "Recall",
                          false_pos_rate = "False positive rate"),
         measure = factor(measure, c("Precision", "Recall", "False positive rate"))) |>
  ggplot(aes(set, value, fill = model)) +
  geom_col(position = "dodge") +
  facet_wrap(~measure, scales = "free_y") +
  scale_y_continuous(labels = scales::percent) +
  labs(x = NULL, y = NULL, fill = NULL,
       title = "Recall drops on the later collection; false positives do not rise") +
  theme(legend.position = "bottom")

Two things change on the later emails.

Recall drops. The lasso catches 86.5% of held-out spam but only 79.1% of the later spam, missing 275 messages. Reading a sample of the missed spam shows why. Most of it is not unreadable or badly parsed; it is spam about topics that barely appeared in the training spam, such as immigration lotteries and overseas manufacturing offers. The model learned the vocabulary of 2002 spam, and spam moved on.

Precision rises, but that is mostly the data. Precision depends on how much of the data is spam. The later collection is about half spam against 15% in training, so a flagged email is much more likely to be spam whatever the model does. The false positive rate, which does not depend on the mix, is the fairer comparison, and it stays low: 0.4% of later ham is flagged.

6.5 Choosing a stricter threshold

A threshold of 0.5 treats both mistakes as equally bad, but losing a real email is worse than seeing one extra spam. Raising the threshold flags fewer emails:

lasso_preds <- predictions |> filter(model == "Lasso logistic")

map_dfr(c(0.3, 0.5, 0.7, 0.9), \(th) {
  lasso_preds |>
    group_by(set) |>
    summarise(evaluate(label, prob, th), .groups = "drop") |>
    mutate(threshold = th)
}) |>
  select(set, threshold, recall, false_pos_rate, ham_flagged, spam_missed) |>
  mutate(across(c(recall, false_pos_rate), pct)) |>
  arrange(set, threshold)
set threshold recall false_pos_rate ham_flagged spam_missed
held-out test 0.3 90.6% 2.2% 12 9
held-out test 0.5 86.5% 1.5% 8 13
held-out test 0.7 81.2% 1.3% 7 18
held-out test 0.9 59.4% 0.9% 5 39
later collection 0.3 85.8% 0.8% 11 187
later collection 0.5 79.1% 0.4% 5 275
later collection 0.7 70.5% 0.1% 1 388
later collection 0.9 51.1% 0.0% 0 644

On the held-out set, moving from 0.5 to 0.7 removes only one false positive but lets five more spam emails through. At 0.9, recall falls to about 60%. For this model 0.5 to 0.7 is the sensible range; a real filter would usually also send borderline mail to a “possible spam” folder rather than deleting it.

6.6 Retraining with newer email

If the drop in recall is caused by spam changing over time, adding newer examples to the training data should recover it. To test that, the later collection is split in half. One half is added to the training data, the vocabulary and both models are rebuilt, and the other half is used for testing.

later_split <- later |>
  group_by(folder) |>
  mutate(half = if_else(row_number() %in% sample(n(), floor(n() / 2)), "train", "test")) |>
  ungroup()

later_train <- later_split |> filter(half == "train")
later_test  <- later_split |> filter(half == "test")

# Ids must be unique once the two collections are combined
combined <- bind_rows(train, later_train) |> mutate(id = row_number())
later_test <- later_test |> mutate(id = row_number())

vocab2 <- tokenize(combined) |>
  distinct(id, word) |>
  count(word) |>
  filter(n >= 10) |>
  pull(word) |>
  sort()

X_combined <- build_dtm(combined, vocab2)
X_later_test <- build_dtm(later_test, vocab2)

nb2 <- nb_fit(X_combined, combined$label)
cv_lasso2 <- cv.glmnet(lasso_matrix(X_combined, combined), factor(combined$label, c("ham", "spam")),
                       family = "binomial", alpha = 1, nfolds = 5)

# For comparison: the original models on the same test half
X_later_test_v1 <- build_dtm(later_test, vocab)

retrain_results <- bind_rows(
  evaluate(later_test$label, nb_predict(nb, X_later_test_v1)) |>
    mutate(model = "Naive Bayes", training = "training period only"),
  evaluate(later_test$label, nb_predict(nb2, X_later_test)) |>
    mutate(model = "Naive Bayes", training = "plus half of later emails"),
  evaluate(later_test$label, lasso_predict(X_later_test_v1, later_test)) |>
    mutate(model = "Lasso logistic", training = "training period only"),
  evaluate(later_test$label,
           as.numeric(predict(cv_lasso2, lasso_matrix(X_later_test, later_test),
                              s = "lambda.1se", type = "response"))) |>
    mutate(model = "Lasso logistic", training = "plus half of later emails")
)

retrain_results |>
  select(model, training, accuracy, recall, false_pos_rate, spam_missed) |>
  mutate(across(c(accuracy, recall, false_pos_rate), pct))
model training accuracy recall false_pos_rate spam_missed
Naive Bayes training period only 91.6% 83.8% 0.9% 107
Naive Bayes plus half of later emails 95.6% 91.5% 0.4% 56
Lasso logistic training period only 89.7% 79.1% 0.1% 138
Lasso logistic plus half of later emails 97.0% 94.2% 0.3% 38

Retraining more than recovers the lost recall. On the same test half, the lasso’s recall rises from 79.1% to 94.2%, and Naive Bayes’s from 83.8% to 91.5%, while the false positive rate stays below 1%. This supports the explanation above: the model did not fail because the newer emails were harder to read, it failed because it had never seen their kind of spam. This is why real spam filters are retrained continually.

7 What the models learned

The lasso’s coefficients show which features push an email towards spam (positive) or ham (negative).

coefs <- coef(cv_lasso, s = "lambda.1se")
coefs <- tibble(feature = rownames(coefs), weight = as.numeric(coefs)) |>
  filter(feature != "(Intercept)", weight != 0)

bind_rows(slice_max(coefs, weight, n = 15), slice_min(coefs, weight, n = 15)) |>
  mutate(direction = if_else(weight > 0, "pushes towards spam", "pushes towards ham"),
         feature = fct_reorder(feature, weight)) |>
  ggplot(aes(weight, feature, fill = direction)) +
  geom_col() +
  scale_fill_manual(values = c("pushes towards spam" = "firebrick",
                               "pushes towards ham" = "steelblue")) +
  labs(x = "Lasso coefficient", y = NULL, fill = NULL,
       title = "The 15 strongest spam and ham features") +
  theme(legend.position = "bottom")

The spam side reads like a list of spam clichés: formal greetings to strangers (“sir”, “madam”), “guaranteed”, “click”, “mortgage”, “deposit”. The share of capital letters has the largest coefficient, but it is measured from 0 to 1 while words are 0 or 1, so the two are not directly comparable: an email with 10 percentage points more capitals gets about the same push as one strong spam word. An HTML body also pushes towards spam. Both are classic spam signals. A few foreign-language words (“du”, “pa”) also appear, because the foreign-language email in the training data is mostly spam.

The ham side reflects where the ham came from: technical mailing lists. Words like “wrote” (as in “Bob wrote:” in a quoted reply), “settings”, “seminar” and “analysis” are typical of discussion between people who know each other. This is a weakness as much as a strength. The filter has learned what these mailing lists look like, and it would be less sure about a personal email from a relative that happens to mention money.

8 Conclusions

  • Both models classify held-out emails well. About 96–97% are classified correctly, with the lasso slightly ahead and making fewer false positives. The simple Naive Bayes, written in about ten lines of R, is nearly as good.
  • Most false positives are “hard ham”, legitimate commercial mail that uses the language of spam. Word frequencies alone cannot tell wanted marketing from unwanted.
  • Newer documents are the real test. On the later collection the false positive rate stays low, but recall falls from about 86% to 79–82%, because the newer spam covers topics the model never saw. Adding half of the newer emails to the training data more than recovers that recall, so the drop is caused by spam changing over time rather than by the model breaking.
  • Data preparation mattered more than model choice. Removing the headers avoided a model that only learns “came from a mailing list”. Stripping <style> blocks removed CSS words that were being treated as evidence. Building the vocabulary from the training set alone kept the test honest.

A next step would be to give the model information that words cannot capture, such as whether the sender is in the recipient’s address book or whether they have replied to them before. That is exactly what would separate hard ham from spam.