Let’s build a model for NY Times bestsellers list. We can build a model to predict the total weeks on best sellers list.

Explore data

library(tidyverse)

nyt_titles <- readr::read_tsv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-05-10/nyt_titles.tsv')

Do the debut rank and the best rank of the book relate to the total weeks it is on the best sellers list?

nyt_titles %>%
  select(id, author, year, debut_rank:best_rank, total_weeks) %>%
  pivot_longer(debut_rank:best_rank, names_to = "dim") %>%
  ggplot(aes(value, total_weeks, color = dim)) +
  geom_point(alpha = 0.4, show.legend = FALSE) +
  scale_y_log10() +
  facet_wrap(~dim, scales = "free_x") +
  labs(x = NULL)

Build a model

We can start by loading the tidymodels metapackage, splitting our data into training and testing sets, and creating resamples.

library(tidymodels)

set.seed(123)
book_split <- initial_split(nyt_titles, strata = total_weeks)
book_train <- training(book_split)
book_test <- testing(book_split)

set.seed(234)
book_folds <- bootstraps(book_train, strata = total_weeks)
book_folds
## # Bootstrap sampling using stratification 
## # A tibble: 25 × 2
##    splits              id         
##    <list>              <chr>      
##  1 <split [5571/2010]> Bootstrap01
##  2 <split [5571/2029]> Bootstrap02
##  3 <split [5571/2103]> Bootstrap03
##  4 <split [5571/2052]> Bootstrap04
##  5 <split [5571/2029]> Bootstrap05
##  6 <split [5571/2062]> Bootstrap06
##  7 <split [5571/2044]> Bootstrap07
##  8 <split [5571/2076]> Bootstrap08
##  9 <split [5571/2072]> Bootstrap09
## 10 <split [5571/2009]> Bootstrap10
## # ℹ 15 more rows

In this analysis, we are using a function from usemodels to provide scaffolding for getting started with tidymodels tuning. The two inputs we need are:

a formula to describe our model total weeks ~ . our training data book_train

library(usemodels)
use_ranger(total_weeks ~ debut_rank + best_rank, data = book_train)
## ranger_recipe <- 
##   recipe(formula = total_weeks ~ debut_rank + best_rank, data = book_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(79561)
## ranger_tune <-
##   tune_grid(ranger_workflow, resamples = stop("add your rsample object"), grid = stop("add number of candidate points"))
ranger_recipe <- 
  recipe(formula = total_weeks ~ debut_rank + best_rank, data = book_train) 

ranger_spec <- 
  rand_forest(mtry = tune(), min_n = tune(), trees = 1000) %>% 
  set_mode("regression") %>% 
  set_engine("ranger") 

ranger_workflow <- 
  workflow() %>% 
  add_recipe(ranger_recipe) %>% 
  add_model(ranger_spec) 

set.seed(79561)
doParallel::registerDoParallel()
ranger_tune <-
  tune_grid(ranger_workflow, resamples = book_folds, grid = 11)

The usemodels output required us to decide for ourselves on the resamples and grid to use; it provides sensible defaults for many options based on our data but we still need to use good judgment for some modeling inputs.

Explore results

We can check out the best-performing models in the tuning results.

show_best(ranger_tune, metric = "rmse")
## # A tibble: 5 × 8
##    mtry min_n .metric .estimator  mean     n std_err .config              
##   <int> <int> <chr>   <chr>      <dbl> <int>   <dbl> <chr>                
## 1     1     6 rmse    standard    11.1    25   0.136 Preprocessor1_Model07
## 2     1    13 rmse    standard    11.1    25   0.136 Preprocessor1_Model10
## 3     1    39 rmse    standard    11.1    25   0.136 Preprocessor1_Model08
## 4     1     4 rmse    standard    11.1    25   0.136 Preprocessor1_Model09
## 5     1    36 rmse    standard    11.1    25   0.136 Preprocessor1_Model01
show_best(ranger_tune, metric = "rsq")
## # A tibble: 5 × 8
##    mtry min_n .metric .estimator     mean     n  std_err .config              
##   <int> <int> <chr>   <chr>         <dbl> <int>    <dbl> <chr>                
## 1     1     6 rsq     standard   0.000813    25 0.000174 Preprocessor1_Model07
## 2     1     4 rsq     standard   0.000807    25 0.000174 Preprocessor1_Model09
## 3     1    36 rsq     standard   0.000803    25 0.000174 Preprocessor1_Model01
## 4     1    12 rsq     standard   0.000802    25 0.000175 Preprocessor1_Model02
## 5     1    22 rsq     standard   0.000802    25 0.000176 Preprocessor1_Model05

How did all the possible parameter combinations do?

autoplot(ranger_tune)

We can finalize our random forest workflow with the best performing parameters.

final_rf <- ranger_workflow %>%
  finalize_workflow(select_best(ranger_tune, metric = "rmse"))

final_rf
## ══ Workflow ════════════════════════════════════════════════════════════════════
## Preprocessor: Recipe
## Model: rand_forest()
## 
## ── Preprocessor ────────────────────────────────────────────────────────────────
## 0 Recipe Steps
## 
## ── Model ───────────────────────────────────────────────────────────────────────
## Random Forest Model Specification (regression)
## 
## Main Arguments:
##   mtry = 1
##   trees = 1000
##   min_n = 34
## 
## Computational engine: ranger

The function last_fit() fits this finalized random forest one last time to the training data and evaluates one last time on the testing data.

book_fit <- last_fit(final_rf, book_split)
book_fit
## # Resampling results
## # Manual resampling 
## # A tibble: 1 × 6
##   splits              id               .metrics .notes   .predictions .workflow 
##   <list>              <chr>            <list>   <list>   <list>       <list>    
## 1 <split [5572/1859]> train/test split <tibble> <tibble> <tibble>     <workflow>

The metrics in book_fit are computed using the testing data.

collect_metrics(book_fit)
## # A tibble: 2 × 4
##   .metric .estimator    .estimate .config             
##   <chr>   <chr>             <dbl> <chr>               
## 1 rmse    standard   11.3         Preprocessor1_Model1
## 2 rsq     standard    0.000000213 Preprocessor1_Model1

The predictions in book_fit are also for the testing data.

collect_predictions(book_fit) %>%
  ggplot(aes(total_weeks, .pred)) +
  geom_abline(lty = 1, color = "gray50") +
  geom_point(alpha = 0.5, color = "midnightblue")

We can use the trained workflow from book_fit for prediction, or save it to use later.

predict(book_fit$.workflow[[1]], book_test[15, ])
## # A tibble: 1 × 1
##   .pred
##   <dbl>
## 1  7.72

Lastly, let’s learn about feature importance for this model using the vip package. For a ranger model, we do need to go back to the model specification itself and update the engine with importance = “permutation” in order to compute feature importance. This means fitting the model one more time.

library(vip)

imp_spec <- ranger_spec %>%
  finalize_model(select_best(ranger_tune, metric = "rmse")) %>%
  set_engine("ranger", importance = "permutation")

workflow() %>%
  add_recipe(ranger_recipe) %>%
  add_model(imp_spec) %>%
  fit(book_train) %>%
  pull_workflow_fit() %>%
  vip(aesthetics = list(alpha = 0.8, fill = "midnightblue"))

Questions

  1. Question and Data:
  1. Data Exploration and Transformation:
  1. Data Preparation and Modeling:
  1. Model Evaluation:
    • What metrics are used in the model evaluation?
    • The metrics used for model evaluation are the Root Mean Squared Error (RMSE) and the R-squared (rsq). The RMSE measures the average magnitude of errors between predicted and observed values, while the R-squared metric indicates the proportion of variance in the dependent variable that’s predicted by the independent variables in the model.
  2. Conclusion