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 setslibrary(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 textlibrary(quanteda.textmodels) # Naive Bayes classification modellibrary(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 datasetsdir.create("data", showWarnings =FALSE)# Define a function to download and extract the email corpusget_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 setget_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 datasetlength(ham_files)
# Combine ham and spam filesemail_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 bodyget_body <-function(path) { raw <-readChar(path, file.size(path), useBytes =TRUE) %>%iconv("latin1", "UTF-8", sub ="") %>%# avoid encoding errorsstr_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 bodyemail_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 repliesemail_body =str_remove(email_body, "^[\\s|]+"),clean_text = email_body %>%str_to_lower() %>%str_remove_all("<[^>]+>") %>%# HTML tagsstr_remove_all("https?://\\S+|www\\.\\S+") %>%# URLsstr_remove_all("\\S+@\\S+") %>%# email addressesstr_remove_all("'") %>%# can't -> cantstr_replace_all("[[:punct:]]", " ") %>%# other punctuation -> spacestr_remove_all("[0-9]+") %>%# numbersstr_remove_all("\\b\\w{25,}\\b") %>%# long junk stringsstr_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_dataemail_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 testingset.seed(123)email_split<-initial_split(email_data,prop=0.80,strata=label)
[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")
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")
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 0prior ="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.
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.
# 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.