# install.packages(c("tidyverse", "tidytext", "SnowballC", "caret", "tm"))
library(tidyverse)
library(tidytext)
library(SnowballC)
library(caret)
set.seed(1201) # makes the random split reproducibleProject 4 Codebase
Introduction
For Project 4, we develop a supervised machine learning model in R that classifies email messages as either spam or ham (regular email). The model learns from a collection of labeled emails, predicts the classifications of emails it has not encountered before, and we evaluate how well those predictions perform. We use two datasets from the SpamAssassin Public Corpus:
- Spam:
20030228_spam_2.tar.bz2 - Ham:
20030228_easy_ham_2.tar.bz2
The work is divided into two parts:
- Part 1 (Data Preparation): Extract the compressed files from our GitHub repo, import the emails into R, clean the text so only useful words remain, label each email as spam or ham, and split each labeled dataset 50/50 into training and testing sets.
- Part 2 (Modeling and Evaluation): Convert the training messages into a document-term matrix of word frequencies, train a classification model, run it on the test set, and evaluate accuracy, precision, recall and F1 score with a confusion matrix.
Setup
Part 1: Data Preparation
Defining File Paths
raw_github_url <- "https://raw.githubusercontent.com/ceciliadelafuentech/DATA607-Project4/main/"
ham_url <- str_c(
raw_github_url,
"20030228_easy_ham_2.tar.bz2"
)
spam_url <- str_c(
raw_github_url,
"20030228_spam_2.tar.bz2"
)
# Store downloaded and extracted email data in a temporary directory rather than the project folder to avoid adding large data files to GitHub. The data is recreated whenever the analysis is run.
# Create a temporary directory for the downloaded and extracted data
data_dir <- file.path(tempdir(), "spamassassin_data")
# Local paths for downloaded and extracted files
ham_file <- file.path(
data_dir, "downloaded", "20030228_easy_ham_2.tar.bz2"
)
spam_file <- file.path(
data_dir, "downloaded", "20030228_spam_2.tar.bz2"
)
ham_folder <- file.path(data_dir, "extracted", "ham")
spam_folder <- file.path(data_dir, "extracted", "spam")
# Create the temporary folders
dir.create(
dirname(ham_file),
recursive = TRUE,
showWarnings = FALSE
)
dir.create(
ham_folder,
recursive = TRUE,
showWarnings = FALSE
)
dir.create(
spam_folder,
recursive = TRUE,
showWarnings = FALSE
)Download the Files
The compressed files are downloaded from the root of the GitHub repository.
if (!file.exists(ham_file)) {
download.file(
url = ham_url,
destfile = ham_file,
mode = "wb"
)
}
if (!file.exists(spam_file)) {
download.file(
url = spam_url,
destfile = spam_file,
mode = "wb"
)
}Unpacking the Compressed Files
The untar() function extracts the .tar.bz2 files into their corresponding folders.
if (
length(
list.files(
ham_folder,
recursive = TRUE
)
) == 0
) {
untar(
tarfile = ham_file,
exdir = ham_folder,
compressed = "bzip2"
)
}
if (
length(
list.files(
spam_folder,
recursive = TRUE
)
) == 0
) {
untar(
tarfile = spam_file,
exdir = spam_folder,
compressed = "bzip2"
)
}Read the Email Messages
Each file inside the ham or spam folder is treated as one document. Each email is read as a single string with its line breaks kept, so the header can be found and removed during cleaning. Every email is labeled with the folder it came from.
read_messages <- function(
folder,
class_label
) {
message_files <- list.files(
folder,
recursive = TRUE,
full.names = TRUE
)
# Remove the archive command file if it exists
message_files <- message_files[
basename(message_files) != "cmds"
]
map_dfr(
message_files,
\(file) {
message_text <- read_file(
file,
locale = locale(encoding = "latin1")
)
tibble(
message_id = str_c(
class_label,
"_",
basename(file)
),
class = class_label,
text = message_text
)
}
)
}Clean the Email Text
To keep only the useful words, we:
- Remove the header (everything before the first blank line)
- Remove HTML tags, HTML entities (such as
), links and email addresses - Standardize curly apostrophes to straight ones
- Keep only letters and apostrophes, removing numbers and punctuation. Apostrophes are kept only inside words (e.g. “don’t”)
- Remove empty and duplicate emails
Spam is set as the first factor level so it is treated as the positive class during evaluation.
email_data <- bind_rows(
read_messages(
folder = ham_folder,
class_label = "ham"
),
read_messages(
folder = spam_folder,
class_label = "spam"
)
) |>
mutate(
class = factor(class, levels = c("spam", "ham")),
text = text |>
str_remove(regex("^.*?\\n\\s*\\n", dotall = TRUE)) |> # headers
str_replace_all(
regex("<[^>]+>|&[a-z]+;|nbsp|http\\S+|www\\.\\S+|\\S+@\\S+", ignore_case = TRUE),
" "
) |> # HTML, entities, links, emails
str_replace_all("[\u2018\u2019\u0092]", "'") |> # standardize apostrophes
str_replace_all("(?<![A-Za-z])'|'(?![A-Za-z])", " ") |> # letters and apostrophes only
str_squish()
) |>
filter(text != "") |> # empty emails
distinct(text, .keep_all = TRUE) # duplicatesInspect the Data
glimpse(email_data)Rows: 2,585
Columns: 3
$ message_id <chr> "ham_00001.1a31cc283af0060967a233d26548a6ce", "ham_00002.5a…
$ class <fct> ham, ham, ham, ham, ham, ham, ham, ham, ham, ham, ham, ham,…
$ text <chr> "Date: Tue, 20 Aug 2002 17:27:47 -0500 From: Chris Garrigue…
# One row per email (should be TRUE)
n_distinct(email_data$message_id) == nrow(email_data)[1] TRUE
# Check that headers were removed (should be 0)
sum(str_detect(email_data$text,
regex("^(return path|received|delivered to|message id)", ignore_case = TRUE)))[1] 0
email_data |>
count(class)# A tibble: 2 × 2
class n
<fct> <int>
1 spam 1196
2 ham 1389
Split the Data 50/50
Spam and ham are each split separately: 50% of the spam emails and 50% of the ham emails go to training, and the remaining halves go to testing. The respective portions are then combined, so both sets keep the same spam/ham proportions (a stratified split).
training_data <- email_data |>
slice_sample(prop = 0.50, by = class)
# The remaining emails from each class form the testing set
testing_data <- email_data |>
anti_join(training_data, by = "message_id")training_data |>
count(class)# A tibble: 2 × 2
class n
<fct> <int>
1 spam 598
2 ham 694
testing_data |>
count(class)# A tibble: 2 × 2
class n
<fct> <int>
1 spam 598
2 ham 695
Part 2: Modeling and Evaluation
Prepare the training emails
# Build the Spam Classifier
# 1. Prepare the training emails
training_words <- training_data |>
unnest_tokens(word, text) |>
anti_join(stop_words, by = "word") |>
filter(str_detect(word, "[a-z]"))
# Create the training document-term matrix
training_dtm <- training_words |>
count(message_id, word) |>
cast_dtm(
document = message_id,
term = word,
value = n
)Prepare the testing emails
# 2. Prepare the testing emails
testing_words <- testing_data |>
unnest_tokens(word, text) |>
anti_join(stop_words, by = "word") |>
filter(str_detect(word, "[a-z]")) |>
filter(word %in% colnames(training_dtm))
# Create the testing document-term matrix
testing_dtm <- testing_words |>
count(message_id, word) |>
cast_dtm(
document = message_id,
term = word,
value = n
)Convert both matrices to sparse matrices
# 3. Convert both matrices to sparse matrices
training_matrix <- Matrix::sparseMatrix(
i = training_dtm$i,
j = training_dtm$j,
x = training_dtm$v,
dims = dim(training_dtm),
dimnames = dimnames(training_dtm)
)
# Include all testing emails, including any with no remaining words
testing_matrix <- Matrix::sparseMatrix(
i = match(rownames(testing_dtm)[testing_dtm$i],
testing_data$message_id),
j = match(colnames(testing_dtm)[testing_dtm$j],
colnames(training_dtm)),
x = testing_dtm$v,
dims = c(nrow(testing_data), ncol(training_dtm)),
dimnames = list(testing_data$message_id,
colnames(training_dtm))
)Align training labels with the training matrix
# 4. Align training labels with the training matrix
training_labels <- training_data$class[
match(rownames(training_matrix), training_data$message_id)
]
# Count word occurrences in spam and ham emails
spam_rows <- which(training_labels == "spam")
ham_rows <- which(training_labels == "ham")
spam_words <- Matrix::colSums(
training_matrix[spam_rows, , drop = FALSE]
)
ham_words <- Matrix::colSums(
training_matrix[ham_rows, , drop = FALSE]
)Calculate word probabilities using Laplace smoothing
# 5. Calculate word probabilities using Laplace smoothing
alpha <- 1
spam_prob <- (spam_words + alpha) /
(sum(spam_words) + alpha * ncol(training_matrix))
ham_prob <- (ham_words + alpha) /
(sum(ham_words) + alpha * ncol(training_matrix))
# Calculate prior probabilities for spam and ham
class_prob <- prop.table(table(training_labels))Calculate log probabilities for testing emails
# 6. Calculate log probabilities for testing emails
spam_score <- as.vector(
testing_matrix %*% log(spam_prob)
) + log(class_prob["spam"])
ham_score <- as.vector(
testing_matrix %*% log(ham_prob)
) + log(class_prob["ham"])
# Predict spam or ham
predictions <- ifelse(spam_score > ham_score, "spam", "ham")
predictions <- factor(
predictions,
levels = c("spam", "ham")
)
# Count predicted spam and ham emails
table(predictions)predictions
spam ham
590 703
Align actual testing labels with predictions
# 7. Align actual testing labels with predictions
testing_labels <- testing_data$class[
match(rownames(testing_matrix), testing_data$message_id)
]
testing_labels <- factor(
testing_labels,
levels = c("spam", "ham")
)Evaluate model performance
# 8. Evaluate model performance
results <- caret::confusionMatrix(
data = predictions,
reference = testing_labels,
positive = "spam"
)
resultsConfusion Matrix and Statistics
Reference
Prediction spam ham
spam 583 7
ham 15 688
Accuracy : 0.983
95% CI : (0.9744, 0.9893)
No Information Rate : 0.5375
P-Value [Acc > NIR] : <2e-16
Kappa : 0.9657
Mcnemar's Test P-Value : 0.1356
Sensitivity : 0.9749
Specificity : 0.9899
Pos Pred Value : 0.9881
Neg Pred Value : 0.9787
Prevalence : 0.4625
Detection Rate : 0.4509
Detection Prevalence : 0.4563
Balanced Accuracy : 0.9824
'Positive' Class : spam
# Calculate the F1 score
precision <- results$byClass["Pos Pred Value"]
recall <- results$byClass["Sensitivity"]
f1_score <- 2 * (precision * recall) / (precision + recall)
f1_scorePos Pred Value
0.9814815
# Summary of the main metrics
tibble(
metric = c("Accuracy", "Precision", "Recall", "F1 Score"),
value = c(
results$overall["Accuracy"],
results$byClass[c("Precision", "Recall", "F1")]
)
) |>
mutate(value = round(value, 3))# A tibble: 4 × 2
metric value
<chr> <dbl>
1 Accuracy 0.983
2 Precision 0.988
3 Recall 0.975
4 F1 Score 0.981
Conclusion
In this project, we developed a supervised machine learning model to classify emails as spam or ham using the SpamAssassin Public Corpus. First, we cleaned and prepared the email data, removed common stop words, and converted the messages into document-term matrices to represent word frequencies. We then used a Multinomial Naive Bayes approach to calculate word probabilities and generate predictions based on the words appearing in each email.
To evaluate the model, we compared its predictions against the actual classifications in the testing dataset using a confusion matrix. On the test set, the model achieved an accuracy of 98.3%, indicating that it correctly classified the vast majority of testing emails. Because accuracy alone can hide which kinds of mistakes a model makes, we also looked at precision, recall and F1 score, with spam as the positive class:
- Precision (98.8%): Of the emails the model flagged as spam, this share really were spam. 7 ham emails were wrongly flagged as spam (false positives).
- Recall (97.5%): Of the actual spam emails, this share were caught by the model. 15 spam emails were missed (false negatives).
- F1 score (0.981): A single score that balances precision and recall, which is useful when both kinds of mistakes matter.
Overall, this project demonstrated how text preprocessing and probabilistic machine learning can be combined to build an effective email spam classifier.
AI Assistance
Generative AI (ChatGPT and Claude Opus 5.5) was used as a supplementary learning and development tool throughout this project. It assisted with understanding R code, troubleshooting errors, explaining machine learning concepts, and improving code organization. All code was reviewed, tested, and adapted by us, and we made the final decisions regarding the analysis, implementation, and interpretation of results.