library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.3     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── 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
spam <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-08-15/spam.csv')
## Rows: 4601 Columns: 7
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): yesno
## dbl (6): crl.tot, dollar, bang, money, n000, make
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

Explore Data

spam %>%
  count(yesno)
## # A tibble: 2 × 2
##   yesno     n
##   <chr> <int>
## 1 n      2788
## 2 y      1813
spam %>%
  count(yesno, crl.tot)
## # A tibble: 1,275 × 3
##    yesno crl.tot     n
##    <chr>   <dbl> <int>
##  1 n           1     9
##  2 n           2     8
##  3 n           3    31
##  4 n           4    46
##  5 n           5   114
##  6 n           6    49
##  7 n           7    49
##  8 n           8    43
##  9 n           9    65
## 10 n          10    37
## # ℹ 1,265 more rows
# Remove any outliers
spam <- spam %>%
  filter(bang < 2500, crl.tot < 2500)

# Convert yesno to factor
spam %>% 
  mutate_if(is.character, as.factor)
## # A tibble: 4,542 × 7
##    crl.tot dollar  bang money  n000  make yesno
##      <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl> <fct>
##  1     278  0     0.778  0     0     0    y    
##  2    1028  0.18  0.372  0.43  0.43  0.21 y    
##  3    2259  0.184 0.276  0.06  1.16  0.06 y    
##  4     191  0     0.137  0     0     0    y    
##  5     191  0     0.135  0     0     0    y    
##  6      54  0     0      0     0     0    y    
##  7     112  0.054 0.164  0     0     0    y    
##  8      49  0     0      0     0     0    y    
##  9    1257  0.203 0.181  0.15  0     0.15 y    
## 10     749  0.081 0.244  0     0.19  0.06 y    
## # ℹ 4,532 more rows
spam %>%
    filter(n000 > 0, bang > 0) %>%
    ggplot(aes(n000, bang, color = yesno)) +
    geom_point(alpha = 0.2, size = 1.1)

spam %>%
  filter(dollar < 2) %>%
  ggplot(aes(dollar, y = ..density.., fill = yesno)) +
  geom_histogram(position = "identity", alpha = 0.5)
## Warning: The dot-dot notation (`..density..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(density)` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Engineering

library(tidymodels)
## ── Attaching packages ────────────────────────────────────── tidymodels 1.1.1 ──
## ✔ broom        1.0.5     ✔ rsample      1.2.0
## ✔ dials        1.2.0     ✔ tune         1.1.2
## ✔ infer        1.0.5     ✔ workflows    1.1.3
## ✔ modeldata    1.2.0     ✔ workflowsets 1.0.1
## ✔ parsnip      1.1.1     ✔ yardstick    1.2.0
## ✔ recipes      1.0.8
## ── Conflicts ───────────────────────────────────────── tidymodels_conflicts() ──
## ✖ scales::discard() masks purrr::discard()
## ✖ dplyr::filter()   masks stats::filter()
## ✖ recipes::fixed()  masks stringr::fixed()
## ✖ dplyr::lag()      masks stats::lag()
## ✖ yardstick::spec() masks readr::spec()
## ✖ recipes::step()   masks stats::step()
## • Use tidymodels_prefer() to resolve common conflicts.
set.seed(123)
spam_split <- initial_split(spam, strata = yesno)
spam_train <- training(spam_split)
museum_test <- testing(spam_split)

set.seed(234)
spam_folds <- vfold_cv(spam_train, strata = yesno)
spam_folds
## #  10-fold cross-validation using stratification 
## # A tibble: 10 × 2
##    splits             id    
##    <list>             <chr> 
##  1 <split [3065/341]> Fold01
##  2 <split [3065/341]> Fold02
##  3 <split [3065/341]> Fold03
##  4 <split [3065/341]> Fold04
##  5 <split [3065/341]> Fold05
##  6 <split [3065/341]> Fold06
##  7 <split [3066/340]> Fold07
##  8 <split [3066/340]> Fold08
##  9 <split [3066/340]> Fold09
## 10 <split [3066/340]> Fold10
library(themis)
spam_rec <-
  recipe(formula = yesno ~ ., data = spam_train) %>%
  step_unknown(all_nominal_predictors()) %>%
  step_other(all_nominal_predictors(), threshold = 0.03) %>%
  step_impute_linear(dollar)

spam_spec <-
  rand_forest(trees = 1000) %>%
  set_mode("classification") %>%
  set_engine("ranger")

spam_workflow <-
  workflow() %>%
  add_recipe(spam_rec) %>%
  add_model(spam_spec)

doParallel::registerDoParallel()
set.seed(74403)
ranger_rs <-
  fit_resamples(spam_workflow,
    resamples = spam_folds,
    control = control_resamples(save_pred = TRUE)
  )

Build Models

xgb_spec <-
  boost_tree(
    trees = tune(),
    min_n = tune(),
    mtry = tune(),
    learn_rate = tune()
  ) %>%
  set_engine("xgboost") %>%
  set_mode("classification")

xgb_wf <- workflow(spam_rec, xgb_spec)
library(finetune)
doParallel::registerDoParallel()

set.seed(345)
xgb_rs <- 
  tune_race_anova(
  xgb_wf,
  resamples = spam_folds,
  grid = 15,
  control = control_race(verbose_elim = TRUE)
)
## i Creating pre-processing data to finalize unknown parameter: mtry
## ℹ Racing will maximize the roc_auc metric.
## ℹ Resamples are analyzed in a random order.
## ℹ Fold10: 7 eliminated; 8 candidates remain.
## 
## ℹ Fold07: 1 eliminated; 7 candidates remain.
## 
## ℹ Fold03: 2 eliminated; 5 candidates remain.
## 
## ℹ Fold05: 0 eliminated; 5 candidates remain.
## 
## ℹ Fold09: 0 eliminated; 5 candidates remain.
## 
## ℹ Fold04: 0 eliminated; 5 candidates remain.
## 
## ℹ Fold06: 0 eliminated; 5 candidates remain.
xgb_rs
## # Tuning results
## # 10-fold cross-validation using stratification 
## # A tibble: 10 × 5
##    splits             id     .order .metrics          .notes          
##    <list>             <chr>   <int> <list>            <list>          
##  1 <split [3065/341]> Fold01      2 <tibble [30 × 8]> <tibble [0 × 3]>
##  2 <split [3065/341]> Fold02      3 <tibble [30 × 8]> <tibble [0 × 3]>
##  3 <split [3066/340]> Fold10      1 <tibble [30 × 8]> <tibble [0 × 3]>
##  4 <split [3066/340]> Fold07      4 <tibble [16 × 8]> <tibble [0 × 3]>
##  5 <split [3065/341]> Fold03      5 <tibble [14 × 8]> <tibble [0 × 3]>
##  6 <split [3065/341]> Fold05      6 <tibble [10 × 8]> <tibble [0 × 3]>
##  7 <split [3066/340]> Fold09      7 <tibble [10 × 8]> <tibble [0 × 3]>
##  8 <split [3065/341]> Fold04      8 <tibble [10 × 8]> <tibble [0 × 3]>
##  9 <split [3065/341]> Fold06      9 <tibble [10 × 8]> <tibble [0 × 3]>
## 10 <split [3066/340]> Fold08     10 <tibble [10 × 8]> <tibble [0 × 3]>

Evaluate model

plot_race(xgb_rs)

collect_metrics(xgb_rs)
## # A tibble: 10 × 10
##     mtry trees min_n learn_rate .metric  .estimator  mean     n std_err .config 
##    <int> <int> <int>      <dbl> <chr>    <chr>      <dbl> <int>   <dbl> <chr>   
##  1     1   869    29    0.0263  accuracy binary     0.881    10 0.00432 Preproc…
##  2     1   869    29    0.0263  roc_auc  binary     0.926    10 0.00329 Preproc…
##  3     2  1882    21    0.00156 accuracy binary     0.879    10 0.00509 Preproc…
##  4     2  1882    21    0.00156 roc_auc  binary     0.926    10 0.00326 Preproc…
##  5     3   594    24    0.0139  accuracy binary     0.880    10 0.00418 Preproc…
##  6     3   594    24    0.0139  roc_auc  binary     0.926    10 0.00346 Preproc…
##  7     4   935     8    0.00826 accuracy binary     0.880    10 0.00498 Preproc…
##  8     4   935     8    0.00826 roc_auc  binary     0.927    10 0.00316 Preproc…
##  9     4  1272    33    0.0176  accuracy binary     0.881    10 0.00354 Preproc…
## 10     4  1272    33    0.0176  roc_auc  binary     0.925    10 0.00378 Preproc…
xgb_last <-
  xgb_wf %>%
  finalize_workflow(select_best(xgb_rs, "accuracy")) %>%
  last_fit(spam_split)

collect_metrics(xgb_last)
## # A tibble: 2 × 4
##   .metric  .estimator .estimate .config             
##   <chr>    <chr>          <dbl> <chr>               
## 1 accuracy binary         0.868 Preprocessor1_Model1
## 2 roc_auc  binary         0.911 Preprocessor1_Model1
collect_predictions(xgb_last) %>%
  conf_mat(yesno, .pred_class)
##           Truth
## Prediction   n   y
##          n 651 107
##          y  43 335
library(vip)
## 
## Attaching package: 'vip'
## The following object is masked from 'package:utils':
## 
##     vi
xgb_last %>%
  extract_fit_engine() %>%
  vip()

Questions

1.1 How accurate can we predict whether an email is considered spam or not?

1.2 The dataset consisting of 2982 entries and 7 variables. The primary variable, yesno, indicates if an email is spam. Other numeric columns represent attributes like word frequencies (dollar, bang, money, n000).

1.3 The primary variable, yesno, distinguishes emails as spam or not. It’s categorical, with ‘y’ indicating yes it is spam and “n” for no it is not spam. Numeric variables such as dollar, bang, and money reflect specific word or symbol frequencies in emails.

2.1 We removed any outliers from the numeric variables and then converted the yesno variable to a factor.

3.1 We removed any outliers from the numeric variables and then converted the yesno variable to a factor.

3.2 The machine learning models used in the analysis are Random Forest and XGBoost.

4.1 The metrics used for model evaluation in the analysis are “accuracy” and “roc_auc”

5.1 This analysis was able to give accurate readings on what variables are more important in determining if the email is spam. The accuracy was 86.8% and the ROC_accuracy was 91.1%. The variable “bang” which means how often ‘!’ occure in an email, was the most importance variable in determining spam emails.