Let’s build a model for board games. We can build a model to predict the rating of the board game from the characteristics.
ratings <- read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-01-25/ratings.csv")
## Rows: 21831 Columns: 10
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (3): name, url, thumbnail
## dbl (7): num, id, year, rank, average, bayes_average, users_rated
##
## ℹ 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.
details <- read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-01-25/details.csv")
## Rows: 21631 Columns: 23
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (10): primary, description, boardgamecategory, boardgamemechanic, boardg...
## dbl (13): num, id, yearpublished, minplayers, maxplayers, playingtime, minpl...
##
## ℹ 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.
ratings_joined <-
ratings %>%
left_join(details, by = "id")
ggplot(ratings_joined, aes(average)) +
geom_histogram(alpha = 0.8)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
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 minimum recommended age for the game related to the rating?
ratings_joined %>%
filter(!is.na(minage)) %>%
mutate(minage = cut_number(minage, 4)) %>%
ggplot(aes(minage, average, fill = minage)) +
geom_boxplot(alpha = 0.2, show.legend = FALSE)
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 minimum/maximum age and playing time, and stratify by our outcome average.
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 suppressPackageStartupMessages() to eliminate package startup messages
ratings_joined <- sample_n(ratings_joined, 100)
set.seed(123)
game_split <-
ratings_joined %>%
select(name, average, matches("min|max"), boardgamecategory) %>%
na.omit() %>%
initial_split(strata = average)
game_train <- training(game_split)
game_test <- testing(game_split)
set.seed(234)
game_folds <- vfold_cv(game_train, strata = average)
## Warning: The number of observations in each quantile is below the recommended threshold of 20.
## • Stratification will use 3 breaks instead.
game_folds
## # 10-fold cross-validation using stratification
## # A tibble: 10 × 2
## splits id
## <list> <chr>
## 1 <split [63/9]> Fold01
## 2 <split [63/9]> Fold02
## 3 <split [63/9]> Fold03
## 4 <split [63/9]> Fold04
## 5 <split [66/6]> Fold05
## 6 <split [66/6]> Fold06
## 7 <split [66/6]> Fold07
## 8 <split [66/6]> Fold08
## 9 <split [66/6]> Fold09
## 10 <split [66/6]> 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, " ", "_")
}
game_rec <-
recipe(average ~ ., data = game_train) %>%
update_role(name, new_role = "id") %>%
step_tokenize(boardgamecategory, custom_token = split_category) %>%
step_tokenfilter(boardgamecategory, max_tokens = 30) %>%
step_tf(boardgamecategory)
## just to make sure this works as expected
game_prep <- prep(game_rec)
bake(game_prep, new_data = NULL) %>% str()
## tibble [72 × 37] (S3: tbl_df/tbl/data.frame)
## $ name : Factor w/ 72 levels "1841: Railways in Northern Italy",..: 2 67 72 70 28 6 58 43 48 51 ...
## $ minplayers : num [1:72] 2 2 2 2 3 2 2 2 2 2 ...
## $ maxplayers : num [1:72] 0 4 99 6 8 6 6 4 6 6 ...
## $ minplaytime : num [1:72] 0 30 10 45 30 60 15 30 20 30 ...
## $ maxplaytime : num [1:72] 0 30 10 45 30 60 30 30 0 45 ...
## $ minage : num [1:72] 12 9 4 8 12 8 14 0 8 8 ...
## $ average : num [1:72] 5.58 5.22 4.57 5.53 5.52 5.1 5.13 5.81 5.37 5.75 ...
## $ tf_boardgamecategory_abstract_strategy : int [1:72] 0 0 0 0 0 0 0 1 0 0 ...
## $ tf_boardgamecategory_ancient : int [1:72] 0 0 0 0 0 1 0 0 0 0 ...
## $ tf_boardgamecategory_animals : int [1:72] 0 0 1 0 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_aviation_flight : int [1:72] 0 0 0 0 0 0 0 0 0 1 ...
## $ tf_boardgamecategory_bluffing : int [1:72] 0 0 0 0 1 0 0 0 0 0 ...
## $ tf_boardgamecategory_card_game : int [1:72] 0 0 0 1 0 1 1 0 1 0 ...
## $ tf_boardgamecategory_childrens_game : int [1:72] 0 0 0 0 0 1 0 0 0 0 ...
## $ tf_boardgamecategory_comic_book_strip : int [1:72] 0 0 0 0 0 1 0 0 0 0 ...
## $ tf_boardgamecategory_deduction : int [1:72] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_dice : int [1:72] 0 0 1 0 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_economic : int [1:72] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_educational : int [1:72] 0 0 0 1 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_exploration : int [1:72] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_fantasy : int [1:72] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_fighting : int [1:72] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_horror : int [1:72] 0 1 0 0 0 0 1 0 0 0 ...
## $ tf_boardgamecategory_humor : int [1:72] 0 0 0 0 1 0 0 0 0 0 ...
## $ tf_boardgamecategory_medieval : int [1:72] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_memory : int [1:72] 0 0 0 1 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_miniatures : int [1:72] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_movies_tv_radio_theme: int [1:72] 0 0 0 0 0 0 1 0 0 0 ...
## $ tf_boardgamecategory_negotiation : int [1:72] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_party_game : int [1:72] 0 0 0 0 1 0 0 0 0 0 ...
## $ tf_boardgamecategory_print_play : int [1:72] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_puzzle : int [1:72] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_science_fiction : int [1:72] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_territory_building : int [1:72] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_trivia : int [1:72] 1 0 0 1 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_wargame : int [1:72] 0 0 0 0 0 0 0 0 0 0 ...
## $ tf_boardgamecategory_world_war_ii : int [1:72] 0 0 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(game_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_game_rs <-
tune_grid(
xgb_wf,
game_folds,
grid = 5,
control = control_race(verbose_elim = TRUE, pkgs = "tidyverse")
)
## i Creating pre-processing data to finalize unknown parameter: mtry
xgb_game_rs
## # Tuning results
## # 10-fold cross-validation using stratification
## # A tibble: 10 × 4
## splits id .metrics .notes
## <list> <chr> <list> <list>
## 1 <split [63/9]> Fold01 <tibble [10 × 7]> <tibble [2 × 3]>
## 2 <split [63/9]> Fold02 <tibble [10 × 7]> <tibble [1 × 3]>
## 3 <split [63/9]> Fold03 <tibble [10 × 7]> <tibble [1 × 3]>
## 4 <split [63/9]> Fold04 <tibble [10 × 7]> <tibble [1 × 3]>
## 5 <split [66/6]> Fold05 <tibble [10 × 7]> <tibble [1 × 3]>
## 6 <split [66/6]> Fold06 <tibble [10 × 7]> <tibble [1 × 3]>
## 7 <split [66/6]> Fold07 <tibble [10 × 7]> <tibble [1 × 3]>
## 8 <split [66/6]> Fold08 <tibble [10 × 7]> <tibble [1 × 3]>
## 9 <split [66/6]> Fold09 <tibble [10 × 7]> <tibble [1 × 3]>
## 10 <split [66/6]> Fold10 <tibble [10 × 7]> <tibble [1 × 3]>
##
## There were issues with some computations:
##
## - Warning(s) x11: 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_game_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 20 659 21 rmse standard 0.716 10 0.0649 Preprocessor1_Model3
## 2 7 1954 31 rmse standard 0.762 10 0.0623 Preprocessor1_Model1
## 3 32 1236 10 rmse standard 0.765 10 0.0627 Preprocessor1_Model5
## 4 14 1057 8 rmse standard 0.788 10 0.0570 Preprocessor1_Model2
## 5 24 382 36 rmse standard 0.817 10 0.0599 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_game_rs, "rmse")) %>%
last_fit(game_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 [72/24]> 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)
game_shap <-
shap.prep(
xgb_model = extract_fit_engine(xgb_fit),
X_train = bake(game_prep,
has_role("predictor"),
new_data = NULL,
composition = "matrix"
)
)
Now we can make visualizations! We can look at an overall summary:
shap.plot.summary(game_shap)
Or create partial dependence plots for specific variables:
shap.plot.dependence(
game_shap,
x = "minage",
color_feature = "minplayers",
size0 = 1.2,
smooth = FALSE, add_hist = TRUE
)
Learning this kind of complex, non-linear behavior is where xgboost models shine.