Let’s build a model for NY Times bestsellers list. We can build a model to predict the total weeks on best sellers list.
library(tidyverse)
nyt_titles <- readr::read_tsv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-05-10/nyt_titles.tsv')
## Rows: 7431 Columns: 8
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: "\t"
## chr (2): title, author
## dbl (5): id, year, total_weeks, debut_rank, best_rank
## date (1): first_week
##
## ℹ 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.
# Remove four rows with missing values in author
nyt_titles <- nyt_titles %>%
# remove outliers in total weeks
filter(total_weeks < 100) %>%
# Remove missing values
filter(!is.na(author)) %>%
# Log transform the target variable
mutate(total_weeks = log(total_weeks)) %>%
# Add a decade variable
mutate(decade = year %/% 10 * 10)
This is a pretty sizeable rectangular dataset so let’s use an xgboost model; xgboost is a good fit for that type of dataset. How is a characteristic like the decade that the book released is related to the total weeks? How is author related to total weeks?
nyt_titles %>%
filter(!is.na(year)) %>%
mutate(year = cut_number(year, 10)) %>%
ggplot(aes(year, total_weeks, fill = year)) +
geom_boxplot(alpha = 0.2, show.legend = FALSE)
nyt_titles %>%
group_by(author) %>%
summarise(avg_total_weeks = mean(total_weeks)) %>%
ungroup() %>%
slice_max(order_by = avg_total_weeks, n = 20) %>%
ggplot(aes(avg_total_weeks, fct_reorder(author, avg_total_weeks))) +
geom_col(fill = "midnightblue") +
labs(title = "Top Authors by Total Weeks",
x = "Avg. Total Weeks", y = NULL)
This kind of relationship is what we hope our xgboost model can use.
Let’s start our modeling by setting up our “data budget.” We’ll subset down to only variables like id, author, total_weeks and year, decade, and stratify by our outcome total_weeks
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.
nyt_titles <- sample_n(nyt_titles, 100)
set.seed(123)
book_split <-
nyt_titles %>%
select(id, title, author, total_weeks, year, decade) %>%
na.omit() %>%
initial_split(strata = total_weeks)
book_train <- training(book_split)
book_test <- testing(book_split)
set.seed(234)
book_folds <- vfold_cv(book_train, strata = total_weeks)
## Warning: The number of observations in each quantile is below the recommended threshold of 20.
## • Stratification will use 3 breaks instead.
book_folds
## # 10-fold cross-validation using stratification
## # A tibble: 10 × 2
## splits id
## <list> <chr>
## 1 <split [65/8]> Fold01
## 2 <split [65/8]> Fold02
## 3 <split [65/8]> Fold03
## 4 <split [66/7]> Fold04
## 5 <split [66/7]> Fold05
## 6 <split [66/7]> Fold06
## 7 <split [66/7]> Fold07
## 8 <split [66/7]> Fold08
## 9 <split [66/7]> Fold09
## 10 <split [66/7]> Fold10
Next, let’s set up our feature engineering. In the screencast, I walk through starting with default tokenizing and then creating a custom tokenizer. Sometimes a dataset requires more care and custom feature engineering; the tidymodels ecosystem provides lots of fluent options for common use cases and then the ability to extend our framework for more specific needs while maintaining good statistical practice.
library(textrecipes)
split_category <- function(x) {
x %>%
str_split(", ") %>%
map(str_remove_all, "[:punct:]") %>%
map(str_squish) %>%
map(str_to_lower) %>%
map(str_replace_all, " ", "_")
}
book_rec <-
recipe(total_weeks ~ ., data = book_train) %>%
update_role(title, new_role = "id") %>%
step_tokenize(author, custom_token = split_category) %>%
step_tokenfilter(author, max_tokens = 30) %>%
step_tf(author)
## just to make sure this works as expected
book_prep <- prep(book_rec)
bake(book_prep, new_data = NULL) %>% str()
## tibble [73 × 35] (S3: tbl_df/tbl/data.frame)
## $ id : num [1:73] 6916 4761 4060 5983 6114 ...
## $ title : Factor w/ 73 levels "A MOTHER'S KISSES",..: 69 47 40 58 60 54 56 30 24 2 ...
## $ year : num [1:73] 2020 2014 1938 2000 2013 ...
## $ decade : num [1:73] 2020 2010 1930 2000 2010 1930 2010 2000 2010 2010 ...
## $ total_weeks : num [1:73] 0 0 0 0.693 0 ...
## $ tf_author_a_s_byatt : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_alistair_maclean : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_amanda_quick : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_anne_tyler : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_arthur_hailey : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_betty_smith : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_brad_thor : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_bruce_jay_friedman : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_charles_johnson : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_christine_feehan : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_dan_brown : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_david_baldacci : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_dean_koontz : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_donna_leon : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_edwin_gilbert : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_elizabeth_chevalier : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_elizabeth_strout : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_evelyn_eaton : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_fannie_flagg : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_frank_g_slaughter : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_gore_vidal : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_guillermo_del_toro_and_chuck_hogan: int [1:73] 0 0 0 0 0 0 1 0 0 0 ...
## $ tf_author_gunnar_gunnarsson : int [1:73] 0 0 1 0 0 0 0 0 0 0 ...
## $ tf_author_halldor_laxness : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_helen_macinnes : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_henry_bellamann : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_ian_mcewan : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_j_a_jance : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_jack_higgins : int [1:73] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_author_jacqueline_winspear : int [1:73] 0 1 0 0 0 0 0 0 0 0 ...
Now let’s create a tunable xgboost model specification, with only some of the most important hyperparameters tunable, and combine it with our preprocessing recipe in a workflow(). To achieve higher performance, we could try more careful and/or extensive choices for hyperparameter tuning.
xgb_spec <-
boost_tree(
trees = tune(),
mtry = tune(),
min_n = tune(),
learn_rate = 0.01
) %>%
set_engine("xgboost") %>%
set_mode("regression")
xgb_wf <- workflow(book_rec, xgb_spec)
xgb_wf
## ══ Workflow ════════════════════════════════════════════════════════════════════
## Preprocessor: Recipe
## Model: boost_tree()
##
## ── Preprocessor ────────────────────────────────────────────────────────────────
## 3 Recipe Steps
##
## • step_tokenize()
## • step_tokenfilter()
## • step_tf()
##
## ── Model ───────────────────────────────────────────────────────────────────────
## Boosted Tree Model Specification (regression)
##
## Main Arguments:
## mtry = tune()
## trees = tune()
## min_n = tune()
## learn_rate = 0.01
##
## Computational engine: xgboost
Now we can use tune_grid to eliminate parameter combinations that are not doing well.
library(finetune)
doParallel::registerDoParallel()
set.seed(234)
xgb_book_rs <-
tune_grid(
xgb_wf,
book_folds,
grid = 5,
control = control_race(verbose_elim = TRUE, pkgs = "tidyverse")
)
## i Creating pre-processing data to finalize unknown parameter: mtry
xgb_book_rs
## # Tuning results
## # 10-fold cross-validation using stratification
## # A tibble: 10 × 4
## splits id .metrics .notes
## <list> <chr> <list> <list>
## 1 <split [65/8]> Fold01 <tibble [10 × 7]> <tibble [1 × 3]>
## 2 <split [65/8]> Fold02 <tibble [10 × 7]> <tibble [1 × 3]>
## 3 <split [65/8]> Fold03 <tibble [10 × 7]> <tibble [1 × 3]>
## 4 <split [66/7]> Fold04 <tibble [10 × 7]> <tibble [1 × 3]>
## 5 <split [66/7]> Fold05 <tibble [10 × 7]> <tibble [1 × 3]>
## 6 <split [66/7]> Fold06 <tibble [10 × 7]> <tibble [1 × 3]>
## 7 <split [66/7]> Fold07 <tibble [10 × 7]> <tibble [1 × 3]>
## 8 <split [66/7]> Fold08 <tibble [10 × 7]> <tibble [1 × 3]>
## 9 <split [66/7]> Fold09 <tibble [10 × 7]> <tibble [1 × 3]>
## 10 <split [66/7]> Fold10 <tibble [10 × 7]> <tibble [1 × 3]>
##
## There were issues with some computations:
##
## - Warning(s) x10: A correlation computation is required, but `estimate` is constant...
##
## Run `show_notes(.Last.tune.result)` for more information.
We can visualize how the possible parameter combinations we tried did during the “race.” Notice how we saved a TON of time by not evaluating the parameter combinations that were clearly doing poorly on all the resamples; we only kept going with the good parameter combinations.
We ended up with three hyperparameter configurations in the end, all of which are pretty much the same.
show_best(xgb_book_rs)
## Warning: No value of `metric` was given; metric 'rmse' will be used.
## # A tibble: 5 × 9
## mtry trees min_n .metric .estimator mean n std_err .config
## <int> <int> <int> <chr> <chr> <dbl> <int> <dbl> <chr>
## 1 13 1057 8 rmse standard 0.971 10 0.0605 Preprocessor1_Model2
## 2 7 1954 31 rmse standard 0.974 10 0.0855 Preprocessor1_Model1
## 3 30 1236 10 rmse standard 0.978 10 0.0586 Preprocessor1_Model5
## 4 19 659 21 rmse standard 1.01 10 0.0703 Preprocessor1_Model3
## 5 23 382 36 rmse standard 1.08 10 0.0655 Preprocessor1_Model4
Let’s use last_fit() to fit one final time to the training data and evaluate one final time on the testing data.
xgb_last <-
xgb_wf %>%
finalize_workflow(select_best(xgb_book_rs, "rmse")) %>%
last_fit(book_split)
xgb_last
## # Resampling results
## # Manual resampling
## # A tibble: 1 × 6
## splits id .metrics .notes .predictions .workflow
## <list> <chr> <list> <list> <list> <list>
## 1 <split [73/27]> train/test split <tibble> <tibble> <tibble> <workflow>
An xgboost model is not directly interpretable but we have several options for understanding why the model makes the predictions it does.
Let’s start with model-based variable importance using the vip package.
library(vip)
##
## Attaching package: 'vip'
## The following object is masked from 'package:utils':
##
## vi
xgb_fit <- extract_fit_parsnip(xgb_last)
vip(xgb_fit, geom = "point", num_features = 12)
The maximum playing time and minimum age are the most important predictors driving the predicted game rating.
We can also use a model-agnostic approach like Shapley Additive Explanations, where the average contributions of features are computed under different combinations or “coalitions” of feature orderings. The SHAPforxgboost package makes setting this up for an xgboost model particularly nice.
We start by computing what we need for SHAP values, with the underlying xgboost engine fit and the predictors in a matrix format.
library(SHAPforxgboost)
book_shap <-
shap.prep(
xgb_model = extract_fit_engine(xgb_fit),
X_train = bake(book_prep,
has_role("predictor"),
new_data = NULL,
composition = "matrix"
)
)
Now we can make visualizations! We can look at an overall summary:
shap.plot.summary(book_shap)
Or create partial dependence plots for specific variables:
shap.plot.dependence(
book_shap,
x = "year",
color_feature = "best_rank",
size0 = 1.2,
smooth = FALSE, add_hist = TRUE
)
Learning this kind of complex, non-linear behavior is where xgboost models shine.