-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPick-N-Mix.html
More file actions
1226 lines (906 loc) · 35.6 KB
/
Pick-N-Mix.html
File metadata and controls
1226 lines (906 loc) · 35.6 KB
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>Pick N Mix</title>
<meta charset="utf-8" />
<meta name="author" content="Nathan Khadaroo-McCheyne" />
<link href="libs/remark-css/default.css" rel="stylesheet" />
<link href="libs/remark-css/default-fonts.css" rel="stylesheet" />
<script src="libs/kePrint/kePrint.js"></script>
<link href="libs/lightable/lightable.css" rel="stylesheet" />
</head>
<body>
<textarea id="source">
class: center, middle, inverse, title-slide
# Pick N Mix
## Machine Learning Fundamentals in R
### Nathan Khadaroo-McCheyne
### PhD student at the Cathie Marsh Institute for Social Research <br> and the Institute for Data Science & Artificial Intelligence <br> Data Padawan at Open Data Manchester
---
---
# Workshop structure:
--
- We'll begin by going over the libraries needed to run the examples as these can take a while to install.
--
- An overview of why Tidymodels is such an exciting new meta-package, and also highlight some alternatives.
--
- Machine learning in a nutshell
--
- Introducing the 🐧Palmer penguins data 🐧!
--
- An example of unsupervised learning: k means clustering.
--
- An example of classification: Predicting the sex of the penguins using logistic regression and random forests.
---
class: inverse, center, middle
# Getting Started
---
### How to install the packages:
--
We'll be doing our machine learning using the [Tidymodels](https://www.tidymodels.org) environment.
You can install the **Tidymodels** package from CRAN:
```r
# install.packages("tidymodels")
library(tidymodels)
```
--
We'll also be using packages from the **Tidyverse** which we can also get from CRAN:
```r
# install.packages("tidyverse")
library(tidyverse)
```
--
We will also be using the ranger package to fit random forests, and the vip package for variable importance plots:
```r
library(ranger)
library(vip)
```
---
### How to load the data:
--
**First way:**
--
<br>
- Using the [palmer penguins package](https://allisonhorst.github.io/palmerpenguins/).
```r
install.packages("palmerpenguins")
library(palmerpenguins)
penguins <- penguins
```
--
**Second way:**
--
<br>
- Downloading it from the tidy Tuesday github page:
```r
url = "https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-07-28/penguins.csv"
#penguins <- read_csv(url)
```
--
If you want to find out more about how to use Github check out Dr Rachel Ainsworth's [Pick N Mix session on using Github](https://vimeo.com/435771660)!
---
class: inverse, center, middle
# 🌰🌰Machine Learning in a nutshell 🌰🌰
---
# What is machine learning?
--
- An umbrella concept for computational techniques through which the discovery of patterns in data can be automated. The boundaries of this term are disputed and it is often used interchangeably with terms such as statistical learning, pattern recognition, AI, or even statistics.
--
- Two main types of algorithms: supervised, and unsupervised. We will be looking at both today.
--
- Supervised learning involves working with data where both dependent and independent variables are known. This includes tasks such as regression and classification.
--
- Unsupervised learning involves searching for patterns with data that is unlabeled. This includes tasks such as clustering and principal component analysis.
---
# Machine learning in R: What is tidymodels?
--
- Tidymodels is a meta-package (like the tidyverse!) developed by the RStudio team.
--
- "The tidymodels framework is a collection of packages for modelling and machine learning using tidyverse principles."
--
- Priority is on ease of use, consistency, and readable code (rather that speed).
--
- "Successor" to the widely used [caret package](http://topepo.github.io/caret/index.html), especially Parsnip.
--
- Emphasis is on predictive modelling (supervised learning).
--
- Still in development, and new packages are popping up fast.
---
# Some alternatives:
--
**Scikit-learn:**
--
- This is a Python library, and (probably?) the most used software for machine learning. Until Tidymodels came along I think this library gave Python the edge over R for easy machine learning.
--
- The [documentation](https://scikit-learn.org/stable/) is fantastic, worth checking out for a good intro to most machine learning topics!
--
**mlr3:**
--
- The other big machine learning library in R.
--
- Allows for some features not currently available in Tidymodels such as spatial cross-validation (more on that later)
---
class: inverse, center, middle
# 🐧🐧 Penguin time 🐧🐧
---
# The Palmer Penguins:

---
- Originally published in [Gorman KB, Williams TD, Fraser WR (2014). Ecological sexual dimorphism and environmental variability within a community of Antarctic penguins (genus Pygoscelis)](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0090081).
--
- Bundled into the palmerpenguins R package by Dr. Kristen Gorman, Dr. Allison Horst, and Dr. Alison Hill as an alternative to libraries such as iris or mtcars. This contains a raw data set and a cleaned data set.
--
- Featured as the 31st [Tidy Tuesday](https://github.com/rfordatascience/tidytuesday/blob/master/data/2020/2020-07-28/readme.md) data set in 2020.
--
- You can find out more about the origins of this data set in [this post on the RStudio Education blog](https://education.rstudio.com/blog/2020/07/palmerpenguins-cran/).
--
```r
names(penguins)
```
```
## [1] "species" "island" "bill_length_mm"
## [4] "bill_depth_mm" "flipper_length_mm" "body_mass_g"
## [7] "sex" "year"
```
--
```r
names(penguins_raw)
```
```
## [1] "studyName" "Sample Number" "Species"
## [4] "Region" "Island" "Stage"
## [7] "Individual ID" "Clutch Completion" "Date Egg"
## [10] "Culmen Length (mm)" "Culmen Depth (mm)" "Flipper Length (mm)"
## [13] "Body Mass (g)" "Sex" "Delta 15 N (o/oo)"
## [16] "Delta 13 C (o/oo)" "Comments"
```
---
- Let's begin by visualizing some of the variables in the data set:
--
```r
penguins %>%
filter(!is.na(sex)) %>%
ggplot(aes(flipper_length_mm, bill_length_mm,
color = sex,
size = body_mass_g)) +
geom_point(alpha = 0.5) +
facet_wrap(~species)
```
<!-- -->
---
class: inverse, center, middle
# Clustering:
---
# K-Means clustering:
A popular method for clustering data is k-means clustering.
--
This approach seeks to separate data in k clusters, where the within-cluster sum-of-squares is minimized: `\(\sum_{i=0}^{n}\min_{\mu_j \in C}(||x_i - \mu_j||^2)\)`
--
This is done in three steps:
--
- Step one: Choosing the initial centres, this is usually done randomly, though in some variants centres are deliberately set far away from each other (most prominently k-means++).
--
- Step two: Assign each point in the sample to its nearest centre.
--
- Step three: Calculate the mean value of all points assigned to every centre, this point is now the new centre for that cluster.
--
Step two and three are iterated until some stopping condition is met (typically when the difference between the current and new centres falls below a certain threshold).
---


---
# K-means in R:
- There are many approaches to fitting a k-means model, today we will be using the [kmeans()](https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/kmeans) function from the R Stats package (usually loaded as default).
--
- This function uses an efficient version of the approach described above as presented in "Algorithm AS 136: A K-Means Clustering Algorithm" by [Hartigan, J. A., & Wong, M. A. (1979)]().
--
- More generally it is important to keep in mind that there is almost always a difference between statistical methods as understood theoretically by users, and how they are implemented computationally (an excellent example of this is [Matthew Drury's blogpost](http://madrury.github.io/jekyll/update/statistics/2016/07/20/lm-in-R.html) on how R fits linear regression models).
---
# Preprocessing:
This code creates a new tibble called penguins_scaled, which contains all the numeric variables from penguins other than the variable for year, and scales all the variables.
```r
penguins_scaled <- penguins %>%
drop_na %>%
select(where(is.numeric),
-year) %>%
mutate_at(colnames(.),
~(scale(.) %>% as.vector))
```
<table>
<thead>
<tr>
<th style="text-align:right;"> bill_length_mm </th>
<th style="text-align:right;"> bill_depth_mm </th>
<th style="text-align:right;"> flipper_length_mm </th>
<th style="text-align:right;"> body_mass_g </th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:right;"> -0.8946955 </td>
<td style="text-align:right;"> 0.7795590 </td>
<td style="text-align:right;"> -1.4246077 </td>
<td style="text-align:right;"> -0.5676206 </td>
</tr>
<tr>
<td style="text-align:right;"> -0.8215515 </td>
<td style="text-align:right;"> 0.1194043 </td>
<td style="text-align:right;"> -1.0678666 </td>
<td style="text-align:right;"> -0.5055254 </td>
</tr>
<tr>
<td style="text-align:right;"> -0.6752636 </td>
<td style="text-align:right;"> 0.4240910 </td>
<td style="text-align:right;"> -0.4257325 </td>
<td style="text-align:right;"> -1.1885721 </td>
</tr>
<tr>
<td style="text-align:right;"> -1.3335592 </td>
<td style="text-align:right;"> 1.0842457 </td>
<td style="text-align:right;"> -0.5684290 </td>
<td style="text-align:right;"> -0.9401915 </td>
</tr>
<tr>
<td style="text-align:right;"> -0.8581235 </td>
<td style="text-align:right;"> 1.7444004 </td>
<td style="text-align:right;"> -0.7824736 </td>
<td style="text-align:right;"> -0.6918109 </td>
</tr>
<tr>
<td style="text-align:right;"> -0.9312674 </td>
<td style="text-align:right;"> 0.3225288 </td>
<td style="text-align:right;"> -1.4246077 </td>
<td style="text-align:right;"> -0.7228585 </td>
</tr>
</tbody>
</table>
---
# Clustering and getting results:
--
K-means has an element of randomness so we need to set the random seed to ensure reproducibility:
```r
set.seed(1234)
```
--
First, we fit the k means clustering using the [kmeans function](). We can then extract the results and combine it with our data-frame with the [augment function]() from the broom package:
```r
k_clust <- penguins_scaled %>%
kmeans(centers = 3) %>%
augment(drop_na(penguins))
```
<table class="table" style="font-size: 14px; margin-left: auto; margin-right: auto;">
<thead>
<tr>
<th style="text-align:left;"> species </th>
<th style="text-align:left;"> island </th>
<th style="text-align:right;"> bill_length_mm </th>
<th style="text-align:right;"> bill_depth_mm </th>
<th style="text-align:right;"> flipper_length_mm </th>
<th style="text-align:right;"> body_mass_g </th>
<th style="text-align:left;"> sex </th>
<th style="text-align:right;"> year </th>
<th style="text-align:left;"> .cluster </th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left;"> Adelie </td>
<td style="text-align:left;"> Torgersen </td>
<td style="text-align:right;"> 39.1 </td>
<td style="text-align:right;"> 18.7 </td>
<td style="text-align:right;"> 181 </td>
<td style="text-align:right;"> 3750 </td>
<td style="text-align:left;"> male </td>
<td style="text-align:right;"> 2007 </td>
<td style="text-align:left;"> 3 </td>
</tr>
<tr>
<td style="text-align:left;"> Adelie </td>
<td style="text-align:left;"> Torgersen </td>
<td style="text-align:right;"> 39.5 </td>
<td style="text-align:right;"> 17.4 </td>
<td style="text-align:right;"> 186 </td>
<td style="text-align:right;"> 3800 </td>
<td style="text-align:left;"> female </td>
<td style="text-align:right;"> 2007 </td>
<td style="text-align:left;"> 3 </td>
</tr>
<tr>
<td style="text-align:left;"> Adelie </td>
<td style="text-align:left;"> Torgersen </td>
<td style="text-align:right;"> 40.3 </td>
<td style="text-align:right;"> 18.0 </td>
<td style="text-align:right;"> 195 </td>
<td style="text-align:right;"> 3250 </td>
<td style="text-align:left;"> female </td>
<td style="text-align:right;"> 2007 </td>
<td style="text-align:left;"> 3 </td>
</tr>
<tr>
<td style="text-align:left;"> Adelie </td>
<td style="text-align:left;"> Torgersen </td>
<td style="text-align:right;"> 36.7 </td>
<td style="text-align:right;"> 19.3 </td>
<td style="text-align:right;"> 193 </td>
<td style="text-align:right;"> 3450 </td>
<td style="text-align:left;"> female </td>
<td style="text-align:right;"> 2007 </td>
<td style="text-align:left;"> 3 </td>
</tr>
<tr>
<td style="text-align:left;"> Adelie </td>
<td style="text-align:left;"> Torgersen </td>
<td style="text-align:right;"> 39.3 </td>
<td style="text-align:right;"> 20.6 </td>
<td style="text-align:right;"> 190 </td>
<td style="text-align:right;"> 3650 </td>
<td style="text-align:left;"> male </td>
<td style="text-align:right;"> 2007 </td>
<td style="text-align:left;"> 3 </td>
</tr>
<tr>
<td style="text-align:left;"> Adelie </td>
<td style="text-align:left;"> Torgersen </td>
<td style="text-align:right;"> 38.9 </td>
<td style="text-align:right;"> 17.8 </td>
<td style="text-align:right;"> 181 </td>
<td style="text-align:right;"> 3625 </td>
<td style="text-align:left;"> female </td>
<td style="text-align:right;"> 2007 </td>
<td style="text-align:left;"> 3 </td>
</tr>
</tbody>
</table>
---
# Visualising results:
We can then visualize the clusters.
```r
k_clust %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm,
colour = .cluster)) +
geom_point() +
scale_colour_manual(values = c("darkorange","purple","cyan4"))
```
<!-- -->
These look pretty similar to the species! Let's explore that further...
---
Here the color corresponds to the species of the penguin, and the number to the cluster assigned to it by our algorithm :
```r
k_clust %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm,
* colour = species)) +
* geom_text(aes(label= .cluster)) +
scale_colour_manual(values = c("darkorange","purple","cyan4"))
```
<!-- -->
---
We can get even closer using additional variables from the penguins_raw data-set:
<!-- -->
---
# Choosing the number of clusters:
First we can fit 9 different models with k = 1 to k = 9.
```r
# Setting the random seed:
set.seed(1234)
# Fitting the models:
kclusts <-
tibble(k = 1:9) %>%
mutate(
kclust = map(k, ~kmeans(penguins_scaled, .x)),
tidied = map(kclust, tidy),
glanced = map(kclust, glance),
augmented = map(kclust, augment, penguins_scaled))
```
---
Then extract information on each model using broom:
```r
clusters <-
kclusts %>%
unnest(cols = c(tidied))
assignments <-
kclusts %>%
unnest(cols = c(augmented))
clusterings <-
kclusts %>%
unnest(cols = c(glanced))
```
---
As before we can look at the results using ggplot:
```r
ggplot(assignments, aes(x = bill_length_mm , y = bill_depth_mm)) +
geom_point(aes(color = .cluster), alpha = 0.8) +
facet_wrap(~ k)
```
<!-- -->
---
We can also draw an "elbow plot":
```r
ggplot(clusterings, aes(k, tot.withinss)) +
geom_line() +
geom_point()
```
<!-- -->
---
class: inverse, center, middle
#Classification:
---
We're going to explore a simple classification task: predicting the sex of our penguins. This example is from Julia Silge's [tidy tuesday blogpost](https://juliasilge.com/blog/palmer-penguins/).
The following diagram from [Kuhn and Johnson (2019)](https://bookdown.org/max/FES/resampling.html) illustrates the kind of workflow we will be doing:

--
---
# Preprocessing:
--
- First we are going to remove any penguins that have missing data for sex:
```r
penguins_prep <- penguins %>%
filter(!is.na(sex)) %>%
select(-year, -island)
```
---
# Much ado about sampling:
--
- First we can split our data into a testing and training sets using the [rsample package](https://rsample.tidymodels.org):
--
```r
set.seed(123)
*penguin_split <- initial_split(penguins_prep, strata = sex)
penguin_train <- training(penguin_split)
penguin_test <- testing(penguin_split)
```
--
- We will also create bootstrap re-samples of our training data using the bootstraps function from the same package.
```r
set.seed(123)
penguin_boot <- bootstraps(penguin_train)
```
---
# Specifying the models:
--
- The [parsnip package](https://www.tidymodels.org/find/parsnip/) "provide[s] a tidy, unified interface to models that can be used to try a range of models without getting bogged down in the syntactical minutiae of the underlying packages".
--
- We will specify two simple models, a logistic regression model using glm (part of base r), and a random forest model from the [ranger package](https://github.com/imbs-hl/ranger):
```r
glm_spec <- logistic_reg() %>%
set_engine("glm")
rf_spec <- rand_forest() %>%
set_mode("classification") %>%
set_engine("ranger")
```
--
- We can also create an empty workflow object at this stage:
```r
penguin_wf <- workflow() %>%
add_formula(sex ~ .)
```
---
# Fitting the models:
We then add our models to the workflow, and fit them to *each* of the resamples.
--
- For the logistic regression model:
```r
glm_rs <- penguin_wf %>%
add_model(glm_spec) %>%
fit_resamples(resamples = penguin_boot,
control = control_resamples(save_pred = TRUE))
```
--
- For the random forest model:
```r
rf_rs <- penguin_wf %>%
add_model(rf_spec) %>%
fit_resamples(
resamples = penguin_boot,
control = control_resamples(save_pred = TRUE))
```
---
# Evaluating performance:
We can then look at how our models have performed using the [collect_metrics](https://tune.tidymodels.org/reference/collect_predictions.html) function from the [tune package](https://tune.tidymodels.org/index.html):
--
- For the logistic regression model:
```r
collect_metrics(glm_rs)
```
<table>
<thead>
<tr>
<th style="text-align:left;"> .metric </th>
<th style="text-align:left;"> .estimator </th>
<th style="text-align:right;"> mean </th>
<th style="text-align:right;"> n </th>
<th style="text-align:right;"> std_err </th>
<th style="text-align:left;"> .config </th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left;"> accuracy </td>
<td style="text-align:left;"> binary </td>
<td style="text-align:right;"> 0.8969609 </td>
<td style="text-align:right;"> 25 </td>
<td style="text-align:right;"> 0.0063087 </td>
<td style="text-align:left;"> Preprocessor1_Model1 </td>
</tr>
<tr>
<td style="text-align:left;"> roc_auc </td>
<td style="text-align:left;"> binary </td>
<td style="text-align:right;"> 0.9638741 </td>
<td style="text-align:right;"> 25 </td>
<td style="text-align:right;"> 0.0036765 </td>
<td style="text-align:left;"> Preprocessor1_Model1 </td>
</tr>
</tbody>
</table>
--
- For the random forest model:
```r
collect_metrics(rf_rs)
```
<table>
<thead>
<tr>
<th style="text-align:left;"> .metric </th>
<th style="text-align:left;"> .estimator </th>
<th style="text-align:right;"> mean </th>
<th style="text-align:right;"> n </th>
<th style="text-align:right;"> std_err </th>
<th style="text-align:left;"> .config </th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left;"> accuracy </td>
<td style="text-align:left;"> binary </td>
<td style="text-align:right;"> 0.8903000 </td>
<td style="text-align:right;"> 25 </td>
<td style="text-align:right;"> 0.0059459 </td>
<td style="text-align:left;"> Preprocessor1_Model1 </td>
</tr>
<tr>
<td style="text-align:left;"> roc_auc </td>
<td style="text-align:left;"> binary </td>
<td style="text-align:right;"> 0.9585038 </td>
<td style="text-align:right;"> 25 </td>
<td style="text-align:right;"> 0.0034207 </td>
<td style="text-align:left;"> Preprocessor1_Model1 </td>
</tr>
</tbody>
</table>
---
Let's take a closer look at the performance of the logistic regression model, we can easily obtain a confusion matrix as a tidy tibble by using the [conf_mat_resampled](https://tune.tidymodels.org/reference/conf_mat_resampled.html) function. This gives us teh *average* confusion matrix over our 25 bootstraps:
```r
glm_rs %>%
conf_mat_resampled() %>%
kable()
```
<table>
<thead>
<tr>
<th style="text-align:left;"> Prediction </th>
<th style="text-align:left;"> Truth </th>
<th style="text-align:right;"> Freq </th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left;"> female </td>
<td style="text-align:left;"> female </td>
<td style="text-align:right;"> 40.56 </td>
</tr>
<tr>
<td style="text-align:left;"> female </td>
<td style="text-align:left;"> male </td>
<td style="text-align:right;"> 4.48 </td>
</tr>
<tr>
<td style="text-align:left;"> male </td>
<td style="text-align:left;"> female </td>
<td style="text-align:right;"> 4.92 </td>
</tr>
<tr>
<td style="text-align:left;"> male </td>
<td style="text-align:left;"> male </td>
<td style="text-align:right;"> 41.36 </td>
</tr>
</tbody>
</table>
---
We can also look at these results using a Receiver Operator Characteristic (ROC) curve:
```r
glm_rs %>%
collect_predictions() %>%
group_by(id) %>%
roc_curve(sex, .pred_female) %>%
ggplot(aes(1 - specificity, sensitivity, color = id)) +
geom_abline(lty = 2, color = "gray80", size = 1.5) +
geom_path(show.legend = FALSE, alpha = 0.6, size = 1.2) +
coord_equal()
```
<!-- -->
This is looking pretty good! But...
---
# Bringing back the test data:
--
We might be **over-fitting** the data! To check that our model will perform well on new data we have to see how it performs on our testing data.
--
We can do this easily using the [last_fit](https://tune.tidymodels.org/reference/last_fit.html) function, this takes the model which performs the best on our training data, and fits it to the test data:
```r
penguin_final <- penguin_wf %>%
add_model(glm_spec) %>%
last_fit(penguin_split)
```
---
As with our training data, we can use [collect_metrics](https://tune.tidymodels.org/reference/collect_predictions.html) and [collect_predictions](https://tune.tidymodels.org/reference/collect_predictions.html) to look at the performance of our model:
```r
collect_metrics(penguin_final) %>% kable()
```
<table>
<thead>
<tr>
<th style="text-align:left;"> .metric </th>
<th style="text-align:left;"> .estimator </th>
<th style="text-align:right;"> .estimate </th>
<th style="text-align:left;"> .config </th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left;"> accuracy </td>
<td style="text-align:left;"> binary </td>
<td style="text-align:right;"> 0.9397590 </td>
<td style="text-align:left;"> Preprocessor1_Model1 </td>
</tr>
<tr>
<td style="text-align:left;"> roc_auc </td>
<td style="text-align:left;"> binary </td>
<td style="text-align:right;"> 0.9912892 </td>
<td style="text-align:left;"> Preprocessor1_Model1 </td>
</tr>
</tbody>
</table>
```r
collect_predictions(penguin_final) %>%
conf_mat(sex, .pred_class)
```
```
## Truth
## Prediction female male
## female 39 3
## male 2 39
```
---
We can also create another ROC curve for our final fit:
```r
penguin_final %>%
collect_predictions() %>%
roc_curve(sex, .pred_female) %>%
ggplot(aes(1 - specificity, sensitivity)) +
geom_abline(lty = 2, color = "gray80", size = 1.5) +
geom_path(show.legend = FALSE, alpha = 0.6, size = 1.2) +
coord_equal()
```
<!-- -->
---
We can use the [tidy function](https://broom.tidymodels.org/index.html) from the broom package to get the coefficients for our model:
```r
penguin_final$.workflow[[1]] %>%
tidy(exponentiate = TRUE) %>%
kable()
```
<table>
<thead>
<tr>
<th style="text-align:left;"> term </th>
<th style="text-align:right;"> estimate </th>
<th style="text-align:right;"> std.error </th>
<th style="text-align:right;"> statistic </th>
<th style="text-align:right;"> p.value </th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left;"> (Intercept) </td>
<td style="text-align:right;"> 0.0000000 </td>
<td style="text-align:right;"> 13.4721255 </td>
<td style="text-align:right;"> -5.897487 </td>
<td style="text-align:right;"> 0.0000000 </td>
</tr>
<tr>
<td style="text-align:left;"> speciesChinstrap </td>
<td style="text-align:right;"> 0.0013402 </td>
<td style="text-align:right;"> 1.7011363 </td>