-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.html
3176 lines (2404 loc) · 110 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="" xml:lang="">
<head>
<title>Machine Learning in R</title>
<meta charset="utf-8" />
<meta name="author" content="Simon Schölzel" />
<script src="libs/header-attrs-2.11/header-attrs.js"></script>
<link href="libs/panelset-0.2.6/panelset.css" rel="stylesheet" />
<script src="libs/panelset-0.2.6/panelset.js"></script>
<script src="libs/xaringanExtra-webcam-0.0.1/webcam.js"></script>
<script id="xaringanExtra-webcam-options" type="application/json">{"width":"200","height":"200","margin":"1em"}</script>
<link href="libs/xaringanExtra-extra-styles-0.2.6/xaringanExtra-extra-styles.css" rel="stylesheet" />
<meta name="github-repo" content="simonschoe/ml-with-tidymodels"/>
<meta name="twitter:title" content="Modeling Workflows with Tidymodels"/>
<meta name="twitter:description" content="Video series on tidymodels, a unified framework towards modeling and machine learning in R using tidy data principles."/>
<meta name="twitter:url" content="https://simonschoe.github.io/ml-with-tidymodels"/>
<meta name="twitter:image" content="https://simonschoe.github.io/ml-with-tidymodels/img/share-card.png"/>
<meta name="twitter:image:alt" content="Title slide for Modeling Workflows with Tidymodels"/>
<meta name="twitter:card" content="summary_large_image"/>
<meta property="og:title" content="Modeling Workflows with Tidymodels"/>
<meta property="og:description" content="Video series on tidymodels, a unified framework towards modeling and machine learning in R using tidy data principles."/>
<meta property="og:url" content="https://simonschoe.github.io/ml-with-tidymodels"/>
<meta property="og:image" content="https://simonschoe.github.io/ml-with-tidymodels/img/share-card.png"/>
<meta property="og:image:alt" content="Title slide for Modeling Workflows with Tidymodels"/>
<meta property="og:type" content="website"/>
<meta property="og:locale" content="en_US"/>
<meta property="article:author" content="Simon Schölzel"/>
<link rel="stylesheet" href="custom/xaringan-themer.css" type="text/css" />
<link rel="stylesheet" href="custom/custom-theme.css" type="text/css" />
</head>
<body>
<textarea id="source">
class: center, middle, hide-count
count: false
# Machine Learning in R
### Modeling Workflows with Tidymodels
___
**Simon Schölzel**
Winter Term 2021/2022
.small[(updated: 2021-10-22)]
<br><br>
<a href="https://www.wiwi.uni-muenster.de/"><img src="https://www.wiwi.uni-muenster.de/fakultaet/sites/all/themes/wwucd/assets/images/logos/secondary_wiwi_aacsb_german.jpg" alt="fb4-logo" height="45"></a> <a href="https://www.wiwi.uni-muenster.de/ctrl/aktuelles"><img src="https://www.wiwi.uni-muenster.de/ctrl/sites/all/themes/wwucd/assets/images/logos/berenslogo5.jpg" alt="ftb-logo" height="45"></a> <a href="https://www.wiwi.uni-muenster.de/iff2/de/news"><img src="https://www.wiwi.uni-muenster.de/iff2/sites/all/themes/wwucd/assets/images/logos/logo_iff2_en2.jpg" alt="ipb-logo" height="45"></a>
---
name: agenda
## Agenda
**1 Learning Objectives**
**2 Introduction to `tidymodels`**
**3 Himalayan Climbing Expeditions Data**
**4 The Core `tidymodels` Packages**
>4.1 `rsample`: General Resampling Infrastructure
4.2 `recipes`: Preprocessing Tools to Create Design Matrices
4.3 `parsnip`: A Common API to Modeling and Analysis Functions
4.4 `workflows`: Modeling Workflows
4.5 `dials`: Tools for Creating Tuning Parameter Values
4.6 `tune`: Tidy Tuning Tools
4.7 `broom`: Convert Statistical Objects into Tidy Tibbles
4.8 `yardstick`: Tidy Characterizations of Model Performance
**5 Additions to the `tidymodels` Ecosystem**
---
## 1 Learning Objectives 💡
This workshop introduces `tidymodels`, a unified framework towards modeling and machine learning in `R` using tidy data principles. You will get to know tools that facilitate every step of your machine learning workflow, from resampling, over preprocessing and model building, to model tuning and performance evaluation.
More specifically, after this lecture you will
- be familiar with the core packages of the `tidymodels` ecosystem and hopefully realize the value of a unified modeling framework,<br><br>
- know how to design a full-fledged machine learning pipeline for a particular prediction task,<br><br>
- broaden your technical skill set by learning about declarative programming, hyperparameter scales and parallel processing, and<br><br>
- most importantly, be capable of conducting your own machine learning projects in `R`.
---
class: middle, center, inverse
# 2 Introduction to `tidymodels`
---
background-image: url(https://www.tidymodels.org/images/tidymodels.png)
background-position: 97.5% 2.5%
background-size: 7.5%
layout: true
---
## 2 Introduction to `tidymodels`
> The tidymodels framework is a collection of packages for modeling and machine learning using tidyverse principles. ~ [tidymodels.org](https://www.tidymodels.org/)
.pull-left[.center[
<img src="https://raw.githubusercontent.com/tidymodels/tidymodels/master/tidymodels_hex.png" width="40%" height="40%" />
Official `tidymodels` [Hex Sticker](https://github.com/rstudio/hex-stickers)
]]
.pull-right[
.pull-left[
<img src="https://avatars.githubusercontent.com/u/12505835?v=4" width="80%" height="80%" />
**Julia Silge** - Software Engineer @ RStudio
]
.pull-right[
<img src="https://avatars.githubusercontent.com/u/5731043?v=4" width="80%" height="80%" />
**Max Kuhn** - Software Engineer @ RStudio
]]
--
> Whenever possible, the software should be able to protect users from committing mistakes. Software should make it easy for users to do the right thing. ~ [Kuhn/Silge (2021)](https://www.tmwr.org/software-modeling.html#software-modeling)
???
- a framework for modeling (guardrails) using using tidy data principles
- very similar to the unified `scikit-learn` package in the context of `Python`
- by the way, this is general a central distinction between R and Python: Python advocates the paradigm of having one unified approach for every problem (which makes it at times also less flexible)
---
## 2 Introduction to `tidymodels`
> The tidymodels framework is a **collection of packages** for modeling and machine learning using tidyverse principles. ~ [tidymodels.org](https://www.tidymodels.org/)
.pull-left[
**`tidymodels` core packages:**
- `rsample`: general methods for resampling
- `recipes`: unified interface to data preprocessing
- `parsnip`: unified interface to modeling
- `workflows`: combine model blueprints and preprocessing recipes
- `dials`: create tuning parameters
- `tune`: hyperparameter tuning
- `broom`: tidy model outputs
- `yardstick`: model evaluation
]
.pull-right[
<img src="./img/tidymodels-hex.PNG" width="85%" height="85%" style="display: block; margin: auto;" />
]
???
- tidymodels can be viewed as another meta-package that shares the design philosophy, grammar and data structures of the tidyverse
- each package has its own goal which makes tidymodels a modular collection of package
- A goal of the tidymodels packages is that the interfaces to common tasks are standardized
- we will discuss each package along the modeling workflow: resampling, preprocessing, model building, hyperparameter tuning, model evaluation
---
## 2 Introduction to `tidymodels`
> The tidymodels framework is a **collection of packages** for modeling and machine learning using tidyverse principles. ~ [tidymodels.org](https://www.tidymodels.org/)
```r
install.packages("tidymodels")
library(tidymodels)
```
```
-- Attaching packages ----------------------------- tidymodels 0.1.4 --
v broom 0.7.9 v recipes 0.1.17
v dials 0.0.10 v rsample 0.1.0
v dplyr 1.0.7 v tibble 3.1.4
v ggplot2 3.3.5 v tidyr 1.1.4
v infer 1.0.0 v tune 0.1.6
v modeldata 0.1.1 v workflows 0.2.3
v parsnip 0.1.7 v workflowsets 0.1.0
v purrr 0.3.4 v yardstick 0.0.8
-- Conflicts ------------------------------- tidymodels_conflicts() --
x purrr::discard() masks scales::discard()
x dplyr::filter() masks stats::filter()
x dplyr::lag() masks stats::lag()
x recipes::step() masks stats::step()
* Use suppressPackageStartupMessages() to eliminate package startup messages
```
???
Explain:
- very similar when you load the whole tidyverse
- as you can see tidymodels loads also some of the tidyverse packages (however, usually you would load both at the beginning of your R session) -> this means that some tidymodels functions also use dplyr, purrr and ggplot2 functionality
- again we have some conflicts here, so these functions override functions by the base `R` `stats` package
- `tidymodels v0.1.4`: relatively new package ecosystem, it is not unlikely that some of the features or function interfaces will change slightly in the future
---
## 2 Introduction to `tidymodels`
Remember, modeling is one of the main steps in our day-2-day data science workflow. And this is precisely where `tidymodels` fits in!
<br><br><br>
<img src="https://www.tmwr.org/premade/data-science-model.svg" width="75%" height="75%" style="display: block; margin: auto;" />
.center[
*Source: [Kuhn/Silge (2021), ch. 1.3](https://www.tmwr.org/software-modeling.html#model-phases)*
]
---
layout: false
class: middle, center, inverse
# 3 Himalayan Climbing<br>Expeditions Data
---
## 3 Himalayan Climbing Expeditions Data
In order to illustrate the features of the `tidymodels` ecosystem, we use the [Himalayan Climbing Expeditions](https://github.com/rfordatascience/tidytuesday/blob/master/data/2020/2020-09-22/readme.md) data set from the [`tidytuesday` project](https://github.com/rfordatascience/tidytuesday).
```r
# install.packages("tidytuesdayR")
tt_data <- tidytuesdayR::tt_load(2020, week = 39)
```
```
> --- Compiling #TidyTuesday Information for 2020-09-22 ----
> --- There are 3 files available ---
> --- Starting Download ---
>
> Downloading file 1 of 3: `peaks.csv`
> Downloading file 2 of 3: `members.csv`
> Downloading file 3 of 3: `expeditions.csv`
>
> --- Download complete ---
```
???
- Tidytuesday: social project to motivate the R online community to learn working with tools like ggplot2, dplyr and tidyr and applying them to real-world data
- around 50 different data sets right now
- this dataset consists of three different csv files
---
## 3 Himalayan Climbing Expeditions Data
The data set contains a large record of data spanning the 1905-2019 period about
- 🏔 the several **peaks** of the mountain range,
- 🐾 the conducted **expeditions** during this period, and
- 🧗♀️ the **members** of each expedition.
--
<br>
**Task:** Predict the likelihood of an expedition coming to a lethal end (i.e. *binary classification task*).
```r
tt_data$members %>%
skimr::skim()
```
```
> Output on next slide
```
???
- Motivations for the task: derive drivers for a successful expedition and eventually reduce death rates.
- use `skimr` package to get a high-level view of the data and most important descriptives
---
## 3 Himalayan Climbing Expeditions Data
.panelset[
.panel[
.panel-name[Data Summary]
```
> -- Data Summary ------------------------
> Values
> Name Piped data
> Number of rows 76519
> Number of columns 21
> _______________________
> Column type frequency:
> character 10
> logical 6
> numeric 5
> ________________________
> Group variables None
```
]
.panel[
.panel-name[Character Vars]
```
> -- Variable type: character ---------------------------------------------------------------------------
> # A tibble: 10 x 8
> skim_variable n_missing complete_rate min max empty n_unique whitespace
> * <chr> <int> <dbl> <int> <int> <int> <int> <int>
> 1 expedition_id 0 1 9 9 0 10350 0
> 2 member_id 0 1 12 12 0 76518 0
> 3 peak_id 0 1 4 4 0 391 0
> 4 peak_name 15 1.00 4 25 0 390 0
> 5 season 0 1 6 7 0 5 0
> 6 sex 2 1.00 1 1 0 2 0
> 7 citizenship 10 1.00 2 23 0 212 0
> 8 expedition_role 21 1.00 4 25 0 524 0
> 9 death_cause 75413 0.0145 3 27 0 12 0
> 10 injury_type 74807 0.0224 3 27 0 11 0
```
]
.panel[
.panel-name[Logical Vars]
```
> -- Variable type: logical -----------------------------------------------------------------------------
> # A tibble: 6 x 5
> skim_variable n_missing complete_rate mean count
> * <chr> <int> <dbl> <dbl> <chr>
> 1 hired 0 1 0.206 FAL: 60788, TRU: 15731
> 2 success 0 1 0.382 FAL: 47320, TRU: 29199
> 3 solo 0 1 0.00158 FAL: 76398, TRU: 121
> 4 oxygen_used 0 1 0.238 FAL: 58286, TRU: 18233
> 5 died 0 1 0.0145 FAL: 75413, TRU: 1106
> 6 injured 0 1 0.0224 FAL: 74806, TRU: 1713
```
]
.panel[
.panel-name[Numeric Vars]
```
> -- Variable type: numeric -----------------------------------------------------------------------------
> # A tibble: 5 x 11
> skim_variable n_missing complete_rate mean sd p0 p25 p50 p75 p100 hist
> * <chr> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr>
> 1 year 0 1 2000. 14.8 1905 1991 2004 2012 2019 ▁▁▁▃▇
> 2 age 3497 0.954 37.3 10.4 7 29 36 44 85 ▁▇▅▁▁
> 3 highpoint_metres 21833 0.715 7471. 1040. 3800 6700 7400 8400 8850 ▁▁▆▃▇
> 4 death_height_metres 75451 0.0140 6593. 1308. 400 5800 6600 7550 8830 ▁▁▂▇▆
> 5 injury_height_metres 75510 0.0132 7050. 1214. 400 6200 7100 8000 8880 ▁▁▂▇▇
```
]
]
???
**Pt. 1:**
- total of 76,519 expedition members
- categorization of data types
**Pt. 2:**
- three id columns, these are likely not supposed to end up in any predictive model -> in any case, if you have an id variable with predictive value you should question in the data generating process behind the id column
- 391 different peaks, but only 390 different peak names
- with 76,519 climbers, almost 1000 died (75,413 non-death causes), and another 600 came back injured (74,807 non-injured) -> imbalanced prediction task
- 524 different expedition roles
- why do we have five seasons? (probably an unknown category)
**Pt. 3:**
logical:
- never missing
- `hired` natives (around 20% of the expedition members)
- only 38% expeditions made it to the top (`success`)
- likely we can have expeditions that were successful, but where one or several member died
- died and injured corresponds to the numbers of `death_cause` and `injury_type`
**Pt. 4:**
numeric:
- hist of `year` expeditions took place more and more often in the two recent decades
- `age`: most climbers i would expect to be between 20-40, with few very old climbers (85), and some super young (7?!)
- `age` and `highpoint_metres` has a lot of missings!
usually, you would do a lot more EDA right now:
- plot of expedition year against success/failure rates -> more recent expeditions likely more successful as you know more about the region/have better equipment
- plot of age against success/failure rates -> younger, more athletic climbers more successful?
- check which peaks or seasons are most associated with climber deaths
- check if oxygen use is associated with death rates
- good practice is always to do a correlation matrix
---
## 3 Himalayan Climbing Expeditions Data
```r
climbers_df <- tt_data$members %>%
select(member_id, peak_name, season, year, sex, age, citizenship,
expedition_role, hired, solo, oxygen_used, success, died) %>%
filter((!is.na(sex) & !is.na(citizenship) & !is.na(peak_name) & !is.na(expedition_role)) == T) %>%
mutate(across(where(~ is.character(.) | is.logical(.)), as.factor))
climbers_df
```
```
> # A tibble: 76,471 x 13
> member_id peak_name season year sex age citizenship
> <fct> <fct> <fct> <dbl> <fct> <dbl> <fct>
> 1 AMAD78301-01 Ama Dablam Autumn 1978 M 40 France
> 2 AMAD78301-02 Ama Dablam Autumn 1978 M 41 France
> 3 AMAD78301-03 Ama Dablam Autumn 1978 M 27 France
> 4 AMAD78301-04 Ama Dablam Autumn 1978 M 40 France
> 5 AMAD78301-05 Ama Dablam Autumn 1978 M 34 France
> 6 AMAD78301-06 Ama Dablam Autumn 1978 M 25 France
> 7 AMAD78301-07 Ama Dablam Autumn 1978 M 41 France
> 8 AMAD78301-08 Ama Dablam Autumn 1978 M 29 France
> 9 AMAD79101-03 Ama Dablam Spring 1979 M 35 USA
> 10 AMAD79101-04 Ama Dablam Spring 1979 M 37 W Germany
> # ... with 76,461 more rows, and 6 more variables:
> # expedition_role <fct>, hired <fct>, solo <fct>,
> # oxygen_used <fct>, success <fct>, died <fct>
```
???
Note: After the removal of missing values in the `sex`, `citizenship`, `peak_name` and `expedition_role` predictor the data set shrinks 76,519 to 76,471 observations
---
layout: false
class: middle, center, inverse
# 4.1 `rsample`:<br><br>General Resampling Infrastructure
---
background-image: url(https://www.tidymodels.org/images/rsample.png)
background-position: 97.5% 2.5%
background-size: 7%
layout: true
---
name: data-split
## 4.1 `rsample`: Resampling Infrastructure
`rsample` provides methods for data partitioning (i.e. splitting the data into training and test set) and resampling (i.e. drawing repeated samples from the training set to obtain the sampling distributions).
<br>
--
**Data Partitioning:** First, let's divide our data into a training and test set via `initial_split()`. The resulting `rsplit` object indexes the original data points according to their data set membership.
```r
set.seed(2021)
climbers_split <- initial_split(climbers_df, prop = 0.8, strata = died)
climbers_split
```
```
> <Analysis/Assess/Total>
> <61176/15295/76471>
```
???
- for imbalanced samples, random sample can lead to catastrophic model
- strata: conduct a stratified split -> keep proportions (i.e. imbalance) in training as well as in test set (1.5% death cases) -> since sampling is random it might otherwise be case that sampling creates an even severer or slighter imbalance
- with regression problems, stratified samples can be drawn based on a binned outcome (e.g., quartiles)
- indexing is more memory efficient
---
## 4.1 `rsample`: Resampling Infrastructure
To extract the training and test data, we can use the `training()` and `testing()` functions.
.panelset[
.panel[.panel-name[Train Set]
```r
train_set <- training(climbers_split)
train_set
```
```
> # A tibble: 61,176 x 13
> member_id peak_name season year sex age citizenship
> <fct> <fct> <fct> <dbl> <fct> <dbl> <fct>
> 1 AMAD78301-01 Ama Dablam Autumn 1978 M 40 France
> 2 AMAD78301-02 Ama Dablam Autumn 1978 M 41 France
> 3 AMAD78301-04 Ama Dablam Autumn 1978 M 40 France
> 4 AMAD78301-06 Ama Dablam Autumn 1978 M 25 France
> 5 AMAD78301-08 Ama Dablam Autumn 1978 M 29 France
> 6 AMAD79101-03 Ama Dablam Spring 1979 M 35 USA
> 7 AMAD79101-04 Ama Dablam Spring 1979 M 37 W Germany
> 8 AMAD79101-05 Ama Dablam Spring 1979 M 23 USA
> 9 AMAD79101-01 Ama Dablam Spring 1979 M 44 USA
> 10 AMAD79101-06 Ama Dablam Spring 1979 M 25 USA
> # ... with 61,166 more rows, and 6 more variables:
> # expedition_role <fct>, hired <fct>, solo <fct>,
> # oxygen_used <fct>, success <fct>, died <fct>
```
]
.panel[.panel-name[Test Set]
```r
test_set <- testing(climbers_split)
test_set
```
```
> # A tibble: 15,295 x 13
> member_id peak_name season year sex age citizenship
> <fct> <fct> <fct> <dbl> <fct> <dbl> <fct>
> 1 AMAD78301-03 Ama Dablam Autumn 1978 M 27 France
> 2 AMAD78301-05 Ama Dablam Autumn 1978 M 34 France
> 3 AMAD78301-07 Ama Dablam Autumn 1978 M 41 France
> 4 AMAD79101-10 Ama Dablam Spring 1979 M 30 USA
> 5 AMAD79101-15 Ama Dablam Spring 1979 M 29 USA
> 6 AMAD79101-18 Ama Dablam Spring 1979 M 23 Nepal
> 7 AMAD79301-03 Ama Dablam Autumn 1979 F 33 France
> 8 AMAD79301-13 Ama Dablam Autumn 1979 M 31 France
> 9 AMAD79301-14 Ama Dablam Autumn 1979 M 28 France
> 10 AMAD79301-22 Ama Dablam Autumn 1979 M 31 France
> # ... with 15,285 more rows, and 6 more variables:
> # expedition_role <fct>, hired <fct>, solo <fct>,
> # oxygen_used <fct>, success <fct>, died <fct>
```
]
]
---
## 4.1 `rsample`: Resampling Infrastructure
**Resampling**: Training predictive models which involve hyperparameters requires a three-way data split:
- The *Training Set*, which is used for model training (i.e. estimating model coefficients).
- The *Validation Set*, which is used for parameter tuning (i.e. finding optimal hyperparameters).
- The *Test Set*, which is used for computing an unbiased estimate of model performance.
--
<br>
.panelset[
.panel[.panel-name[Option 1]
.pull-left[
**Validation Split:** Partition the initial `train_set` into a smaller training as well as a validation set using `validation_split()`.
]
.pull-right[
<img src="https://www.tmwr.org/premade/validation-alt.svg" width="40%" height="40%" style="display: block; margin: auto;" />
]
]
.panel[.panel-name[Option 2]
.pull-left[
**Resampling:** Use a resampling approach, such as cross-validation (CV) or the bootstrap, to create resamples from our initial training set.
A **resample** is the outcome of a resampling method, e.g., a fold resulting from `\(k\)`-fold cross-validation or a bootstrapped and out-of-bag sample resulting from The Bootstrap.
]
.pull-right[
<img src="https://www.tmwr.org/premade/resampling.svg" width="70%" height="70%" style="display: block; margin: auto;" />
]
]
]
???
Data sets:
- training to optimize model coefs, validation to optimize hyperparameters (as part of model tuning as well as feature engineering), test to evaluate the model
- refit the optimal model on training and validation set and evaluate on the test set
- i prefer the terms training and validation instead of analysis and assessment set in the context of resampling (often test, validation and hold-out set are used interchangeably)
CV vs. train-test-split:
- we usually prefer the former as we would like to generate a distribution of our error measure and to account for uncertainty in the estimate
- You may increase the number of folds as your sample size decreases to retain more datapoints for model training.
---
## 4.1 `rsample`: Resampling Infrastructure
Here we implement a 10-fold CV approach using the `vfold_cv()` function. It returns a `tibble` containing the indexes of 10 separate splits.
```r
set.seed(2021)
climbers_folds <- train_set %>%
vfold_cv(v = 10, repeats = 1, strata = died)
climbers_folds
```
```
> # 10-fold cross-validation using stratification
> # A tibble: 10 x 2
> splits id
> <list> <chr>
> 1 <split [55058/6118]> Fold01
> 2 <split [55058/6118]> Fold02
> 3 <split [55058/6118]> Fold03
> 4 <split [55058/6118]> Fold04
> 5 <split [55058/6118]> Fold05
> 6 <split [55058/6118]> Fold06
> 7 <split [55059/6117]> Fold07
> 8 <split [55059/6117]> Fold08
> 9 <split [55059/6117]> Fold09
> 10 <split [55059/6117]> Fold10
```
---
## 4.1 `rsample`: Resampling Infrastructure
To extract the training and validation data, we can again use `training()` and `testing()`.
.panelset[
.panel[.panel-name[Train Set]
```r
climbers_folds %>% purrr::pluck("splits", 1) %>% training()
```
```
> # A tibble: 55,058 x 13
> member_id peak_name season year sex age citizenship
> <fct> <fct> <fct> <dbl> <fct> <dbl> <fct>
> 1 AMAD78301-01 Ama Dablam Autumn 1978 M 40 France
> 2 AMAD78301-02 Ama Dablam Autumn 1978 M 41 France
> 3 AMAD78301-04 Ama Dablam Autumn 1978 M 40 France
> 4 AMAD78301-06 Ama Dablam Autumn 1978 M 25 France
> 5 AMAD78301-08 Ama Dablam Autumn 1978 M 29 France
> 6 AMAD79101-04 Ama Dablam Spring 1979 M 37 W Germany
> 7 AMAD79101-05 Ama Dablam Spring 1979 M 23 USA
> 8 AMAD79101-01 Ama Dablam Spring 1979 M 44 USA
> 9 AMAD79101-06 Ama Dablam Spring 1979 M 25 USA
> 10 AMAD79101-08 Ama Dablam Spring 1979 M 32 USA
> # ... with 55,048 more rows, and 6 more variables:
> # expedition_role <fct>, hired <fct>, solo <fct>,
> # oxygen_used <fct>, success <fct>, died <fct>
```
]
.panel[.panel-name[Test Set]
```r
climbers_folds %>% purrr::pluck("splits", 1) %>% testing()
```
```
> # A tibble: 6,118 x 13
> member_id peak_name season year sex age citizenship
> <fct> <fct> <fct> <dbl> <fct> <dbl> <fct>
> 1 AMAD79101-03 Ama Dablam Spring 1979 M 35 USA
> 2 AMAD79101-07 Ama Dablam Spring 1979 M 28 USA
> 3 AMAD79301-09 Ama Dablam Autumn 1979 M 25 France
> 4 AMAD79301-26 Ama Dablam Autumn 1979 M NA Nepal
> 5 AMAD79301-24 Ama Dablam Autumn 1979 M NA Nepal
> 6 AMAD79302-03 Ama Dablam Autumn 1979 M 27 New Zealand
> 7 AMAD79303-05 Ama Dablam Autumn 1979 M 36 Austria
> 8 AMAD80302-05 Ama Dablam Autumn 1980 M 24 Japan
> 9 AMAD81102-01 Ama Dablam Spring 1981 M 21 Australia
> 10 AMAD81301-05 Ama Dablam Autumn 1981 M 28 USA
> # ... with 6,108 more rows, and 6 more variables:
> # expedition_role <fct>, hired <fct>, solo <fct>,
> # oxygen_used <fct>, success <fct>, died <fct>
```
]
]
???
- usually, you don't use `training()` and `testing()` as you let higher level functions access the individual resamples during hyperparameter tuning
---
## 4.1 `rsample`: Resampling Infrastructure
**Alternative resampling approaches:** In conjunction to `\(k\)`-fold CV, `rsample` enables various alternative resampling schemes for producing a more robust estimate of model performance.
.panelset[
.panel[.panel-name[Repeated k-fold CV]
For `repeats > 1`, `vfold_cv()` repeats the CV approach to reduce the standard error of the estimate at the cost of higher computational demand ( `\(k∗R\)` folds).
```r
set.seed(2021)
train_set %>%
vfold_cv(v = 10, repeats = 2, strata = died)
```
]
.panel[.panel-name[The Bootstrap]
`bootstraps()` conducts sampling with replacement whereby model performance is estimated based on the "out-of-bag" observations.
```r
set.seed(2021)
train_set %>%
bootstraps(times = 25, strata = died)
```
]
.panel[.panel-name[Monte Carlo CV (MCCV)]
`mc_cv()` lies somewhere in between `\(k\)`-fold CV and the bootstraps since it enables partly overlapping assessment sets by generating each resample anew.
```r
set.seed(2021)
train_set %>%
mc_cv(prop = 0.9, times = 25, strata = died)
```
]
.panel[.panel-name[Time-Series Resampling]
<img src="https://i.stack.imgur.com/fXZ6k.png" width="40%" style="float:right; padding:10px" />
For temporally correlated data `rsample` provides a suitable partitioning and resampling infrastructure as well.
For example, use `initial_time_split()` to conduct a non-random early-late-split and `rolling_origin()` or the `slide_*()` methods to generate time-series resamples.
<br><br><br><br>
.right[
*Source: [Stack Exchange](https://stats.stackexchange.com/questions/14099/using-k-fold-cross-validation-for-time-series-model-selection)*
]
]
]
.footnote[
*Note: Find more information about the resampling approaches implemented in `rsample` in [Kuhn/Silge (2021), ch. 10](https://www.tmwr.org/resampling.html#resampling-methods).*
]
???
- repeated CV: reduces validation set error independent of the way the folds were resampled -> increases computational demand -> i have simply more estimates for the validation set error that I can average
- MC CV:
- create one resample by sampling 90% as training and 10% as validation set data
- create another resample by reperforming the previous step
- perform again 10 resamples are created
- with time-dependent data, random sampling can lead to disastrous models
---
layout: false
class: middle, center, inverse
# 4.2 `recipes`:<br><br>Preprocessing Tools to Create Design Matrices
---
background-image: url(https://www.tidymodels.org/images/recipes.png)
background-position: 97.5% 2.5%
background-size: 7%
layout: true
---
## 4.2 `recipes`: Preprocessing Tools
> In statistics, a **design matrix** (also known as **regressor matrix** or **model matrix**) is a matrix of values of explanatory variables of a set of objects, often denoted by `\(X\)`. Each row represents an individual object, with the successive columns corresponding to the variables and their specific values for that object. ~ [Wikipedia](https://en.wikipedia.org/wiki/Design_matrix)
<br>
--
Every model in `R` requires a design matrix as input. Intuitively, we can think of a design matrix as a tidy data frame (with one observation per row and one predictor per column) which can be directly processed by the model function.
--
Oftentimes, however, data frames or matrices that we apply to a model function do not come in the required format. For example:
- A linear model requires categorical predictors to be (one-hot) encoded as `\(C-1\)` binary dummies.
- In contrast, a decision tree can deal with categorical predictors.
- A support vector machine performs best with standardized predictors.
- And numerous models reject missing values in their model matrix.
.footnote[
*Note: Some functions internally convert a data frame to a numeric design matrix (e.g., `lm()` automatically one-hot encodes unordered factors and creates polynomial contrasts from ordered factors).*
]
???
Most R functions create the design matrix automatically from a given data frame according to the formula that is provided in the function call.
---
name: recipe-call
## 4.2 `recipes`: Preprocessing Tools
The `recipes` package provides functions for defining a blueprint for data preprocessing (aka *feature engineering*). Each `recipe` is constructed by chaining multiple preprocessing steps.
--
First, create a `recipe` object from your data using the `recipe()` function and the two arguments:
- `formula`: A formula to declare variable roles, i.e. everything on the left-hand side (LHS) of the `~` is declared as `outcome` and everything on the right-hand side (RHS) as `predictor`.
- `data`: The data to which the feature engineering steps are later applied. The data set is only used to catalogue the variables and their respective types (which is why you generally provide the training set).
```r
mod_recipe <- recipe(formula = died ~ ., data = train_set)
mod_recipe
```
```
> Recipe
>
> Inputs:
>
> role #variables
> outcome 1
> predictor 12
```
---
## 4.2 `recipes`: Preprocessing Tools
Second, we add new preprocessing steps to the recipe (using the family of `step_*()` functions):
- Use `update_role()` to assign a new custom role to a predictor. As `member_id` simply enumerates our observations, it is assigned the `"id"` role and hence not considered in any downstream modeling task.
```r
mod_recipe <- mod_recipe %>% update_role(member_id, new_role = "id")
mod_recipe
```
```
> Recipe
>
> Inputs:
>
> role #variables
> id 1
> outcome 1
> predictor 11
```
.pull-right[.pull-right[.footnote[
<i>Note: Change the role of a predictor to keep it in the data, however, without being used during model fitting. Usually `step_*()` functions do not change the role of a predictor. However, each `step_*()` function contains a `role` argument to explicitly specify the role of a newly generated predictor.</i>
]]]
???
- with the `new_role` argument I can set any custom role name
---
## 4.2 `recipes`: Preprocessing Tools
Second, we add new preprocessing steps to the recipe (using the family of `step_*()` functions):
- Use `step_impute_median()` to impute `NA` values by the median predictor value. Since roughly 3,500 missing values are inherent to `age`, we use median-imputation to retain those observations.
```r
mod_recipe <- mod_recipe %>% step_impute_median(age)
mod_recipe
```
```
> Recipe
>
> Inputs:
>
> role #variables
> id 1
> outcome 1
> predictor 11
>
> Operations:
>
> Median Imputation for age
```
???
- essence of recipes: the steps are only declared and not directly executed!
- we are constructing a blueprint which we can later apply in one go to our data
- median imputation is just one way of replacing missing values -> median more robust towards outlier
---
## 4.2 `recipes`: Preprocessing Tools
Second, we add new preprocessing steps to the recipe (using the family of `step_*()` functions):
- Use `step_normalize()` to scale numerical data to zero mean and unit standard deviation (which is required for scale-sensitive classifiers).
```r
mod_recipe <- mod_recipe %>% step_normalize(all_numeric_predictors())
mod_recipe
```
```
> Recipe
>
> Inputs:
>
> role #variables
> id 1
> outcome 1
> predictor 11
>
> Operations:
>
> Median Imputation for age
> Centering and scaling for all_numeric_predictors()
```
.pull-right[.pull-right[.footnote[
*Note: Variables can be selected by referring either to their name, their data type, their role (as specified by the recipe) or by using the `select()` helpers from `dplyr` (e.g., `contains()`, `starts_with()`).*
]]]
---
## 4.2 `recipes`: Preprocessing Tools
Second, we add new preprocessing steps to the recipe (using the family of `step_*()` functions):
- Use `step_other()` to lump together rarely occurring factor levels. `peak_name`, `citizenship` and `expedition_role` all have several 100 factor levels and hence a high risk of being near-zero variance predictors. All factor levels with a relative frequency below 5% are pooled into `"other"`.
```r
mod_recipe <- mod_recipe %>% step_other(peak_name, citizenship, expedition_role, threshold = 0.05)
mod_recipe
```
```
> Recipe
>
> Inputs:
>
> role #variables
> id 1
> outcome 1
> predictor 11
>
> Operations:
>
> Median Imputation for age
> Centering and scaling for all_numeric_predictors()
> Collapsing factor levels for peak_name, citizenship, expedit...
```
.pull-right[.pull-right[.footnote[
*Note: You should always take care of the order of your steps. For example, you should first lump together factor levels and then create dummies.*
]]]
---
## 4.2 `recipes`: Preprocessing Tools
Second, we add new preprocessing steps to the recipe (using the family of `step_*()` functions):
- Use `step_dummy()` to one-hot encode categorical predictors.
```r
mod_recipe <- mod_recipe %>% step_dummy(all_predictors(), -all_numeric(), one_hot = F)
mod_recipe
```
```
> Recipe
>
> Inputs:
>
> role #variables
> id 1
> outcome 1
> predictor 11
>
> Operations:
>
> Median Imputation for age
> Centering and scaling for all_numeric_predictors()
> Collapsing factor levels for peak_name, citizenship, expedit...
> Dummy variables from all_predictors(), -all_numeric()
```
.pull-right[.pull-right[.footnote[
*Note: Use `one_hot = T` in case you want to retain all `\(C\)` factor levels instead of just `\(C-1\)`.*
]]]
???
same holds for the normalize steps which should follow the median-impute step.
---
## 4.2 `recipes`: Preprocessing Tools