1. Setup Chunk:

This chunk is setting an option for the knitr package to include code when rendering the R Markdown document. echo = TRUE means that the code chunks will be displayed in the output.

# Load necessary libraries
library(readxl)
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/
library(tidyverse)
## Warning: package 'forcats' was built under R version 4.3.2
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats   1.0.0     ✔ readr     2.1.4
## ✔ lubridate 1.9.2     ✔ stringr   1.5.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ readr::col_factor() masks scales::col_factor()
## ✖ purrr::discard()    masks scales::discard()
## ✖ dplyr::filter()     masks stats::filter()
## ✖ stringr::fixed()    masks recipes::fixed()
## ✖ dplyr::lag()        masks stats::lag()
## ✖ readr::spec()       masks yardstick::spec()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(finetune)
library(janitor)
## 
## Attaching package: 'janitor'
## 
## The following objects are masked from 'package:stats':
## 
##     chisq.test, fisher.test
# Set knitr options
knitr::opts_chunk$set(echo = TRUE)

2. Loading Libraries and Reading Data:

Here, you are loading three libraries (readxl, tidymodels, and tidyverse). Then, you read an Excel file (“Game By Game - Team Offensive Statistics.xlsx”) into a data frame called Game_By_Game_Team_Offensive_Statistics, and you assign it to the variable data.

# Read data
Game_By_Game_Team_Offensive_Statistics <- read_excel("Game By Game - Team Offensive Statistics.xlsx")
data <- Game_By_Game_Team_Offensive_Statistics

Goal

Our modeling goal is to be able to predict whether the PSU Football team will win a game based on their offensive production.

Explore Data

3. Summary of Data:

This chunk generates a summary of the data, displaying descriptive statistics for each variable.

# Display summary of data
summary(data)
##    OPPONENT            RUSH ATT        RUSH YDS        RUSH TD     
##  Length:165         Min.   :21.00   Min.   : -5.0   Min.   :0.000  
##  Class :character   1st Qu.:37.00   1st Qu.: 97.0   1st Qu.:1.000  
##  Mode  :character   Median :44.00   Median :156.0   Median :1.000  
##                     Mean   :44.81   Mean   :168.3   Mean   :1.776  
##                     3rd Qu.:52.00   3rd Qu.:232.0   3rd Qu.:3.000  
##                     Max.   :81.00   Max.   :415.0   Max.   :7.000  
##    RUSH Long       RECEPTIONS        REC YDS          REC TD     
##  Min.   : 5.00   Min.   : 0.000   Min.   :  0.0   Min.   :0.000  
##  1st Qu.:15.00   1st Qu.: 5.000   1st Qu.: 64.0   1st Qu.:0.000  
##  Median :23.00   Median : 8.000   Median : 96.0   Median :1.000  
##  Mean   :26.58   Mean   : 8.539   Mean   :109.7   Mean   :0.903  
##  3rd Qu.:34.00   3rd Qu.:12.000   3rd Qu.:145.0   3rd Qu.:1.000  
##  Max.   :70.00   Max.   :25.000   Max.   :397.0   Max.   :3.000  
##     REC Long        PASS YDS        PASS TD        PASS Long    
##  Min.   : 0.00   Min.   :  0.0   Min.   :0.000   Min.   : 0.00  
##  1st Qu.:22.00   1st Qu.: 64.0   1st Qu.:0.000   1st Qu.:22.00  
##  Median :30.00   Median : 96.0   Median :1.000   Median :30.00  
##  Mean   :32.94   Mean   :109.7   Mean   :0.903   Mean   :32.94  
##  3rd Qu.:42.00   3rd Qu.:145.0   3rd Qu.:1.000   3rd Qu.:42.00  
##  Max.   :90.00   Max.   :397.0   Max.   :3.000   Max.   :90.00  
##     KICK ATT        KICK YDS         KICK TD          KICK Long    
##  Min.   :0.000   Min.   :  0.00   Min.   :0.00000   Min.   : 0.00  
##  1st Qu.:2.000   1st Qu.: 36.00   1st Qu.:0.00000   1st Qu.:21.00  
##  Median :3.000   Median : 68.00   Median :0.00000   Median :28.00  
##  Mean   :3.709   Mean   : 76.01   Mean   :0.04848   Mean   :31.65  
##  3rd Qu.:5.000   3rd Qu.:103.00   3rd Qu.:0.00000   3rd Qu.:37.00  
##  Max.   :9.000   Max.   :290.00   Max.   :1.00000   Max.   :95.00  
##     PUNT ATT        PUNT YDS         PUNT TD          PUNT Long     
##  Min.   :0.000   Min.   : -3.00   Min.   :0.00000   Min.   : 0.000  
##  1st Qu.:0.000   1st Qu.:  0.00   1st Qu.:0.00000   1st Qu.: 0.000  
##  Median :1.000   Median :  4.00   Median :0.00000   Median : 2.000  
##  Mean   :1.291   Mean   : 12.36   Mean   :0.05455   Mean   : 7.352  
##  3rd Qu.:2.000   3rd Qu.: 17.00   3rd Qu.:0.00000   3rd Qu.:11.000  
##  Max.   :5.000   Max.   :127.00   Max.   :1.00000   Max.   :85.000  
##      W/L                 WIN        
##  Length:165         Min.   :0.0000  
##  Class :character   1st Qu.:0.0000  
##  Mode  :character   Median :1.0000  
##                     Mean   :0.5394  
##                     3rd Qu.:1.0000  
##                     Max.   :1.0000

How does the amount of rushing yards and receiving yards affect win percentage?

4. Exploratory Data Analysis - Hexbin Plot for Rushing Yards and Receiving Yards:

This code creates a hexbin plot to visualize the relationship between rushing yards (RUSH YDS), receiving yards (REC YDS), and the win percentage (WIN).

data %>%
  ggplot(aes(`RUSH YDS`, `REC YDS`, z = WIN)) +
  stat_summary_hex(alpha = 0.8, bins = 15) +
  scale_fill_viridis_c(labels = scales::percent) +
  labs(fill = "% win")

It looks like PSU has a better chance to win when they have over 200 rushing yards and roughly 125 receiving yards.

How do the number of offensive touchdowns affect win percentage?

5. Exploratory Data Analysis - Hexbin Plot for Rushing Touchdowns and Receiving Touchdowns:

This code creates another hexbin plot, this time for rushing touchdowns (RUSH TD), receiving touchdowns (REC TD), and the win percentage (WIN).

data %>%
  ggplot(aes(`RUSH TD`, `REC TD`, z = WIN)) +
  stat_summary_hex(alpha = 0.8, bins = 15) +
  scale_fill_viridis_c(labels = scales::percent) +
  labs(fill = "% win")

It looks like as long as the offense scores 3 rushing touchdowns they will have an increased chance at winning!

Let’s transform the data into something usable.

6. Data Transformation:

This chunk cleans the column names of the data frame using the clean_names function and stores the result in a new data frame called Cleaned_data.

Cleaned_data <- data %>%
  clean_names()

Let’s build a model to figure out which variables are most important in determining a win.

7. Data Splitting for Modeling:

This code sets the seed for reproducibility, converts the win variable to a factor with levels “Win” and “Loss”, performs an initial split into training and testing sets, and creates cross-validation folds (data_folds) for model evaluation.

set.seed(123)
data_split <- Cleaned_data %>%
  mutate(
    win = if_else(as.logical(win), "Win", "Loss"),
    win = factor(win)
  ) %>%
  initial_split(strata = win)
data_train <- training(data_split)
data_test <- testing(data_split)

set.seed(234)
data_folds <- vfold_cv(data_train, strata = win)
data_folds
## #  10-fold cross-validation using stratification 
## # A tibble: 10 × 2
##    splits           id    
##    <list>           <chr> 
##  1 <split [110/13]> Fold01
##  2 <split [110/13]> Fold02
##  3 <split [110/13]> Fold03
##  4 <split [110/13]> Fold04
##  5 <split [110/13]> Fold05
##  6 <split [110/13]> Fold06
##  7 <split [111/12]> Fold07
##  8 <split [112/11]> Fold08
##  9 <split [112/11]> Fold09
## 10 <split [112/11]> Fold10

Let’s build a recipe to predict a win

8. Recipe for Data Preprocessing:

This chunk defines a recipe (data_rec) for preprocessing the data. It includes steps like handling novel levels in the opponent variable and converting unknown levels to dummy variables.

data_rec <- recipe(win ~ ., data = data_train) %>%
  step_novel(opponent) %>%
  step_unknown(all_nominal_predictors()) %>%
  step_dummy(all_nominal_predictors()) 

# Check the prepared data
prepped_data <- prep(data_rec)

# Print the prepped data
print(prepped_data)
## 
## ── Recipe ──────────────────────────────────────────────────────────────────────
## 
## ── Inputs
## Number of variables by role
## outcome:    1
## predictor: 21
## 
## ── Training information
## Training data contained 123 data points and no incomplete rows.
## 
## ── Operations
## • Novel factor level assignment for: opponent | Trained
## • Unknown factor level assignment for: opponent, w_l | Trained
## • Dummy variables from: opponent, w_l | Trained

9. Model Specification and Workflow:

This code specifies a boosted tree model using the xgboost algorithm and sets up a workflow (xgb_wf) that combines the preprocessing recipe and the model specification.

xgb_spec <-
  boost_tree(
    trees = tune(),
    min_n = tune(),
    mtry = tune(),
    learn_rate = 0.01
  ) %>%
  set_engine("xgboost") %>%
  set_mode("classification")

xgb_wf <- workflow(data_rec, xgb_spec)

Use racing to tune xgboost

10. Tuning XGBoost Hyperparameters:

This chunk performs hyperparameter tuning for the xgboost model using racing, parallelizing the process with doParallel.

library(finetune)
doParallel::registerDoParallel()

set.seed(345)
xgb_rs <- tune_race_anova(
  xgb_wf,
  resamples = data_folds,
  grid = 15,
  metrics = metric_set(mn_log_loss),
  control = control_race(verbose_elim = TRUE)
)
## i Creating pre-processing data to finalize unknown parameter: mtry
## ℹ Racing will minimize the mn_log_loss metric.
## ℹ Resamples are analyzed in a random order.
## ℹ Fold10: All but one parameter combination were eliminated.

11. Plotting Racing Results:

This code plots the racing results, showing the performance of different hyperparameter combinations.

plot_race(xgb_rs)

12. Displaying Best Hyperparameters:

This code displays the best hyperparameters based on the racing results.

show_best(xgb_rs)
## # A tibble: 1 × 9
##    mtry trees min_n .metric     .estimator  mean     n std_err .config          
##   <int> <int> <int> <chr>       <chr>      <dbl> <int>   <dbl> <chr>            
## 1    38  1273     6 mn_log_loss binary     0.139    10 0.00445 Preprocessor1_Mo…

13. Finalizing the Model and Making Predictions:

This chunk finalizes the workflow by selecting the best hyperparameters and fits the model to the entire training dataset.

xgb_last <- xgb_wf %>%
  finalize_workflow(select_best(xgb_rs, "mn_log_loss")) %>%
  last_fit(data_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 [123/42]> train/test split <tibble> <tibble> <tibble>     <workflow>

14. Evaluating Model Performance:

This code collects predictions from the final model and calculates the log loss on the training data.

collect_predictions(xgb_last) %>%
  mn_log_loss(win, .pred_Win)
## # A tibble: 1 × 3
##   .metric     .estimator .estimate
##   <chr>       <chr>          <dbl>
## 1 mn_log_loss binary          2.11

15. Feature Importance Plot:

Finally, this chunk uses the vip package to create a variable importance plot for the top 15 features in the final model.

library(vip)
## 
## Attaching package: 'vip'
## The following object is masked from 'package:utils':
## 
##     vi
extract_workflow(xgb_last) %>%
  extract_fit_parsnip() %>%
  vip(geom = "point", num_features = 15)