Data-607- Project 4 – Document Classification of Spam and Ham Emails: Codebase

Author

Bikash Bhowmik

Published

December 5, 2026

Introduction

This project implements a supervised document classification workflow using the SpamAssassin Public Mail Corpus. The goal is to classify email documents as spam or ham using labeled training documents and evaluate the model on withheld test documents.

The workflow includes reading raw email files, creating a document-level dataset, cleaning and tokenizing text, exploring word frequencies and TF-IDF, building document-term features, training a Naive Bayes classifier, evaluating predictions, and visualizing results.

Load Required Packages

library(tidyverse)
library(tidytext)
library(stringr)
library(readr)
library(purrr)
library(fs)
library(e1071)
library(caret)

Define Project Paths

The raw email files are expected in data/raw/, and processed outputs will be saved in data/processed/.

ham_dir <- "D:/Cuny_sps/Data-607/Project-4/easy_ham"
spam_dir <- "D:/Cuny_sps/Data-607/Project-4/spam"
processed_dir <- "D:/Cuny_sps/Data-607/Project-4/processed"

Validate Folder Structure

dir.exists(ham_dir)
[1] TRUE
dir.exists(spam_dir)
[1] TRUE
if (!dir.exists(ham_dir)) {
  stop("The ham folder was not found. Please check the path: ", ham_dir)
}
if (!dir.exists(spam_dir)) {
  stop("The spam folder was not found. Please check the path: ", spam_dir)
}
if (!dir.exists(processed_dir)) {
  dir.create(processed_dir, recursive = TRUE)
}

Read Raw Email File Paths

Each file represents one email. Its class is determined by the folder in which it is stored.

ham_files <- dir_ls(ham_dir, type = "file")
spam_files <- dir_ls(spam_dir, type = "file")

length(ham_files)
[1] 2501
length(spam_files)
[1] 501

Create a Safe Email Reading Function

Some emails may contain unusual characters or encoding issues. This function reads each file and combines its lines into one string. If a file cannot be read, it returns NA.

read_email_safe <- function(path) {
  tryCatch(
    {
      read_lines(
        path,
        locale = locale(encoding = "Latin1"),
        progress = FALSE
      ) |>
        paste(collapse = " ")
    },
    error = function(e) NA_character_
  )
}

Build the Document-Level Dataset

The ham and spam files are converted into labeled datasets and combined. Each row represents one email.

ham_emails <- tibble(
  doc_id = paste0("ham_", seq_along(ham_files)),
  label = "ham",
  file_path = as.character(ham_files),
  text = map_chr(ham_files, read_email_safe)
)

spam_emails <- tibble(
  doc_id = paste0("spam_", seq_along(spam_files)),
  label = "spam",
  file_path = as.character(spam_files),
  text = map_chr(spam_files, read_email_safe)
)

emails <- bind_rows(ham_emails, spam_emails) |>
  mutate(
    label = factor(label, levels = c("ham", "spam")),
    text = str_squish(text)
  ) |>
  filter(
    !is.na(text),
    text != "",
    !str_detect(file_path, "cmds$")
  )

glimpse(emails)
Rows: 3,000
Columns: 4
$ doc_id    <chr> "ham_1", "ham_2", "ham_3", "ham_4", "ham_5", "ham_6", "ham_7…
$ label     <fct> ham, ham, ham, ham, ham, ham, ham, ham, ham, ham, ham, ham, …
$ file_path <chr> "D:/Cuny_sps/Data-607/Project-4/easy_ham/00001.7c53336b37003…
$ text      <chr> "From exmh-workers-admin@redhat.com Thu Aug 22 12:36:23 2002…

Validate the Document-Level Dataset

emails |> count(label)
# A tibble: 2 × 2
  label     n
  <fct> <int>
1 ham    2500
2 spam    500
validation_summary <- emails |>
  summarize(
    total_documents = n(),
    missing_labels = sum(is.na(label)),
    missing_text = sum(is.na(text)),
    empty_text = sum(str_trim(text) == "", na.rm = TRUE)
  )

validation_summary
# A tibble: 1 × 4
  total_documents missing_labels missing_text empty_text
            <int>          <int>        <int>      <int>
1            3000              0            0          0
if (validation_summary$missing_text > 0) {
  warning("Some email files could not be read and produced missing text.")
}
if (validation_summary$empty_text > 0) {
  warning("Some email files appear to have empty text.")
}

Save the Processed Document-Level Dataset

emails_clean_export <- emails |>
  mutate(text = str_squish(text))

write_csv(
  emails_clean_export,
  file.path(processed_dir, "spam_ham_emails.csv")
)

Initial Class Distribution

emails |>
  count(label) |>
  ggplot(aes(x = label, y = n)) +
  geom_col() +
  labs(
    title = "Class Distribution of Spam and Ham Emails",
    x = "Email Class",
    y = "Number of Documents"
  ) +
  theme_minimal()

Text Cleaning and Tokenization

Emails are tokenized into individual words. Common stop words are removed, and only alphabetic words with at least three characters are retained.

data("stop_words")

email_tokens <- emails |>
  select(doc_id, label, text) |>
  unnest_tokens(word, text) |>
  anti_join(stop_words, by = "word") |>
  filter(
    str_detect(word, "^[a-z]+$"),
    str_length(word) >= 3
  )

glimpse(email_tokens)
Rows: 705,559
Columns: 3
$ doc_id <chr> "ham_1", "ham_1", "ham_1", "ham_1", "ham_1", "ham_1", "ham_1", …
$ label  <fct> ham, ham, ham, ham, ham, ham, ham, ham, ham, ham, ham, ham, ham…
$ word   <chr> "exmh", "workers", "admin", "thu", "aug", "return", "path", "ex…

Validate the Tokenized Dataset

email_tokens |> count(label)
# A tibble: 2 × 2
  label      n
  <fct>  <int>
1 ham   528901
2 spam  176658
email_tokens |>
  summarize(
    total_tokens = n(),
    unique_words = n_distinct(word),
    documents_with_tokens = n_distinct(doc_id)
  )
# A tibble: 1 × 3
  total_tokens unique_words documents_with_tokens
         <int>        <int>                 <int>
1       705559        31893                  3000

Most Common Words by Class

top_words <- email_tokens |>
  count(label, word, sort = TRUE) |>
  group_by(label) |>
  slice_max(n, n = 15, with_ties = FALSE) |>
  ungroup()

top_words
# A tibble: 30 × 3
   label word          n
   <fct> <chr>     <int>
 1 ham   received  14086
 2 ham   list      13388
 3 ham   localhost 12624
 4 ham   fork      10877
 5 ham   sep        9790
 6 ham   esmtp      8407
 7 ham   http       7518
 8 ham   subject    7151
 9 ham   mailto     6170
10 ham   admin      6058
# ℹ 20 more rows

Top Word Frequency Visualization

top_words |>
  mutate(word = reorder_within(word, n, label)) |>
  ggplot(aes(x = word, y = n)) +
  geom_col() +
  coord_flip() +
  facet_wrap(~ label, scales = "free_y") +
  scale_x_reordered() +
  labs(
    title = "Most Common Words in Spam and Ham Emails",
    x = "Word",
    y = "Frequency"
  ) +
  theme_minimal()

TF-IDF Feature Exploration

TF-IDF is calculated using the email class as the document group to identify words that are distinctive within each class.

tfidf_by_class <- email_tokens |>
  count(label, word, sort = TRUE) |>
  bind_tf_idf(word, label, n) |>
  arrange(desc(tf_idf))

tfidf_by_class |>
  group_by(label) |>
  slice_max(tf_idf, n = 15, with_ties = FALSE) |>
  ungroup()
# A tibble: 30 × 6
   label word          n      tf   idf   tf_idf
   <fct> <chr>     <int>   <dbl> <dbl>    <dbl>
 1 ham   fork      10877 0.0206  0.693 0.0143  
 2 ham   rpm        5869 0.0111  0.693 0.00769 
 3 ham   exmh       4972 0.00940 0.693 0.00652 
 4 ham   zzzlist    2726 0.00515 0.693 0.00357 
 5 ham   razor      2076 0.00393 0.693 0.00272 
 6 ham   rssfeeds   1869 0.00353 0.693 0.00245 
 7 ham   zzzzteana   926 0.00175 0.693 0.00121 
 8 ham   wrote       925 0.00175 0.693 0.00121 
 9 ham   devel       907 0.00171 0.693 0.00119 
10 ham   khare       740 0.00140 0.693 0.000970
# ℹ 20 more rows

TF-IDF Visualization

tfidf_by_class |>
  group_by(label) |>
  slice_max(tf_idf, n = 15, with_ties = FALSE) |>
  ungroup() |>
  mutate(word = reorder_within(word, tf_idf, label)) |>
  ggplot(aes(x = word, y = tf_idf)) +
  geom_col() +
  coord_flip() +
  facet_wrap(~ label, scales = "free_y") +
  scale_x_reordered() +
  labs(
    title = "Distinctive Terms by Email Class Using TF-IDF",
    x = "Word",
    y = "TF-IDF"
  ) +
  theme_minimal()

Because the corpus contains raw email files, some frequent and distinctive terms may come from email headers, mailing-list metadata, or HTML formatting. These terms are part of the documents seen by the classifier, but should be interpreted as document-level signals rather than only message-body language.

Save Token-Level Feature Output

write_csv(
  tfidf_by_class,
  file.path(processed_dir, "spam_ham_features.csv")
)

Train/Test Split

The dataset is divided into training and testing sets using a stratified split. Approximately 80% of the emails are used for training and 20% for testing.

set.seed(607)

train_index <- createDataPartition(
  emails$label,
  p = 0.80,
  list = FALSE
)

email_train <- emails[train_index, ]
email_test <- emails[-train_index, ]

email_train |> count(label)
# A tibble: 2 × 2
  label     n
  <fct> <int>
1 ham    2000
2 spam    400
email_test |> count(label)
# A tibble: 2 × 2
  label     n
  <fct> <int>
1 ham     500
2 spam    100

Create Document-Term Matrix Features

The vocabulary is selected from the training data only, preventing information from the test documents from influencing feature selection. The 750 most frequent terms within each training class are considered, and the resulting terms are combined into one vocabulary.

train_tokens <- email_tokens |>
  filter(doc_id %in% email_train$doc_id)

top_model_terms <- train_tokens |>
  count(label, word, sort = TRUE) |>
  group_by(label) |>
  slice_max(n, n = 750, with_ties = FALSE) |>
  ungroup() |>
  distinct(word) |>
  pull(word)

length(top_model_terms)
[1] 1162

The selected vocabulary is used to create a document-term table. Each row represents an email, and each word column contains its count in that email.

model_tokens <- email_tokens |>
  filter(word %in% top_model_terms) |>
  count(doc_id, word, name = "count")

dtm <- model_tokens |>
  pivot_wider(
    names_from = word,
    values_from = count,
    values_fill = 0
  )

dtm <- emails |>
  select(doc_id, label) |>
  left_join(dtm, by = "doc_id") |>
  mutate(
    across(where(is.numeric), ~ replace_na(.x, 0))
  )

dtm_summary <- tibble(
  documents = nrow(dtm),
  total_columns = ncol(dtm),
  feature_columns = ncol(dtm) - 2
)

dtm_summary
# A tibble: 1 × 3
  documents total_columns feature_columns
      <int>         <int>           <dbl>
1      3000          1164            1162

Create Training and Testing Matrices

For modeling, word counts are converted to binary word-presence features. Each term is represented as present or absent. The rows are explicitly aligned with the corresponding email IDs.

train_dtm <- dtm |>
  filter(doc_id %in% email_train$doc_id) |>
  slice(match(email_train$doc_id, doc_id))

test_dtm <- dtm |>
  filter(doc_id %in% email_test$doc_id) |>
  slice(match(email_test$doc_id, doc_id))

train_labels <- train_dtm$label
test_labels <- test_dtm$label

train_x <- train_dtm |>
  select(-doc_id, -label) |>
  mutate(
    across(
      everything(),
      ~ factor(if_else(.x > 0, "yes", "no"),
               levels = c("no", "yes"))
    )
  )

test_x <- test_dtm |>
  select(-doc_id, -label) |>
  mutate(
    across(
      everything(),
      ~ factor(if_else(.x > 0, "yes", "no"),
               levels = c("no", "yes"))
    )
  )

dim(train_x)
[1] 2400 1162
dim(test_x)
[1]  600 1162

Train the Naive Bayes Classifier

A Naive Bayes classifier is trained using the binary word-presence features. Laplace smoothing helps handle terms that may not appear in one of the classes.

nb_model <- naiveBayes(
  x = train_x,
  y = train_labels,
  laplace = 1
)

model_summary <- tibble(
  model_type = "Naive Bayes",
  feature_type = "Binary word-presence",
  training_documents = nrow(train_x),
  testing_documents = nrow(test_x),
  laplace_smoothing = 1
)

model_summary
# A tibble: 1 × 5
  model_type feature_type training_documents testing_documents laplace_smoothing
  <chr>      <chr>                     <int>             <int>             <dbl>
1 Naive Bay… Binary word…               2400               600                 1

Generate Predictions

The trained classifier predicts the labels of the withheld testing documents.

nb_pred <- predict(nb_model, newdata = test_x)

prediction_results <- tibble(
  doc_id = email_test$doc_id,
  label = test_labels,
  predicted_label = nb_pred
)

prediction_results |> count(label, predicted_label)
# A tibble: 4 × 3
  label predicted_label     n
  <fct> <fct>           <int>
1 ham   ham               496
2 ham   spam                4
3 spam  ham                 6
4 spam  spam               94

Evaluate Model Performance

The confusion matrix compares predicted labels with actual labels. Spam is designated as the positive class.

confusion_output <- confusionMatrix(
  data = prediction_results$predicted_label,
  reference = prediction_results$label,
  positive = "spam"
)

confusion_output
Confusion Matrix and Statistics

          Reference
Prediction ham spam
      ham  496    6
      spam   4   94
                                         
               Accuracy : 0.9833         
                 95% CI : (0.9696, 0.992)
    No Information Rate : 0.8333         
    P-Value [Acc > NIR] : <2e-16         
                                         
                  Kappa : 0.9395         
                                         
 Mcnemar's Test P-Value : 0.7518         
                                         
            Sensitivity : 0.9400         
            Specificity : 0.9920         
         Pos Pred Value : 0.9592         
         Neg Pred Value : 0.9880         
             Prevalence : 0.1667         
         Detection Rate : 0.1567         
   Detection Prevalence : 0.1633         
      Balanced Accuracy : 0.9660         
                                         
       'Positive' Class : spam           
                                         

Confusion Matrix Table

confusion_table <- as.data.frame(confusion_output$table)
confusion_table
  Prediction Reference Freq
1        ham       ham  496
2       spam       ham    4
3        ham      spam    6
4       spam      spam   94

Confusion Matrix Visualization

The diagonal cells represent correct predictions, while the off-diagonal cells represent errors.

confusion_table |>
  ggplot(aes(x = Reference, y = Prediction, fill = Freq)) +
  geom_tile() +
  geom_text(aes(label = Freq), size = 5) +
  labs(
    title = "Confusion Matrix for Spam and Ham Classification",
    x = "True Class",
    y = "Predicted Class"
  ) +
  theme_minimal()

Metric Summary

The model is evaluated using accuracy, spam recall, specificity, and precision. These metrics provide a more complete assessment than accuracy alone.

metric_summary <- tibble(
  metric = c(
    "Accuracy",
    "Sensitivity / Spam Recall",
    "Specificity",
    "Precision"
  ),
  estimate = c(
    confusion_output$overall["Accuracy"],
    confusion_output$byClass["Sensitivity"],
    confusion_output$byClass["Specificity"],
    confusion_output$byClass["Precision"]
  )
) |>
  mutate(estimate = as.numeric(estimate))

metric_summary
# A tibble: 4 × 2
  metric                    estimate
  <chr>                        <dbl>
1 Accuracy                     0.983
2 Sensitivity / Spam Recall    0.94 
3 Specificity                  0.992
4 Precision                    0.959

Metric Summary Visualization

metric_summary |>
  ggplot(aes(x = metric, y = estimate)) +
  geom_col() +
  coord_cartesian(ylim = c(0, 1)) +
  labs(
    title = "Naive Bayes Classification Metric Summary",
    x = "Metric",
    y = "Estimate"
  ) +
  theme_minimal()

Save Model Predictions

The prediction results are saved with the document ID, actual class, and predicted class.

write_csv(
  prediction_results,
  file.path(processed_dir, "spam_ham_predictions.csv")
)

Interpretation of Model Results

The original reported results showed that the classifier was evaluated on 600 test emails. It correctly classified 496 ham emails and 93 spam emails. Four ham emails were incorrectly predicted as spam, and seven spam emails were incorrectly predicted as ham.

The reported overall accuracy was 98.17%. However, accuracy alone is not sufficient because the dataset contains more ham emails than spam emails.

Spam recall was 93.00%, meaning the classifier identified 93% of actual spam emails. Precision was 95.88%, meaning most emails predicted as spam were truly spam. Specificity was 99.20%, indicating that the model correctly identified most legitimate ham emails.

These results suggest that binary word-presence Naive Bayes can be effective for this classification task. The relatively small number of false positives and false negatives indicates strong performance across both classes.

Important: These are the originally reported results. Run the revised code and use the newly generated confusion matrix and metrics if they differ, since vocabulary selection is now performed using training data only.

Conclusion

This project demonstrates a supervised document classification workflow using the SpamAssassin Public Mail Corpus. Raw email files are transformed into a structured dataset, cleaned and tokenized, and explored using word frequencies and TF-IDF.

A Naive Bayes classifier is trained using binary word-presence features and evaluated on withheld testing data. The evaluation uses a confusion matrix, accuracy, spam recall, specificity, and precision.

The workflow illustrates the importance of text preprocessing, stratified sampling, training-only feature selection, and multiple evaluation metrics when developing a document classification model.