Our goal is to build a classification model to predict the spam email(yesno).
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.
spam %>%
skimr::skim()
| Name | Piped data |
| Number of rows | 4601 |
| Number of columns | 7 |
| _______________________ | |
| Column type frequency: | |
| character | 1 |
| numeric | 6 |
| ________________________ | |
| Group variables | None |
Variable type: character
| skim_variable | n_missing | complete_rate | min | max | empty | n_unique | whitespace |
|---|---|---|---|---|---|---|---|
| yesno | 0 | 1 | 1 | 1 | 0 | 2 | 0 |
Variable type: numeric
| skim_variable | n_missing | complete_rate | mean | sd | p0 | p25 | p50 | p75 | p100 | hist |
|---|---|---|---|---|---|---|---|---|---|---|
| crl.tot | 0 | 1 | 283.29 | 606.35 | 1 | 35 | 95 | 266.00 | 15841.00 | ▇▁▁▁▁ |
| dollar | 0 | 1 | 0.08 | 0.25 | 0 | 0 | 0 | 0.05 | 6.00 | ▇▁▁▁▁ |
| bang | 0 | 1 | 0.27 | 0.82 | 0 | 0 | 0 | 0.32 | 32.48 | ▇▁▁▁▁ |
| money | 0 | 1 | 0.09 | 0.44 | 0 | 0 | 0 | 0.00 | 12.50 | ▇▁▁▁▁ |
| n000 | 0 | 1 | 0.10 | 0.35 | 0 | 0 | 0 | 0.00 | 5.45 | ▇▁▁▁▁ |
| make | 0 | 1 | 0.10 | 0.31 | 0 | 0 | 0 | 0.00 | 4.54 | ▇▁▁▁▁ |
What is the relationship between being a spam email and having the word ‘money’ or dollar signs in the email?
spam %>%
filter(dollar > 0, money > 0) %>%
ggplot(aes(money, dollar, color = yesno)) +
geom_point(alpha = 0.3, size = 1.0)
How is the frequency of the word money and dollar signs correlated to the email being spam?
spam %>%
ggplot(aes(dollar, y = after_stat(density), fill = yesno)) +
geom_histogram(position = "identity", alpha = 1.0)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
spam %>%
ggplot(aes(money, y = after_stat(density), fill = yesno)) +
geom_histogram(position = "identity", alpha = 1.0)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
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)
spam_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 [3104/346]> Fold01
## 2 <split [3105/345]> Fold02
## 3 <split [3105/345]> Fold03
## 4 <split [3105/345]> Fold04
## 5 <split [3105/345]> Fold05
## 6 <split [3105/345]> Fold06
## 7 <split [3105/345]> Fold07
## 8 <split [3105/345]> Fold08
## 9 <split [3105/345]> Fold09
## 10 <split [3106/344]> Fold10
usemodels::use_ranger(yesno ~ ., data = spam_train)
## ranger_recipe <-
## recipe(formula = yesno ~ ., data = spam_train)
##
## ranger_spec <-
## rand_forest(mtry = tune(), min_n = tune(), trees = 1000) %>%
## set_mode("classification") %>%
## set_engine("ranger")
##
## ranger_workflow <-
## workflow() %>%
## add_recipe(ranger_recipe) %>%
## add_model(ranger_spec)
##
## set.seed(58117)
## ranger_tune <-
## tune_grid(ranger_workflow, resamples = stop("add your rsample object"), grid = stop("add number of candidate points"))
library(themis)
ranger_recipe <-
recipe(formula = yesno ~ ., data = spam_train) %>%
step_unknown(all_nominal_predictors()) %>%
step_other(all_nominal_predictors(), threshold = 0.03)
ranger_spec <-
rand_forest(trees = 1000) %>%
set_mode("classification") %>%
set_engine("ranger")
ranger_workflow <-
workflow() %>%
add_recipe(ranger_recipe) %>%
add_model(ranger_spec)
doParallel::registerDoParallel()
set.seed(74403)
ranger_rs <-
fit_resamples(ranger_workflow,
resamples = spam_folds,
control = control_resamples(save_pred = TRUE)
)
collect_metrics(ranger_rs)
## # A tibble: 2 × 6
## .metric .estimator mean n std_err .config
## <chr> <chr> <dbl> <int> <dbl> <chr>
## 1 accuracy binary 0.881 10 0.00604 Preprocessor1_Model1
## 2 roc_auc binary 0.932 10 0.00511 Preprocessor1_Model1
collect_predictions(ranger_rs) %>%
group_by(id) %>%
roc_curve(yesno, .pred_n) %>%
autoplot()
conf_mat_resampled(ranger_rs, tidy = FALSE) %>%
autoplot()
final_fitted <- last_fit(ranger_workflow, spam_split)
collect_metrics(final_fitted)
## # A tibble: 2 × 4
## .metric .estimator .estimate .config
## <chr> <chr> <dbl> <chr>
## 1 accuracy binary 0.877 Preprocessor1_Model1
## 2 roc_auc binary 0.907 Preprocessor1_Model1
collect_predictions(final_fitted) %>%
conf_mat(yesno, .pred_class) %>%
autoplot()
library(vip)
##
## Attaching package: 'vip'
## The following object is masked from 'package:utils':
##
## vi
imp_data <- ranger_recipe %>%
prep() %>%
bake(new_data = NULL)
ranger_spec %>%
set_engine("ranger", importance = "permutation") %>%
fit(yesno ~ ., data = imp_data) %>%
vip(geom = "point")
1.1 Our goal is to build a classification model using the frequencies of repeated words or symbols to predict the spam email(yesno).
1.2 This dataset contains 7 variables tallying 2982 entries used to classify emails based on the frequency of certain words and symbols. The target variable, yesno, indicates if an email is spam.
1.3 The key predictors in this dataset are the frequency of words and symbol that occur such as dollar signs $, money, !’ marks, and n000, and make.
2.1 I filtered the data to only show values greater than 0. This allowed for the data to only show variables where the occurences took place.
3.1 The machine learning model used in the analysis is the “random forest” model.
4.1 Accuracy: This metric measures the proportion of correct predictions made by the model out of all predictions. In the context of the spam detection task, accuracy indicates how often the model correctly identified an email as either spam or not spam.
ROC_AUC: This metric evaluates the model’s ability to distinguish between the classes. Specifically, for spam detection, ROC_AUC indicates the model’s capability to differentiate between spam and non-spam emails effectively. A higher AUC value suggests a better-performing model.
They both show the accuracy of determining whether an email is spam or not.