Project4: Document Classification

Author

Tenzin Thakuri

Introduction

For this project (Document Classification), I will use the SpamAssassin public email corpus from SpamAssassin Public Corpus to build a model that predicts whether a new email is spam or ham (legitimate email).

Datasets:

-Ham dataset: 20021010_easy_ham.tar.bz2

-Spam dataset: 20021010_spam.tar.bz2

Loading the required libraries

library(tidyverse)          # Data manipulation and cleaning
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.0     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.3     ✔ tibble    3.3.1
✔ lubridate 1.9.5     ✔ tidyr     1.3.2
✔ purrr     1.2.1     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(rsample)            # Splitting data into training and testing sets
library(quanteda)           # Text analysis and document-feature matrices
Package version: 4.5.1
Unicode version: 15.1
ICU version: 74.1
Parallel computing: 14 of 14 threads used.
See https://quanteda.io for tutorials and examples.
library(tidytext)            # Tokenization of email text
library(quanteda.textmodels) # Naive Bayes classification model
library(caret)               # Model evaluation and confusion matrix
Loading required package: lattice

Attaching package: 'caret'

The following object is masked from 'package:rsample':

    calibration

The following object is masked from 'package:purrr':

    lift

Code base

base_url <- "https://spamassassin.apache.org/old/publiccorpus/"
# Create a directory to store the downloaded and extracted datasets
dir.create("data", showWarnings = FALSE)
# Define a function to download and extract the email corpus
get_corpus <- function(file) {
  dest <- file.path("data", file)
  if (!file.exists(dest)) download.file(paste0(base_url, file), dest, mode = "wb")
    # Extract the archived email files into the data directory
  # untar() is an R function used to extract files from a compressed archive, such as .tar, .tar.gz, or .tar.bz2.
  untar(dest, exdir = "data")
}
# Download and extract the ham and spam email data set
get_corpus("20021010_easy_ham.tar.bz2")
get_corpus("20021010_spam.tar.bz2")

ham_files  <- list.files("data/easy_ham", full.names = TRUE)
spam_files <- list.files("data/spam",     full.names = TRUE)
# Count numnber of emails in each dataset
length(ham_files)
[1] 2551
length(spam_files)
[1] 501
head(ham_files)
[1] "data/easy_ham/0001.ea7e79d3153e7469e7a9c3e0af6a357e"
[2] "data/easy_ham/0002.b3120c4bcbf3101e661161ee7efcb8bf"
[3] "data/easy_ham/0003.acfc5ad94bbd27118a0d8685d18c89dd"
[4] "data/easy_ham/0004.e8d5727378ddde5c3be181df593f1712"
[5] "data/easy_ham/0005.8c3b9e9c0f3f183ddaf7592a11b99957"
[6] "data/easy_ham/0006.ee8b0dba12856155222be180ba122058"
head(spam_files)
[1] "data/spam/0000.7b1b73cf36cf9dbc3d64e3f2ee2b91f1"
[2] "data/spam/0001.bfc8d64d12b325ff385cca8d07b84288"
[3] "data/spam/0002.24b47bb3ce90708ae29d0aec1da08610"
[4] "data/spam/0003.4b3d943b8df71af248d12f8b2e7a224a"
[5] "data/spam/0004.1874ab60c71f0b31b580f313a3f6e777"
[6] "data/spam/0005.1f42bb885de0ef7fc5cd09d34dc2ba54"

There are 2551 ham emails and 501 spam emails.

# Combine ham and spam files
email_files <- bind_rows(tibble(file_path=ham_files)%>%mutate(label="ham"),
                           tibble(file_path = spam_files) %>% mutate(label = "spam"))%>%
    filter(basename(file_path) != "cmds")   # not an email
# read one file and return only the body
get_body <- function(path) {
  raw <- readChar(path, file.size(path), useBytes = TRUE) %>%
    iconv("latin1", "UTF-8", sub = "") %>%       # avoid encoding errors
    str_replace_all("\r\n", "\n")
  str_replace(raw, "(?s)^.*?\n\n", "")           # drop headers (everything up to first blank line)
}

email_data <- email_files %>%
  mutate(email_body = map_chr(file_path, get_body)) %>%
  select(email_body,label)
# get first email body
email_data %>% 
  slice(1) %>% 
  pull(email_body)
[1] "    Date:        Wed, 21 Aug 2002 10:54:46 -0500\n    From:        Chris Garrigues <cwg-dated-1030377287.06fa6d@DeepEddy.Com>\n    Message-ID:  <1029945287.4797.TMDA@deepeddy.vircio.com>\n\n\n  | I can't reproduce this error.\n\nFor me it is very repeatable... (like every time, without fail).\n\nThis is the debug log of the pick happening ...\n\n18:19:03 Pick_It {exec pick +inbox -list -lbrace -lbrace -subject ftp -rbrace -rbrace} {4852-4852 -sequence mercury}\n18:19:03 exec pick +inbox -list -lbrace -lbrace -subject ftp -rbrace -rbrace 4852-4852 -sequence mercury\n18:19:04 Ftoc_PickMsgs {{1 hit}}\n18:19:04 Marking 1 hits\n18:19:04 tkerror: syntax error in expression \"int ...\n\nNote, if I run the pick command by hand ...\n\ndelta$ pick +inbox -list -lbrace -lbrace -subject ftp -rbrace -rbrace  4852-4852 -sequence mercury\n1 hit\n\nThat's where the \"1 hit\" comes from (obviously).  The version of nmh I'm\nusing is ...\n\ndelta$ pick -version\npick -- nmh-1.0.4 [compiled on fuchsia.cs.mu.OZ.AU at Sun Mar 17 14:55:56 ICT 2002]\n\nAnd the relevant part of my .mh_profile ...\n\ndelta$ mhparam pick\n-seq sel -list\n\n\nSince the pick command works, the sequence (actually, both of them, the\none that's explicit on the command line, from the search popup, and the\none that comes from .mh_profile) do get created.\n\nkre\n\nps: this is still using the version of the code form a day ago, I haven't\nbeen able to reach the cvs repository today (local routing issue I think).\n\n\n\n_______________________________________________\nExmh-workers mailing list\nExmh-workers@redhat.com\nhttps://listman.redhat.com/mailman/listinfo/exmh-workers\n\n"

Text preprocessing

email_data <- email_data %>%
  mutate(
    # leading spaces and pipe characters from quoted replies
    email_body = str_remove(email_body, "^[\\s|]+"),

    clean_text = email_body %>%
      str_to_lower() %>%
      str_remove_all("<[^>]+>") %>%                 # HTML tags
      str_remove_all("https?://\\S+|www\\.\\S+") %>% # URLs
      str_remove_all("\\S+@\\S+") %>%               # email addresses
      str_remove_all("'") %>%                       # can't -> cant
      str_replace_all("[[:punct:]]", " ") %>%       # other punctuation -> space
      str_remove_all("[0-9]+") %>%                  # numbers
      str_remove_all("\\b\\w{25,}\\b") %>%          # long junk strings
      str_squish()
  ) %>%
  filter(clean_text != "")                          # drop empty emails

Text preprocessing was performed to clean and standardize email bodies before classification. HTML tags, URLs, email addresses, punctuation, numbers, and unusually long strings were removed. All text was converted to lowercase, and extra whitespace was eliminated. Empty emails were excluded to prepare the data for tokenization and Naive Bayes classification.

email_data %>% 
  slice(1) %>% 
  pull(clean_text)
[1] "date wed aug from chris garrigues message id | i cant reproduce this error for me it is very repeatable like every time without fail this is the debug log of the pick happening pick it exec pick +inbox list lbrace lbrace subject ftp rbrace rbrace sequence mercury exec pick +inbox list lbrace lbrace subject ftp rbrace rbrace sequence mercury ftoc pickmsgs hit marking hits tkerror syntax error in expression int note if i run the pick command by hand delta$ pick +inbox list lbrace lbrace subject ftp rbrace rbrace sequence mercury hit thats where the hit comes from obviously the version of nmh im using is delta$ pick version pick nmh compiled on fuchsia cs mu oz au at sun mar ict and the relevant part of my mh profile delta$ mhparam pick seq sel list since the pick command works the sequence actually both of them the one thats explicit on the command line from the search popup and the one that comes from mh profile do get created kre ps this is still using the version of the code form a day ago i havent been able to reach the cvs repository today local routing issue i think exmh workers mailing list"
# created id in email_data
email_data <- email_data %>% mutate(id = row_number())

A unique id is assigned to each email to identify individual documents. These ids help keep track of emails and correctly match their actual labels with the model’s predictions.

Train/test split

# 80% for training 20% for testing

set.seed(123)
email_split<-initial_split(email_data,
                           prop=0.80,
                           strata=label)
train_data <- training(email_split)

test_data <- testing(email_split)
nrow(train_data)
[1] 2439
nrow(test_data)
[1] 610
train_data %>% count(label) %>% mutate(prop = n / sum(n))
# A tibble: 2 × 3
  label     n  prop
  <chr> <int> <dbl>
1 ham    2040 0.836
2 spam    399 0.164
test_data  %>% count(label) %>% mutate(prop = n / sum(n))
# A tibble: 2 × 3
  label     n  prop
  <chr> <int> <dbl>
1 ham     510 0.836
2 spam    100 0.164
train_words <- train_data %>%
  select(id, label, clean_text) %>%
  unnest_tokens(word, clean_text) %>%
  anti_join(stop_words, by = "word")
train_data %>% 
  slice(1) %>% 
  pull(clean_text)
[1] "date wed aug from chris garrigues message id | i cant reproduce this error for me it is very repeatable like every time without fail this is the debug log of the pick happening pick it exec pick +inbox list lbrace lbrace subject ftp rbrace rbrace sequence mercury exec pick +inbox list lbrace lbrace subject ftp rbrace rbrace sequence mercury ftoc pickmsgs hit marking hits tkerror syntax error in expression int note if i run the pick command by hand delta$ pick +inbox list lbrace lbrace subject ftp rbrace rbrace sequence mercury hit thats where the hit comes from obviously the version of nmh im using is delta$ pick version pick nmh compiled on fuchsia cs mu oz au at sun mar ict and the relevant part of my mh profile delta$ mhparam pick seq sel list since the pick command works the sequence actually both of them the one thats explicit on the command line from the search popup and the one that comes from mh profile do get created kre ps this is still using the version of the code form a day ago i havent been able to reach the cvs repository today local routing issue i think exmh workers mailing list"

Tokenization and document-feature matrix

Tokenization breaks the email body into individual words (tokens). Common stop words, such as “the”, “is”, and “and”, are removed because they often provide limited information for distinguishing spam from ham emails.

Training Data

tokens_train <- train_data %>%
  unnest_tokens(word, clean_text) %>%
  anti_join(stop_words, by = "word")
token_counts <- tokens_train %>% count(id, label, word)

The document-feature matrix (DFM) represents each email as a collection of word frequencies. Each row represents an email, each column represents a unique word, and each cell contains the number of times that word appears in the email. This numerical representation allows the Naive Bayes model to analyze the text.

dfm_train<-token_counts%>%
    cast_dfm(document = id, term = word, value = n)
dfm_train
dfm of 2,439 documents x 36,626 features (265,649 occurrences, 99.80% sparsity).
    features
docs ago au aug chris code command compiled created cs cvs
   1   1  1   1     1    1       3        1       1  1   1
   2   0  0   0     0    0       0        0       0  0   0
   4   0  0   0     0    0       0        0       0  0   0
   5   0  0   1     0    0       2        0       0  0   0
   6   0  0   0     0    0       0        0       0  0   0
   7   0  0   0     0    0       0        0       0  0   0
[ reached max_ndoc ... 2,433 more documents, reached max_nfeat ... 36,616 more
features ]

The document IDs are used to match each training email with its correct ham or spam label. This ensures that the model receives the correct classification label for every document in the DFM.

ids <- as.integer(docnames(dfm_train))
y_train <- train_data$label[match(ids, train_data$id)]

nrow(dfm_train) == length(y_train)   # must be TRUE
[1] TRUE
table(y_train)
y_train
 ham spam 
2040  399 

Test Data

The same tokenization and document-feature matrix process is applied to the testing emails.

tokens_test <- test_data %>%
  unnest_tokens(word, clean_text) %>%
  anti_join(stop_words, by = "word")
token_counts_test <- tokens_test %>% count(id, label, word)
dfm_test<-token_counts_test%>%
    cast_dfm(document = id, term = word, value = n)
dfm_test
dfm of 610 documents x 15,990 features (64,993 occurrences, 99.54% sparsity).
    features
docs agencies ap appeared armed attempt august authorities automatic ballet
  3         2  1        1     1       1      1           1         1      1
  15        0  0        0     0       0      0           0         0      0
  22        0  0        0     0       0      1           0         0      0
  28        0  0        0     0       0      0           0         0      0
  32        0  0        0     0       0      0           0         0      0
  38        0  0        0     0       0      0           0         0      0
    features
docs blocks
  3       1
  15      0
  22      0
  28      0
  32      0
  38      0
[ reached max_ndoc ... 604 more documents, reached max_nfeat ... 15,980 more
features ]
dfm_test <- dfm_match(
  dfm_test,
  features = featnames(dfm_train)
)

Train the model using Naive Bayes classifier

The Naive Bayes classifier is trained using the training DFM and its corresponding email labels.

nb <- textmodel_nb(
  dfm_train,
  y_train,
  smooth = 1,           # Laplace smoothing, so unseen words don't give probability 0
  prior = "docfreq"     # use the real ham/spam proportions as the prior
)
ids_test <- as.integer(docnames(dfm_test))
y_test   <- test_data$label[match(ids_test, test_data$id)]

nrow(dfm_test) == length(y_test)   # must be TRUE
[1] TRUE

The trained Naive Bayes model is used to predict the categories of emails in the testing data set.

pred <- predict(nb, newdata = dfm_test)
results <- tibble(
  id = as.integer(docnames(dfm_test)),
  predicted = as.character(pred)
) %>%
  left_join(
    test_data %>% select(id, label),
    by = "id"
  ) %>%
  rename(actual = label)

Model evaluation

class(pred);   class(y_test)
[1] "factor"
[1] "character"
levels(pred);  levels(y_test)
[1] "ham"  "spam"
NULL
length(pred);  length(y_test)
[1] 610
[1] 610
sum(is.na(pred)); sum(is.na(y_test))
[1] 0
[1] 0
table(pred, useNA = "ifany")
pred
 ham spam 
 513   97 
table(y_test, useNA = "ifany")
y_test
 ham spam 
 510  100 

The model is evaluated by comparing its predicted labels with the actual labels from the testing dataset.

# Since y_test is character so converted it into factor
y_test <- factor(y_test, levels = c("ham", "spam"))

levels(y_test)
[1] "ham"  "spam"
table(predicted = pred, actual = y_test)
         actual
predicted ham spam
     ham  509    4
     spam   1   96
confusionMatrix(pred, y_test, positive = "spam", mode = "prec_recall")
Confusion Matrix and Statistics

          Reference
Prediction ham spam
      ham  509    4
      spam   1   96
                                         
               Accuracy : 0.9918         
                 95% CI : (0.981, 0.9973)
    No Information Rate : 0.8361         
    P-Value [Acc > NIR] : <2e-16         
                                         
                  Kappa : 0.9697         
                                         
 Mcnemar's Test P-Value : 0.3711         
                                         
              Precision : 0.9897         
                 Recall : 0.9600         
                     F1 : 0.9746         
             Prevalence : 0.1639         
         Detection Rate : 0.1574         
   Detection Prevalence : 0.1590         
      Balanced Accuracy : 0.9790         
                                         
       'Positive' Class : spam           
                                         

The model achieved 99% accuracy in classifying ham and spam emails, precision 98.97% and 96% recall. This shows that most of the emails predicted as spam were actually spam however it missed 4 actual spam emails by classifying them as ham.

conf_matrix <- results %>%
  count(actual, predicted)

conf_matrix
# A tibble: 4 × 3
  actual predicted     n
  <chr>  <chr>     <int>
1 ham    ham         509
2 ham    spam          1
3 spam   ham           4
4 spam   spam         96
ggplot(conf_matrix, aes(x = predicted, y = actual, fill = n)) +
  geom_tile(color = "white", linewidth = 1) +
  geom_text(aes(label = n), size = 6, fontface = "bold") +
  scale_fill_gradient(low = "white", high = "steelblue") +
  labs(
    title = "Naive Bayes Confusion Matrix",
    subtitle = "Spam and Ham Email Classification",
    x = "Predicted Class",
    y = "Actual Class",
    fill = "Number of Emails"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", size = 14),
    axis.text = element_text(size = 12),
    axis.title = element_text(size = 12)
  )

The confusion matrix shows that the Naive Bayes model correctly classified 509 emails as ham and 96 spam emails.
however it incorrectly classified 4 emails as spam and 1 ham email.

Conclusion

Using the SpamAssassin public email corpus, I performed text preprocessing by extracting and cleaning the email bodies. The dataset was then split into training and testing sets using the rsample package. Both sets were tokenized, and stop words were removed to prepare the text for analysis. Document-feature matrices (DFMs) were created for both datasets and used to train a Naive Bayes classification model with the caret package.

The model was evaluated using a confusion matrix and achieved promising results. It correctly classified 509 emails as ham and 96 emails as spam. However, it incorrectly classified 4 legitimate emails (ham) as spam and 1 spam email as ham. The model achieved an overall accuracy of approximately 99%, precision of 98.97%, and recall of 96%.

Overall, the Naive Bayes classifier performed well in distinguishing spam emails from legitimate emails.

Citation

Anthropic. (2026). Claude Sonnet 5.5 [Large language model]. https://claude.ai
https://claude.ai/share/21432316-61c5-4971-be3d-03eaeabacea1