In this analysis, let’s fit a model to predict the average moving rating from horror movies dating back to the 1950’s.

library(tidymodels)
## ── Attaching packages ────────────────────────────────────── tidymodels 1.1.1 ──
## ✔ broom        1.0.5     ✔ recipes      1.0.8
## ✔ dials        1.2.0     ✔ rsample      1.2.0
## ✔ dplyr        1.1.3     ✔ tibble       3.2.1
## ✔ ggplot2      3.4.3     ✔ tidyr        1.3.0
## ✔ infer        1.0.5     ✔ tune         1.1.2
## ✔ modeldata    1.2.0     ✔ workflows    1.1.3
## ✔ parsnip      1.1.1     ✔ workflowsets 1.0.1
## ✔ purrr        1.0.2     ✔ yardstick    1.2.0
## ── Conflicts ───────────────────────────────────────── tidymodels_conflicts() ──
## ✖ purrr::discard() masks scales::discard()
## ✖ dplyr::filter()  masks stats::filter()
## ✖ dplyr::lag()     masks stats::lag()
## ✖ recipes::step()  masks stats::step()
## • Learn how to get started at https://www.tidymodels.org/start/
horror_movies <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-11-01/horror_movies.csv')
## Rows: 32540 Columns: 20
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (10): original_title, title, original_language, overview, tagline, post...
## dbl   (8): id, popularity, vote_count, vote_average, budget, revenue, runtim...
## lgl   (1): adult
## date  (1): release_date
## 
## ℹ 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.
horror_movies %>%
  ggplot(aes(vote_average)) +
  geom_histogram(bins = 15)

Explore data

What are the most common words used to describe the genres in the horror movies.

library(tidytext)

tidy_horror <-
  horror_movies %>%
  unnest_tokens(word, genre_names)

tidy_horror %>%
  count(word, sort = TRUE)
## # A tibble: 21 × 2
##    word         n
##    <chr>    <int>
##  1 horror   32543
##  2 thriller  7680
##  3 comedy    4963
##  4 drama     4271
##  5 mystery   3138
##  6 fiction   2714
##  7 science   2714
##  8 fantasy   2195
##  9 action    1966
## 10 crime     1153
## # ℹ 11 more rows

What is the mean rating for these words?

tidy_horror %>%
  group_by(word) %>%
  summarise(
    n = n(),
    rating = mean(vote_average)
  ) %>%
  ggplot(aes(n, rating)) +
  geom_hline(
    yintercept = mean(horror_movies$vote_average), linewidth = 2,
    color = "gray50", size = 1.5
  ) +
  geom_jitter(color = "midnightblue", alpha = 0.7) +
  geom_text(aes(label = word),
    check_overlap = TRUE,
    vjust = "top", hjust = "left"
  ) +
  scale_x_log10()
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

Build models

set.seed(123)
horror_split <- initial_split(horror_movies, strata = revenue)
horror_train <- training(horror_split)
horror_test <- testing(horror_split)

set.seed(234)
horror_folds <- vfold_cv(horror_train, strata = revenue)
horror_folds
## #  10-fold cross-validation using stratification 
## # A tibble: 10 × 2
##    splits               id    
##    <list>               <chr> 
##  1 <split [21964/2441]> Fold01
##  2 <split [21964/2441]> Fold02
##  3 <split [21964/2441]> Fold03
##  4 <split [21964/2441]> Fold04
##  5 <split [21964/2441]> Fold05
##  6 <split [21965/2440]> Fold06
##  7 <split [21965/2440]> Fold07
##  8 <split [21965/2440]> Fold08
##  9 <split [21965/2440]> Fold09
## 10 <split [21965/2440]> Fold10

Let’s transform our text data into features useful for our model by tokenizing and computing (in this case) tf-idf

library(textrecipes)

horror_rec <-
  recipe(vote_average ~ genre_names, data = horror_train) %>%
  step_tokenize(genre_names) %>%
  step_tokenfilter(genre_names, max_tokens = 21) %>%
  step_tfidf(genre_names)

## just to check this works
prep(horror_rec) %>% bake(new_data = NULL)
## # A tibble: 24,405 × 22
##    vote_average tfidf_genre_names_action tfidf_genre_names_adventure
##           <dbl>                    <dbl>                       <dbl>
##  1          7.1                    0                           1.32 
##  2          6.8                    0                           0    
##  3          7.9                    0                           0    
##  4          7                      0                           0    
##  5          5.8                    0                           0    
##  6          6.5                    0.359                       0.496
##  7          6.8                    0                           0    
##  8          7.3                    0                           0    
##  9          6.1                    0                           0    
## 10          6.1                    0                           0    
## # ℹ 24,395 more rows
## # ℹ 19 more variables: tfidf_genre_names_animation <dbl>,
## #   tfidf_genre_names_comedy <dbl>, tfidf_genre_names_crime <dbl>,
## #   tfidf_genre_names_documentary <dbl>, tfidf_genre_names_drama <dbl>,
## #   tfidf_genre_names_family <dbl>, tfidf_genre_names_fantasy <dbl>,
## #   tfidf_genre_names_fiction <dbl>, tfidf_genre_names_history <dbl>,
## #   tfidf_genre_names_horror <dbl>, tfidf_genre_names_movie <dbl>, …

Now let’s create two model specifications to compare. Random forests are not known for performing well with natural language predictors, but this dataset involves very short text descriptions so let’s give it a try. Support vector machines do tend to work well with text data so let’s include that one too.

rf_spec <-
  rand_forest(trees = 500) %>%
  set_mode("regression")

rf_spec
## Random Forest Model Specification (regression)
## 
## Main Arguments:
##   trees = 500
## 
## Computational engine: ranger
svm_spec <-
  svm_linear() %>%
  set_mode("regression")

svm_spec
## Linear Support Vector Machine Model Specification (regression)
## 
## Computational engine: LiblineaR

Now it’s time to put the preprocessing and model together in a workflow()

svm_wf <- workflow(horror_rec, svm_spec)
rf_wf <- workflow(horror_rec, rf_spec)

Evaluate models

These models have no tuning parameters so we can evaluate them as they are. Learn about tuning hyperparameters here.

doParallel::registerDoParallel()
contrl_preds <- control_resamples(save_pred = TRUE)

svm_rs <- fit_resamples(
  svm_wf,
  resamples = horror_folds,
  control = contrl_preds
)

ranger_rs <- fit_resamples(
  rf_wf,
  resamples = horror_folds,
  control = contrl_preds
)

How did these two models compare?

collect_metrics(svm_rs)
## # A tibble: 2 × 6
##   .metric .estimator   mean     n std_err .config             
##   <chr>   <chr>       <dbl> <int>   <dbl> <chr>               
## 1 rmse    standard   2.80      10 0.00730 Preprocessor1_Model1
## 2 rsq     standard   0.0492    10 0.00126 Preprocessor1_Model1
collect_metrics(ranger_rs)
## # A tibble: 2 × 6
##   .metric .estimator   mean     n std_err .config             
##   <chr>   <chr>       <dbl> <int>   <dbl> <chr>               
## 1 rmse    standard   2.81      10 0.00712 Preprocessor1_Model1
## 2 rsq     standard   0.0465    10 0.00112 Preprocessor1_Model1

We can visualize these results by comparing the predicted rating with the true rating:

bind_rows(
  collect_predictions(svm_rs) %>%
    mutate(mod = "SVM"),
  collect_predictions(ranger_rs) %>%
    mutate(mod = "ranger")
) %>%
  ggplot(aes(vote_average, .pred, color = id)) +
  geom_abline(lty = 2, color = "gray50", size = 1.2) +
  geom_jitter(width = 0.5, alpha = 0.5) +
  facet_wrap(vars(mod)) +
  coord_fixed()

These models perform similarly, but the data in the ranger fit better as the line hit more data points. Perhaps we would choose ranger model. The function last_fit() fits one final time on the training data and evaluates on the testing data. This is the first time we have used the testing data.

final_fitted <- last_fit(rf_wf, horror_split)
collect_metrics(final_fitted)  ## metrics evaluated on the *testing* data
## # A tibble: 2 × 4
##   .metric .estimator .estimate .config             
##   <chr>   <chr>          <dbl> <chr>               
## 1 rmse    standard      2.82   Preprocessor1_Model1
## 2 rsq     standard      0.0441 Preprocessor1_Model1

This object contains a fitted workflow that we can use for prediction.

final_wf <- extract_workflow(final_fitted)
predict(final_wf, horror_test[55,])
## # A tibble: 1 × 1
##   .pred
##   <dbl>
## 1  3.80