-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.html
2430 lines (1711 loc) · 61 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>Intro to tidymodels with nflfastR</title>
<meta charset="utf-8" />
<meta name="author" content="Tom Mock: @thomas_mock" />
<meta name="date" content="2020-10-24" />
<script src="tidymodels_intro_files/header-attrs-2.4/header-attrs.js"></script>
<link rel="stylesheet" href="xaringan-themer.css" type="text/css" />
</head>
<body>
<textarea id="source">
class: center, middle, inverse, title-slide
# Intro to <code>tidymodels</code> with <code>nflfastR</code>
### Tom Mock: <a href="https://twitter.com/thomas_mock"><code>@thomas_mock</code></a>
### 2020-10-24
---
layout: true
<div class="my-footer"><span>cmsac-tidymodels.netlify.app/</span></div>
<!-- this adds the link footer to all slides, depends on my-footer class in css-->
---
### What have I done?
* Scored 100% of our game-winning goals on my 2010 College Lacrosse Team (we only won 1 game 😢)
* Bachelor's in Kinesiology (2011) - Effect of Sugar vs Sugar-Free Mouth Rinse on Performance
* Master's in Exercise Physiology (2014) - Effect of Exercise on Circulating Brain Biomarkers
* PhD in Neurobiology (2018) - Effect of Aging + Glutathione Deficiency on Motor and Cognitive Function
--
### What do I do?
* RStudio, Customer Success (2018 - Current) - I run our High Technology + Sports vertical, helping RStudio's customers use our Pro and open source software to solve problems with data
--
* [`#TidyTuesday`](https://github.com/rfordatascience/tidytuesday/blob/master/README.md) - Weekly data analysis community project (~4,000 participants in past 3 years)
--
* [TheMockUp.blog](https://themockup.blog/) - Explanatory blogging about `How to do Stuff` with data + `#rstats`, *mostly* with NFL data
--
* [`espnscrapeR`](https://jthomasmock.github.io/espnscrapeR/) - collect data from ESPN's public APIs, mostly for QBR and team standings
---
.pull-left[
### The `nflscrapR` team:
(data from 2009-current)
* Maksim Horowitz
* Ron Yurko
* Sam Ventura
* Rishav Dutta
### The `nflfastR` team:
(data from 2000-current)
* Ben Baldwin
* Sebastian Carl
]
.pull-right[
<img src="https://pbs.twimg.com/profile_images/1076883081192263680/hj53KzOl_400x400.jpg" width="50%" />
<img src="https://raw.githubusercontent.com/mrcaseb/nflfastR/master/man/figures/logo.png" width="50%" />
]
These datasets set the bar for publicly-available NFL data!
---
### Shoutout to the NFL Big Data Bowl
![](https://storage.googleapis.com/kaggle-competitions/kaggle/15696/logos/thumb76_76.png?t=2019-10-04-16-17-46)
[Kaggle link](https://www.kaggle.com/c/nfl-big-data-bowl-2021)
> This competition uses NFL’s Next Gen Stats data, which includes the position and speed of every player on the field during each play. You’ll employ player tracking data for all drop-back pass plays from the 2018 regular season. The goal of submissions is to identify unique and impactful approaches to measure defensive performance on these plays.
---
### Personas
* You've done some modeling in R
💻 + 📈
--
* You're interested in fitting models in R with sports data
💻 + 📈 + 🏈
--
* You've used the `tidyverse` for analyses and `purrr` specifically for nested data
⭐ + 🐱
--
* You're new to `tidymodels` AND you want to fit models to sports data
💡 + 💻 + 📈 + 🏈
--
* You're awesome because you came to CMSAC!
🙌 🏈
---
### Focus for Today
90 Minutes (with breaks)
Binary classification:
- Logistic Regression
- Random Forest
--
Slides at: [cmsac-tidymodels.netlify.app/](https://cmsac-tidymodels.netlify.app/#1)
Source code at: [github.com/jthomasmock/nfl-workshop](https://github.com/jthomasmock/nfl-workshop)
--
To follow along, you can read in the subsetted data with the code below:
```r
raw_plays <- read_rds(
url("https://github.com/jthomasmock/nfl-workshop/blob/master/raw_plays.rds?raw=true")
)
```
---
### Level-Setting
As much as I'd love to learn and teach *all* of Machine Learning/Statistics in 90 min...
--
It's just not possible!
--
### Goals for today
* Make you comfortable with the **syntax** and **packages** via `tidymodels` unified interface
* So when you're learning or modeling on your own, you get to focus on the **stats** rather than re-learning different APIs over and over...
--
Along the way, we'll cover minimal examples and then some more quick best practices where `tidymodels` makes it easier to do more things!
---
# `tidymodels`
`tidymodels` is a collection of packages for modeling and machine learning using `tidyverse` principles.
## Packages
* `rsample`: efficient data splitting and resampling
* `parsnip`: tidy, unified interface to models
* `recipes`: tidy interface to data pre-processing tools for feature engineering
* `workflows`: bundles your pre-processing, modeling, and post-processing
* `tune`: helps optimize the hyperparameters and pre-processing steps
* `yardstick`: measures the performance metrics
* `dials`: creates and manages tuning parameters/grids
* `broom`: converts common R statistical objects into predictable formats
* [`broom` available methods](https://broom.tidymodels.org/articles/available-methods.html)
---
class: inverse, center, middle
# `tidymodels` vs `broom` *alone*
---
### `broom`
> `broom` summarizes key information about models in tidy `tibble()`s.
--
> `broom` tidies 100+ models from popular modelling packages and almost all of the model objects in the `stats` package that comes with base R. `vignette("available-methods")` lists method availability.
--
> While broom is useful for summarizing the result of a single analysis in a consistent format, it is really designed for high-throughput applications, where you must combine results from multiple analyses.
--
I *personally* use `broom` for more classical statistics and `tidymodels` for machine learning. A more detailed summary of what `broom` is about can be found in the [`broom` docs](https://cran.r-project.org/web/packages/broom/vignettes/broom.html).
---
### Before we get to sweeping
Why do we care so much about QBs, passing, and EPA?
--
.pull-left[
<img src="images/qbr_win_plot.png" width="85%" />
]
--
.pull-right[
<img src="images/qbr_win_tab.png" width="50%" />
]
---
### `lm()` example
.pull-left[
```r
# get all weekly QBR for 2020 season
basic_data <- crossing(
season = 2020, week = 1:6
) %>%
pmap_dfr(espnscrapeR::get_nfl_qbr)
basic_plot <- basic_data %>%
ggplot(
aes(x = total_epa, y = qbr_total)
) +
geom_point() +
geom_smooth(method = "lm") +
theme_minimal() +
labs(
x = "EPA", y = "QBR",
title = "EPA is correlated with QBR"
)
```
]
--
.pull-right[
<img src="tidymodels_intro_files/figure-html/unnamed-chunk-8-1.png" width="360" />
]
---
### `base` example
.small[
```r
# fit a basic linear model
basic_lm <- lm(qbr_total~total_epa, data = basic_data)
```
]
--
.small[
```r
basic_lm
```
```
##
## Call:
## lm(formula = qbr_total ~ total_epa, data = basic_data)
##
## Coefficients:
## (Intercept) total_epa
## 31.696 6.007
```
]
--
.small[
```r
summary(basic_lm)
```
```
##
## Call:
## lm(formula = qbr_total ~ total_epa, data = basic_data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -26.6789 -7.3896 -0.2737 7.1539 27.7642
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 31.6959 1.3716 23.11 <2e-16 ***
## total_epa 6.0065 0.2186 27.48 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 10.78 on 182 degrees of freedom
## Multiple R-squared: 0.8058, Adjusted R-squared: 0.8047
## F-statistic: 755.2 on 1 and 182 DF, p-value: < 2.2e-16
```
]
---
### `broom` example
```r
broom::tidy(basic_lm)
```
```
## # A tibble: 2 x 5
## term estimate std.error statistic p.value
## <chr> <dbl> <dbl> <dbl> <dbl>
## 1 (Intercept) 31.7 1.37 23.1 5.02e-56
## 2 total_epa 6.01 0.219 27.5 1.12e-66
```
--
```r
broom::glance(basic_lm)
```
```
## # A tibble: 1 x 12
## r.squared adj.r.squared sigma statistic p.value df logLik AIC BIC
## <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 0.806 0.805 10.8 755. 1.12e-66 1 -698. 1401. 1411.
## # … with 3 more variables: deviance <dbl>, df.residual <int>, nobs <int>
```
---
#### Want more `broom`?
There's a lot more to `broom` for *tidy-ier* modeling - out of scope for today, but I have a detailed [**blogpost**](https://themockup.blog/posts/2020-05-01-tidy-long-models/).
.medium[
```r
tidy_off_models <- nest_off_data %>%
mutate(
fit = map(data, ~ lm(value.y ~ value.x, data = .x)),
tidy_output = map(fit, glance)
)
tidy_off_models
```
]
--
.medium[
```
# # A tibble: 12 x 4
# metric data fit tidy_output
# <chr> <list> <list> <list>
# 1 pass_att <tibble [593 × 5]> <lm> <tibble [1 × 12]>
# 2 pass_comp_pct <tibble [593 × 5]> <lm> <tibble [1 × 12]>
# 3 yds_att <tibble [593 × 5]> <lm> <tibble [1 × 12]>
# 4 pass_yds <tibble [593 × 5]> <lm> <tibble [1 × 12]>
# 5 pass_td <tibble [593 × 5]> <lm> <tibble [1 × 12]>
# 6 int <tibble [593 × 5]> <lm> <tibble [1 × 12]>
# 7 pass_rating <tibble [593 × 5]> <lm> <tibble [1 × 12]>
# 8 first_downs <tibble [593 × 5]> <lm> <tibble [1 × 12]>
# 9 pass_first_pct <tibble [593 × 5]> <lm> <tibble [1 × 12]>
# 10 pass_20plus <tibble [593 × 5]> <lm> <tibble [1 × 12]>
# 11 pass_40plus <tibble [593 × 5]> <lm> <tibble [1 × 12]>
# 12 sacks <tibble [593 × 5]> <lm> <tibble [1 × 12]>
```
]
---
#### Want more `broom`?
There's a lot more to `broom` for *tidy-ier* modeling - out of scope for today, but I have a detailed [**blogpost**](https://themockup.blog/posts/2020-05-01-tidy-long-models/).
<img src="https://themockup.blog/posts/2020-05-01-tidy-long-models/distill-preview.png" width="60%" />
---
class:inverse, center, middle
# Tidy Machine Learning w/ `tidymodels`
<img src="https://raw.githubusercontent.com/rstudio/hex-stickers/master/SVG/tidymodels.svg" width="25%" />
---
### Core ideas for Today
A workflow for `tidy` machine learning
* Split the data
* Pre-Process and Choose a Model
* Combine into a Workflow
* Generate Predictions and Assess Model Metrics
---
# Goal of Machine Learning
### 🔨 construct models that
--
### 🎯 generate accurate predictions
--
### 🆕 for future, yet-to-be-seen data
--
[Feature Engineering - Max Kuhn and Kjell Johnston](http://www.feat.engineering/) and Alison Hill
---
### Classification
Showing two examples today, comparing their outcomes, and then giving you the chance to explore on your own!
--
But how do you assess classifier accuracy?
---
### Assessing Accuracy
Accuracy = How often the classifier is correct out of the total possible predictions?
--
Accuracy = True Positives + True Negatives / (True Positives + True Negatives + False Positives + False Negatives)
--
* True Positive Rate (Sensitivity/Recall):
- Out of all **true positives**, how many did you predict right?
- True Positives / (True Positives + False Negatives)
- Usually plotted on Y for ROC curve
--
* True Negative Rate (Specificity):
- Out of all **true negatives**, how many did you predict right?
- True Negatives / (True Negatives + False Positives)
- Usually plotted on X as `1 - Specificity` for ROC curve
--
There are several other types of calculations you can generate, but these cover the core ideas
---
#### ROC Curve example
.medium[
* False Positive Rate == (`1 - Specificity`) on X
* True Positive Rate (Sensitivity) on Y
]
--
.medium[
* AUC = Area Under the Curve (higher = better)
]
--
<img src="https://bradleyboehmke.github.io/HOML/02-modeling-process_files/figure-html/modeling-process-roc-1.png" width="50%" />
Adapted from [Hands on Machine Learning with R](https://bradleyboehmke.github.io/HOML/process.html#classification-models)
---
### Assessing Accuracy
Confusion Matrix: Predicted vs Actual
- True Positive vs False Positive
- False Negative vs True Negative
- 🎯 Goal: Maximize the True, Minimize the False (or maybe not)
---
### Confusion Matrix
<img src="images/gt1.png" width="75%" />
Adapted from [Hands on Machine Learning with R](https://bradleyboehmke.github.io/HOML/process.html#classification-models)
---
### Confusion Matrix
<img src="images/gt2.png" width="75%" />
Adapted from [Hands on Machine Learning with R](https://bradleyboehmke.github.io/HOML/process.html#classification-models)
---
### Confusion Matrix
.pull-left[
```
## Truth
## Prediction Event Non-Event
## Event 10918 3647
## Non-Event 2665 5763
```
]
.pull-right[
```r
table_conf_mat %>%
autoplot("heatmap")
```
<img src="tidymodels_intro_files/figure-html/unnamed-chunk-23-1.png" width="360" />
]
---
### Calibration Plot
How well do the predictions stand up against the observed?
.pull-left[
<img src="tidymodels_intro_files/figure-html/unnamed-chunk-24-1.png" width="432" />
]
--
.pull-right[
<img src="https://www.tmwr.org/figures/resampling-cv-pred-plot-1.svg" width="75%" />
]
---
class: inverse, center, middle
# Break!
# ☕
---
### The Dataset
Filtered down from the `nflscrapR` and `nflfastR` datasets (~2.25 GB) to only non-penalty run and pass plays for the 2017-2019 regular seasons, and on downs 1st, 2nd or 3rd. This is about 92,000 plays.
--
#### The goal: Predict if an upcoming play will be a `run` or a `pass`
--
.small[
```r
glimpse(raw_plays)
```
```
## Rows: 91,976
## Columns: 20
## $ game_id <dbl> 2017090700, 2017090700, 2017090700, 201709…
## $ posteam <chr> "NE", "NE", "NE", "NE", "NE", "NE", "NE", …
## $ play_type <chr> "pass", "pass", "run", "run", "pass", "run…
## $ yards_gained <dbl> 0, 8, 8, 3, 19, 5, 16, 0, 2, 7, 0, 3, 10, …
## $ ydstogo <dbl> 10, 10, 2, 10, 7, 10, 5, 2, 2, 10, 10, 10,…
## $ down <dbl> 1, 2, 3, 1, 2, 1, 2, 1, 2, 1, 1, 2, 3, 1, …
## $ game_seconds_remaining <dbl> 3595, 3589, 3554, 3532, 3506, 3482, 3455, …
## $ yardline_100 <dbl> 73, 73, 65, 57, 54, 35, 30, 2, 2, 75, 32, …
## $ qtr <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, …
## $ posteam_score <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 7, …
## $ defteam <chr> "KC", "KC", "KC", "KC", "KC", "KC", "KC", …
## $ defteam_score <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, …
## $ score_differential <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, -7, 7, 7, 7, 7,…
## $ shotgun <dbl> 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, …
## $ no_huddle <dbl> 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, …
## $ posteam_timeouts_remaining <dbl> 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, …
## $ defteam_timeouts_remaining <dbl> 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, …
## $ wp <dbl> 0.5060180, 0.4840546, 0.5100098, 0.5529816…
## $ goal_to_go <dbl> 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, …
## $ half_seconds_remaining <dbl> 1795, 1789, 1754, 1732, 1706, 1682, 1655, …
```
]
---
### Data Prep
I use `dbplyr` only pull into memory the specific rows/columns we need from the 2.2 GB of data on disk. Full details about `dbplyr` + `nflfastR` data on my [**blog**](https://themockup.blog/posts/2019-04-28-nflfastr-dbplyr-rsqlite/), and there's a `update_db()` function in `nflfastR` itself!
.medium[
```r
pbp_db <- tbl(DBI::dbConnect(RSQLite::SQLite(), "pbp_db.sqlite"), "pbp_clean_2000-2019")
raw_plays <- pbp_db %>%
filter(
play_type %in% c("run", "pass"),
penalty == 0,
qtr <= 4,
season_type == "REG",
season >= 2017,
down %in% c(1:3),
!is.na(yardline_100)
) %>%
select(
game_id, posteam,
play_type, yards_gained, ydstogo, down, game_seconds_remaining,
yardline_100, qtr, posteam, posteam_score, defteam, defteam_score,
score_differential, shotgun, no_huddle, posteam_timeouts_remaining,
defteam_timeouts_remaining, wp, goal_to_go, half_seconds_remaining
) %>%
collect()
```
]
---
### Feature Engineering
I added a few features, namely a running total of number of runs/passes pre-snap and what the previous play was.
.small[
```r
all_plays <- raw_plays %>%
group_by(game_id, posteam) %>%
mutate(
run = if_else(play_type == "run", 1, 0),
pass = if_else(play_type == "pass", 1, 0),
total_runs = if_else(play_type == "run", cumsum(run) - 1, cumsum(run)),
total_pass = if_else(play_type == "pass", cumsum(pass) - 1, cumsum(pass)),
previous_play = if_else(posteam == lag(posteam),
lag(play_type), "First play of Drive"
),
previous_play = if_else(is.na(previous_play),
replace_na("First play of Drive"), previous_play
)
) %>%
ungroup() %>%
mutate_at(vars(
play_type, shotgun, no_huddle,
posteam_timeouts_remaining, defteam_timeouts_remaining,
previous_play, goal_to_go
), as.factor) %>%
mutate(
down = factor(down, levels = c(1, 2, 3), ordered = TRUE),
qtr = factor(qtr, levels = c(1, 2, 3, 4), ordered = TRUE),
in_red_zone = if_else(yardline_100 <= 20, 1, 0),
in_fg_range = if_else(yardline_100 <= 35, 1, 0),
two_min_drill = if_else(half_seconds_remaining <= 120, 1, 0)
) %>%
mutate(
in_red_zone = factor(if_else(yardline_100 <= 20, 1, 0)),
in_fg_range = factor(if_else(yardline_100 <= 35, 1, 0)),
two_min_drill = factor(if_else(half_seconds_remaining <= 120, 1, 0))
) %>%
select(-run, -pass)
```
]
---
### Core ideas for Today
A workflow for `tidy` machine learning
* Split the data
* Pre-Process and Choose a Model
* Combine into a Workflow
* Generate Predictions and Assess Model Metrics
---
### Split
```r
split_data <- initial_split(data, 0.75)
train_data <- training(split_data)
test_data <- testing(split_data)
```
---
### Pre-Process & choose a model
```r
model_recipe <- recipe(pred ~ predictors, data = train_data)
```
```r
# Choose a model and an engine
lr_mod <- logistic_reg(mode = "classification") %>%
set_engine("glm")
```
---
### Combine into a workflow
```r
# Combine the model and recipe to the workflow
lr_wflow <- workflow() %>%
add_recipe(model_recipe) %>%
add_model(lr_mod)
# Fit/train the model
model_fit <- lr_wflow %>%
fit(data = train_data)
```
---
### Predict and get metrics
```r
# Get predictions
pred_lr <- predict(pbp_fit_lr, test_data)
# Check metrics
pred_lr %>%
metrics(truth = pred, .pred_class) %>%
bind_cols(select(test_data, pred)) %>%
bind_cols(predict(fit_lr, test_data, type = "prob"))
```
---
.small[
**Split**
```r
# Split
split_pbp <- initial_split(all_plays, 0.75, strata = play_type)
# Split into test/train
train_data <- training(split_pbp)
test_data <- testing(split_pbp)
```
**Pre-Process & Choose a model**
```r
pbp_rec <- recipe(play_type ~ ., data = train_data) %>%
step_rm(half_seconds_remaining) %>% # remove
step_string2factor(posteam, defteam) %>% # convert to factors
update_role(yards_gained, game_id, new_role = "ID") %>% # add as ID
step_corr(all_numeric(), threshold = 0.7) %>% # remove auto-correlated
step_center(all_numeric()) %>% # substract mean from numeric
step_zv(all_predictors()) # remove zero-variance predictors
# Choose a model and an engine
lr_mod <- logistic_reg(mode = "classification") %>%
set_engine("glm")
```
**Combine into a workflow**
```r
# Combine the model and recipe to the workflow
lr_wflow <- workflow() %>%
add_recipe(pbp_rec) %>%
add_model(lr_mod)
# Fit/train the model
pbp_fit_lr <- lr_wflow %>%
fit(data = train_data)
```
**Predict and get metrics**
```r
# Get predictions
pbp_pred_lr <- predict(pbp_fit_lr, test_data) %>%
bind_cols(test_data %>% select(play_type)) %>%
bind_cols(predict(pbp_fit_lr, test_data, type = "prob"))
# Check metrics
pbp_pred_lr %>%
metrics(truth = play_type, .pred_class)
```
]
---
class: inverse, center, middle
# `rsample`
![](https://raw.githubusercontent.com/tidymodels/rsample/master/man/figures/logo.png)
---
### `rsample`
Now that I've created the dataset to use, I'll start with `tidymodels` proper.
`rsample` at a mininum does your train/test split, but also takes care of things like boostrapping, stratification, v-fold cross validation, validation splits, rolling origin, etc.
---
## Data Splitting w/ `rsample`
Do the initial split and stratify by play type to make sure there are equal ratios of run vs pass in `test` and `train`
```r
split_pbp <- initial_split(all_plays, 0.75, strata = play_type)
split_pbp
```
```
## <Analysis/Assess/Total>
## <68983/22993/91976>
```
```r
# separate the training data
train_data <- training(split_pbp)
# separate the testing data
test_data <- testing(split_pbp)
```
---
### Test vs Train
Split into `train_data` and `test_data` and then confirm the ratios.
.medium[
```r
train_data %>%
count(play_type) %>%
mutate(ratio = n/sum(n))
```
```
## # A tibble: 2 x 3
## play_type n ratio
## <fct> <int> <dbl>
## 1 pass 40752 0.591
## 2 run 28231 0.409
```
```r
test_data %>%
count(play_type) %>%
mutate(ratio = n/sum(n))
```
```
## # A tibble: 2 x 3
## play_type n ratio
## <fct> <int> <dbl>
## 1 pass 13583 0.591
## 2 run 9410 0.409
```
]
---
class: inverse, center, middle
# Model `recipes`
![](https://raw.githubusercontent.com/tidymodels/recipes/master/man/figures/logo.png)
---
## Add recipe steps with `recipes`
`recipe` steps are changes we make to the dataset, including things like centering, dummy encoding, update columns as ID only, or even custom feature engineering.
```r
pbp_rec <- recipe(play_type ~ ., data = train_data) %>%
step_rm(half_seconds_remaining) %>% # remove
step_string2factor(posteam, defteam) %>% # convert to factors
# ignore these vars for train/test, but include in data as ID
update_role(yards_gained, game_id, new_role = "ID") %>%
# removes vars that have large absolute correlations w/ other vars
step_corr(all_numeric(), threshold = 0.7) %>%
step_center(all_numeric()) %>% # substract mean from numeric
step_zv(all_predictors()) # remove zero-variance predictors
```
---
### In `recipes` vs `dplyr`/`tidyr`
Generally:
* In `tidyverse`, do reshaping or basic cleaning
* In `recipes` do statistical transformations or other things that are intended for modeling
- Possible `step_???` for many many things!
--
### `usemodels`
Relatively early in package life cycle, but helps with boilerplate
.small[
```r
usemodels::use_ranger(play_type ~ ., train_data)
```
```
## ranger_recipe <-
## recipe(formula = play_type ~ ., data = train_data) %>%
## step_string2factor(one_of(posteam, defteam))
##
## ranger_spec <-
## rand_forest(mtry = tune(), min_n = tune(), trees = 1000) %>%
## set_mode("classification") %>%
## set_engine("ranger")
##
## ranger_workflow <-
## workflow() %>%
## add_recipe(ranger_recipe) %>%
## add_model(ranger_spec)
##
## set.seed(68747)