forked from lgatto/IntroMachineLearningWithR
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsupervised-learning.html
More file actions
1632 lines (1593 loc) · 112 KB
/
Copy pathsupervised-learning.html
File metadata and controls
1632 lines (1593 loc) · 112 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>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Chapter 5 Supervised Learning | An Introduction to Machine Learning with R</title>
<meta name="description" content="An hands-on introduction to machine learning with R." />
<meta name="generator" content="bookdown 0.17 and GitBook 2.6.7" />
<meta property="og:title" content="Chapter 5 Supervised Learning | An Introduction to Machine Learning with R" />
<meta property="og:type" content="book" />
<meta property="og:description" content="An hands-on introduction to machine learning with R." />
<meta name="github-repo" content="lgatto/IntroMachineLearningWithR" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="Chapter 5 Supervised Learning | An Introduction to Machine Learning with R" />
<meta name="twitter:description" content="An hands-on introduction to machine learning with R." />
<meta name="author" content="Laurent Gatto" />
<meta name="date" content="2020-02-28" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="prev" href="unsupervised-learning.html"/>
<link rel="next" href="final-notes.html"/>
<script src="libs/jquery-2.2.3/jquery.min.js"></script>
<link href="libs/gitbook-2.6.7/css/style.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-table.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-bookdown.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-highlight.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-search.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-fontsettings.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-clipboard.css" rel="stylesheet" />
<script src="libs/htmlwidgets-1.5.1/htmlwidgets.js"></script>
<link href="libs/datatables-css-0.0.0/datatables-crosstalk.css" rel="stylesheet" />
<script src="libs/datatables-binding-0.12/datatables.js"></script>
<link href="libs/dt-core-1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="libs/dt-core-1.10.20/css/jquery.dataTables.extra.css" rel="stylesheet" />
<script src="libs/dt-core-1.10.20/js/jquery.dataTables.min.js"></script>
<link href="libs/crosstalk-1.0.0/css/crosstalk.css" rel="stylesheet" />
<script src="libs/crosstalk-1.0.0/js/crosstalk.min.js"></script>
<style type="text/css">
a.sourceLine { display: inline-block; line-height: 1.25; }
a.sourceLine { pointer-events: none; color: inherit; text-decoration: inherit; }
a.sourceLine:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode { white-space: pre; position: relative; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
code.sourceCode { white-space: pre-wrap; }
a.sourceLine { text-indent: -1em; padding-left: 1em; }
}
pre.numberSource a.sourceLine
{ position: relative; left: -4em; }
pre.numberSource a.sourceLine::before
{ content: attr(data-line-number);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; pointer-events: all; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
color: #aaaaaa;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
a.sourceLine::before { text-decoration: underline; }
}
code span.al { color: #ff0000; font-weight: bold; } /* Alert */
code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code span.at { color: #7d9029; } /* Attribute */
code span.bn { color: #40a070; } /* BaseN */
code span.bu { } /* BuiltIn */
code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code span.ch { color: #4070a0; } /* Char */
code span.cn { color: #880000; } /* Constant */
code span.co { color: #60a0b0; font-style: italic; } /* Comment */
code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code span.do { color: #ba2121; font-style: italic; } /* Documentation */
code span.dt { color: #902000; } /* DataType */
code span.dv { color: #40a070; } /* DecVal */
code span.er { color: #ff0000; font-weight: bold; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #40a070; } /* Float */
code span.fu { color: #06287e; } /* Function */
code span.im { } /* Import */
code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
code span.kw { color: #007020; font-weight: bold; } /* Keyword */
code span.op { color: #666666; } /* Operator */
code span.ot { color: #007020; } /* Other */
code span.pp { color: #bc7a00; } /* Preprocessor */
code span.sc { color: #4070a0; } /* SpecialChar */
code span.ss { color: #bb6688; } /* SpecialString */
code span.st { color: #4070a0; } /* String */
code span.va { color: #19177c; } /* Variable */
code span.vs { color: #4070a0; } /* VerbatimString */
code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
</style>
</head>
<body>
<div class="book without-animation with-summary font-size-2 font-family-1" data-basepath=".">
<div class="book-summary">
<nav role="navigation">
<ul class="summary">
<li class="chapter" data-level="1" data-path="index.html"><a href="index.html"><i class="fa fa-check"></i><b>1</b> Preface</a><ul>
<li class="chapter" data-level="1.1" data-path="index.html"><a href="index.html#caution"><i class="fa fa-check"></i><b>1.1</b> Caution</a></li>
<li class="chapter" data-level="1.2" data-path="index.html"><a href="index.html#installation"><i class="fa fa-check"></i><b>1.2</b> Installation</a></li>
<li class="chapter" data-level="1.3" data-path="index.html"><a href="index.html#license"><i class="fa fa-check"></i><b>1.3</b> License</a></li>
<li class="chapter" data-level="1.4" data-path="index.html"><a href="index.html#contact"><i class="fa fa-check"></i><b>1.4</b> Contact</a></li>
</ul></li>
<li class="chapter" data-level="2" data-path="an-introduction-to-machine-learning-with-r.html"><a href="an-introduction-to-machine-learning-with-r.html"><i class="fa fa-check"></i><b>2</b> An Introduction to Machine Learning with R</a><ul>
<li class="chapter" data-level="2.1" data-path="an-introduction-to-machine-learning-with-r.html"><a href="an-introduction-to-machine-learning-with-r.html#objectives-and-pre-requisites"><i class="fa fa-check"></i><b>2.1</b> Objectives and pre-requisites</a></li>
<li class="chapter" data-level="2.2" data-path="an-introduction-to-machine-learning-with-r.html"><a href="an-introduction-to-machine-learning-with-r.html#why-r"><i class="fa fa-check"></i><b>2.2</b> Why R?</a></li>
<li class="chapter" data-level="2.3" data-path="an-introduction-to-machine-learning-with-r.html"><a href="an-introduction-to-machine-learning-with-r.html#overview-of-machine-learning-ml"><i class="fa fa-check"></i><b>2.3</b> Overview of machine learning (ML)</a></li>
<li class="chapter" data-level="2.4" data-path="an-introduction-to-machine-learning-with-r.html"><a href="an-introduction-to-machine-learning-with-r.html#material-and-methods"><i class="fa fa-check"></i><b>2.4</b> Material and methods</a><ul>
<li class="chapter" data-level="2.4.1" data-path="an-introduction-to-machine-learning-with-r.html"><a href="an-introduction-to-machine-learning-with-r.html#example-data"><i class="fa fa-check"></i><b>2.4.1</b> Example data</a></li>
<li class="chapter" data-level="2.4.2" data-path="an-introduction-to-machine-learning-with-r.html"><a href="an-introduction-to-machine-learning-with-r.html#packages"><i class="fa fa-check"></i><b>2.4.2</b> Packages</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="3" data-path="example-datasets.html"><a href="example-datasets.html"><i class="fa fa-check"></i><b>3</b> Example datasets</a><ul>
<li class="chapter" data-level="3.1" data-path="example-datasets.html"><a href="example-datasets.html#edgar-andersons-iris-data"><i class="fa fa-check"></i><b>3.1</b> Edgar Anderson’s Iris Data</a></li>
<li class="chapter" data-level="3.2" data-path="example-datasets.html"><a href="example-datasets.html#motor-trend-car-road-tests"><i class="fa fa-check"></i><b>3.2</b> Motor Trend Car Road Tests</a></li>
<li class="chapter" data-level="3.3" data-path="example-datasets.html"><a href="example-datasets.html#sub-cellular-localisation"><i class="fa fa-check"></i><b>3.3</b> Sub-cellular localisation</a></li>
<li class="chapter" data-level="3.4" data-path="example-datasets.html"><a href="example-datasets.html#the-diamonds-data"><i class="fa fa-check"></i><b>3.4</b> The diamonds data</a></li>
<li class="chapter" data-level="3.5" data-path="example-datasets.html"><a href="example-datasets.html#the-sonar-data"><i class="fa fa-check"></i><b>3.5</b> The Sonar data</a></li>
<li class="chapter" data-level="3.6" data-path="example-datasets.html"><a href="example-datasets.html#housing-values-in-suburbs-of-boston"><i class="fa fa-check"></i><b>3.6</b> Housing Values in Suburbs of Boston</a></li>
<li class="chapter" data-level="3.7" data-path="example-datasets.html"><a href="example-datasets.html#customer-churn"><i class="fa fa-check"></i><b>3.7</b> Customer churn</a></li>
</ul></li>
<li class="chapter" data-level="4" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html"><i class="fa fa-check"></i><b>4</b> Unsupervised Learning</a><ul>
<li class="chapter" data-level="4.1" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html#introduction"><i class="fa fa-check"></i><b>4.1</b> Introduction</a></li>
<li class="chapter" data-level="4.2" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html#k-means-clustering"><i class="fa fa-check"></i><b>4.2</b> k-means clustering</a><ul>
<li class="chapter" data-level="4.2.1" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html#how-does-k-means-work"><i class="fa fa-check"></i><b>4.2.1</b> How does k-means work</a></li>
<li class="chapter" data-level="4.2.2" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html#model-selection"><i class="fa fa-check"></i><b>4.2.2</b> Model selection</a></li>
<li class="chapter" data-level="4.2.3" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html#how-to-determine-the-number-of-clusters"><i class="fa fa-check"></i><b>4.2.3</b> How to determine the number of clusters</a></li>
</ul></li>
<li class="chapter" data-level="4.3" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html#hierarchical-clustering"><i class="fa fa-check"></i><b>4.3</b> Hierarchical clustering</a><ul>
<li class="chapter" data-level="4.3.1" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html#how-does-hierarchical-clustering-work"><i class="fa fa-check"></i><b>4.3.1</b> How does hierarchical clustering work</a></li>
<li class="chapter" data-level="4.3.2" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html#defining-clusters"><i class="fa fa-check"></i><b>4.3.2</b> Defining clusters</a></li>
</ul></li>
<li class="chapter" data-level="4.4" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html#pre-processing"><i class="fa fa-check"></i><b>4.4</b> Pre-processing</a></li>
<li class="chapter" data-level="4.5" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html#principal-component-analysis-pca"><i class="fa fa-check"></i><b>4.5</b> Principal component analysis (PCA)</a><ul>
<li class="chapter" data-level="4.5.1" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html#how-does-it-work"><i class="fa fa-check"></i><b>4.5.1</b> How does it work</a></li>
<li class="chapter" data-level="4.5.2" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html#visualisation"><i class="fa fa-check"></i><b>4.5.2</b> Visualisation</a></li>
<li class="chapter" data-level="4.5.3" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html#data-pre-processing"><i class="fa fa-check"></i><b>4.5.3</b> Data pre-processing</a></li>
<li class="chapter" data-level="4.5.4" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html#final-comments-on-pca"><i class="fa fa-check"></i><b>4.5.4</b> Final comments on PCA</a></li>
</ul></li>
<li class="chapter" data-level="4.6" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html#t-distributed-stochastic-neighbour-embedding"><i class="fa fa-check"></i><b>4.6</b> t-Distributed Stochastic Neighbour Embedding</a><ul>
<li class="chapter" data-level="4.6.1" data-path="unsupervised-learning.html"><a href="unsupervised-learning.html#parameter-tuning"><i class="fa fa-check"></i><b>4.6.1</b> Parameter tuning</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="5" data-path="supervised-learning.html"><a href="supervised-learning.html"><i class="fa fa-check"></i><b>5</b> Supervised Learning</a><ul>
<li class="chapter" data-level="5.1" data-path="supervised-learning.html"><a href="supervised-learning.html#introduction-1"><i class="fa fa-check"></i><b>5.1</b> Introduction</a></li>
<li class="chapter" data-level="5.2" data-path="supervised-learning.html"><a href="supervised-learning.html#preview"><i class="fa fa-check"></i><b>5.2</b> Preview</a></li>
<li class="chapter" data-level="5.3" data-path="supervised-learning.html"><a href="supervised-learning.html#model-performance"><i class="fa fa-check"></i><b>5.3</b> Model performance</a><ul>
<li class="chapter" data-level="5.3.1" data-path="supervised-learning.html"><a href="supervised-learning.html#in-sample-and-out-of-sample-error"><i class="fa fa-check"></i><b>5.3.1</b> In-sample and out-of-sample error</a></li>
<li class="chapter" data-level="5.3.2" data-path="supervised-learning.html"><a href="supervised-learning.html#cross-validation"><i class="fa fa-check"></i><b>5.3.2</b> Cross-validation</a></li>
</ul></li>
<li class="chapter" data-level="5.4" data-path="supervised-learning.html"><a href="supervised-learning.html#classification-performance"><i class="fa fa-check"></i><b>5.4</b> Classification performance</a><ul>
<li class="chapter" data-level="5.4.1" data-path="supervised-learning.html"><a href="supervised-learning.html#confusion-matrix"><i class="fa fa-check"></i><b>5.4.1</b> Confusion matrix</a></li>
<li class="chapter" data-level="5.4.2" data-path="supervised-learning.html"><a href="supervised-learning.html#receiver-operating-characteristic-roc-curve"><i class="fa fa-check"></i><b>5.4.2</b> Receiver operating characteristic (ROC) curve</a></li>
<li class="chapter" data-level="5.4.3" data-path="supervised-learning.html"><a href="supervised-learning.html#auc-in-caret"><i class="fa fa-check"></i><b>5.4.3</b> AUC in <code>caret</code></a></li>
</ul></li>
<li class="chapter" data-level="5.5" data-path="supervised-learning.html"><a href="supervised-learning.html#random-forest"><i class="fa fa-check"></i><b>5.5</b> Random forest</a><ul>
<li class="chapter" data-level="5.5.1" data-path="supervised-learning.html"><a href="supervised-learning.html#decision-trees"><i class="fa fa-check"></i><b>5.5.1</b> Decision trees</a></li>
<li class="chapter" data-level="5.5.2" data-path="supervised-learning.html"><a href="supervised-learning.html#training-a-random-forest"><i class="fa fa-check"></i><b>5.5.2</b> Training a random forest</a></li>
</ul></li>
<li class="chapter" data-level="5.6" data-path="supervised-learning.html"><a href="supervised-learning.html#data-pre-processing-1"><i class="fa fa-check"></i><b>5.6</b> Data pre-processing</a><ul>
<li class="chapter" data-level="5.6.1" data-path="supervised-learning.html"><a href="supervised-learning.html#missing-values"><i class="fa fa-check"></i><b>5.6.1</b> Missing values</a></li>
<li class="chapter" data-level="5.6.2" data-path="supervised-learning.html"><a href="supervised-learning.html#median-imputation"><i class="fa fa-check"></i><b>5.6.2</b> Median imputation</a></li>
<li class="chapter" data-level="5.6.3" data-path="supervised-learning.html"><a href="supervised-learning.html#knn-imputation"><i class="fa fa-check"></i><b>5.6.3</b> kNN imputation</a></li>
</ul></li>
<li class="chapter" data-level="5.7" data-path="supervised-learning.html"><a href="supervised-learning.html#scaling-and-centering"><i class="fa fa-check"></i><b>5.7</b> Scaling and centering</a><ul>
<li class="chapter" data-level="5.7.1" data-path="supervised-learning.html"><a href="supervised-learning.html#multiple-pre-processing-methods"><i class="fa fa-check"></i><b>5.7.1</b> Multiple pre-processing methods</a></li>
</ul></li>
<li class="chapter" data-level="5.8" data-path="supervised-learning.html"><a href="supervised-learning.html#model-selection-1"><i class="fa fa-check"></i><b>5.8</b> Model selection</a><ul>
<li class="chapter" data-level="5.8.1" data-path="supervised-learning.html"><a href="supervised-learning.html#glmnet-model"><i class="fa fa-check"></i><b>5.8.1</b> <code>glmnet</code> model</a></li>
<li class="chapter" data-level="5.8.2" data-path="supervised-learning.html"><a href="supervised-learning.html#random-forest-model"><i class="fa fa-check"></i><b>5.8.2</b> random forest model</a></li>
<li class="chapter" data-level="5.8.3" data-path="supervised-learning.html"><a href="supervised-learning.html#knn-model"><i class="fa fa-check"></i><b>5.8.3</b> kNN model</a></li>
<li class="chapter" data-level="5.8.4" data-path="supervised-learning.html"><a href="supervised-learning.html#support-vector-machine-model"><i class="fa fa-check"></i><b>5.8.4</b> Support vector machine model</a></li>
<li class="chapter" data-level="5.8.5" data-path="supervised-learning.html"><a href="supervised-learning.html#naive-bayes"><i class="fa fa-check"></i><b>5.8.5</b> Naive Bayes</a></li>
<li class="chapter" data-level="5.8.6" data-path="supervised-learning.html"><a href="supervised-learning.html#comparing-models"><i class="fa fa-check"></i><b>5.8.6</b> Comparing models</a></li>
<li class="chapter" data-level="5.8.7" data-path="supervised-learning.html"><a href="supervised-learning.html#pre-processing-1"><i class="fa fa-check"></i><b>5.8.7</b> Pre-processing</a></li>
<li class="chapter" data-level="5.8.8" data-path="supervised-learning.html"><a href="supervised-learning.html#predict-using-the-best-model"><i class="fa fa-check"></i><b>5.8.8</b> Predict using the best model</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="6" data-path="final-notes.html"><a href="final-notes.html"><i class="fa fa-check"></i><b>6</b> Final notes</a><ul>
<li class="chapter" data-level="6.1" data-path="final-notes.html"><a href="final-notes.html#other-learning-algorithms"><i class="fa fa-check"></i><b>6.1</b> Other learning algorithms</a><ul>
<li class="chapter" data-level="" data-path="final-notes.html"><a href="final-notes.html#semi-supervised-learning"><i class="fa fa-check"></i>Semi-supervised learning</a></li>
<li class="chapter" data-level="" data-path="final-notes.html"><a href="final-notes.html#deep-learning-in-r"><i class="fa fa-check"></i>Deep learning in R</a></li>
</ul></li>
<li class="chapter" data-level="6.2" data-path="final-notes.html"><a href="final-notes.html#model-performance-1"><i class="fa fa-check"></i><b>6.2</b> Model performance</a></li>
<li class="chapter" data-level="6.3" data-path="final-notes.html"><a href="final-notes.html#credit-and-acknowledgements"><i class="fa fa-check"></i><b>6.3</b> Credit and acknowledgements</a></li>
<li class="chapter" data-level="6.4" data-path="final-notes.html"><a href="final-notes.html#references-and-further-reading"><i class="fa fa-check"></i><b>6.4</b> References and further reading</a></li>
<li class="chapter" data-level="6.5" data-path="final-notes.html"><a href="final-notes.html#session-information"><i class="fa fa-check"></i><b>6.5</b> Session information</a></li>
</ul></li>
</ul>
</nav>
</div>
<div class="book-body">
<div class="body-inner">
<div class="book-header" role="navigation">
<h1>
<i class="fa fa-circle-o-notch fa-spin"></i><a href="./">An Introduction to Machine Learning with R</a>
</h1>
</div>
<div class="page-wrapper" tabindex="-1" role="main">
<div class="page-inner">
<section class="normal" id="section-">
<div id="supervised-learning" class="section level1">
<h1><span class="header-section-number">Chapter 5</span> Supervised Learning</h1>
<div id="introduction-1" class="section level2">
<h2><span class="header-section-number">5.1</span> Introduction</h2>
<p>In <strong>supervised learning</strong> (SML), the learning algorithm is presented
with labelled example inputs, where the labels indicate the desired
output. SML itself is composed of <strong>classification</strong>, where the output
is qualitative, and <strong>regression</strong>, where the output is quantitative.</p>
<p>When two sets of labels, or classes, are available, one speaks of
<strong>binary classification</strong>. A classical example thereof is labelling an
email as <em>spam</em> or <em>not spam</em>. When more classes are to be learnt, one
speaks of a <strong>multi-class problem</strong>, such as annotation of a new <em>Iris</em>
example as being from the <em>setosa</em>, <em>versicolor</em> or <em>virginica</em>
species. In these cases, the output is a single label (of one of the
anticipated classes). If multiple labels may be assigned to each
example, one speaks of <strong>multi-label classification</strong>.</p>
</div>
<div id="preview" class="section level2">
<h2><span class="header-section-number">5.2</span> Preview</h2>
<p>To start this chapter, let’s use a simple, but useful classification
algorithm, k-nearest neighbours (kNN) to classify the <em>iris</em>
flowers. We will use the <code>knn</code> function from the <em><a href="https://CRAN.R-project.org/package=class">class</a></em>
package.</p>
<p>K-nearest neighbours works by directly measuring the (Euclidean)
distance between observations and inferring the class of unlabelled data
from the class of its nearest neighbours. In the figure below, the
unlabelled instances <em>1</em> and <em>2</em> will be assigned classes <em>c1</em> (blue)
and <em>c2</em> (red) as their closest neighbours are red and blue,
respectively.</p>
<div class="figure"><span id="fig:knnex"></span>
<img src="IntroMachineLearningWithR_files/figure-html/knnex-1.png" alt="Schematic illustrating the k nearest neighbors algorithm." width="672" />
<p class="caption">
Figure 5.1: Schematic illustrating the k nearest neighbors algorithm.
</p>
</div>
<p>Typically in machine learning, there are two clear steps, where one
first <strong>trains</strong> a model and then uses the model to <strong>predict</strong> new
outputs (class labels in this case). In the kNN, these two steps are
combined into a single function call to <code>knn</code>.</p>
<p>Lets draw a set of 50 random iris observations to train the model and
predict the species of another set of 50 randomly chosen flowers. The
<code>knn</code> function takes the training data, the new data (to be inferred)
and the labels of the training data, and returns (by default) the
predicted class.</p>
<div class="sourceCode" id="cb58"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb58-1" data-line-number="1"><span class="kw">set.seed</span>(12L)</a>
<a class="sourceLine" id="cb58-2" data-line-number="2">tr <-<span class="st"> </span><span class="kw">sample</span>(<span class="dv">150</span>, <span class="dv">50</span>)</a>
<a class="sourceLine" id="cb58-3" data-line-number="3">nw <-<span class="st"> </span><span class="kw">sample</span>(<span class="dv">150</span>, <span class="dv">50</span>)</a>
<a class="sourceLine" id="cb58-4" data-line-number="4"><span class="kw">library</span>(<span class="st">"class"</span>)</a>
<a class="sourceLine" id="cb58-5" data-line-number="5">knnres <-<span class="st"> </span><span class="kw">knn</span>(iris[tr, <span class="dv">-5</span>], iris[nw, <span class="dv">-5</span>], iris<span class="op">$</span>Species[tr])</a>
<a class="sourceLine" id="cb58-6" data-line-number="6"><span class="kw">head</span>(knnres)</a></code></pre></div>
<pre><code>## [1] versicolor setosa versicolor setosa setosa setosa
## Levels: setosa versicolor virginica</code></pre>
<p>We can now compare the observed kNN-predicted class and the expected
known outcome and calculate the overall accuracy of our model.</p>
<div class="sourceCode" id="cb60"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb60-1" data-line-number="1"><span class="kw">table</span>(knnres, iris<span class="op">$</span>Species[nw])</a></code></pre></div>
<pre><code>##
## knnres setosa versicolor virginica
## setosa 20 0 0
## versicolor 0 17 2
## virginica 0 0 11</code></pre>
<div class="sourceCode" id="cb62"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb62-1" data-line-number="1"><span class="kw">mean</span>(knnres <span class="op">==</span><span class="st"> </span>iris<span class="op">$</span>Species[nw])</a></code></pre></div>
<pre><code>## [1] 0.96</code></pre>
<p>We have omitted an important argument from <code>knn</code>, which is the
parameter <em>k</em> of the classifier. This parameter defines how many
nearest neighbours will be considered to assign a class to a new
unlabelled observation. From the arguments of the function,</p>
<div class="sourceCode" id="cb64"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb64-1" data-line-number="1"><span class="kw">args</span>(knn)</a></code></pre></div>
<pre><code>## function (train, test, cl, k = 1, l = 0, prob = FALSE, use.all = TRUE)
## NULL</code></pre>
<p>we see that the default value is 1. But is this a good value? Wouldn’t
we prefer to look at more neighbours and infer the new class using a
vote based on more labels?</p>
<blockquote>
<p>Challenge</p>
<p>Repeat the kNN classification above by using another value of k, and
compare the accuracy of this new model to the one above. Make sure
to use the same <code>tr</code> and <code>nw</code> training and new data to avoid any
biases in the comparison.</p>
</blockquote>
<details>
<div class="sourceCode" id="cb66"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb66-1" data-line-number="1">knnres5 <-<span class="st"> </span><span class="kw">knn</span>(iris[tr, <span class="dv">-5</span>], iris[nw, <span class="dv">-5</span>], iris<span class="op">$</span>Species[tr], <span class="dt">k =</span> <span class="dv">5</span>)</a>
<a class="sourceLine" id="cb66-2" data-line-number="2"><span class="kw">mean</span>(knnres5 <span class="op">==</span><span class="st"> </span>iris<span class="op">$</span>Species[nw])</a></code></pre></div>
<pre><code>## [1] 0.94</code></pre>
<div class="sourceCode" id="cb68"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb68-1" data-line-number="1"><span class="kw">table</span>(knnres5, knnres)</a></code></pre></div>
<pre><code>## knnres
## knnres5 setosa versicolor virginica
## setosa 20 0 0
## versicolor 0 19 1
## virginica 0 0 10</code></pre>
</details>
<blockquote>
<p>Challenge</p>
<p>Rerun the kNN classifier with a value of <em>k</em> > 1, and specify <code>prob = TRUE</code> to obtain the proportion of the votes for the winning class.</p>
</blockquote>
<details>
<div class="sourceCode" id="cb70"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb70-1" data-line-number="1">knnres5prob <-<span class="st"> </span><span class="kw">knn</span>(iris[tr, <span class="dv">-5</span>], iris[nw, <span class="dv">-5</span>], iris<span class="op">$</span>Species[tr], <span class="dt">k =</span> <span class="dv">5</span>, <span class="dt">prob =</span> <span class="ot">TRUE</span>)</a>
<a class="sourceLine" id="cb70-2" data-line-number="2"><span class="kw">table</span>(<span class="kw">attr</span>(knnres5prob, <span class="st">"prob"</span>))</a></code></pre></div>
<pre><code>##
## 0.6 0.8 0.833333333333333 1
## 3 13 1 33</code></pre>
</details>
<p>This introductory example leads to two important and related questions
that we need to consider:</p>
<ul>
<li><p>How can we do a good job in training and testing data? In the
example above, we choose random training and new data.</p></li>
<li><p>How can we estimate our model parameters (<em>k</em> in the example above)
so as to obtain good classification accuracy?</p></li>
</ul>
</div>
<div id="model-performance" class="section level2">
<h2><span class="header-section-number">5.3</span> Model performance</h2>
<div id="in-sample-and-out-of-sample-error" class="section level3">
<h3><span class="header-section-number">5.3.1</span> In-sample and out-of-sample error</h3>
<p>In supervised machine learning, we have a desired output and thus know
precisely what is to be computed. It thus becomes possible to directly
evaluate a model using a quantifiable and objective metric. For
regression, we will use the <strong>root mean squared error</strong> (RMSE), which
is what linear regression (<code>lm</code> in R) seeks to minimise. For
classification, we will use <strong>model prediction accuracy</strong>.</p>
<p>Typically, we won’t want to calculate any of these metrics using
observations that were also used to calculate the model. This
approach, called <strong>in-sample error</strong> leads to optimistic assessment of
our model. Indeed, the model has already <em>seen</em> these data upon
construction, and is considered optimised for these observations
in particular; it is said to <strong>over-fit</strong> the data. We prefer to
calculate an <strong>out-of-sample error</strong>, on new data, to gain a better
idea of how to model performs on unseen data, and estimate how well
the model <strong>generalises</strong>.</p>
<p>In this course, we will focus on the <em><a href="https://CRAN.R-project.org/package=caret">caret</a></em> package for
Classification And REgression Training (see also
<a href="https://topepo.github.io/caret/index.html" class="uri">https://topepo.github.io/caret/index.html</a>). It provides a common and
consistent interface to many, often repetitive, tasks in supervised
learning.</p>
<div class="sourceCode" id="cb72"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb72-1" data-line-number="1"><span class="kw">library</span>(<span class="st">"caret"</span>)</a></code></pre></div>
<p>The code chunk below uses the <code>lm</code> function to model the price of
round cut diamonds and then predicts the price of these very same
diamonds with the <code>predict</code> function.</p>
<div class="sourceCode" id="cb73"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb73-1" data-line-number="1"><span class="kw">data</span>(diamonds)</a>
<a class="sourceLine" id="cb73-2" data-line-number="2">model <-<span class="st"> </span><span class="kw">lm</span>(price <span class="op">~</span><span class="st"> </span>., diamonds)</a>
<a class="sourceLine" id="cb73-3" data-line-number="3">p <-<span class="st"> </span><span class="kw">predict</span>(model, diamonds)</a></code></pre></div>
<blockquote>
<p>Challenge</p>
<p>Calculate the root mean squared error for the prediction above</p>
</blockquote>
<details>
<div class="sourceCode" id="cb74"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb74-1" data-line-number="1"><span class="co">## Error on prediction</span></a>
<a class="sourceLine" id="cb74-2" data-line-number="2">error <-<span class="st"> </span>p <span class="op">-</span><span class="st"> </span>diamonds<span class="op">$</span>price</a>
<a class="sourceLine" id="cb74-3" data-line-number="3">rmse_in <-<span class="st"> </span><span class="kw">sqrt</span>(<span class="kw">mean</span>(error<span class="op">^</span><span class="dv">2</span>)) <span class="co">## in-sample RMSE</span></a>
<a class="sourceLine" id="cb74-4" data-line-number="4">rmse_in</a></code></pre></div>
<pre><code>## [1] 1129.843</code></pre>
</details>
<p>Let’s now repeat the exercise above, but by calculating the
out-of-sample RMSE. We prepare a 80/20 split of the data and use
80% to fit our model, and predict the target variable (this is called the
<strong>training data</strong>), the price, on the 20% of unseen data (the <strong>testing
data</strong>).</p>
<blockquote>
<p>Challenge</p>
<ol style="list-style-type: decimal">
<li>Let’s create a <strong>random</strong> 80/20 split to define the test and
train subsets.</li>
<li>Train a regression model on the training data.</li>
<li>Test the model on the testing data.</li>
<li>Calculating the out-of-sample RMSE.</li>
</ol>
</blockquote>
<details>
<div class="sourceCode" id="cb76"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb76-1" data-line-number="1"><span class="kw">set.seed</span>(<span class="dv">42</span>)</a>
<a class="sourceLine" id="cb76-2" data-line-number="2">ntest <-<span class="st"> </span><span class="kw">nrow</span>(diamonds) <span class="op">*</span><span class="st"> </span><span class="fl">0.80</span></a>
<a class="sourceLine" id="cb76-3" data-line-number="3">test <-<span class="st"> </span><span class="kw">sample</span>(<span class="kw">nrow</span>(diamonds), ntest)</a>
<a class="sourceLine" id="cb76-4" data-line-number="4">model <-<span class="st"> </span><span class="kw">lm</span>(price <span class="op">~</span><span class="st"> </span>., <span class="dt">data =</span> diamonds[test, ])</a>
<a class="sourceLine" id="cb76-5" data-line-number="5">p <-<span class="st"> </span><span class="kw">predict</span>(model, diamonds[<span class="op">-</span>test, ])</a>
<a class="sourceLine" id="cb76-6" data-line-number="6">error <-<span class="st"> </span>p <span class="op">-</span><span class="st"> </span>diamonds<span class="op">$</span>price[<span class="op">-</span>test]</a>
<a class="sourceLine" id="cb76-7" data-line-number="7">rmse_out <-<span class="st"> </span><span class="kw">sqrt</span>(<span class="kw">mean</span>(error<span class="op">^</span><span class="dv">2</span>)) <span class="co">## out-of-sample RMSE</span></a>
<a class="sourceLine" id="cb76-8" data-line-number="8">rmse_out</a></code></pre></div>
<pre><code>## [1] 1137.466</code></pre>
</details>
<p>The values for the out-of-sample RMSE will vary depending on what
exact split was used. The diamonds is a rather extensive data set, and
thus even when building our model using a subset of the available data
(80% above), we manage to generate a model with a low RMSE, and
possibly lower than the in-sample error.</p>
<p>When dealing with datasets of smaller sizes, however, the presence of
a single outlier in the train and test data split can substantially
influence the model and the RMSE. We can’t rely on such an approach and
need a more robust one where we can generate and use multiple,
different train/test sets to sample a set of RMSEs, leading to a
better estimate of the out-of-sample RMSE.</p>
</div>
<div id="cross-validation" class="section level3">
<h3><span class="header-section-number">5.3.2</span> Cross-validation</h3>
<p>Instead of doing a single training/testing split, we can systematise
this process, produce multiple, different out-of-sample train/test
splits, that will lead to a better estimate of the out-of-sample RMSE.</p>
<p>The figure below illustrates the cross validation procedure, creating
3 folds. One would typically do a 10-fold cross validation (if the
size of the data permits it). We split the data into 3 <em>random</em> and
complementary folds, so that each data point appears exactly once in
each fold. This leads to a total test set size that is identical to
the size of the full dataset but is composed of out-of-sample
predictions.</p>
<div class="figure">
<img src="figure/xval.png" alt="Schematic of 3-fold cross validation producing three training (blue) and testing (white) splits." />
<p class="caption">Schematic of 3-fold cross validation producing three training (blue) and testing (white) splits.</p>
</div>
<p>After cross-validation, all models used within each fold are
discarded, and a new model is built using the whole dataset, with the
best model parameter(s), i.e those that generalised over all folds.</p>
<p>This makes cross-validation quite time consuming, as it takes <em>x+1</em>
(where <em>x</em> in the number of cross-validation folds) times as long as
fitting a single model, but is essential.</p>
<p>Note that it is important to maintain the class proportions within the
different folds, i.e. respect the proportion of the different classes
in the original data. This is also taken care when using the
<em><a href="https://CRAN.R-project.org/package=caret">caret</a></em> package.</p>
<p>The procedure of creating folds and training the models is handled by
the <code>train</code> function in <em><a href="https://CRAN.R-project.org/package=caret">caret</a></em>. Below, we apply it to
the diamond price example that we used when introducing the model
performance.</p>
<ul>
<li>We start by setting a random seed to be able to reproduce the example.</li>
<li>We specify the method (the learning algorithm) we want to use. Here,
we use <code>"lm"</code>, but, as we will see later, there are many others to
choose from<a href="final-notes.html#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a>.</li>
<li>We then set the out-of-sample training procedure to 10-fold cross
validation (<code>method = "cv"</code> and <code>number = 10</code>). To simplify the
output in the material for better readability, we set the verbosity
flag to <code>FALSE</code>, but it is useful to set it to <code>TRUE</code> in interactive
mode.</li>
</ul>
<div class="sourceCode" id="cb78"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb78-1" data-line-number="1"><span class="kw">set.seed</span>(<span class="dv">42</span>)</a>
<a class="sourceLine" id="cb78-2" data-line-number="2">model <-<span class="st"> </span><span class="kw">train</span>(price <span class="op">~</span><span class="st"> </span>., diamonds,</a>
<a class="sourceLine" id="cb78-3" data-line-number="3"> <span class="dt">method =</span> <span class="st">"lm"</span>,</a>
<a class="sourceLine" id="cb78-4" data-line-number="4"> <span class="dt">trControl =</span> <span class="kw">trainControl</span>(<span class="dt">method =</span> <span class="st">"cv"</span>,</a>
<a class="sourceLine" id="cb78-5" data-line-number="5"> <span class="dt">number =</span> <span class="dv">10</span>,</a>
<a class="sourceLine" id="cb78-6" data-line-number="6"> <span class="dt">verboseIter =</span> <span class="ot">FALSE</span>))</a>
<a class="sourceLine" id="cb78-7" data-line-number="7">model</a></code></pre></div>
<pre><code>## Linear Regression
##
## 53940 samples
## 9 predictor
##
## No pre-processing
## Resampling: Cross-Validated (10 fold)
## Summary of sample sizes: 48547, 48545, 48546, 48545, 48546, 48546, ...
## Resampling results:
##
## RMSE Rsquared MAE
## 1130.819 0.9197489 740.5712
##
## Tuning parameter 'intercept' was held constant at a value of TRUE</code></pre>
<p>Once we have trained our model, we can directly use this <code>train</code>
object as input to the <code>predict</code> method:</p>
<div class="sourceCode" id="cb80"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb80-1" data-line-number="1">p <-<span class="st"> </span><span class="kw">predict</span>(model, diamonds)</a>
<a class="sourceLine" id="cb80-2" data-line-number="2">error <-<span class="st"> </span>p <span class="op">-</span><span class="st"> </span>diamonds<span class="op">$</span>price</a>
<a class="sourceLine" id="cb80-3" data-line-number="3">rmse_xval <-<span class="st"> </span><span class="kw">sqrt</span>(<span class="kw">mean</span>(error<span class="op">^</span><span class="dv">2</span>)) <span class="co">## xval RMSE</span></a>
<a class="sourceLine" id="cb80-4" data-line-number="4">rmse_xval</a></code></pre></div>
<pre><code>## [1] 1129.843</code></pre>
<blockquote>
<p>Challenge</p>
<p>Train a linear model using 10-fold cross-validation and then use it
to predict the median value of owner-occupied homes in Boston from
the <code>Boston</code> dataset as described above. Then calculate the RMSE.</p>
</blockquote>
<details>
<div class="sourceCode" id="cb82"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb82-1" data-line-number="1"><span class="kw">library</span>(<span class="st">"MASS"</span>)</a>
<a class="sourceLine" id="cb82-2" data-line-number="2"><span class="kw">data</span>(Boston)</a>
<a class="sourceLine" id="cb82-3" data-line-number="3">model <-<span class="st"> </span><span class="kw">train</span>(medv <span class="op">~</span><span class="st"> </span>.,</a>
<a class="sourceLine" id="cb82-4" data-line-number="4"> Boston,</a>
<a class="sourceLine" id="cb82-5" data-line-number="5"> <span class="dt">method =</span> <span class="st">"lm"</span>,</a>
<a class="sourceLine" id="cb82-6" data-line-number="6"> <span class="dt">trControl =</span> <span class="kw">trainControl</span>(<span class="dt">method =</span> <span class="st">"cv"</span>,</a>
<a class="sourceLine" id="cb82-7" data-line-number="7"> <span class="dt">number =</span> <span class="dv">10</span>))</a>
<a class="sourceLine" id="cb82-8" data-line-number="8">model</a></code></pre></div>
<pre><code>## Linear Regression
##
## 506 samples
## 13 predictor
##
## No pre-processing
## Resampling: Cross-Validated (10 fold)
## Summary of sample sizes: 455, 456, 457, 456, 454, 456, ...
## Resampling results:
##
## RMSE Rsquared MAE
## 4.838479 0.7301286 3.433261
##
## Tuning parameter 'intercept' was held constant at a value of TRUE</code></pre>
<div class="sourceCode" id="cb84"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb84-1" data-line-number="1">p <-<span class="st"> </span><span class="kw">predict</span>(model, Boston)</a>
<a class="sourceLine" id="cb84-2" data-line-number="2"><span class="kw">sqrt</span>(<span class="kw">mean</span>((p <span class="op">-</span><span class="st"> </span>Boston<span class="op">$</span>medv)<span class="op">^</span><span class="dv">2</span>))</a></code></pre></div>
<pre><code>## [1] 4.679191</code></pre>
</details>
</div>
</div>
<div id="classification-performance" class="section level2">
<h2><span class="header-section-number">5.4</span> Classification performance</h2>
<p>Above, we have used the RMSE to assess the performance of our
regression model. When using a classification algorithm, we want to
assess its accuracy to do so.</p>
<div id="confusion-matrix" class="section level3">
<h3><span class="header-section-number">5.4.1</span> Confusion matrix</h3>
<p>Instead of calculating an error between predicted value and known
value, in classification we will directly compare the predicted
class matches with the known label. To do so, rather than calculating the
mean accuracy as we did above, in the introductory kNN example, we can
calculate a <strong>confusion matrix</strong>.</p>
<p>A confusion matrix contrasts predictions to actual results. Correct
results are <em>true positives</em> (TP) and <em>true negatives</em> (TN) are found
along the diagonal. All other cells indicate false results, i.e <em>false
negatives</em> (FN) and <em>false positives</em> (FP).</p>
<table>
<thead>
<tr class="header">
<th></th>
<th align="left">Reference Yes</th>
<th align="left">Reference No</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Predicted Yes</td>
<td align="left">TP</td>
<td align="left">FP</td>
</tr>
<tr class="even">
<td>Predicted No</td>
<td align="left">FN</td>
<td align="left">TN</td>
</tr>
</tbody>
</table>
<p>The values that populate this table will depend on the cutoff that
we set to define whether the classifier should predict <em>Yes</em> or
<em>No</em>. Intuitively, we might want to use 0.5 as a threshold, and assign
every result with a probability > 0.5 to <em>Yes</em> and <em>No</em> otherwise.</p>
<p>Let’s experiment with this using the <code>Sonar</code> dataset, and see if we
can differentiate mines from rocks using a logistic classification
model use the <code>glm</code> function from the <em><a href="https://CRAN.R-project.org/package=stats">stats</a></em> package.</p>
<div class="sourceCode" id="cb86"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb86-1" data-line-number="1"><span class="kw">library</span>(<span class="st">"mlbench"</span>)</a>
<a class="sourceLine" id="cb86-2" data-line-number="2"><span class="kw">data</span>(Sonar)</a>
<a class="sourceLine" id="cb86-3" data-line-number="3"><span class="co">## 60/40 split</span></a>
<a class="sourceLine" id="cb86-4" data-line-number="4">tr <-<span class="st"> </span><span class="kw">sample</span>(<span class="kw">nrow</span>(Sonar), <span class="kw">round</span>(<span class="kw">nrow</span>(Sonar) <span class="op">*</span><span class="st"> </span><span class="fl">0.6</span>))</a>
<a class="sourceLine" id="cb86-5" data-line-number="5">train <-<span class="st"> </span>Sonar[tr, ]</a>
<a class="sourceLine" id="cb86-6" data-line-number="6">test <-<span class="st"> </span>Sonar[<span class="op">-</span>tr, ]</a></code></pre></div>
<div class="sourceCode" id="cb87"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb87-1" data-line-number="1">model <-<span class="st"> </span><span class="kw">glm</span>(Class <span class="op">~</span><span class="st"> </span>., <span class="dt">data =</span> train, <span class="dt">family =</span> <span class="st">"binomial"</span>)</a>
<a class="sourceLine" id="cb87-2" data-line-number="2">p <-<span class="st"> </span><span class="kw">predict</span>(model, test, <span class="dt">type =</span> <span class="st">"response"</span>)</a>
<a class="sourceLine" id="cb87-3" data-line-number="3"><span class="kw">summary</span>(p)</a></code></pre></div>
<pre><code>## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.0000 0.0000 0.8545 0.5123 1.0000 1.0000</code></pre>
<div class="sourceCode" id="cb89"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb89-1" data-line-number="1">cl <-<span class="st"> </span><span class="kw">ifelse</span>(p <span class="op">></span><span class="st"> </span><span class="fl">0.5</span>, <span class="st">"M"</span>, <span class="st">"R"</span>)</a>
<a class="sourceLine" id="cb89-2" data-line-number="2"><span class="kw">table</span>(cl, test<span class="op">$</span>Class)</a></code></pre></div>
<pre><code>##
## cl M R
## M 12 31
## R 31 9</code></pre>
<p>The caret package offers its own, more informative function to
calculate a confusion matrix:</p>
<div class="sourceCode" id="cb91"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb91-1" data-line-number="1"><span class="kw">confusionMatrix</span>(<span class="kw">factor</span>(cl), test<span class="op">$</span>Class)</a></code></pre></div>
<pre><code>## Confusion Matrix and Statistics
##
## Reference
## Prediction M R
## M 12 31
## R 31 9
##
## Accuracy : 0.253
## 95% CI : (0.1639, 0.3604)
## No Information Rate : 0.5181
## P-Value [Acc > NIR] : 1
##
## Kappa : -0.4959
##
## Mcnemar's Test P-Value : 1
##
## Sensitivity : 0.2791
## Specificity : 0.2250
## Pos Pred Value : 0.2791
## Neg Pred Value : 0.2250
## Prevalence : 0.5181
## Detection Rate : 0.1446
## Detection Prevalence : 0.5181
## Balanced Accuracy : 0.2520
##
## 'Positive' Class : M
## </code></pre>
<p>We get, among others</p>
<ul>
<li>the accuracy: <span class="math inline">\(\frac{TP + TN}{TP + TN + FP + FN}\)</span></li>
<li>the sensitivity (recall, TP rate): <span class="math inline">\(\frac{TP}{TP + FN}\)</span></li>
<li>the specificity: <span class="math inline">\(\frac{TN}{TN + FP}\)</span></li>
<li>positive predictive value (precision): <span class="math inline">\(\frac{TP}{TP + FP}\)</span></li>
<li>negative predictive value: <span class="math inline">\(\frac{TN}{TN + FN}\)</span></li>
<li>FP rate (fall-out): <span class="math inline">\(\frac{FP}{FP + TN}\)</span></li>
</ul>
<blockquote>
<p>Challenge</p>
<p>Compare the model accuracy (or any other metric) using thresholds of
0.1 and 0.9.</p>
</blockquote>
<details>
<div class="sourceCode" id="cb93"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb93-1" data-line-number="1"><span class="kw">confusionMatrix</span>(<span class="kw">factor</span>(<span class="kw">ifelse</span>(p <span class="op">></span><span class="st"> </span><span class="fl">0.9</span>, <span class="st">"M"</span>, <span class="st">"R"</span>)), test<span class="op">$</span>Class)</a></code></pre></div>
<pre><code>## Confusion Matrix and Statistics
##
## Reference
## Prediction M R
## M 11 30
## R 32 10
##
## Accuracy : 0.253
## 95% CI : (0.1639, 0.3604)
## No Information Rate : 0.5181
## P-Value [Acc > NIR] : 1.0000
##
## Kappa : -0.4933
##
## Mcnemar's Test P-Value : 0.8989
##
## Sensitivity : 0.2558
## Specificity : 0.2500
## Pos Pred Value : 0.2683
## Neg Pred Value : 0.2381
## Prevalence : 0.5181
## Detection Rate : 0.1325
## Detection Prevalence : 0.4940
## Balanced Accuracy : 0.2529
##
## 'Positive' Class : M
## </code></pre>
<div class="sourceCode" id="cb95"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb95-1" data-line-number="1"><span class="kw">confusionMatrix</span>(<span class="kw">factor</span>(<span class="kw">ifelse</span>(p <span class="op">></span><span class="st"> </span><span class="fl">0.1</span>, <span class="st">"M"</span>, <span class="st">"R"</span>)), test<span class="op">$</span>Class)</a></code></pre></div>
<pre><code>## Confusion Matrix and Statistics
##
## Reference
## Prediction M R
## M 12 31
## R 31 9
##
## Accuracy : 0.253
## 95% CI : (0.1639, 0.3604)
## No Information Rate : 0.5181
## P-Value [Acc > NIR] : 1
##
## Kappa : -0.4959
##
## Mcnemar's Test P-Value : 1
##
## Sensitivity : 0.2791
## Specificity : 0.2250
## Pos Pred Value : 0.2791
## Neg Pred Value : 0.2250
## Prevalence : 0.5181
## Detection Rate : 0.1446
## Detection Prevalence : 0.5181
## Balanced Accuracy : 0.2520
##
## 'Positive' Class : M
## </code></pre>
</details>
</div>
<div id="receiver-operating-characteristic-roc-curve" class="section level3">
<h3><span class="header-section-number">5.4.2</span> Receiver operating characteristic (ROC) curve</h3>
<p>There is no reason to use 0.5 as a threshold. One could use a low
threshold to catch more mines with less certainty or or higher
threshold to catch fewer mines with more certainty.</p>
<p>This illustrates the need to adequately balance TP and FP rates. We
need to have a way to do a cost-benefit analysis, and the solution
will often depend on the question/problem.</p>
<p>One solution would be to try with different classification
thresholds. Instead of inspecting numerous confusion matrices, it is
possible to automate the calculation of the TP and FP rates at each
threshold and visualise all results along a ROC curve.</p>
<p>This can be done with the <code>colAUC</code> function from the
<em><a href="https://CRAN.R-project.org/package=caTools">caTools</a></em> package:</p>
<div class="sourceCode" id="cb97"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb97-1" data-line-number="1">caTools<span class="op">::</span><span class="kw">colAUC</span>(p, test[[<span class="st">"Class"</span>]], <span class="dt">plotROC =</span> <span class="ot">TRUE</span>)</a></code></pre></div>
<p><img src="IntroMachineLearningWithR_files/figure-html/unnamed-chunk-11-1.png" width="672" /></p>
<pre><code>## [,1]
## M vs. R 0.7767442</code></pre>
<ul>
<li>x: FP rate (1 - specificity)</li>
<li>y: TP rate (sensitivity)</li>
<li>each point along the curve represents a confusion matrix for a given
threshold</li>
</ul>
<p>In addition, the <code>colAUC</code> function returns the area under the curve
(AUC) model accuracy metric. This is single number metric, summarising
the model performance along all possible thresholds:</p>
<ul>
<li>an AUC of 0.5 corresponds to a random model</li>
<li>values > 0.5 do better than a random guess</li>
<li>a value of 1 represents a perfect model</li>
<li>a value 0 represents a model that is always wrong</li>
</ul>
</div>
<div id="auc-in-caret" class="section level3">
<h3><span class="header-section-number">5.4.3</span> AUC in <code>caret</code></h3>
<p>When using <em><a href="https://CRAN.R-project.org/package=caret">caret</a></em>’s <code>trainControl</code> function to train a
model, we can set it so that it computes the ROC and AUC properties
for us.</p>
<div class="sourceCode" id="cb99"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb99-1" data-line-number="1"><span class="co">## Create trainControl object: myControl</span></a>
<a class="sourceLine" id="cb99-2" data-line-number="2">myControl <-<span class="st"> </span><span class="kw">trainControl</span>(</a>
<a class="sourceLine" id="cb99-3" data-line-number="3"> <span class="dt">method =</span> <span class="st">"cv"</span>, <span class="co">## cross validation</span></a>
<a class="sourceLine" id="cb99-4" data-line-number="4"> <span class="dt">number =</span> <span class="dv">10</span>, <span class="co">## 10-fold</span></a>
<a class="sourceLine" id="cb99-5" data-line-number="5"> <span class="dt">summaryFunction =</span> twoClassSummary, <span class="co">## NEW</span></a>
<a class="sourceLine" id="cb99-6" data-line-number="6"> <span class="dt">classProbs =</span> <span class="ot">TRUE</span>, <span class="co"># IMPORTANT</span></a>
<a class="sourceLine" id="cb99-7" data-line-number="7"> <span class="dt">verboseIter =</span> <span class="ot">FALSE</span></a>
<a class="sourceLine" id="cb99-8" data-line-number="8">)</a>
<a class="sourceLine" id="cb99-9" data-line-number="9"><span class="co">## Train glm with custom trainControl: model</span></a>
<a class="sourceLine" id="cb99-10" data-line-number="10">model <-<span class="st"> </span><span class="kw">train</span>(Class <span class="op">~</span><span class="st"> </span>., Sonar,</a>
<a class="sourceLine" id="cb99-11" data-line-number="11"> <span class="dt">method =</span> <span class="st">"glm"</span>, <span class="co">## to use glm's logistic regression</span></a>
<a class="sourceLine" id="cb99-12" data-line-number="12"> <span class="dt">trControl =</span> myControl)</a>
<a class="sourceLine" id="cb99-13" data-line-number="13"></a>
<a class="sourceLine" id="cb99-14" data-line-number="14"><span class="co">## Print model to console</span></a>
<a class="sourceLine" id="cb99-15" data-line-number="15"><span class="kw">print</span>(model)</a></code></pre></div>
<pre><code>## Generalized Linear Model
##
## 208 samples
## 60 predictor
## 2 classes: 'M', 'R'
##
## No pre-processing
## Resampling: Cross-Validated (10 fold)
## Summary of sample sizes: 187, 188, 188, 187, 188, 187, ...
## Resampling results:
##
## ROC Sens Spec
## 0.733447 0.7477273 0.6688889</code></pre>
<blockquote>
<p>Challenge</p>
<p>Define a <code>train</code> object that uses the AUC and 10-fold cross
validation to classify the Sonar data using a logistic regression,
as demonstrated above.</p>
</blockquote>
</div>
</div>
<div id="random-forest" class="section level2">
<h2><span class="header-section-number">5.5</span> Random forest</h2>
<p>Random forest models are accurate and non-linear models and robust to
over-fitting and hence quite popular. They however require
hyperparameters to be tuned manually, like the value <em>k</em> in the
example above.</p>
<p>Building a random forest starts by generating a high number of
individual decision trees. A single decision tree isn’t very accurate,
but many different trees built using different inputs (with
bootstrapped inputs, features and observations) enable us to explore a
broad search space and, once combined, produce accurate models, a
technique called <em>bootstrap aggregation</em> or <em>bagging</em>.</p>
<div id="decision-trees" class="section level3">
<h3><span class="header-section-number">5.5.1</span> Decision trees</h3>
<p>A great advantage of decision trees is that they make a complex
decision simpler by breaking it down into smaller, simpler decisions
using a divide-and-conquer strategy. They basically identify a set of
if-else conditions that split the data according to the value of the
features.</p>
<div class="sourceCode" id="cb101"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb101-1" data-line-number="1"><span class="kw">library</span>(<span class="st">"rpart"</span>) <span class="co">## recursive partitioning</span></a>
<a class="sourceLine" id="cb101-2" data-line-number="2">m <-<span class="st"> </span><span class="kw">rpart</span>(Class <span class="op">~</span><span class="st"> </span>., <span class="dt">data =</span> Sonar,</a>
<a class="sourceLine" id="cb101-3" data-line-number="3"> <span class="dt">method =</span> <span class="st">"class"</span>)</a>
<a class="sourceLine" id="cb101-4" data-line-number="4"><span class="kw">library</span>(<span class="st">"rpart.plot"</span>)</a>
<a class="sourceLine" id="cb101-5" data-line-number="5"><span class="kw">rpart.plot</span>(m)</a></code></pre></div>
<div class="figure"><span id="fig:rpart"></span>
<img src="IntroMachineLearningWithR_files/figure-html/rpart-1.png" alt="Descision tree with its if-else conditions" width="672" />
<p class="caption">
Figure 5.2: Descision tree with its if-else conditions
</p>
</div>
<div class="sourceCode" id="cb102"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb102-1" data-line-number="1">p <-<span class="st"> </span><span class="kw">predict</span>(m, Sonar, <span class="dt">type =</span> <span class="st">"class"</span>)</a>
<a class="sourceLine" id="cb102-2" data-line-number="2"><span class="kw">table</span>(p, Sonar<span class="op">$</span>Class)</a></code></pre></div>
<pre><code>##
## p M R
## M 95 10
## R 16 87</code></pre>
<p>Decision trees choose splits based on most homogeneous partitions, and
lead to smaller and more homogeneous partitions over their iterations.</p>
<p>An issue with single decision trees is that they can grow, and become
large and complex with many branches, which corresponds to
over-fitting. Over-fitting models noise, rather than general patterns in
the data, focusing on subtle patterns (outliers) that won’t
generalise.</p>
<p>To avoid over-fitting, individual decision trees are pruned. Pruning
can happen as a pre-condition when growing the tree, or afterwards, by
pruning a large tree.</p>
<ul>
<li><p><em>Pre-pruning</em>: stop growing process, i.e stops divide-and-conquer
after a certain number of iterations (grows tree to a certain
predefined level), or requires a minimum number of observations in
each mode to allow splitting.</p></li>
<li><p><em>Post-pruning</em>: grow a large and complex tree, and reduce its size;
nodes and branches that have a negligible effect on the
classification accuracy are removed.</p></li>
</ul>
</div>
<div id="training-a-random-forest" class="section level3">
<h3><span class="header-section-number">5.5.2</span> Training a random forest</h3>
<p>Let’s return to random forests and train a model using the <code>train</code>
function from <em><a href="https://CRAN.R-project.org/package=caret">caret</a></em>:</p>
<div class="sourceCode" id="cb104"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb104-1" data-line-number="1"><span class="kw">set.seed</span>(<span class="dv">12</span>)</a>
<a class="sourceLine" id="cb104-2" data-line-number="2">model <-<span class="st"> </span><span class="kw">train</span>(Class <span class="op">~</span><span class="st"> </span>.,</a>
<a class="sourceLine" id="cb104-3" data-line-number="3"> <span class="dt">data =</span> Sonar,</a>
<a class="sourceLine" id="cb104-4" data-line-number="4"> <span class="dt">method =</span> <span class="st">"ranger"</span>)</a>
<a class="sourceLine" id="cb104-5" data-line-number="5"><span class="kw">print</span>(model)</a></code></pre></div>
<pre><code>## Random Forest
##
## 208 samples
## 60 predictor
## 2 classes: 'M', 'R'
##
## No pre-processing
## Resampling: Bootstrapped (25 reps)
## Summary of sample sizes: 208, 208, 208, 208, 208, 208, ...
## Resampling results across tuning parameters:
##
## mtry splitrule Accuracy Kappa
## 2 gini 0.8090731 0.6131571
## 2 extratrees 0.8136902 0.6234492
## 31 gini 0.7736954 0.5423516
## 31 extratrees 0.8285153 0.6521921
## 60 gini 0.7597299 0.5140905
## 60 extratrees 0.8157646 0.6255929
##
## Tuning parameter 'min.node.size' was held constant at a value of 1
## Accuracy was used to select the optimal model using the largest value.
## The final values used for the model were mtry = 31, splitrule = extratrees
## and min.node.size = 1.</code></pre>
<div class="sourceCode" id="cb106"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb106-1" data-line-number="1"><span class="kw">plot</span>(model)</a></code></pre></div>
<p><img src="IntroMachineLearningWithR_files/figure-html/rfplotmodel-1.png" width="672" /></p>
<p>The main hyperparameter is <em>mtry</em>, i.e. the number of randomly selected
variables used at each split. Two variables produce random models, while
hundreds of variables tend to be less random, but risk
over-fitting. The <code>caret</code> package can automate the tuning of the hyperparameter using a
<strong>grid search</strong>, which can be parametrised by setting <code>tuneLength</code>
(that sets the number of hyperparameter values to test) or directly
defining the <code>tuneGrid</code> (the hyperparameter values), which requires
knowledge of the model.</p>
<div class="sourceCode" id="cb107"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb107-1" data-line-number="1">model <-<span class="st"> </span><span class="kw">train</span>(Class <span class="op">~</span><span class="st"> </span>.,</a>
<a class="sourceLine" id="cb107-2" data-line-number="2"> <span class="dt">data =</span> Sonar,</a>
<a class="sourceLine" id="cb107-3" data-line-number="3"> <span class="dt">method =</span> <span class="st">"ranger"</span>,</a>
<a class="sourceLine" id="cb107-4" data-line-number="4"> <span class="dt">tuneLength =</span> <span class="dv">5</span>)</a></code></pre></div>
<div class="sourceCode" id="cb108"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb108-1" data-line-number="1"><span class="kw">set.seed</span>(<span class="dv">42</span>)</a>
<a class="sourceLine" id="cb108-2" data-line-number="2">myGrid <-<span class="st"> </span><span class="kw">expand.grid</span>(<span class="dt">mtry =</span> <span class="kw">c</span>(<span class="dv">5</span>, <span class="dv">10</span>, <span class="dv">20</span>, <span class="dv">40</span>, <span class="dv">60</span>),</a>
<a class="sourceLine" id="cb108-3" data-line-number="3"> <span class="dt">splitrule =</span> <span class="kw">c</span>(<span class="st">"gini"</span>, <span class="st">"extratrees"</span>),</a>
<a class="sourceLine" id="cb108-4" data-line-number="4"> <span class="dt">min.node.size =</span> <span class="dv">1</span>) <span class="co">## Minimal node size; default 1 for classification</span></a>
<a class="sourceLine" id="cb108-5" data-line-number="5">model <-<span class="st"> </span><span class="kw">train</span>(Class <span class="op">~</span><span class="st"> </span>.,</a>
<a class="sourceLine" id="cb108-6" data-line-number="6"> <span class="dt">data =</span> Sonar,</a>
<a class="sourceLine" id="cb108-7" data-line-number="7"> <span class="dt">method =</span> <span class="st">"ranger"</span>,</a>
<a class="sourceLine" id="cb108-8" data-line-number="8"> <span class="dt">tuneGrid =</span> myGrid,</a>
<a class="sourceLine" id="cb108-9" data-line-number="9"> <span class="dt">trControl =</span> <span class="kw">trainControl</span>(<span class="dt">method =</span> <span class="st">"cv"</span>,</a>
<a class="sourceLine" id="cb108-10" data-line-number="10"> <span class="dt">number =</span> <span class="dv">5</span>,</a>
<a class="sourceLine" id="cb108-11" data-line-number="11"> <span class="dt">verboseIter =</span> <span class="ot">FALSE</span>))</a>
<a class="sourceLine" id="cb108-12" data-line-number="12"><span class="kw">print</span>(model)</a></code></pre></div>
<pre><code>## Random Forest
##
## 208 samples
## 60 predictor
## 2 classes: 'M', 'R'
##
## No pre-processing
## Resampling: Cross-Validated (5 fold)
## Summary of sample sizes: 166, 167, 167, 167, 165
## Resampling results across tuning parameters:
##
## mtry splitrule Accuracy Kappa
## 5 gini 0.8076277 0.6098253
## 5 extratrees 0.8416579 0.6784745
## 10 gini 0.7927667 0.5799348
## 10 extratrees 0.8418848 0.6791453
## 20 gini 0.7882316 0.5718852
## 20 extratrees 0.8516355 0.6991879
## 40 gini 0.7880048 0.5716461
## 40 extratrees 0.8371229 0.6695638
## 60 gini 0.7833482 0.5613525
## 60 extratrees 0.8322448 0.6599318
##
## Tuning parameter 'min.node.size' was held constant at a value of 1
## Accuracy was used to select the optimal model using the largest value.
## The final values used for the model were mtry = 20, splitrule = extratrees
## and min.node.size = 1.</code></pre>
<div class="sourceCode" id="cb110"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb110-1" data-line-number="1"><span class="kw">plot</span>(model)</a></code></pre></div>
<p><img src="IntroMachineLearningWithR_files/figure-html/tuneGrid-1.png" width="672" /></p>
<blockquote>
<p>Challenge</p>
<p>Experiment with training a random forest model as described above,
by using 5-fold cross validation, and setting a <code>tuneLength</code> of 5.</p>
</blockquote>
<details>
<div class="sourceCode" id="cb111"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb111-1" data-line-number="1"><span class="kw">set.seed</span>(<span class="dv">42</span>)</a>
<a class="sourceLine" id="cb111-2" data-line-number="2">model <-<span class="st"> </span><span class="kw">train</span>(Class <span class="op">~</span><span class="st"> </span>.,</a>
<a class="sourceLine" id="cb111-3" data-line-number="3"> <span class="dt">data =</span> Sonar,</a>
<a class="sourceLine" id="cb111-4" data-line-number="4"> <span class="dt">method =</span> <span class="st">"ranger"</span>,</a>
<a class="sourceLine" id="cb111-5" data-line-number="5"> <span class="dt">tuneLength =</span> <span class="dv">5</span>,</a>
<a class="sourceLine" id="cb111-6" data-line-number="6"> <span class="dt">trControl =</span> <span class="kw">trainControl</span>(<span class="dt">method =</span> <span class="st">"cv"</span>,</a>
<a class="sourceLine" id="cb111-7" data-line-number="7"> <span class="dt">number =</span> <span class="dv">5</span>,</a>
<a class="sourceLine" id="cb111-8" data-line-number="8"> <span class="dt">verboseIter =</span> <span class="ot">FALSE</span>))</a>
<a class="sourceLine" id="cb111-9" data-line-number="9"><span class="kw">plot</span>(model)</a></code></pre></div>
<img src="IntroMachineLearningWithR_files/figure-html/rftrainsol-1.png" width="672" />
</details>
</div>
</div>
<div id="data-pre-processing-1" class="section level2">
<h2><span class="header-section-number">5.6</span> Data pre-processing</h2>
<div id="missing-values" class="section level3">
<h3><span class="header-section-number">5.6.1</span> Missing values</h3>
<p>Real datasets often come with missing values. In R, these should be
encoded using <code>NA</code>. There are basically two approaches to deal with
such cases.</p>
<ul>
<li><p>Drop the observations with missing values, or, if one feature
contains a very high proportion of NAs, drop the feature
altogether. These approaches are only applicable when the proportion
of missing values is relatively small. Otherwise, it could lead to
losing too much data.</p></li>
<li><p>Impute (replace) missing values.</p></li>
</ul>
<p>Data imputation can however have critical consequences depending on the
proportion of missing values and their nature. From a statistical
point of view, missing values are classified as <em>missing completely at
random</em> (MCAR), <em>missing at random</em> (MAR) or <em>missing not at random</em>
(MNAR), and the type of the missing values will influence the
efficiency of the imputation method.</p>
<p>The figure below shows how different imputation methods perform
depending on the proportion and nature of missing values
(from <a href="https://www.ncbi.nlm.nih.gov/pubmed/26906401">Lazar <em>et al.</em></a>,
on quantitative proteomics data).</p>
<div class="figure">
<img src="figure/imp.png" alt="Normalised RMSE (RMSE-observation standard deviation ration) describing the effect of different imputation methods depending on the nature and proportion of the missing values: kNN (a), SVDimpute (b), MLE (c), MinDet (d), and MinProb (e)." />
<p class="caption">Normalised RMSE (RMSE-observation standard deviation ration) describing the effect of different imputation methods depending on the nature and proportion of the missing values: kNN (a), SVDimpute (b), MLE (c), MinDet (d), and MinProb (e).</p>
</div>
<p>Let’s start by simulating a dataset containing missing values using
the <code>mtcars</code> dataset. Below, we will want to predict the <code>mpg</code>
variable using <code>cyl</code>, <code>disp</code>, and <code>hp</code>, with the latter containing 10
missing values.</p>
<div class="sourceCode" id="cb112"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb112-1" data-line-number="1"><span class="kw">data</span>(mtcars)</a>
<a class="sourceLine" id="cb112-2" data-line-number="2">mtcars[<span class="kw">sample</span>(<span class="kw">nrow</span>(mtcars), <span class="dv">10</span>), <span class="st">"hp"</span>] <-<span class="st"> </span><span class="ot">NA</span></a>
<a class="sourceLine" id="cb112-3" data-line-number="3">Y <-<span class="st"> </span>mtcars<span class="op">$</span>mpg <span class="co">## target variable</span></a>
<a class="sourceLine" id="cb112-4" data-line-number="4">X <-<span class="st"> </span>mtcars[, <span class="dv">2</span><span class="op">:</span><span class="dv">4</span>] <span class="co">## predictors</span></a></code></pre></div>
<p>If we now wanted to train a model (using the non-formula interface):</p>
<div class="sourceCode" id="cb113"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb113-1" data-line-number="1"><span class="kw">try</span>(<span class="kw">train</span>(X, Y))</a></code></pre></div>
<pre><code>## note: only 2 unique complexity parameters in default grid. Truncating the grid to 2 .
##
## Something is wrong; all the RMSE metric values are missing:
## RMSE Rsquared MAE
## Min. : NA Min. : NA Min. : NA
## 1st Qu.: NA 1st Qu.: NA 1st Qu.: NA
## Median : NA Median : NA Median : NA
## Mean :NaN Mean :NaN Mean :NaN
## 3rd Qu.: NA 3rd Qu.: NA 3rd Qu.: NA
## Max. : NA Max. : NA Max. : NA
## NA's :2 NA's :2 NA's :2
## Error : Stopping</code></pre>
<p>(Note that the occurrence of the error will depend on the model
chosen.)</p>
<p>We could perform imputation manually, but <em><a href="https://CRAN.R-project.org/package=caret">caret</a></em>
provides a whole range of pre-processing methods, including imputation
methods, that can directly be passed when training the model.</p>
</div>
<div id="median-imputation" class="section level3">
<h3><span class="header-section-number">5.6.2</span> Median imputation</h3>
<p>Imputation using median of features. This method works well if the