-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.html
1535 lines (940 loc) · 28.9 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>
<head>
<title>Machine Learning 101</title>
<meta charset="utf-8">
<meta name="author" content=" Sarah Romanes <span><i class="fab fa-twitter faa-float animated "></i>&nbsp;@sarah_romanes</span>" />
<link href="libs/remark-css/kunoichi.css" rel="stylesheet" />
<link href="libs/remark-css/ninjutsu.css" rel="stylesheet" />
<link href="libs/font-awesome-animation/font-awesome-animation-emi.css" rel="stylesheet" />
<script src="libs/fontawesome/js/fontawesome-all.min.js"></script>
<link href="libs/font-awesome/css/fontawesome-all.min.css" rel="stylesheet" />
<link rel="stylesheet" href="assets\custom.css" type="text/css" />
</head>
<body>
<textarea id="source">
class: center, middle, inverse, title-slide
# Machine Learning 101
## Model Assessment in R
### <br><br>Sarah Romanes <span><i class="fab fa-twitter faa-float animated "></i>&nbsp;@sarah_romanes</span>
### <br>17-Oct-2018<br><br><span><i class="fas fa-link faa-vertical animated " style=" color:white;"></i>&nbsp;bit.ly/rladies-sydney-ML-2</span>
---
layout: false
class: bg-main3 split-30 hide-slide-number
.column[
]
.column.slide-in-right[.content.vmiddle[
.sliderbox.shade_main.pad1[
.font5[Welcome!]
]
]]
---
class: split-two white
.column.bg-main1[.content.vmiddle.center[
# Overview
<br>
### This two part R-Ladies workshop is designed to give you a small taster into the large field that is known as .orange[**Machine Learning**]! Last week, we covered supervised learning techniques, and this week we will cover model assessment.
<br>
### You can always visit last weeks slides at .orange[bit.ly/r-ladies-ML-1] with the corresponding <i class="fab fa-github "></i> repo [here](https://github.com/sarahromanes/r-ladies-ML-1).
]]
.column.bg-main3[.content.vmiddle.center[
<img src="images/machinewar.png", width="70%">
##### [SMBC](https://www.smbc-comics.com/comic/rise-of-the-machines)
]]
---
# .purple[Recap - What *is* Machine Learning?]
<br>
### Machine learning is concerned with finding functions `\(Y=f(X)+\epsilon\)` that best **predict** outputs (responses), given data inputs (predictors).
<br>
<center>
<img src="images/ml-process.png", width="50%">
</center>
<br>
### Mathematically, Machine Learning problems are simply *optimisation* problems, in which we will use .purple[<i class="fab fa-r-project "></i>] to help us solve!
---
layout: false
class: bg-main3 split-30 hide-slide-number
.column[
]
.column.slide-in-right[.content.vmiddle[
.sliderbox.shade_main.pad1[
.font5[Performance Metrics]
]
]]
---
class: split-two white
.column.bg-main1[.content[
<br>
# Regression - revisited
### Recall the simulated dataset `Income`, which looked at the relationship between `Education` (years) and `Income` (thousands).
```r
data <- read.csv("data/Income.csv")
head(data)
```
```
## Education Income
## 1 10.00000 26.65884
## 2 10.40134 27.30644
## 3 10.84281 22.13241
## 4 11.24415 21.16984
## 5 11.64548 15.19263
## 6 12.08696 26.39895
```
### How can we assess how well a regression model fits the data?
]]
.column[.content.vmiddle.center[
<img src="index_files/figure-html/unnamed-chunk-2-1.png" width="504" />
]]
---
class: split-two white
.column.bg-main1[.content[
<br>
# Is a straight line the best fit?
<br>
<br>
<br>
## Last week we considered fitting a .orange[Linear] model to this data, resulting in the following line...
#### (Revise how this was fit [here](https://sarahromanes.github.io/r-ladies-ML-1/#9).)
]]
.column[.content.vmiddle.center[
<img src="index_files/figure-html/unnamed-chunk-3-1.png" width="504" />
]]
---
class: split-two white
.column.bg-main1[.content[
<br>
# Is a straight line the best fit?
<br>
<br>
<br>
## ... however there are many types of curves we could have fit to this dataset!
]]
.column[.content.vmiddle.center[
<img src="images/curves.jpg", width="60%">
]]
---
class: split-two white
.column.bg-main1[.content[
<br>
# Is a straight line the best fit?
<br>
<br>
<br>
## ... however there are many types of curves we could have fit to this dataset!
<br>
## Consider now the .orange[*polynomial*] curve of degree 17. Does it fit better than our straight line?
]]
.column[.content.vmiddle.center[
<img src="index_files/figure-html/unnamed-chunk-4-1.png" width="504" />
]]
---
class: split-two white
.column.bg-main1[.content[
<br>
# Regression metrics: the RMSE
<br>
# The RMSE is the .orange[Root Mean Squared Error], which is a metric of how far away our fitted line lies away from the observations (on average).
]]
.column[.content.vmiddle.center[
<img src="images/rmse.png", width="80%">
]]
---
class: split-60 white
.column.bg-main1[.content[
<br>
# Regression metrics: the RMSE
<br>
```r
fit.lm <- lm(data=data, Income~Education)
fit.poly <- lm(data=data, Income~poly(Education, 17))
fitted.vals.lm <- predict(fit.lm,
data.frame(Education=data$Education))
fitted.vals.poly <- predict(fit.poly,
data.frame(Education=data$Education))
```
#### RMSE - Linear Model
```r
sqrt(mean((data$Income-fitted.vals.lm)^2))
```
```
## [1] 5.461576
```
#### RMSE - Polynomial Model
```r
sqrt(mean((data$Income-fitted.vals.poly)^2))
```
```
## [1] 2.803986
```
]]
.column.bg-main3[.content.vmiddle.center[
## We can find the RMSE of the two models proposed before.
## .orange[The polynomial fit has a lower RMSE. Does this mean we should use it?]
]]
---
# .purple[Bias and Variance]
<br>
## In order to minimise test error on new data points, statistical theory (out of the scope of this workshop) tells us that we need to select a function that achieves *low variance* and *low bias*.
<br>
--
## - .pink[**Variance**] refers to the amount by which our predictions would change if we estimated using a different training set. The more flexible the model, the higher the variance.
--
## - .pink[**Bias**] refers to the error that introduced by the approximation we are making with our model (represent complicated data by a simple model). The more simple the model, the higher the bias.
---
class: middle center bg-main1
# High variance (over fitted) models can be problematic...
<img src="images/bird.jpg", width="70%">
---
class: middle center bg-main1
# ... as well as high bias (under fitted) models!
<img src="images/constraints.png", width="70%">
---
# .purple[The Bias-Variance Tradeoff]
<br>
## As you may have guessed, there is a trade off between increasing variance (flexibility) and decreasing bias (simplicity) and vice versa.
<br>
<center>
<img src="images/tradeoff.png", width="50%">
</center>
<br>
### This is known as the .pink[Bias-Variance Tradeoff], and will be revisited in the next section!
---
class: split-two white
.column.bg-main1[.content[
<br>
# The middle ground!
<br>
## For this dataset, we might consider the `loess` model as a nice middle ground between bias and variance.
```r
*fit.loess <- loess(data=data, Income~Education)
fitted.vals.loess <- predict(fit.loess,
data.frame(
Education=data$Education))
rmse.loess <- sqrt(mean((data$Income-fitted.vals.loess)^2))
rmse.loess
```
```
## [1] 3.806408
```
]]
.column[.content.vmiddle.center[
<img src="index_files/figure-html/unnamed-chunk-9-1.png" width="504" />
]]
---
class: split-two white
.column.bg-main1[.content[
<br>
# The classification setting
<br>
### Recall the dataset `Exam`, where two exam scores are given for each student, and a Label represents whether they passed or failed the course.
```r
data<- read.csv("data/Exam.csv", header=T)
head(data,4)
```
```
## Exam1 Exam2 Label
## 1 34.62366 78.02469 0
## 2 30.28671 43.89500 0
## 3 35.84741 72.90220 0
## 4 60.18260 86.30855 1
```
### How do we assess model accuracy for a classifier?
]]
.column[.content.vmiddle.center[
<img src="index_files/figure-html/unnamed-chunk-11-1.png" width="504" />
]]
---
class: split-two white
.column.bg-main1[.content[
<br>
# Classification metrics
<br>
# The .orange[Resubstitution Error Rate] is a measure of the proportion of data points we predict correctly when we try to predict all the points we used to fit the model.
]]
.column[.content.vmiddle.center[
<img src="images/rser.png", width="80%">
]]
---
class: split-60 white
.column.bg-main1[.content[
<br>
# The Resubstitution Error Rate
<br>
```r
*fit.glm <- glm(data=data,
* Label ~ .,
* family=binomial(link="logit"))
```
]]
.column.bg-main3[.content.vmiddle.center[
# First, we fit a `glm` against all predictors like we did last week.
]]
---
class: split-60 white
.column.bg-main1[.content[
<br>
# The Resubstitution Error Rate
<br>
```r
fit.glm <- glm(data=data,
Label ~ .,
family=binomial(link="logit"))
*fitted.vals <- round(predict(fit.glm,
* newdata = data[, c("Exam1", "Exam2")],
* type="response"))
```
]]
.column.bg-main3[.content.vmiddle.center[
# We then predict the values of all the data points we used to build the model.
#### (Remember, for `glm`, we predict the *probability* of being class 1, and then round).
]]
---
class: split-60 white
.column.bg-main1[.content[
<br>
# The Resubstitution Error Rate
<br>
```r
fit.glm <- glm(data=data,
Label ~ .,
family=binomial(link="logit"))
fitted.vals <- round(predict(fit.glm,
newdata = data[, c("Exam1", "Exam2")],
type="response"))
*err <- mean(fitted.vals!=data$Label)
err
```
```
## [1] 0.11
```
]]
.column.bg-main3[.content.vmiddle.center[
# We can then find the .orange[*resubstitution error rate*] by looking at the proportion of labels that were not correctly predicted.
]]
---
class: split-60 white
.column.bg-main1[.content[
<br>
# The Confusion Matrix <i class="fas fa-question-circle "></i>
<br>
```r
fit.glm <- glm(data=data,
Label ~ .,
family=binomial(link="logit"))
fitted.vals <- round(predict(fit.glm,
newdata = data[, c("Exam1", "Exam2")],
type="response"))
```
```r
library(caret)
*confusion.glm <- confusionMatrix(as.factor(fitted.vals),
* as.factor(data$Label))
confusion.glm$table
```
```
## Reference
## Prediction 0 1
## 0 34 5
## 1 6 55
```
]]
.column.bg-main3[.content.vmiddle.center[
## We can examine how our model predicted all the data points, using `confusionMatrix` from the `caret` package. Note, that we are required to put in factor inputs.
]]
---
class: split-60 white
.column.bg-main1[.content[
<br>
# The Confusion Matrix <i class="fas fa-question-circle "></i>
<br>
```r
fit.glm <- glm(data=data,
Label ~ .,
family=binomial(link="logit"))
fitted.vals <- round(predict(fit.glm,
newdata = data[, c("Exam1", "Exam2")],
type="response"))
```
```r
library(caret)
*confusion.glm <- confusionMatrix(as.factor(fitted.vals),
* as.factor(data$Label))
*confusion.glm$table
```
```
## Reference
## Prediction 0 1
## 0 34 5
## 1 6 55
```
]]
.column.bg-main3[.content.vmiddle.center[
## Looking at the `table` output, reading *vertically*, we can assess model performance. Out of the 40 failures in our dataset, `glm` sucessfully predicts 34. Out of the 60 passes in our data, `glm` sucessfully predicts 55.
]]
---
class: middle center bg-main1
# Your turn!
## <span><i class="fas fa-sync-alt fa-4x faa-spin animated "></i></span>
---
class: split-60 white
.column.bg-main1[.content[
<br>
# Classifying and assessing model fit for Diabetes data
<br>
```r
data <- read.csv("data/diabetes.csv")
dim(data)
```
```
## [1] 768 9
```
```r
str(data)
'data.frame': 768 obs. of 9 variables:
$ pregnant : int 6 1 8 1 0 5 3 10 2 8 ...
$ glucose : int 148 85 183 89 137 116 78 115 197 125 ...
$ hg : int 72 66 64 66 40 74 50 0 70 96 ...
$ thickness: int 35 29 0 23 35 0 32 0 45 0 ...
$ insulin : int 0 0 0 94 168 0 88 0 543 0 ...
$ bmi : num 33.6 26.6 23.3 28.1 43.1 25.6 31 35.3 30.5 0 ...
$ pedigree : num 0.627 0.351 0.672 0.167 2.288 ...
$ age : int 50 31 32 21 33 30 26 29 53 54 ...
*$ class : int 1 0 1 0 1 0 1 0 1 1 ...
```
]]
.column.bg-main3[.content.vmiddle.center[
# Build a machine learning model to predict whether or not the patients in the dataset have diabetes (`class`).
# Further, assess the performance of .orange[*your model*] on classifying `class`.
]]
---
layout: false
class: bg-main3 split-30 hide-slide-number
.column[
]
.column.slide-in-right[.content.vmiddle[
.sliderbox.shade_main.pad1[
.font5[Cross Validation]
]
]]
---
class: middle center bg-main1
# Building reliable and accurate models is paramount in machine learning...
<img src="images/netflix.jpg", width="70%">
---
class: middle center bg-main1
# ... however, it can be hard to get new data to assess model performance!
<img src="images/newdata.jpg", width="70%">
---
class: split-two white
.column.bg-main1[.content[
<br>
# Cross Validation
<br>
## Often, we want to see how well our model can predict new data points. However, it is often impossible to get completely new data.
## So, we split our data into .orange[*training]* and .orange[*testing*] sets to evaluate performance, treating the *testing* data as new data points.
]]
.column[.content.vmiddle.center[
<img src="images/Cv1.png", width="80%">
]]
---
class: split-two white
.column.bg-main1[.content[
<br>
# Cross Validation
<br>
## To do this, we split our data into .orange[K-Folds].
<br>
## The first fold is treated as a testing set, and the method is fit on the remaining K − 1 folds.
]]
.column[.content.vmiddle.center[
<img src="images/Cv1.png", width="80%">
]]
---
class: split-two white
.column.bg-main1[.content[
<br>
# Cross Validation
<br>
<br>
## The misclassification error rate is then computed on the observations in the held-out fold.
## This procedure is .orange[repeated K] times; each time, a different group of observations is treated as a testing set.
]]
.column[.content.vmiddle.center[
<img src="images/Cv2.png", width="80%">
]]
---
class: split-two white
.column.bg-main1[.content[
<br>
# Cross Validation
<br>
<br>
# The .orange[CV error rate] is then calculated as the average of these K error rates.
]]
.column[.content.vmiddle.center[
<img src="images/Cv3.png", width="80%">
]]
---
# .purple[How many folds?]
<br>
<center>
<img src="images/splits.png", width="70%">
</center>
<br>
#### Generally, .pink[k between 5 and 10] avoids over-training the model (variance), whilst avoiding too few training points (bias).
---
class: split-60 white
.column.bg-main1[.content[
<br>
# 5-fold CV for Diabetes `knn` model
<br>
```r
library(class) # for KNN function
K <- 5 # number of folds
n <- nrow(data) # number of data points
X <- data[,-9] # predictors
y <- as.factor(data$class) # response
```
]]
.column.bg-main3[.content.vmiddle.center[
# Let's perform a .orange[5-fold] CV for the `knn` model. First, we split up our response and predictors.
]]
---
class: split-60 white
.column.bg-main1[.content[
<br>
# K-fold CV in <i class="fab fa-r-project "></i> using `cvTools`
<br>
```r
library(cvTools)
set.seed(1)
*cvSets <- cvFolds(n,K)
```
```r
str(cvSets)
List of 5
$ n : num 768
$ K : num 5
$ R : num 1
$ subsets: int [1:768, 1] 110 386 469 511 39 485 741 563 572 759 ...
$ which : int [1:768] 1 2 3 4 5 1 2 3 4 5 ...
```
]]
.column.bg-main3[.content.vmiddle.center[
## Using the `cvTools` package, we can use the function `cvFolds` to seperate our `n` data points into `K` paritions for cross validation.
#### Note, we `set.seed(1)` to ensure reproducible results.
]]
---
class: split-60 white
.column.bg-main1[.content[
<br>
# K-fold CV in <i class="fab fa-r-project "></i> using `cvTools`
<br>
```r
library(cvTools)
set.seed(1)
cvSets <- cvFolds(n,K)
```
```r
str(cvSets)
List of 5
$ n : num 768
$ K : num 5
$ R : num 1
*$ subsets: int [1:768, 1] 110 386 469 511 39 485 741 563 572 759 ...
*$ which : int [1:768] 1 2 3 4 5 1 2 3 4 5 ...
```
]]
.column.bg-main3[.content.vmiddle.center[
## The important outputs are `subsets` and `which`.
<br>
## For each fold (given by `which`), `subset` tells us which index of the data belongs to what fold. Eg, datapoint 110 belongs to fold 1, etc
]]
---
class: split-60 white
.column.bg-main1[.content[
<br>
# K-fold CV in <i class="fab fa-r-project "></i> using `cvTools`
<br>
```r
error.fold <- c()
*for(j in 1:K){
fold.j <- which(cvSets$which==j)
test.inds <- cvSets$subsets[fold.j]
X.test <- X[test.inds,]
X.train <- X[-test.inds,]
y.test <- y[test.inds]
y.train <- y[-test.inds]
fit <- knn(X.train, X.test, y.train, k=9)
error.fold[j] <- sum(fit!=y.test)
*}
cv.error <- sum(error.fold)/n
cv.error
```
]]
.column.bg-main3[.content.vmiddle.center[
# Now, we set up a for loop to iterate through the test/training folds.
]]
---
class: split-60 white
.column.bg-main1[.content[
<br>
# K-fold CV in <i class="fab fa-r-project "></i> using `cvTools`
<br>
```r
error.fold <- c()
for(j in 1:K){
* fold.j <- which(cvSets$which==j)
* test.inds <- cvSets$subsets[fold.j]
X.test <- X[test.inds,]
X.train <- X[-test.inds,]
y.test <- y[test.inds]
y.train <- y[-test.inds]