Introduction to machine learning with tidymodels

The basics

Author

Dr Jamie Soul

Loading the metapackage

The tidymodels packages loads a set of modular packages that we will use to build a machine learning workflow - from preparing the data to assessing the performance.

library(tidymodels)
── Attaching packages ────────────────────────────────────── tidymodels 1.1.0 ──
✔ broom        1.0.4     ✔ recipes      1.0.6
✔ dials        1.2.0     ✔ rsample      1.1.1
✔ dplyr        1.1.2     ✔ tibble       3.2.1
✔ ggplot2      3.4.2     ✔ tidyr        1.3.0
✔ infer        1.0.4     ✔ tune         1.1.1
✔ modeldata    1.1.0     ✔ workflows    1.1.3
✔ parsnip      1.1.0     ✔ workflowsets 1.0.1
✔ purrr        1.0.1     ✔ 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/

Example small classification problem

Let’s cover the basic principles with an example medical dataset looking to see if we can predict patients who have stroke from life style variables.

Note

Exploratory data analysis is a critical step is any data science project.

Here we use the skimr package to get an overview of the dataframe which quickly highlight the BMI column has missing values.

#load the needed libraries
library(tidyverse)
library(janitor)
library(skimr)
library(MLDataR)

#explicitly call the built in data
#warning - this dataset is only chosen for illustration purposes
#see bmi,smoking status versus age
data("stroke_classification")

#janitor is useful to make the column names tidy
stroke_classification <- clean_names(stroke_classification)
stroke_classification <- stroke_classification[ stroke_classification$gender %in% c("Male","Female"),]

#make the primary outcome a factor
stroke_classification$stroke <- as.factor(stroke_classification$stroke)

#Good idea to take a look at the data!
skim(stroke_classification)
Data summary
Name stroke_classification
Number of rows 5109
Number of columns 11
_______________________
Column type frequency:
character 1
factor 1
numeric 9
________________________
Group variables None

Variable type: character

skim_variable n_missing complete_rate min max empty n_unique whitespace
gender 0 1 4 6 0 2 0

Variable type: factor

skim_variable n_missing complete_rate ordered n_unique top_counts
stroke 0 1 FALSE 2 0: 4860, 1: 249

Variable type: numeric

skim_variable n_missing complete_rate mean sd p0 p25 p50 p75 p100 hist
pat_id 0 1.00 2555.39 1475.40 1.00 1278.00 2555.00 3833.00 5110.00 ▇▇▇▇▇
age 0 1.00 43.23 22.61 0.08 25.00 45.00 61.00 82.00 ▅▆▇▇▆
hypertension 0 1.00 0.10 0.30 0.00 0.00 0.00 0.00 1.00 ▇▁▁▁▁
heart_disease 0 1.00 0.05 0.23 0.00 0.00 0.00 0.00 1.00 ▇▁▁▁▁
work_related_stress 0 1.00 0.16 0.37 0.00 0.00 0.00 0.00 1.00 ▇▁▁▁▂
urban_residence 0 1.00 0.51 0.50 0.00 0.00 1.00 1.00 1.00 ▇▁▁▁▇
avg_glucose_level 0 1.00 106.14 45.29 55.12 77.24 91.88 114.09 271.74 ▇▃▁▁▁
bmi 201 0.96 28.89 7.85 10.30 23.50 28.10 33.10 97.60 ▇▇▁▁▁
smokes 0 1.00 0.63 0.48 0.00 0.00 1.00 1.00 1.00 ▅▁▁▁▇

Split into test and training

We want the model to generalise to new unseen data, so we split our dataset into a training and test dataset. We’ll fit the model on the training data then evaluate the performance on the unseen test data

#Need to set the seed to be reproducible
set.seed(42)

#save 25% of the data for testing the performance of the model
data_split <- initial_split(stroke_classification, prop = 0.75)

#get the train and test datasets
stroke_train <- training(data_split)
stroke_test  <- testing(data_split)

head(stroke_train)
     pat_id stroke gender age hypertension heart_disease work_related_stress
2609   2609      0 Female  56            0             0                   0
4070   4070      0   Male  31            0             0                   0
2369   2369      0 Female  28            0             0                   0
1098   1098      0   Male  52            0             0                   0
1252   1252      0   Male   4            0             0                   0
634     634      0 Female  42            0             0                   0
     urban_residence avg_glucose_level  bmi smokes
2609               0             77.66 40.8      0
4070               1            108.62   NA      1
2369               0             96.86 29.0      1
1098               1            229.20 35.6      1
1252               0            103.76 15.9      1
634                1             97.78 29.8      1

Preprocessing with recipes

library(recipes)

#set the base recipe - use stroke as the outcome and the rest of the data as predictors
stroke_rec <- 
  recipe(stroke ~ ., data = stroke_train)

stroke_rec
── Recipe ──────────────────────────────────────────────────────────────────────
── Inputs 
Number of variables by role
outcome:    1
predictor: 10

Watch out for data leakage!

This is a fundamental example of data leakage where the there is numeric patient ID column that is completely sufficient to distinguish between our outcome of interest. Often it is more subtle - see (Whalen et al. 2021)

library(cowplot)

ggplot(stroke_train,aes(pat_id,stroke)) +
  geom_jitter() +
  theme_cowplot()

Updating recipe to include an ID

Having spotted the problem now we can specify that this column should be used only as an ID column. We could have just removed this column, but it is useful to keep track of individual observations in the modelling steps.

stroke_rec <- stroke_rec %>%
  update_role(pat_id, new_role = "ID")

stroke_rec
── Recipe ──────────────────────────────────────────────────────────────────────
── Inputs 
Number of variables by role
outcome:   1
predictor: 9
ID:        1

Encode gender as a dummy variable

Many models require categorical variables such as be transformed into numeric dummy variables i.e 0 and 1

#Create dummy variables for the gender
 stroke_rec <- stroke_rec%>%
  step_dummy(gender)

stroke_rec
── Recipe ──────────────────────────────────────────────────────────────────────
── Inputs 
Number of variables by role
outcome:   1
predictor: 9
ID:        1
── Operations 
• Dummy variables from: gender

Can impute the missing BMI values

We may have missing data in more or one of our predictors. This can be a big problem is fields such as proteomics, where the missingness may relate to the of interest outcome itself.

stroke_rec <- stroke_rec %>%
step_normalize(bmi,age,avg_glucose_level) %>%
  step_impute_knn(bmi)

What does the data look like when processed?

Useful to check that the preprocessing isn’t doing anything unexpected.

stroke_rec %>% prep() %>% bake(NULL)
# A tibble: 3,831 × 11
   pat_id     age hypertension heart_disease work_related_stress urban_residence
    <int>   <dbl>        <int>         <int>               <int>           <int>
 1   2609  0.561             0             0                   0               0
 2   4070 -0.549             0             0                   0               1
 3   2369 -0.682             0             0                   0               0
 4   1098  0.384             0             0                   0               1
 5   1252 -1.75              0             0                   0               0
 6    634 -0.0603            0             0                   0               1
 7   2097  0.961             0             0                   0               1
 8   3912  0.162             0             0                   0               1
 9    356  1.01              1             0                   0               0
10   4262 -0.815             0             0                   0               0
# ℹ 3,821 more rows
# ℹ 5 more variables: avg_glucose_level <dbl>, bmi <dbl>, smokes <int>,
#   stroke <fct>, gender_Male <dbl>

Select a model with parsnip

The choice of model depends on your application and type of data. Starting with a simple model is usually a good option to set a baseline for performance.

show_engines("logistic_reg")
# A tibble: 7 × 2
  engine    mode          
  <chr>     <chr>         
1 glm       classification
2 glmnet    classification
3 LiblineaR classification
4 spark     classification
5 keras     classification
6 stan      classification
7 brulee    classification

Select a model with parsnip

Here we’ll choose glm as we have binary outcome data with a handful of predictors. Later we’ll talk about what to do in genomics applications where we may have thousands of predictors.

lm_mod <- logistic_reg() %>% set_engine("glm")
lm_mod
Logistic Regression Model Specification (classification)

Computational engine: glm 

Make a workflow

Workflows aim to make it easy to keep a track of the recipe used to preprocess data and the model used to fit the data.

library(workflows)

#add the model and the recipe to a workflow
stroke_wflow <- 
  workflow() %>% 
  add_model(lm_mod) %>% 
  add_recipe(stroke_rec)

stroke_wflow
══ Workflow ════════════════════════════════════════════════════════════════════
Preprocessor: Recipe
Model: logistic_reg()

── Preprocessor ────────────────────────────────────────────────────────────────
3 Recipe Steps

• step_dummy()
• step_normalize()
• step_impute_knn()

── Model ───────────────────────────────────────────────────────────────────────
Logistic Regression Model Specification (classification)

Computational engine: glm 

Fit to the data

Now we can finally run the workflow which preprocces the data and fits the model of the training data.

stroke_fit <- 
  stroke_wflow %>% 
  fit(data = stroke_train)

stroke_fit
══ Workflow [trained] ══════════════════════════════════════════════════════════
Preprocessor: Recipe
Model: logistic_reg()

── Preprocessor ────────────────────────────────────────────────────────────────
3 Recipe Steps

• step_dummy()
• step_normalize()
• step_impute_knn()

── Model ───────────────────────────────────────────────────────────────────────

Call:  stats::glm(formula = ..y ~ ., family = stats::binomial, data = data)

Coefficients:
        (Intercept)                  age         hypertension  
           -4.18936              1.63005              0.25536  
      heart_disease  work_related_stress      urban_residence  
            0.35684             -0.43530              0.08764  
  avg_glucose_level                  bmi               smokes  
            0.22029             -0.09157              0.22546  
        gender_Male  
            0.03141  

Degrees of Freedom: 3830 Total (i.e. Null);  3821 Residual
Null Deviance:      1500 
Residual Deviance: 1188     AIC: 1208

Extract the fit data

extract_fit_parsnip allows us to get the underlying fitted model from a workflow and tidy from the broom package gives us a nicely formatted tibble.

Different models have different ways of interpreting the importance of the variables. Here we can look at the significance of the coefficients and see that age and avg_glucose_level are positively associated with a stroke in the training set.

stroke_fit %>% 
  extract_fit_parsnip() %>% 
  tidy()
# A tibble: 10 × 5
   term                estimate std.error statistic  p.value
   <chr>                  <dbl>     <dbl>     <dbl>    <dbl>
 1 (Intercept)          -4.19      0.215    -19.5   1.01e-84
 2 age                   1.63      0.139     11.7   1.37e-31
 3 hypertension          0.255     0.197      1.30  1.94e- 1
 4 heart_disease         0.357     0.215      1.66  9.71e- 2
 5 work_related_stress  -0.435     0.189     -2.30  2.12e- 2
 6 urban_residence       0.0876    0.159      0.550 5.82e- 1
 7 avg_glucose_level     0.220     0.0627     3.51  4.40e- 4
 8 bmi                  -0.0916    0.105     -0.876 3.81e- 1
 9 smokes                0.225     0.167      1.35  1.77e- 1
10 gender_Male           0.0314    0.163      0.193 8.47e- 1

Predict with the test set

Now we have trained the model let’s test the performance on the data we haven’t used to fit on.

augment adds the class probabilities as well as the hard class prediction.

#get the predictions for the test set.
stroke_aug <- 
  augment(stroke_fit, stroke_test)

head(stroke_aug)
# A tibble: 6 × 14
  pat_id stroke gender   age hypertension heart_disease work_related_stress
   <int> <fct>  <chr>  <dbl>        <int>         <int>               <int>
1      5 1      Female    79            1             0                   1
2     11 1      Female    81            1             0                   0
3     21 1      Female    71            0             0                   0
4     22 1      Female    52            1             0                   1
5     23 1      Female    79            0             0                   1
6     24 1      Male      82            0             1                   0
# ℹ 7 more variables: urban_residence <int>, avg_glucose_level <dbl>,
#   bmi <dbl>, smokes <int>, .pred_class <fct>, .pred_0 <dbl>, .pred_1 <dbl>

Let’s look a the performance

The yardstick package has all lots of functions related to assessing how well a model is performing. To calculate the accuracy of the model of the test data we used the know outcome skroke or not truth and the predicted outcome of the model estimate.

library(yardstick)


#The accuracy is really high!
accuracy(stroke_aug, truth=stroke,estimate=.pred_class)
# A tibble: 1 × 3
  .metric  .estimator .estimate
  <chr>    <chr>          <dbl>
1 accuracy binary         0.952

It is useful to understand where the model is making mistakes. What does the confusion matrix look like?

#ah!
conf_mat(stroke_aug,stroke, .pred_class)
          Truth
Prediction    0    1
         0 1217   61
         1    0    0

We’ve created a model which has predicted every patient hasn’t had a stroke! This is likely to because the number of observed strokes in the dataset is very low so a model which simply predicts no one has had a stroke performs very well as judged by accuracy alone.

Note

Accuracy is a poor metric to use on datasets with class imbalance.

Look at the AUC

Instead of using the class predictions we can instead use a metric ROC AUC that looks at the ranks of patient probabilities of having a stroke.

two_class_curve <- roc_curve(stroke_aug, truth=stroke, .pred_0)
autoplot(two_class_curve)

The ROC AUC is reasonable so the class boundaries need shifting (default 0.5) to better predict the stroke category of patients.

roc_auc(stroke_aug,stroke, .pred_0)
# A tibble: 1 × 3
  .metric .estimator .estimate
  <chr>   <chr>          <dbl>
1 roc_auc binary         0.836

Try changing the class boundary threshold

The probably package allows us to iterate through many thresholds of the class boundary and look at the trade off between sensitivity and specificity.

library(probably)

threshold_data <- stroke_aug %>%
  threshold_perf(stroke, .pred_0, thresholds = seq(0.7, 1, by = 0.01))

The J index is one way of choosing a threshold and is defined as specificity + sensitivity -1 We can plot the data to see the relationship.

max_j_index_threshold <- threshold_data %>%
  filter(.metric == "j_index") %>%
  filter(.estimate == max(.estimate)) %>%
  pull(.threshold)

ggplot(threshold_data, aes(x = .threshold, y = .estimate, color = .metric)) +
  geom_line() +
  geom_vline(xintercept = max_j_index_threshold, alpha = .6, color = "grey30") + theme_cowplot()

Take homes

  • Check your data, particularly if not your own

  • Split into training and testing appropriately

  • Watch out for data leakage and class imbalance

  • Choose the appropriate metric for performance, thinking what the model will be used for.

References

Whalen, Sean, Jacob Schreiber, William S. Noble, and Katherine S. Pollard. 2021. “Navigating the Pitfalls of Applying Machine Learning in Genomics.” Nature Reviews Genetics 23 (3): 169–81. https://doi.org/10.1038/s41576-021-00434-9.