Author

Anastasiia Gmyrina

Approach

For this project, I will explore how machine learning can be used to classify emails as spam or ham. I will use the Apache SpamAssassin Public Corpus, focusing on two categories: spam_2, which contains spam messages, and hard_ham, which contains legitimate emails that may resemble spam.

My goal is to compare two classification methods, Naive Bayes and Logistic Regression, to see how accurately they can distinguish between the two categories. I will first extract and clean the email text, then divide the data into training and testing sets. After training both models, I will compare their performance using accuracy, precision, recall, and F1 score. I will also examine false positives, since incorrectly identifying a legitimate email as spam can be particularly problematic.

One challenge I expect is that the emails are stored as individual text files with headers, message bodies, and different formatting. Another is that the dataset contains more spam emails than ham emails, which may affect the models’ predictions.

Data preparation

Data loading

Show code
library(tidyverse)
# Extract email datasets if folders are missing
if (!dir.exists("easy_ham_2") || !dir.exists("spam_2")) {
  untar("spamassassin_data.tar.gz", exdir = ".")
}
# List email files and exclude 'cmds', which contains renaming instructions
ham_files <- list.files("easy_ham_2", full.names = TRUE) %>%
  discard(~ basename(.x) == "cmds")
spam_files <- list.files("spam_2", full.names = TRUE) %>%
  discard(~ basename(.x) == "cmds")

length(ham_files)
[1] 1400
Show code
length(spam_files)
[1] 1396

The dataset contains 1,400 ham emails and 1,396 spam emails, for a total of 2,796 messages. The two categories are almost equally represented, which makes the dataset more balanced for training and evaluating classification models.

Check email structure

Before processing the entire dataset, I will examine one email to understand its structure. Each file contains headers, including sender and recipient information, followed by the actual message body.

Show code
email <- readLines(ham_files[1], warn = FALSE)

head(email, 20)
 [1] "Return-Path: <exmh-workers-admin@spamassassin.taint.org>"                                          
 [2] "Delivered-To: yyyy@localhost.netnoteinc.com"                                                       
 [3] "Received: from localhost (localhost [127.0.0.1])"                                                  
 [4] "\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id 7106643C34"                                
 [5] "\tfor <jm@localhost>; Wed, 21 Aug 2002 08:33:03 -0400 (EDT)"                                       
 [6] "Received: from phobos [127.0.0.1]"                                                                 
 [7] "\tby localhost with IMAP (fetchmail-5.9.0)"                                                        
 [8] "\tfor jm@localhost (single-drop); Wed, 21 Aug 2002 13:33:03 +0100 (IST)"                           
 [9] "Received: from listman.spamassassin.taint.org (listman.spamassassin.taint.org [66.187.233.211]) by"
[10] "    dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g7LCXvZ24654 for"                            
[11] "    <jm-exmh@jmason.org>; Wed, 21 Aug 2002 13:33:57 +0100"                                         
[12] "Received: from listman.spamassassin.taint.org (localhost.localdomain [127.0.0.1]) by"              
[13] "    listman.redhat.com (Postfix) with ESMTP id F12A13EA25; Wed, 21 Aug 2002"                       
[14] "    08:34:00 -0400 (EDT)"                                                                          
[15] "Delivered-To: exmh-workers@listman.spamassassin.taint.org"                                         
[16] "Received: from int-mx1.corp.spamassassin.taint.org (int-mx1.corp.spamassassin.taint.org"           
[17] "    [172.16.52.254]) by listman.redhat.com (Postfix) with ESMTP id 750D33F945"                     
[18] "    for <exmh-workers@listman.redhat.com>; Wed, 21 Aug 2002 08:30:55 -0400"                        
[19] "    (EDT)"                                                                                         
[20] "Received: (from mail@localhost) by int-mx1.corp.spamassassin.taint.org (8.11.6/8.11.6)"            

I want to classify emails based on their content, so I will separate the message body from the technical headers. An empty line marks where the body begins. After extracting it, I will combine the individual lines into one text string to make further processing easier.

Show code
which(email == "")[1]
[1] 59
Show code
email_body <- email[26:length(email)]

head(email_body, 15)
 [1] "Received: from ratree.psu.ac.th ([202.28.97.6]) by mx1.spamassassin.taint.org"
 [2] "    (8.11.6/8.11.6) with SMTP id g7LCGNl23207 for <exmh-workers@redhat.com>;" 
 [3] "    Wed, 21 Aug 2002 08:16:24 -0400"                                          
 [4] "Received: from delta.cs.mu.OZ.AU (delta.coe.psu.ac.th [172.30.0.98]) by"      
 [5] "    ratree.psu.ac.th (8.11.6/8.11.6) with ESMTP id g7LCUIl27286;"             
 [6] "    Wed, 21 Aug 2002 19:30:19 +0700 (ICT)"                                    
 [7] "Received: from munnari.OZ.AU (localhost [127.0.0.1]) by delta.cs.mu.OZ.AU"    
 [8] "    (8.11.6/8.11.6) with ESMTP id g7LCU1W09629; Wed, 21 Aug 2002 19:30:01"    
 [9] "    +0700 (ICT)"                                                              
[10] "From: Robert Elz <kre@munnari.OZ.AU>"                                         
[11] "To: Chris Garrigues <cwg-dated-1030314468.7c7c85@DeepEddy.Com>"               
[12] "Cc: exmh-workers@spamassassin.taint.org"                                      
[13] "Subject: Re: New Sequences Window"                                            
[14] "In-Reply-To: <1029882468.3116.TMDA@deepeddy.vircio.com>"                      
[15] "References: <1029882468.3116.TMDA@deepeddy.vircio.com>"                       
Show code
email_text <- str_c(email_body, collapse = " ")

email_text
[1] "Received: from ratree.psu.ac.th ([202.28.97.6]) by mx1.spamassassin.taint.org     (8.11.6/8.11.6) with SMTP id g7LCGNl23207 for <exmh-workers@redhat.com>;     Wed, 21 Aug 2002 08:16:24 -0400 Received: from delta.cs.mu.OZ.AU (delta.coe.psu.ac.th [172.30.0.98]) by     ratree.psu.ac.th (8.11.6/8.11.6) with ESMTP id g7LCUIl27286;     Wed, 21 Aug 2002 19:30:19 +0700 (ICT) Received: from munnari.OZ.AU (localhost [127.0.0.1]) by delta.cs.mu.OZ.AU     (8.11.6/8.11.6) with ESMTP id g7LCU1W09629; Wed, 21 Aug 2002 19:30:01     +0700 (ICT) From: Robert Elz <kre@munnari.OZ.AU> To: Chris Garrigues <cwg-dated-1030314468.7c7c85@DeepEddy.Com> Cc: exmh-workers@spamassassin.taint.org Subject: Re: New Sequences Window In-Reply-To: <1029882468.3116.TMDA@deepeddy.vircio.com> References: <1029882468.3116.TMDA@deepeddy.vircio.com> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Message-Id: <9627.1029933001@munnari.OZ.AU> X-Loop: exmh-workers@spamassassin.taint.org Sender: exmh-workers-admin@spamassassin.taint.org Errors-To: exmh-workers-admin@spamassassin.taint.org X-Beenthere: exmh-workers@spamassassin.taint.org X-Mailman-Version: 2.0.1 Precedence: bulk List-Help: <mailto:exmh-workers-request@spamassassin.taint.org?subject=help> List-Post: <mailto:exmh-workers@spamassassin.taint.org> List-Subscribe: <https://listman.spamassassin.taint.org/mailman/listinfo/exmh-workers>,     <mailto:exmh-workers-request@redhat.com?subject=subscribe> List-Id: Discussion list for EXMH developers <exmh-workers.spamassassin.taint.org> List-Unsubscribe: <https://listman.spamassassin.taint.org/mailman/listinfo/exmh-workers>,     <mailto:exmh-workers-request@redhat.com?subject=unsubscribe> List-Archive: <https://listman.spamassassin.taint.org/mailman/private/exmh-workers/> Date: Wed, 21 Aug 2002 19:30:01 +0700      Date:        Tue, 20 Aug 2002 17:27:47 -0500     From:        Chris Garrigues <cwg-exmh@DeepEddy.Com>     Message-ID:  <1029882468.3116.TMDA@deepeddy.vircio.com>     | I'm hoping that all people with no additional sequences will notice are   | purely cosmetic changes.  Well, first, when exmh (the latest one with your changes) starts, I get...  can't read \"flist(totalcount,unseen)\": no such element in array     while executing \"if {$flist(totalcount,$mhProfile(unseen-sequence)) > 0} { \tFlagInner spool iconspool labelup     } else { \tFlagInner down icondown labeldown     }\"     (procedure \"Flag_MsgSeen\" line 3)     invoked from within \"Flag_MsgSeen\"     (procedure \"MsgSeen\" line 8)     invoked from within \"MsgSeen $msgid\"     (procedure \"MsgShow\" line 12)     invoked from within \"MsgShow $msgid\"     (procedure \"MsgChange\" line 17)     invoked from within \"MsgChange 4862 show\"     invoked from within \"time [list MsgChange $msgid $show\"     (procedure \"Msg_Change\" line 3)     invoked from within \"Msg_Change $msg(id) $show\"     (procedure \"Msg_Show\" line 7)     invoked from within \"Msg_Show cur\"     (\"eval\" body line 1)     invoked from within \"eval $msgShowProc\"     (procedure \"FolderChange\" line 55)     invoked from within \"FolderChange inbox {Msg_Show cur}\"     invoked from within \"time [list  FolderChange $folder $msgShowProc\"     (procedure \"Folder_Change\" line 3)     invoked from within \"Folder_Change $exmh(folder)\"     (procedure \"Exmh\" line 101)     invoked from within \"Exmh\"     (\"after\" script)  which is probably related to my not having an \"unseen\" sequence anywhere (certainly not in inbox) - I read all of my outstanding mail before I tried this new exmh ...  Second, I've been used to having a key binding which was to Msg_MarkUnseen which doesn't seem to exist any more, and I'm not sure what I should replace that with.   There's obviously a way as the \"Sequences\" menu does this. The \"Mark Unseen\" menu entry in the message \"More\" menu is still wanting that function as well...    | For those who have other sequences defined, the window will widen to   | display the other sequences.  Any chance of having that lengthen instead?   I like all my exmh stuff in nice columns (fits the display better).   That is, I use the detached folder list, one column.   The main exmh window takes up full screen, top to bottom, but less than half the width, etc...  I have space for more sequences, in the \"unseen\" window, as long as they remain once nice narrow window (best would be if the sequences could be ordered by some preference, then ones which didn't fit would just fall off the bottom, and not be shown).  I'd also prefer it if that window had no unusual background colouring, just one constant colour - I have been running the unseen window with background black, on a root window that is all black, with no borders or other decorations, but made \"sticky\" - the appearance is just like the folders with unseen messages (and their counts) are written into the root window (because it is sticky, this small display follows me around and do I can see when new mail needs processing).  I also find that I tend to have a bunch of sequences that only ever occur in one folder (some I had forgotten I ever created).  So in addition to the \"sequences to always show\" and \"sequences to never show\", a preference to only show sequences that occur in more than one folder would be useful, and then have the sequences that occor only in the folder I'm visiting appear in the list when that folder is current. This is just to keep the list size somewhat manageable while remaining productive (I quite often use a sequence to remember a particular message in a folder - the name is used only there, and only for one message, it gives me a handle on the message which remains as the folder is packed, sorted, etc).  I haven't updated my exmh for some time now, so I'm not sure if this next one is new, or just new since 2.5, but the Sequences menu (on the bar with New Flist Search ...) only contains \"unseen\" and \"urgent\". It would be useful if it contained all of the sequences that the folder happens to have defined.   A \"New sequence\" entry would also be useful (to mark the message with a sequence name that didn't previously exist, which can be done now using \"Search\" and the pick interface, but is clumsy that way)  Actually, you once could, now when I try this, entering a sequence name in the pick box, and a single message number, or a range N-N in the list of messages, and no pick attributes at all, I now get ...  syntax error in expression \"int(1+1+(1 hit-1)*(3868-1-2)/(4878-1))\"     while executing \"expr int($minlineno+1+($msgid-$minmsgid)*($maxlineno-$minlineno-2)/($maxmsgid-$minmsgid))\"     (procedure \"Ftoc_FindMsg\" line 46)     invoked from within \"Ftoc_FindMsg $msg\"     (procedure \"Ftoc_FindMsgs\" line 5)     invoked from within \"Ftoc_FindMsgs $msgids\"     (procedure \"Ftoc_PickMsgs\" line 5)     invoked from within \"Ftoc_PickMsgs $pick(ids) $pick(addtosel)\"     (procedure \"PickInner\" line 13)     invoked from within \"PickInner {exec pick +inbox -list} {4852 -sequence mercury}\"     (\"uplevel\" body line 1)     invoked from within \"uplevel #0 $cmd\"     (procedure \"busyCursorInner\" line 8)     invoked from within \"busyCursorInner $cmd $widgets\"     (procedure \"busyCursorHack\" line 32)     invoked from within \"busyCursorHack $args\"     (\"cursor\" arm line 1)     invoked from within \"switch $busy(style) { \ticon\t\t{busyIcon $args} \tcursorAll\t{busyCursor $args} \tcursor\t\t{busyCursorHack $args} \tdefault\t\t{eval $args}     }\"     (procedure \"busy\" line 3)     invoked from within \"busy PickInner $cmd $msgs\"     (procedure \"Pick_It\" line 51)     invoked from within \"Pick_It\"     invoked from within \".pick.but.pick invoke\"     (\"uplevel\" body line 1)     invoked from within \"uplevel #0 [list $w invoke]\"     (procedure \"tkButtonUp\" line 7)     invoked from within \"tkButtonUp .pick.but.pick \"     (command bound to event)  It has been ages since I did this last though.   I tried adding a Subject to pick on (easy as I know what's in the message...) which made no difference. Looks as if something is now saying \"1 hit\" when before it didn't, or similar.    | I've also changed the ftoc colorization as discussed briefly on the list a    | week or so ago.  Any chance of making the current message a little brighter background? Just to make it stand out a fraction more than it does (maybe this is more apparent to me than many, as I use very small fonts everywhere, the background of the ftoc line isn't very wide).  Hope this helps.  kre    _______________________________________________ Exmh-workers mailing list Exmh-workers@redhat.com https://listman.redhat.com/mailman/listinfo/exmh-workers "

To process all emails, I will create a function that automatically finds where the message body starts and combines its lines into one text string. This will allow me to extract the text consistently, even when emails have different header lengths.

Show code
read_email <- function(file) {
  email <- readLines(file, warn = FALSE)
  
  body_start <- which(email == "")[1]
  
  email_body <- email[(body_start + 1):length(email)]
  
  str_c(email_body, collapse = " ")
}

Create email dataset

Next I will apply the function to all spam and ham emails and combine the results into one data frame. Each row will represent one email, with its text and a label identifying whether it is spam or ham.

Show code
# Extract text from all emails
ham_text <- map_chr(ham_files, read_email)
spam_text <- map_chr(spam_files, read_email)

# Combine emails into one dataset
emails <- tibble(
  text = c(ham_text, spam_text),
  label = c(
    rep("ham", length(ham_text)),
    rep("spam", length(spam_text))
  )
)

glimpse(emails)
Rows: 2,796
Columns: 2
$ text  <chr> "    Date:        Tue, 20 Aug 2002 17:27:47 -0500     From:     …
$ label <chr> "ham", "ham", "ham", "ham", "ham", "ham", "ham", "ham", "ham", "…

Before training the models, I will clean the email text by converting it to lowercase, removing URLs and punctuation, and replacing extra spaces. This will help make the text more consistent for classification.

Show code
emails <- emails %>%
  mutate(
    text = str_remove_all(text, "<[^>]+>"),
    text = str_to_lower(text),
    text = str_remove_all(text, "https?://\\S+|www\\.\\S+"),
    text = str_replace_all(text, "[[:punct:]]", " "),
    text = str_squish(text)
  )
emails %>%
  select(text, label) %>%
  slice_head(n = 3)

Tokenizing emails

I will split each email into individual words using tokenization. I will also assign an ID to each email so I can connect the words back to their original messages when building the classification models.

Show code
library(tidytext)

email_words <- emails %>%
  mutate(email_id = row_number()) %>%
  unnest_tokens(word, text)

head(email_words, 10)

Explore Word Frequencies

After tokenizing the emails, I will examine the most frequently used words in each category. This will help me identify common patterns and explore whether spam and ham emails use different vocabulary.

Show code
email_words %>%
  count(label, word, sort = TRUE) %>%
  group_by(label) %>%
  slice_max(n, n = 10) %>%
  arrange(label, desc(n))

The most frequent words are common English words that don’t provide much information about whether an email is spam or ham. I will remove these stop words and numbers to focus on more meaningful vocabulary.

Show code
email_words <- email_words %>%
  anti_join(stop_words, by = "word") %>%
  filter(!str_detect(word, "^[0-9]+$"))
email_words %>%
  count(label, word, sort = TRUE) %>%
  group_by(label) %>%
  slice_max(n, n = 10) %>%
  arrange(label, desc(n))

Visualize Word Frequencies

I will visualize the 10 most frequent words in each category to compare the vocabulary used in spam and ham emails.

Show code
email_words %>%
  count(label, word) %>%
  group_by(label) %>%
  slice_max(n, n = 10) %>%
  ggplot(aes(x = reorder(word, n), y = n, fill = label)) +
  geom_col() +
  coord_flip() +
  facet_wrap(~label, scales = "free_y") +
  labs(
    title = "Most Frequent Words in Spam and Ham Emails",
    x = "Word",
    y = "Frequency"
  ) +
  theme_minimal() +
  theme(legend.position = "none")

Ham emails frequently contain technology-related terms such as “linux” and “users”, while spam emails include words like “free”, “business”, and “click”. Some formatting artifacts remain, but the results already show differences in vocabulary between the two categories.

Create a Document-Term Matrix

To prepare the text for classification, I will convert the words into a document-term matrix. This will show how frequently each word appears in each email, allowing the models to work with numerical data instead of raw text.

Show code
dtm <- email_words %>%
  count(email_id, word) %>%
  cast_dtm(email_id, word, n)

dtm
<<DocumentTermMatrix (documents: 2793, terms: 48073)>>
Non-/sparse entries: 256471/134011418
Sparsity           : 100%
Maximal term length: 121
Weighting          : term frequency (tf)

Now i will match emails with matrix

Show code
emails_model <- emails %>%
  mutate(email_id = row_number()) %>%
  filter(email_id %in% email_words$email_id)

nrow(emails_model)
[1] 2793

Before training the models, I will verify that the emails and document-term matrix are in the same order. This is important to ensure that each email is matched with the correct spam or ham label.

Show code
identical(
  as.character(emails_model$email_id),
  rownames(as.matrix(dtm))
)
[1] TRUE

Classification models

Split data into training and testing sets

I will divide the emails into 80% training data and 20% testing data. I’ll use stratified sampling to keep similar proportions of spam and ham in both groups. The training set will be used to build the models, while the testing set will evaluate how well they classify new emails.

Show code
library(rsample)

set.seed(123)

split <- initial_split(emails_model, prop = 0.8, strata = label)

train <- training(split)
test <- testing(split)

table(train$label)

 ham spam 
1120 1114 
Show code
table(test$label)

 ham spam 
 280  279 

To avoid using information from the testing data during training, I will build the vocabulary using only the training emails. Both models will then use the same vocabulary for a fair comparison.

Show code
train_words <- email_words %>%
  filter(email_id %in% train$email_id)

train_vocab <- train_words %>%
  distinct(word)

nrow(train_vocab)
[1] 37648

Some words appear in only a few emails and may not be useful for classification. I will keep words that appear in at least five training emails to reduce the number of features.

Show code
train_vocab <- train_words %>%
  distinct(email_id, word) %>%
  count(word, name = "n_emails") %>%
  filter(n_emails >= 5)

nrow(train_vocab)
[1] 6601

Next, I will convert the training and testing emails into document-term matrices using the vocabulary selected from the training data. Each row represents an email, and each column represents a word. The values show how many times each word appears in an email.

Show code
library(Matrix)

# Keep only words from the training vocabulary
model_words <- email_words %>%
  semi_join(train_vocab, by = "word") %>%
  count(email_id, word, name = "n")

# Create one sparse matrix for all emails
model_matrix <- sparseMatrix(
  i = match(model_words$email_id, emails_model$email_id),
  j = match(model_words$word, train_vocab$word),
  x = model_words$n,
  dims = c(nrow(emails_model), nrow(train_vocab)),
  dimnames = list(
    as.character(emails_model$email_id),
    train_vocab$word
  )
)

# Split into training and testing matrices
train_dtm <- model_matrix[as.character(train$email_id), ]
test_dtm <- model_matrix[as.character(test$email_id), ]

dim(train_dtm)
[1] 2234 6601
Show code
dim(test_dtm)
[1]  559 6601

Naive Bayes Model

I will start with a Naive Bayes model, a common method for spam detection. It uses word frequencies to estimate whether an email is more likely to be spam or ham. I will train the model using the training emails and their known labels.

Show code
library(quanteda)
library(quanteda.textmodels)

# Convert the training matrix to quanteda format
train_dfm <- as.dfm(train_dtm)

# Train the Naive Bayes model
nb_model <- textmodel_nb(
  train_dfm,
  y = factor(train$label)
)

nb_model

Call:
textmodel_nb.dfm(x = train_dfm, y = factor(train$label))

 Distribution: multinomial ; priors: 0.5 0.5 ; smoothing value: 1 ; 2234 training documents;  fitted features. 

After training the Naive Bayes model, I will use it to predict whether each email in the testing set is spam or ham. I will then compare these predictions with the actual labels to evaluate the model’s performance.

Show code
# Convert the testing matrix to quanteda format
test_dfm <- as.dfm(test_dtm)

# Predict email labels
nb_predictions <- predict(nb_model, newdata = test_dfm)

# Compare actual and predicted labels
table(
  Actual = test$label,
  Predicted = nb_predictions
)
      Predicted
Actual ham spam
  ham  276    4
  spam   9  270

The Naive Bayes model correctly classified 546 out of 559 testing emails, achieving an accuracy of approximately 97.67%. Only 4 legitimate emails were incorrectly identified as spam, while 9 spam emails were classified as ham. These results suggest that Naive Bayes performs well on this dataset, although some spam messages still go undetected.

Logistic Regression Model

I will train a Logistic Regression model to classify emails as spam or ham. Unlike Naive Bayes, Logistic Regression estimates the probability of an email being spam based on a combination of word features. I will use the same training and testing data to make the comparison fair.

Show code
library(glmnet)

# Convert labels to 0 (ham) and 1 (spam)
train_y <- ifelse(train$label == "spam", 1, 0)

# Train logistic regression
set.seed(123)

lr_model <- cv.glmnet(
  train_dtm,
  train_y,
  family = "binomial",
  alpha = 0,
  nfolds = 5
)

lr_model

Call:  cv.glmnet(x = train_dtm, y = train_y, nfolds = 5, family = "binomial",      alpha = 0) 

Measure: Binomial Deviance 

    Lambda Index Measure       SE Nonzero
min  2.280   100  0.6418 0.008664    6601
1se  2.389    99  0.6498 0.009009    6601

I will use the trained Logistic Regression model to predict whether each testing email is spam or ham. I will classify emails with a predicted spam probability of at least 50% as spam and compare the predictions with the actual labels.

Show code
# Predict the probability of spam
lr_prob <- predict(
  lr_model,
  newx = test_dtm,
  s = "lambda.min",
  type = "response"
)

# Convert probabilities into spam/ham labels
lr_predictions <- ifelse(lr_prob >= 0.5, "spam", "ham")

# Compare actual and predicted labels
table(
  Actual = test$label,
  Predicted = lr_predictions
)
      Predicted
Actual ham spam
  ham  278    2
  spam   9  270

The Logistic Regression model correctly classified 548 out of 559 testing emails, achieving an accuracy of 98.03%. It incorrectly classified only 2 legitimate emails as spam and missed 9 spam emails. Compared with Naive Bayes, Logistic Regression performed slightly better.

Compare model perfomance

Show code
# Function to calculate performance metrics
evaluate <- function(predicted) {
  actual <- test$label
  
  tp <- sum(actual == "spam" & predicted == "spam")
  fp <- sum(actual == "ham" & predicted == "spam")
  fn <- sum(actual == "spam" & predicted == "ham")
  
  accuracy <- mean(actual == predicted)
  precision <- tp / (tp + fp)
  recall <- tp / (tp + fn)
  f1 <- 2 * precision * recall / (precision + recall)
  
  round(c(accuracy, precision, recall, f1), 3)
}
comparison <- rbind(
  "Naive Bayes" = evaluate(as.vector(nb_predictions)),
  "Logistic Regression" = evaluate(as.vector(lr_predictions))
)

colnames(comparison) <- c("Accuracy", "Precision", "Recall", "F1")

comparison
                    Accuracy Precision Recall    F1
Naive Bayes            0.977     0.985  0.968 0.976
Logistic Regression    0.980     0.993  0.968 0.980

I will use a heatmap to compare the accuracy, precision, recall, and F1 scores of both models. The colors and values will make it easier to see how the models perform across different metrics and identify any differences between them.

Show code
library(tidyverse)
comparison %>%
  as.data.frame() %>%
  rownames_to_column("Model") %>%
  pivot_longer(
    cols = -Model,
    names_to = "Metric",
    values_to = "Score"
  ) %>%
  ggplot(aes(x = Metric, y = Model, fill = Score)) +
  geom_tile(color = "white", linewidth = 1) +
  geom_text(aes(label = sprintf("%.3f", Score)), size = 4) +
  scale_fill_gradient(
    low = "white",
    high = "forestgreen",
    limits = c(0.95, 1)
  ) +
  labs(
    title = "Model Performance Comparison",
    x = NULL,
    y = NULL
  ) +
  theme_minimal()

Conclusion

In this project, I compared Naive Bayes and Logistic Regression to see how accurately they could classify emails as spam or ham based on their text.

Both models performed well, achieving approximately 98% accuracy. Logistic Regression performed slightly better, with 98.03% accuracy compared to 97.67% for Naive Bayes. Both models correctly identified 270 out of 279 spam emails, but Logistic Regression made one fewer false positive, incorrectly classifying only 2 legitimate emails as spam.

Overall, the results show that both methods are effective for spam detection, with only a small difference in performance. One limitation was that some emails contained HTML formatting and encoded text that remained after cleaning. With more time, I would improve the text preprocessing, experiment with different classification thresholds, and test the models on other email datasets to see how well they perform on new data.

AI Use Disclosure

I used ChatGPT throughout this project as a learning and coding assistant. It helped me understand more difficult concepts, particularly how Naive Bayes and Logistic Regression work, how they can be applied to text classification, and how to interpret performance metrics such as precision, recall, and F1 score. I also used ChatGPT to explore different approaches to text preprocessing and understand document-term matrices.