-
Notifications
You must be signed in to change notification settings - Fork 2
/
logistic.html
899 lines (846 loc) · 78.2 KB
/
logistic.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
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Chapter 4 Logistic Regression | Machine Learning with R</title>
<meta name="description" content="This book is about using R for machine learning purposes.">
<meta name="generator" content="bookdown and GitBook 2.6.7">
<meta property="og:title" content="Chapter 4 Logistic Regression | Machine Learning with R" />
<meta property="og:type" content="book" />
<meta property="og:description" content="This book is about using R for machine learning purposes." />
<meta name="github-repo" content="fderyckel/machinelearningwithr" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="Chapter 4 Logistic Regression | Machine Learning with R" />
<meta name="twitter:description" content="This book is about using R for machine learning purposes." />
<meta name="author" content="François de Ryckel">
<meta name="date" content="2019-02-23">
<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="mlr.html">
<link rel="next" href="softmax-and-multinomial-regressions.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" />
<script src="libs/kePrint-0.0.1/kePrint.js"></script>
<style type="text/css">
div.sourceCode { overflow-x: auto; }
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; line-height: 100%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > span.kw { color: #007020; font-weight: bold; } /* Keyword */
code > span.dt { color: #902000; } /* DataType */
code > span.dv { color: #40a070; } /* DecVal */
code > span.bn { color: #40a070; } /* BaseN */
code > span.fl { color: #40a070; } /* Float */
code > span.ch { color: #4070a0; } /* Char */
code > span.st { color: #4070a0; } /* String */
code > span.co { color: #60a0b0; font-style: italic; } /* Comment */
code > span.ot { color: #007020; } /* Other */
code > span.al { color: #ff0000; font-weight: bold; } /* Alert */
code > span.fu { color: #06287e; } /* Function */
code > span.er { color: #ff0000; font-weight: bold; } /* Error */
code > span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
code > span.cn { color: #880000; } /* Constant */
code > span.sc { color: #4070a0; } /* SpecialChar */
code > span.vs { color: #4070a0; } /* VerbatimString */
code > span.ss { color: #bb6688; } /* SpecialString */
code > span.im { } /* Import */
code > span.va { color: #19177c; } /* Variable */
code > span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code > span.op { color: #666666; } /* Operator */
code > span.bu { } /* BuiltIn */
code > span.ex { } /* Extension */
code > span.pp { color: #bc7a00; } /* Preprocessor */
code > span.at { color: #7d9029; } /* Attribute */
code > span.do { color: #ba2121; font-style: italic; } /* Documentation */
code > span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code > span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code > span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
</style>
<link rel="stylesheet" href="style.css" type="text/css" />
</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><strong><a href="./">Machine Learning with R</a></strong></li>
<li class="divider"></li>
<li class="chapter" data-level="1" data-path="index.html"><a href="index.html"><i class="fa fa-check"></i><b>1</b> Prerequisites</a><ul>
<li class="chapter" data-level="1.1" data-path="index.html"><a href="index.html#pre-requisite-and-conventions"><i class="fa fa-check"></i><b>1.1</b> Pre-requisite and conventions</a></li>
<li class="chapter" data-level="1.2" data-path="index.html"><a href="index.html#organization"><i class="fa fa-check"></i><b>1.2</b> Organization</a></li>
<li class="chapter" data-level="1.3" data-path="index.html"><a href="index.html#packages"><i class="fa fa-check"></i><b>1.3</b> Packages</a></li>
</ul></li>
<li class="chapter" data-level="2" data-path="testinference.html"><a href="testinference.html"><i class="fa fa-check"></i><b>2</b> Tests and inferences</a><ul>
<li class="chapter" data-level="2.1" data-path="testinference.html"><a href="testinference.html#normality"><i class="fa fa-check"></i><b>2.1</b> Assumption of normality</a><ul>
<li class="chapter" data-level="2.1.1" data-path="testinference.html"><a href="testinference.html#visual-check-of-normality"><i class="fa fa-check"></i><b>2.1.1</b> Visual check of normality</a></li>
<li class="chapter" data-level="2.1.2" data-path="testinference.html"><a href="testinference.html#normality-tests"><i class="fa fa-check"></i><b>2.1.2</b> Normality tests</a></li>
</ul></li>
<li class="chapter" data-level="2.2" data-path="testinference.html"><a href="testinference.html#ttest"><i class="fa fa-check"></i><b>2.2</b> T-tests</a></li>
<li class="chapter" data-level="2.3" data-path="testinference.html"><a href="testinference.html#anova---analyse-of-variance."><i class="fa fa-check"></i><b>2.3</b> ANOVA - Analyse of variance.</a></li>
<li class="chapter" data-level="2.4" data-path="testinference.html"><a href="testinference.html#covariance"><i class="fa fa-check"></i><b>2.4</b> Covariance</a></li>
</ul></li>
<li class="chapter" data-level="3" data-path="mlr.html"><a href="mlr.html"><i class="fa fa-check"></i><b>3</b> Single & Multiple Linear Regression</a><ul>
<li class="chapter" data-level="3.1" data-path="mlr.html"><a href="mlr.html#single-variable-regression"><i class="fa fa-check"></i><b>3.1</b> Single variable regression</a></li>
<li class="chapter" data-level="3.2" data-path="mlr.html"><a href="mlr.html#multi-variables-regression"><i class="fa fa-check"></i><b>3.2</b> Multi-variables regression</a><ul>
<li class="chapter" data-level="3.2.1" data-path="mlr.html"><a href="mlr.html#predicting-wine-price-again"><i class="fa fa-check"></i><b>3.2.1</b> Predicting wine price (again!)</a></li>
</ul></li>
<li class="chapter" data-level="3.3" data-path="mlr.html"><a href="mlr.html#model-diagnostic-and-evaluation"><i class="fa fa-check"></i><b>3.3</b> Model diagnostic and evaluation</a></li>
<li class="chapter" data-level="3.4" data-path="mlr.html"><a href="mlr.html#final-example---boston-dataset---with-backward-elimination"><i class="fa fa-check"></i><b>3.4</b> Final example - Boston dataset - with backward elimination</a><ul>
<li class="chapter" data-level="3.4.1" data-path="mlr.html"><a href="mlr.html#model-diagmostic"><i class="fa fa-check"></i><b>3.4.1</b> Model diagmostic</a></li>
</ul></li>
<li class="chapter" data-level="3.5" data-path="mlr.html"><a href="mlr.html#references"><i class="fa fa-check"></i><b>3.5</b> References</a></li>
</ul></li>
<li class="chapter" data-level="4" data-path="logistic.html"><a href="logistic.html"><i class="fa fa-check"></i><b>4</b> Logistic Regression</a><ul>
<li class="chapter" data-level="4.1" data-path="logistic.html"><a href="logistic.html#introduction"><i class="fa fa-check"></i><b>4.1</b> Introduction</a></li>
<li class="chapter" data-level="4.2" data-path="logistic.html"><a href="logistic.html#the-logistic-equation."><i class="fa fa-check"></i><b>4.2</b> The logistic equation.</a></li>
<li class="chapter" data-level="4.3" data-path="logistic.html"><a href="logistic.html#performance-of-logistic-regression-model"><i class="fa fa-check"></i><b>4.3</b> Performance of Logistic Regression Model</a></li>
<li class="chapter" data-level="4.4" data-path="logistic.html"><a href="logistic.html#setting-up"><i class="fa fa-check"></i><b>4.4</b> Setting up</a></li>
<li class="chapter" data-level="4.5" data-path="logistic.html"><a href="logistic.html#example-1---graduate-admission"><i class="fa fa-check"></i><b>4.5</b> Example 1 - Graduate Admission</a></li>
<li class="chapter" data-level="4.6" data-path="logistic.html"><a href="logistic.html#example-2---diabetes"><i class="fa fa-check"></i><b>4.6</b> Example 2 - Diabetes</a><ul>
<li class="chapter" data-level="4.6.1" data-path="logistic.html"><a href="logistic.html#accounting-for-missing-values"><i class="fa fa-check"></i><b>4.6.1</b> Accounting for missing values</a></li>
<li class="chapter" data-level="4.6.2" data-path="logistic.html"><a href="logistic.html#imputting-missing-values"><i class="fa fa-check"></i><b>4.6.2</b> Imputting Missing Values</a></li>
<li class="chapter" data-level="4.6.3" data-path="logistic.html"><a href="logistic.html#roc-and-auc"><i class="fa fa-check"></i><b>4.6.3</b> ROC and AUC</a></li>
</ul></li>
<li class="chapter" data-level="4.7" data-path="logistic.html"><a href="logistic.html#references-1"><i class="fa fa-check"></i><b>4.7</b> References</a></li>
</ul></li>
<li class="chapter" data-level="5" data-path="softmax-and-multinomial-regressions.html"><a href="softmax-and-multinomial-regressions.html"><i class="fa fa-check"></i><b>5</b> Softmax and multinomial regressions</a><ul>
<li class="chapter" data-level="5.1" data-path="softmax-and-multinomial-regressions.html"><a href="softmax-and-multinomial-regressions.html#multinomial-logistic-regression"><i class="fa fa-check"></i><b>5.1</b> Multinomial Logistic Regression</a></li>
<li class="chapter" data-level="5.2" data-path="softmax-and-multinomial-regressions.html"><a href="softmax-and-multinomial-regressions.html#references-2"><i class="fa fa-check"></i><b>5.2</b> References</a></li>
</ul></li>
<li class="chapter" data-level="6" data-path="gradient-descent.html"><a href="gradient-descent.html"><i class="fa fa-check"></i><b>6</b> Gradient Descent</a><ul>
<li class="chapter" data-level="6.1" data-path="gradient-descent.html"><a href="gradient-descent.html#example-on-functions"><i class="fa fa-check"></i><b>6.1</b> Example on functions</a></li>
<li class="chapter" data-level="6.2" data-path="gradient-descent.html"><a href="gradient-descent.html#example-on-regressions"><i class="fa fa-check"></i><b>6.2</b> Example on regressions</a></li>
</ul></li>
<li class="chapter" data-level="7" data-path="knnchapter.html"><a href="knnchapter.html"><i class="fa fa-check"></i><b>7</b> KNN - K Nearest Neighbour</a><ul>
<li class="chapter" data-level="7.1" data-path="knnchapter.html"><a href="knnchapter.html#example-1.-prostate-cancer-dataset"><i class="fa fa-check"></i><b>7.1</b> Example 1. Prostate Cancer dataset</a></li>
<li class="chapter" data-level="7.2" data-path="knnchapter.html"><a href="knnchapter.html#example-2.-wine-dataset"><i class="fa fa-check"></i><b>7.2</b> Example 2. Wine dataset</a><ul>
<li class="chapter" data-level="7.2.1" data-path="knnchapter.html"><a href="knnchapter.html#understand-the-data"><i class="fa fa-check"></i><b>7.2.1</b> Understand the data</a></li>
</ul></li>
<li class="chapter" data-level="7.3" data-path="knnchapter.html"><a href="knnchapter.html#references-3"><i class="fa fa-check"></i><b>7.3</b> References</a></li>
</ul></li>
<li class="chapter" data-level="8" data-path="kmeans.html"><a href="kmeans.html"><i class="fa fa-check"></i><b>8</b> Kmeans clustering</a><ul>
<li class="chapter" data-level="8.1" data-path="kmeans.html"><a href="kmeans.html#multinomial-logistic-regression-1"><i class="fa fa-check"></i><b>8.1</b> Multinomial Logistic Regression</a></li>
<li class="chapter" data-level="8.2" data-path="kmeans.html"><a href="kmeans.html#references-4"><i class="fa fa-check"></i><b>8.2</b> References</a></li>
</ul></li>
<li class="chapter" data-level="9" data-path="hierclust.html"><a href="hierclust.html"><i class="fa fa-check"></i><b>9</b> Hierarichal Clustering</a><ul>
<li class="chapter" data-level="9.1" data-path="hierclust.html"><a href="hierclust.html#example-on-the-pokemon-dataset"><i class="fa fa-check"></i><b>9.1</b> Example on the Pokemon dataset</a></li>
<li class="chapter" data-level="9.2" data-path="hierclust.html"><a href="hierclust.html#example-on-regressions-1"><i class="fa fa-check"></i><b>9.2</b> Example on regressions</a></li>
<li class="chapter" data-level="9.3" data-path="hierclust.html"><a href="hierclust.html#references-5"><i class="fa fa-check"></i><b>9.3</b> References</a></li>
</ul></li>
<li class="chapter" data-level="10" data-path="pca.html"><a href="pca.html"><i class="fa fa-check"></i><b>10</b> Principal Component Analysis</a><ul>
<li class="chapter" data-level="10.1" data-path="pca.html"><a href="pca.html#pca-on-an-easy-example."><i class="fa fa-check"></i><b>10.1</b> PCA on an easy example.</a></li>
<li class="chapter" data-level="10.2" data-path="pca.html"><a href="pca.html#references."><i class="fa fa-check"></i><b>10.2</b> References.</a></li>
</ul></li>
<li class="chapter" data-level="11" data-path="trees-and-classification.html"><a href="trees-and-classification.html"><i class="fa fa-check"></i><b>11</b> Trees and Classification</a><ul>
<li class="chapter" data-level="11.1" data-path="trees-and-classification.html"><a href="trees-and-classification.html#introduction-1"><i class="fa fa-check"></i><b>11.1</b> Introduction</a></li>
<li class="chapter" data-level="11.2" data-path="trees-and-classification.html"><a href="trees-and-classification.html#first-example."><i class="fa fa-check"></i><b>11.2</b> First example.</a></li>
<li class="chapter" data-level="11.3" data-path="trees-and-classification.html"><a href="trees-and-classification.html#second-example."><i class="fa fa-check"></i><b>11.3</b> Second Example.</a></li>
<li class="chapter" data-level="11.4" data-path="trees-and-classification.html"><a href="trees-and-classification.html#how-does-a-tree-decide-where-to-split"><i class="fa fa-check"></i><b>11.4</b> How does a tree decide where to split?</a></li>
<li class="chapter" data-level="11.5" data-path="trees-and-classification.html"><a href="trees-and-classification.html#third-example."><i class="fa fa-check"></i><b>11.5</b> Third example.</a></li>
<li class="chapter" data-level="11.6" data-path="trees-and-classification.html"><a href="trees-and-classification.html#references-6"><i class="fa fa-check"></i><b>11.6</b> References</a></li>
</ul></li>
<li class="chapter" data-level="12" data-path="random-forest.html"><a href="random-forest.html"><i class="fa fa-check"></i><b>12</b> Random Forest</a><ul>
<li class="chapter" data-level="12.1" data-path="random-forest.html"><a href="random-forest.html#how-does-it-work"><i class="fa fa-check"></i><b>12.1</b> How does it work?</a></li>
<li class="chapter" data-level="12.2" data-path="random-forest.html"><a href="random-forest.html#references-7"><i class="fa fa-check"></i><b>12.2</b> References</a></li>
</ul></li>
<li class="chapter" data-level="13" data-path="svm.html"><a href="svm.html"><i class="fa fa-check"></i><b>13</b> Support Vector Machine</a><ul>
<li class="chapter" data-level="13.1" data-path="svm.html"><a href="svm.html#support-vecotr-regression"><i class="fa fa-check"></i><b>13.1</b> Support Vecotr Regression</a><ul>
<li class="chapter" data-level="13.1.1" data-path="svm.html"><a href="svm.html#create-data"><i class="fa fa-check"></i><b>13.1.1</b> Create data</a></li>
<li class="chapter" data-level="13.1.2" data-path="svm.html"><a href="svm.html#tuning-a-svm-model"><i class="fa fa-check"></i><b>13.1.2</b> Tuning a SVM model</a></li>
<li class="chapter" data-level="13.1.3" data-path="svm.html"><a href="svm.html#discussion-on-parameters"><i class="fa fa-check"></i><b>13.1.3</b> Discussion on parameters</a></li>
</ul></li>
<li class="chapter" data-level="13.2" data-path="svm.html"><a href="svm.html#references-8"><i class="fa fa-check"></i><b>13.2</b> References</a></li>
</ul></li>
<li class="chapter" data-level="14" data-path="model-evaluation.html"><a href="model-evaluation.html"><i class="fa fa-check"></i><b>14</b> Model Evaluation</a><ul>
<li class="chapter" data-level="14.1" data-path="model-evaluation.html"><a href="model-evaluation.html#biais-variance-tradeoff"><i class="fa fa-check"></i><b>14.1</b> Biais variance tradeoff</a></li>
<li class="chapter" data-level="14.2" data-path="model-evaluation.html"><a href="model-evaluation.html#bagging"><i class="fa fa-check"></i><b>14.2</b> Bagging</a></li>
<li class="chapter" data-level="14.3" data-path="model-evaluation.html"><a href="model-evaluation.html#crossvalidation"><i class="fa fa-check"></i><b>14.3</b> Cross Validation</a></li>
</ul></li>
<li class="chapter" data-level="15" data-path="case-study-text-classification-spam-and-ham-.html"><a href="case-study-text-classification-spam-and-ham-.html"><i class="fa fa-check"></i><b>15</b> Case Study - Text classification: Spam and Ham.</a></li>
<li class="chapter" data-level="16" data-path="mushroom.html"><a href="mushroom.html"><i class="fa fa-check"></i><b>16</b> Case Study - Mushrooms Classification</a><ul>
<li class="chapter" data-level="16.1" data-path="mushroom.html"><a href="mushroom.html#import-the-data"><i class="fa fa-check"></i><b>16.1</b> Import the data</a></li>
<li class="chapter" data-level="16.2" data-path="mushroom.html"><a href="mushroom.html#tidy-the-data"><i class="fa fa-check"></i><b>16.2</b> Tidy the data</a></li>
<li class="chapter" data-level="16.3" data-path="mushroom.html"><a href="mushroom.html#understand-the-data-1"><i class="fa fa-check"></i><b>16.3</b> Understand the data</a><ul>
<li class="chapter" data-level="16.3.1" data-path="mushroom.html"><a href="mushroom.html#transform-the-data"><i class="fa fa-check"></i><b>16.3.1</b> Transform the data</a></li>
<li class="chapter" data-level="16.3.2" data-path="mushroom.html"><a href="mushroom.html#visualize-the-data"><i class="fa fa-check"></i><b>16.3.2</b> Visualize the data</a></li>
<li class="chapter" data-level="16.3.3" data-path="mushroom.html"><a href="mushroom.html#modeling"><i class="fa fa-check"></i><b>16.3.3</b> Modeling</a></li>
</ul></li>
<li class="chapter" data-level="16.4" data-path="mushroom.html"><a href="mushroom.html#communication"><i class="fa fa-check"></i><b>16.4</b> Communication</a></li>
</ul></li>
<li class="chapter" data-level="17" data-path="case-study-the-adults-dataset-.html"><a href="case-study-the-adults-dataset-.html"><i class="fa fa-check"></i><b>17</b> Case study - The adults dataset.</a><ul>
<li class="chapter" data-level="17.1" data-path="case-study-the-adults-dataset-.html"><a href="case-study-the-adults-dataset-.html#introduction-2"><i class="fa fa-check"></i><b>17.1</b> Introduction</a></li>
<li class="chapter" data-level="17.2" data-path="case-study-the-adults-dataset-.html"><a href="case-study-the-adults-dataset-.html#import-the-data-1"><i class="fa fa-check"></i><b>17.2</b> Import the data</a></li>
<li class="chapter" data-level="17.3" data-path="case-study-the-adults-dataset-.html"><a href="case-study-the-adults-dataset-.html#tidy-the-data-1"><i class="fa fa-check"></i><b>17.3</b> Tidy the data</a></li>
</ul></li>
<li class="chapter" data-level="18" data-path="breastcancer.html"><a href="breastcancer.html"><i class="fa fa-check"></i><b>18</b> Case Study - Wisconsin Breast Cancer</a><ul>
<li class="chapter" data-level="18.1" data-path="breastcancer.html"><a href="breastcancer.html#import-the-data-2"><i class="fa fa-check"></i><b>18.1</b> Import the data</a></li>
<li class="chapter" data-level="18.2" data-path="breastcancer.html"><a href="breastcancer.html#tidy-the-data-2"><i class="fa fa-check"></i><b>18.2</b> Tidy the data</a></li>
<li class="chapter" data-level="18.3" data-path="breastcancer.html"><a href="breastcancer.html#understand-the-data-2"><i class="fa fa-check"></i><b>18.3</b> Understand the data</a><ul>
<li class="chapter" data-level="18.3.1" data-path="breastcancer.html"><a href="breastcancer.html#transform-the-data-1"><i class="fa fa-check"></i><b>18.3.1</b> Transform the data</a></li>
<li class="chapter" data-level="18.3.2" data-path="breastcancer.html"><a href="breastcancer.html#pre-process-the-data"><i class="fa fa-check"></i><b>18.3.2</b> Pre-process the data</a></li>
<li class="chapter" data-level="18.3.3" data-path="breastcancer.html"><a href="breastcancer.html#model-the-data-1"><i class="fa fa-check"></i><b>18.3.3</b> Model the data</a></li>
</ul></li>
<li class="chapter" data-level="18.4" data-path="breastcancer.html"><a href="breastcancer.html#references-9"><i class="fa fa-check"></i><b>18.4</b> References</a></li>
</ul></li>
<li class="chapter" data-level="19" data-path="final-words.html"><a href="final-words.html"><i class="fa fa-check"></i><b>19</b> Final Words</a></li>
<li class="chapter" data-level="" data-path="references-10.html"><a href="references-10.html"><i class="fa fa-check"></i>References</a></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="./">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="logistic" class="section level1">
<h1><span class="header-section-number">Chapter 4</span> Logistic Regression</h1>
<div id="introduction" class="section level2">
<h2><span class="header-section-number">4.1</span> Introduction</h2>
<p>Logistic Regression is a classification algorithm. It is used to predict a binary outcome (1 / 0, Yes / No, True / False) given a set of independent variables. To represent binary / categorical outcome, we use dummy variables. You can also think of logistic regression as a special case of linear regression when the outcome variable is categorical, where we are using log of odds as dependent variable. In simple words, it predicts the probability of occurrence of an event by fitting data to a logit function.<br />
Logistic Regression is part of a larger class of algorithms known as Generalized Linear Model (glm).<br />
Although most logisitc regression should be called <strong>binomial logistic regression</strong>, since the variable to predict is binary, however, logistic regression can also be used to predict a dependent variable which can assume more than 2 values. In this second case we call the model <strong>multinomial logistic regression</strong>. A typical example for instance, would be classifying films between “Entertaining”, “borderline” or “boring”.</p>
</div>
<div id="the-logistic-equation." class="section level2">
<h2><span class="header-section-number">4.2</span> The logistic equation.</h2>
<p>The general equation of the <strong>logit model</strong></p>
<p><span class="math display">\[\mathbf{Y} = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + ... + \beta_n x_n\]</span> where <strong>Y</strong> is the variable to predict.<br />
<span class="math inline">\(\beta\)</span> is the coefficients of the predictors and the <span class="math inline">\(x_i\)</span> are the predictors (aka independent variables).<br />
In logistic regression, we are only concerned about the probability of outcome dependent variable ( success or failure). We should then rewrite our function<br />
<span class="math display">\[p = e^{(\beta_0 + \beta_1 x_1 + \beta_2 x_2 + ... + \beta_n x_n)}\]</span>.<br />
This however does not garantee to have p between 0 and 1.<br />
Let’s then have <span class="math display">\[p = \frac{e^{(\beta_0 + \beta_1 x_1 + \beta_2 x_2 + ... + \beta_n x_n)}} {e^{(\beta_0 + \beta_1 x_1 + \beta_2 x_2 + ... + \beta_n x_n)} + 1}\]</span><br />
or <span class="math display">\[p = \frac {e^Y} {e^Y + 1}\]</span><br />
where <em>p</em> is the probability of success. With little further manipulations, we have <span class="math display">\[\frac {p} {1-p} = e^Y\]</span> and <span class="math display">\[\log{\frac{p} {1-p}} = Y\]</span><br />
If we remember what was <strong>Y</strong>, we get <span class="math display">\[\log{\dfrac{p} {1-p}} = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + ... + \beta_n x_n\]</span></p>
<p>This is the equation used in Logistic Regression. Here (p/1-p) is the odd ratio. Whenever the log of odd ratio is found to be positive, the probability of success is always more than 50%.</p>
</div>
<div id="performance-of-logistic-regression-model" class="section level2">
<h2><span class="header-section-number">4.3</span> Performance of Logistic Regression Model</h2>
<p>To evaluate the performance of a logistic regression model, we can consider a few metrics.</p>
<ul>
<li><strong>AIC (Akaike Information Criteria)</strong> The analogous metric of adjusted R-squared in logistic regression is AIC. AIC is the measure of fit which penalizes model for the number of model coefficients. Therefore, we always prefer model with minimum AIC value.<br />
</li>
<li><strong>Null Deviance and Residual Deviance</strong> Null Deviance indicates the response predicted by a model with nothing but an intercept. Lower the value, better the model. Residual deviance indicates the response predicted by a model on adding independent variables. Lower the value, better the model.<br />
</li>
<li><strong>Confusion Matrix</strong> It is nothing but a tabular representation of Actual vs Predicted values. This helps us to find the accuracy of the model and avoid overfitting.<br />
</li>
<li>We can calcualate the accuracy of our model by <span class="math display">\[\frac {True Positives + True Negatives}{True Positives + True Negatives + False Positives + False Negatives}\]</span><br />
</li>
<li>From confusion matrix, <strong>Specificity</strong> and <strong>Sensitivity</strong> can be derived as <span class="math display">\[Specificity = \frac {True Negatives} {True Negative + False Positive}\]</span> and <span class="math display">\[Sensitivity = \frac{True Positive}{True Positive + False Negative}\]</span><br />
</li>
<li><strong>ROC Curve</strong> Receiver Operating Characteristic(ROC) summarizes the model’s performance by evaluating the trade offs between true positive rate (sensitivity) and false positive rate(1- specificity). For plotting ROC, it is advisable to assume p > 0.5 since we are more concerned about success rate. ROC summarizes the predictive power for all possible values of p > 0.5. The area under curve (AUC), referred to as index of accuracy(A) or concordance index, is a perfect performance metric for ROC curve. Higher the area under curve, better the prediction power of the model. The ROC of a perfect predictive model has TP equals 1 and FP equals 0. This curve will touch the top left corner of the graph.</li>
</ul>
</div>
<div id="setting-up" class="section level2">
<h2><span class="header-section-number">4.4</span> Setting up</h2>
<p>As usual we will use the <code>tidyverse</code> and <code>caret</code> package</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(caret) <span class="co"># For confusion matrix</span>
<span class="kw">library</span>(ROCR) <span class="co"># For the ROC curve</span></code></pre></div>
<p>We can now get straight to business and see how to model logisitc regression with R and then have the more interesting discussion on its performance.</p>
</div>
<div id="example-1---graduate-admission" class="section level2">
<h2><span class="header-section-number">4.5</span> Example 1 - Graduate Admission</h2>
<p>We use a dataset about factors influencing graduate admission that can be downloaded from the <a href="http://www.ats.ucla.edu/stat/data/binary.csv">UCLA Institute for Digital Research and Education</a></p>
<p>The dataset has 4 variables</p>
<ul>
<li><code>admit</code> is the response variable<br />
</li>
<li><code>gre</code> is the result of a standardized test<br />
</li>
<li><code>gpa</code> is the result of the student GPA (school reported)</li>
<li><code>rank</code> is the type of university the student apply for (4 = Ivy League, 1 = lower level entry U.)</li>
</ul>
<p>Let’s have a quick look at the data and their summary. The goal is to get familiar with the data, type of predictors (continuous, discrete, categorical, etc.)</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df <-<span class="st"> </span><span class="kw">read_csv</span>(<span class="st">"dataset/grad_admission.csv"</span>)
<span class="kw">glimpse</span>(df)</code></pre></div>
<pre><code>## Observations: 400
## Variables: 4
## $ admit <dbl> 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1…
## $ gre <dbl> 380, 660, 800, 640, 520, 760, 560, 400, 540, 700, 800, 440…
## $ gpa <dbl> 3.61, 3.67, 4.00, 3.19, 2.93, 3.00, 2.98, 3.08, 3.39, 3.92…
## $ rank <dbl> 3, 3, 1, 4, 4, 2, 1, 2, 3, 2, 4, 1, 1, 2, 1, 3, 4, 3, 2, 1…</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co">#Quick check to see if our response variable is balanced-ish</span>
<span class="kw">table</span>(df<span class="op">$</span>admit)</code></pre></div>
<pre><code>##
## 0 1
## 273 127</code></pre>
<p>Well that’s not a very balanced response variable, although it is not hugely unbalanced either as it can be the cases sometimes in medical research.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">## Two-way contingency table of categorical outcome and predictors
<span class="kw">round</span>(<span class="kw">prop.table</span>(<span class="kw">table</span>(df<span class="op">$</span>admit, df<span class="op">$</span>rank), <span class="dv">2</span>), <span class="dv">2</span>)</code></pre></div>
<pre><code>##
## 1 2 3 4
## 0 0.46 0.64 0.77 0.82
## 1 0.54 0.36 0.23 0.18</code></pre>
<p>It seems about right … most students applying to Ivy Leagues graduate programs are not being admitted.</p>
<p>Before we can run our model, let’s transform the <code>rank</code> explanatory variable to a factor.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df2 <-<span class="st"> </span>df
df2<span class="op">$</span>rank <-<span class="st"> </span><span class="kw">factor</span>(df2<span class="op">$</span>rank)
<span class="co"># Run the model</span>
model_lgr_df2 <-<span class="st"> </span><span class="kw">glm</span>(admit <span class="op">~</span><span class="st"> </span>., <span class="dt">data =</span> df2, <span class="dt">family =</span> <span class="st">"binomial"</span>)
<span class="kw">summary</span>(model_lgr_df2)</code></pre></div>
<pre><code>##
## Call:
## glm(formula = admit ~ ., family = "binomial", data = df2)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.6268 -0.8662 -0.6388 1.1490 2.0790
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -3.989979 1.139951 -3.500 0.000465 ***
## gre 0.002264 0.001094 2.070 0.038465 *
## gpa 0.804038 0.331819 2.423 0.015388 *
## rank2 -0.675443 0.316490 -2.134 0.032829 *
## rank3 -1.340204 0.345306 -3.881 0.000104 ***
## rank4 -1.551464 0.417832 -3.713 0.000205 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 499.98 on 399 degrees of freedom
## Residual deviance: 458.52 on 394 degrees of freedom
## AIC: 470.52
##
## Number of Fisher Scoring iterations: 4</code></pre>
<p>The next part of the output shows the coefficients, their standard errors, the z-statistic (sometimes called a Wald z-statistic), and the associated p-values. Both gre and gpa are statistically significant, as are the three terms for rank. The logistic regression coefficients give the change in the log odds of the outcome for a one unit increase in the predictor variable.<br />
For every one unit change in <code>gre</code>, the log odds of admission (versus non-admission) increases by 0.002.<br />
For a one unit increase in <code>gpa</code>, the log odds of being admitted to graduate school increases by 0.804.<br />
The indicator variables for <code>rank</code> have a slightly different interpretation. For example, having attended an undergraduate institution with rank of 2, versus an institution with a rank of 1, changes the log odds of admission by -0.675.</p>
<p>To see how the variables in the model participates in the decrease of <em>Residual Deviance</em>, we can use the <code>ANOVA</code> function on our model.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">anova</span>(model_lgr_df2)</code></pre></div>
<pre><code>## Analysis of Deviance Table
##
## Model: binomial, link: logit
##
## Response: admit
##
## Terms added sequentially (first to last)
##
##
## Df Deviance Resid. Df Resid. Dev
## NULL 399 499.98
## gre 1 13.9204 398 486.06
## gpa 1 5.7122 397 480.34
## rank 3 21.8265 394 458.52</code></pre>
<p>We can test for an overall effect of <code>rank</code> (its significance) using the <code>wald.test function</code> of the <code>aod</code> library. The order in which the coefficients are given in the table of coefficients is the same as the order of the terms in the model. This is important because the wald.test function refers to the coefficients by their order in the model. We use the wald.test function. <code>b</code> supplies the coefficients, while <code>Sigma</code> supplies the variance covariance matrix of the error terms, finally <code>Terms</code> tells R which terms in the model are to be tested, in this case, terms 4, 5, and 6, are the three terms for the levels of <code>rank</code>.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(aod)
<span class="kw">wald.test</span>(<span class="dt">Sigma =</span> <span class="kw">vcov</span>(model_lgr_df2), <span class="dt">b =</span> <span class="kw">coef</span>(model_lgr_df2), <span class="dt">Terms =</span> <span class="dv">4</span><span class="op">:</span><span class="dv">6</span>)</code></pre></div>
<pre><code>## Wald test:
## ----------
##
## Chi-squared test:
## X2 = 20.9, df = 3, P(> X2) = 0.00011</code></pre>
<p>The chi-squared test statistic of 20.9, with three degrees of freedom is associated with a p-value of 0.00011 indicating that the overall effect of rank is statistically significant.</p>
<p>Let’s check how our model is performing. As mentioned earlier, we need to make a choice on the cutoff value (returned probability) to check our accuracy. In this first example, let’s just stick with the usual <code>0.5</code> cutoff value.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">prediction_lgr_df2 <-<span class="st"> </span><span class="kw">predict</span>(model_lgr_df2, <span class="dt">data =</span> df2, <span class="dt">type =</span> <span class="st">"response"</span>)
<span class="kw">head</span>(prediction_lgr_df2, <span class="dv">10</span>)</code></pre></div>
<pre><code>## 1 2 3 4 5 6 7
## 0.1726265 0.2921750 0.7384082 0.1783846 0.1183539 0.3699699 0.4192462
## 8 9 10
## 0.2170033 0.2007352 0.5178682</code></pre>
<p>As it stands, the <code>predict</code> function gives us the probabilty that the observation has a response of 1; in our case, the probability that a student is being admitted into the graduate program.<br />
To check the accuracy of the model, we need a confusion matrix with a cut off value. So let’s clean that vector of probability.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">prediction_lgr_df2 <-<span class="st"> </span><span class="kw">if_else</span>(prediction_lgr_df2 <span class="op">></span><span class="st"> </span><span class="fl">0.5</span> , <span class="dv">1</span>, <span class="dv">0</span>)
<span class="kw">confusionMatrix</span>(<span class="dt">data =</span> <span class="kw">factor</span>(prediction_lgr_df2),
<span class="dt">reference =</span> <span class="kw">factor</span>(df2<span class="op">$</span>admit), <span class="dt">positive =</span> <span class="st">"1"</span>)</code></pre></div>
<pre><code>## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 254 97
## 1 19 30
##
## Accuracy : 0.71
## 95% CI : (0.6628, 0.754)
## No Information Rate : 0.6825
## P-Value [Acc > NIR] : 0.1293
##
## Kappa : 0.1994
## Mcnemar's Test P-Value : 8.724e-13
##
## Sensitivity : 0.2362
## Specificity : 0.9304
## Pos Pred Value : 0.6122
## Neg Pred Value : 0.7236
## Prevalence : 0.3175
## Detection Rate : 0.0750
## Detection Prevalence : 0.1225
## Balanced Accuracy : 0.5833
##
## 'Positive' Class : 1
## </code></pre>
<p>We have an interesting situation here. Although all our variables were significant in our model, the accuracy of our model, <code>71%</code> is just a little bit higher than the basic benchmark which is the no-information model (ie. we just predict the highest class) in this case <code>68.25%</code>.</p>
<p>Before we do a ROC curve, let’s have a quick reminder on ROC.<br />
ROC are plotting the proprotion of TP to FP. So ideally we want to have 100% TP and 0% FP.<br />
<img src="otherpics/perfect_ROC.png" alt="Perfect ROC Curve" /></p>
<p>Pure Random guessing should lead to this curve<br />
<img src="otherpics/random_ROC.png" alt="random guess" /></p>
<p>With that in mind, let’s do a ROC curve on out model</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">prediction_lgr_df2 <-<span class="st"> </span><span class="kw">predict</span>(model_lgr_df2, <span class="dt">data =</span> df2, <span class="dt">type=</span><span class="st">"response"</span>)
pr_admission <-<span class="st"> </span><span class="kw">prediction</span>(prediction_lgr_df2, df2<span class="op">$</span>admit)
prf_admission <-<span class="st"> </span><span class="kw">performance</span>(pr_admission, <span class="dt">measure =</span> <span class="st">"tpr"</span>, <span class="dt">x.measure =</span> <span class="st">"fpr"</span>)
<span class="kw">plot</span>(prf_admission, <span class="dt">colorize =</span> <span class="ot">TRUE</span>, <span class="dt">lwd=</span><span class="dv">3</span>)</code></pre></div>
<p><img src="machinelearningwithR_files/figure-html/roc_admission_pic1-1.png" width="672" /></p>
<p>At least it is better than just random guessing.</p>
<p>In some applications of ROC curves, you want the point closest to the TPR of <span class="math inline">\(1\)</span> and FPR of <span class="math inline">\(0\)</span>. This cut point is “optimal” in the sense it weighs both sensitivity and specificity equally. Now, there is a cost measure in the ROCR package that you can use to create a performance object. Use it to find the cutoff with minimum cost.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">cost_admission_perf =<span class="st"> </span><span class="kw">performance</span>(pr_admission, <span class="st">"cost"</span>)
cutoff <-<span class="st"> </span>pr_admission<span class="op">@</span>cutoffs[[<span class="dv">1</span>]][<span class="kw">which.min</span>(cost_admission_perf<span class="op">@</span>y.values[[<span class="dv">1</span>]])]</code></pre></div>
<p>Using that cutoff value we should get our sensitivity and specificity a bit more in balance. Let’s try</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">prediction_lgr_df2 <-<span class="st"> </span><span class="kw">predict</span>(model_lgr_df2, <span class="dt">data =</span> df2, <span class="dt">type =</span> <span class="st">"response"</span>)
prediction_lgr_df2 <-<span class="st"> </span><span class="kw">if_else</span>(prediction_lgr_df2 <span class="op">></span><span class="st"> </span>cutoff , <span class="dv">1</span>, <span class="dv">0</span>)
<span class="kw">confusionMatrix</span>(<span class="dt">data =</span> <span class="kw">factor</span>(prediction_lgr_df2),
<span class="dt">reference =</span> <span class="kw">factor</span>(df2<span class="op">$</span>admit),
<span class="dt">positive =</span> <span class="st">"1"</span>)</code></pre></div>
<pre><code>## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 250 91
## 1 23 36
##
## Accuracy : 0.715
## 95% CI : (0.668, 0.7588)
## No Information Rate : 0.6825
## P-Value [Acc > NIR] : 0.08878
##
## Kappa : 0.2325
## Mcnemar's Test P-Value : 3.494e-10
##
## Sensitivity : 0.2835
## Specificity : 0.9158
## Pos Pred Value : 0.6102
## Neg Pred Value : 0.7331
## Prevalence : 0.3175
## Detection Rate : 0.0900
## Detection Prevalence : 0.1475
## Balanced Accuracy : 0.5996
##
## 'Positive' Class : 1
## </code></pre>
<p>And bonus, we even gained some accuracy!</p>
<p>I have seen a very cool graph on <a href="http://ethen8181.github.io/machine-learning/unbalanced/unbalanced.html">this website</a> that plots this tradeoff between specificity and sensitivity and shows how this cutoff point can enhance the understanding of the predictive power of our model.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Create tibble with both prediction and actual value</span>
cutoff =<span class="st"> </span><span class="fl">0.487194</span>
cutoff_plot <-<span class="st"> </span><span class="kw">tibble</span>(<span class="dt">predicted =</span> <span class="kw">predict</span>(model_lgr_df2, <span class="dt">data =</span> df2, <span class="dt">type =</span> <span class="st">"response"</span>),
<span class="dt">actual =</span> <span class="kw">as.factor</span>(df2<span class="op">$</span>admit)) <span class="op">%>%</span><span class="st"> </span>
<span class="st"> </span><span class="kw">mutate</span>(<span class="dt">type =</span> <span class="kw">if_else</span>(predicted <span class="op">>=</span><span class="st"> </span>cutoff <span class="op">&</span><span class="st"> </span>actual <span class="op">==</span><span class="st"> </span><span class="dv">1</span>, <span class="st">"TP"</span>,
<span class="kw">if_else</span>(predicted <span class="op">>=</span><span class="st"> </span>cutoff <span class="op">&</span><span class="st"> </span>actual <span class="op">==</span><span class="st"> </span><span class="dv">0</span>, <span class="st">"FP"</span>,
<span class="kw">if_else</span>(predicted <span class="op"><</span><span class="st"> </span>cutoff <span class="op">&</span><span class="st"> </span>actual <span class="op">==</span><span class="st"> </span><span class="dv">0</span>, <span class="st">"TN"</span>, <span class="st">"FN"</span>))))
cutoff_plot<span class="op">$</span>type <-<span class="st"> </span><span class="kw">as.factor</span>(cutoff_plot<span class="op">$</span>type)
<span class="kw">ggplot</span>(cutoff_plot, <span class="kw">aes</span>(<span class="dt">x =</span> actual, <span class="dt">y =</span> predicted, <span class="dt">color =</span> type)) <span class="op">+</span><span class="st"> </span>
<span class="st"> </span><span class="kw">geom_violin</span>(<span class="dt">fill =</span> <span class="st">"white"</span>, <span class="dt">color =</span> <span class="ot">NA</span>) <span class="op">+</span><span class="st"> </span>
<span class="st"> </span><span class="kw">geom_jitter</span>(<span class="dt">shape =</span> <span class="dv">1</span>) <span class="op">+</span><span class="st"> </span>
<span class="st"> </span><span class="kw">geom_hline</span>(<span class="dt">yintercept =</span> cutoff, <span class="dt">color =</span> <span class="st">"blue"</span>, <span class="dt">alpha =</span> <span class="fl">0.5</span>) <span class="op">+</span><span class="st"> </span>
<span class="st"> </span><span class="kw">scale_y_continuous</span>(<span class="dt">limits =</span> <span class="kw">c</span>(<span class="dv">0</span>, <span class="dv">1</span>)) <span class="op">+</span><span class="st"> </span>
<span class="st"> </span><span class="kw">ggtitle</span>(<span class="kw">paste0</span>(<span class="st">"Confusion Matrix with cutoff at "</span>, cutoff))</code></pre></div>
<p><img src="machinelearningwithR_files/figure-html/confusion_plot1-1.png" width="672" /></p>
<p>Last thing … the AUC, aka <em>Area Under the Curve</em>.<br />
The AUC is basically the area under the ROC curve.<br />
You can think of the AUC as sort of a holistic number that represents how well your TP and FP is looking in aggregate.</p>
<p>AUC=0.5 -> BAD</p>
<p>AUC=1 -> GOOD <img src="otherpics/AUC_example.png" alt="Area under ROC" /></p>
<p>So in the context of an ROC curve, the more “up and left” it looks, the larger the AUC will be and thus, the better your classifier is. Comparing AUC values is also really useful when comparing different models, as we can select the model with the high AUC value, rather than just look at the curves.</p>
<p>In our situation with our model <code>model_admission_lr</code>, we can find our AUC with the <code>ROCR</code> package.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">prediction_lgr_df2 <-<span class="st"> </span><span class="kw">predict</span>(model_lgr_df2, <span class="dt">data =</span> df2, <span class="dt">type=</span><span class="st">"response"</span>)
pr_admission <-<span class="st"> </span><span class="kw">prediction</span>(prediction_lgr_df2, df2<span class="op">$</span>admit)
auc_admission <-<span class="st"> </span><span class="kw">performance</span>(pr_admission, <span class="dt">measure =</span> <span class="st">"auc"</span>)
<span class="co"># and to get the exact value </span>
auc_admission<span class="op">@</span>y.values[[<span class="dv">1</span>]]</code></pre></div>
<pre><code>## [1] 0.6928413</code></pre>
</div>
<div id="example-2---diabetes" class="section level2">
<h2><span class="header-section-number">4.6</span> Example 2 - Diabetes</h2>
<p>In our second example we will use the <em>Pima Indians Diabetes Data Set</em> that can be downloaded on the <a href="https://archive.ics.uci.edu/ml/datasets/Pima+Indians+Diabetes">UCI Machine learning website</a>.<br />
We are also dropping a clean version of the file as .csv on our github dataset folder.</p>
<p>The data set records females patients of at least 21 years old of Pima Indian heritage.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df <-<span class="st"> </span><span class="kw">read_csv</span>(<span class="st">"dataset/diabetes.csv"</span>)</code></pre></div>
<p>The dataset has 768 observations and 9 variables.</p>
<p>Let’s rename our variables with the proper names.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">colnames</span>(df) <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"pregnant"</span>, <span class="st">"glucose"</span>, <span class="st">"diastolic"</span>,
<span class="st">"triceps"</span>, <span class="st">"insulin"</span>, <span class="st">"bmi"</span>, <span class="st">"diabetes"</span>, <span class="st">"age"</span>,
<span class="st">"test"</span>)
<span class="kw">glimpse</span>(df)</code></pre></div>
<pre><code>## Observations: 768
## Variables: 9
## $ pregnant <dbl> 6, 1, 8, 1, 0, 5, 3, 10, 2, 8, 4, 10, 10, 1, 5, 7, 0, …
## $ glucose <dbl> 148, 85, 183, 89, 137, 116, 78, 115, 197, 125, 110, 16…
## $ diastolic <dbl> 72, 66, 64, 66, 40, 74, 50, 0, 70, 96, 92, 74, 80, 60,…
## $ triceps <dbl> 35, 29, 0, 23, 35, 0, 32, 0, 45, 0, 0, 0, 0, 23, 19, 0…
## $ insulin <dbl> 0, 0, 0, 94, 168, 0, 88, 0, 543, 0, 0, 0, 0, 846, 175,…
## $ bmi <dbl> 33.6, 26.6, 23.3, 28.1, 43.1, 25.6, 31.0, 35.3, 30.5, …
## $ diabetes <dbl> 0.627, 0.351, 0.672, 0.167, 2.288, 0.201, 0.248, 0.134…
## $ age <dbl> 50, 31, 32, 21, 33, 30, 26, 29, 53, 54, 30, 34, 57, 59…
## $ test <dbl> 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, …</code></pre>
<p>All variables seems to have been recorded with the appropriate type in the data frame. Let’s just change the type of the response variable to factor with <em>positive</em> and <em>negative</em> levels.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df<span class="op">$</span>test <-<span class="st"> </span><span class="kw">factor</span>(df<span class="op">$</span>test)
<span class="co">#levels(df$output) <- c("negative", "positive")</span></code></pre></div>
<p>Let’s do our regression on the whole dataset.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df2 <-<span class="st"> </span>df
model_lgr_df2 <-<span class="st"> </span><span class="kw">glm</span>(test <span class="op">~</span>., <span class="dt">data =</span> df2, <span class="dt">family =</span> <span class="st">"binomial"</span>)
<span class="kw">summary</span>(model_lgr_df2)</code></pre></div>
<pre><code>##
## Call:
## glm(formula = test ~ ., family = "binomial", data = df2)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.5566 -0.7274 -0.4159 0.7267 2.9297
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -8.4046964 0.7166359 -11.728 < 2e-16 ***
## pregnant 0.1231823 0.0320776 3.840 0.000123 ***
## glucose 0.0351637 0.0037087 9.481 < 2e-16 ***
## diastolic -0.0132955 0.0052336 -2.540 0.011072 *
## triceps 0.0006190 0.0068994 0.090 0.928515
## insulin -0.0011917 0.0009012 -1.322 0.186065
## bmi 0.0897010 0.0150876 5.945 2.76e-09 ***
## diabetes 0.9451797 0.2991475 3.160 0.001580 **
## age 0.0148690 0.0093348 1.593 0.111192
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 993.48 on 767 degrees of freedom
## Residual deviance: 723.45 on 759 degrees of freedom
## AIC: 741.45
##
## Number of Fisher Scoring iterations: 5</code></pre>
<p>If we look at the z-statistic and the associated p-values, we can see that the variables <code>triceps</code>, <code>insulin</code> and <code>age</code> are not significant variables.</p>
<p>The logistic regression coefficients give the change in the log odds of the outcome for a one unit increase in the predictor variable. Hence, everything else being equals, any additional pregnancy increase the log odds of having diabetes (class_variable = 1) by another <code>0.1231</code>.</p>
<p>We can see the confidence interval for each variables using the <code>confint</code> function.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">confint</span>(model_lgr_df2)</code></pre></div>
<pre><code>## Waiting for profiling to be done...</code></pre>
<pre><code>## 2.5 % 97.5 %
## (Intercept) -9.860319374 -7.0481062619
## pregnant 0.060918463 0.1868558244
## glucose 0.028092756 0.0426500736
## diastolic -0.023682464 -0.0031039754
## triceps -0.012849460 0.0142115759
## insulin -0.002966884 0.0005821426
## bmi 0.060849478 0.1200608498
## diabetes 0.365370025 1.5386561742
## age -0.003503266 0.0331865712</code></pre>
<p>If we want to get the odds, we basically exponentiate the coefficients.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">exp</span>(<span class="kw">coef</span>(model_lgr_df2))</code></pre></div>
<pre><code>## (Intercept) pregnant glucose diastolic triceps
## 0.0002238137 1.1310905981 1.0357892688 0.9867924485 1.0006191560
## insulin bmi diabetes age
## 0.9988090108 1.0938471417 2.5732758592 1.0149800983</code></pre>
<p>In this way, for every additional year of age, the odds of getting diabetes (test = positive) is increasing by <code>1.015</code>.</p>
<p>Let’s have a first look at how our model perform</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">prediction_lgr_df2 <-<span class="st"> </span><span class="kw">predict</span>(model_lgr_df2, <span class="dt">data =</span> df2, <span class="dt">type=</span><span class="st">"response"</span>)
prediction_lgr_df2 <-<span class="st"> </span><span class="kw">if_else</span>(prediction_lgr_df2 <span class="op">></span><span class="st"> </span><span class="fl">0.5</span>, <span class="dv">1</span>, <span class="dv">0</span>)
<span class="co">#prediction_diabetes_lr <- factor(prediction_diabetes_lr)</span>
<span class="co">#levels(prediction_diabetes_lr) <- c("negative", "positive")</span>
<span class="kw">table</span>(df2<span class="op">$</span>test)</code></pre></div>
<pre><code>##
## 0 1
## 500 268</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">confusionMatrix</span>(<span class="dt">data =</span> <span class="kw">factor</span>(prediction_lgr_df2),
<span class="dt">reference =</span> <span class="kw">factor</span>(df2<span class="op">$</span>test),
<span class="dt">positive =</span> <span class="st">"1"</span>)</code></pre></div>
<pre><code>## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 445 112
## 1 55 156
##
## Accuracy : 0.7826
## 95% CI : (0.7517, 0.8112)
## No Information Rate : 0.651
## P-Value [Acc > NIR] : 1.373e-15
##
## Kappa : 0.4966
## Mcnemar's Test P-Value : 1.468e-05
##
## Sensitivity : 0.5821
## Specificity : 0.8900
## Pos Pred Value : 0.7393
## Neg Pred Value : 0.7989
## Prevalence : 0.3490
## Detection Rate : 0.2031
## Detection Prevalence : 0.2747
## Balanced Accuracy : 0.7360
##
## 'Positive' Class : 1
## </code></pre>
<p>Let’s create our ROC curve</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">prediction_lgr_df2 <-<span class="st"> </span><span class="kw">predict</span>(model_lgr_df2, <span class="dt">data =</span> df2, <span class="dt">type=</span><span class="st">"response"</span>)
pr_diabetes <-<span class="st"> </span><span class="kw">prediction</span>(prediction_lgr_df2, df2<span class="op">$</span>test)
prf_diabetes <-<span class="st"> </span><span class="kw">performance</span>(pr_diabetes, <span class="dt">measure =</span> <span class="st">"tpr"</span>, <span class="dt">x.measure =</span> <span class="st">"fpr"</span>)
<span class="kw">plot</span>(prf_diabetes, <span class="dt">colorize =</span> <span class="ot">TRUE</span>, <span class="dt">lwd =</span> <span class="dv">3</span>)</code></pre></div>
<p><img src="machinelearningwithR_files/figure-html/roc_diabetes_pic1-1.png" width="672" /></p>
<p>Let’s find the best cutoff value for our model.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">cost_diabetes_perf =<span class="st"> </span><span class="kw">performance</span>(pr_diabetes, <span class="st">"cost"</span>)
cutoff <-<span class="st"> </span>pr_diabetes<span class="op">@</span>cutoffs[[<span class="dv">1</span>]][<span class="kw">which.min</span>(cost_diabetes_perf<span class="op">@</span>y.values[[<span class="dv">1</span>]])]</code></pre></div>
<p>Instead of redoing the whole violin-jitter graph for our model, let’s create a function so we can reuse it at a later stage.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">violin_jitter_graph <-<span class="st"> </span><span class="cf">function</span>(cutoff, df_predicted, df_actual){
cutoff_tibble <-<span class="st"> </span><span class="kw">tibble</span>(<span class="dt">predicted =</span> df_predicted, <span class="dt">actual =</span> <span class="kw">as.factor</span>(df_actual)) <span class="op">%>%</span><span class="st"> </span>
<span class="st"> </span><span class="kw">mutate</span>(<span class="dt">type =</span> <span class="kw">if_else</span>(predicted <span class="op">>=</span><span class="st"> </span>cutoff <span class="op">&</span><span class="st"> </span>actual <span class="op">==</span><span class="st"> </span><span class="dv">1</span>, <span class="st">"TP"</span>,
<span class="kw">if_else</span>(predicted <span class="op">>=</span><span class="st"> </span>cutoff <span class="op">&</span><span class="st"> </span>actual <span class="op">==</span><span class="st"> </span><span class="dv">0</span>, <span class="st">"FP"</span>,
<span class="kw">if_else</span>(predicted <span class="op"><</span><span class="st"> </span>cutoff <span class="op">&</span><span class="st"> </span>actual <span class="op">==</span><span class="st"> </span><span class="dv">0</span>, <span class="st">"TN"</span>, <span class="st">"FN"</span>))))
cutoff_tibble<span class="op">$</span>type <-<span class="st"> </span><span class="kw">as.factor</span>(cutoff_tibble<span class="op">$</span>type)
<span class="kw">ggplot</span>(cutoff_tibble, <span class="kw">aes</span>(<span class="dt">x =</span> actual, <span class="dt">y =</span> predicted, <span class="dt">color =</span> type)) <span class="op">+</span><span class="st"> </span>
<span class="st"> </span><span class="kw">geom_violin</span>(<span class="dt">fill =</span> <span class="st">"white"</span>, <span class="dt">color =</span> <span class="ot">NA</span>) <span class="op">+</span><span class="st"> </span>
<span class="st"> </span><span class="kw">geom_jitter</span>(<span class="dt">shape =</span> <span class="dv">1</span>) <span class="op">+</span><span class="st"> </span>
<span class="st"> </span><span class="kw">geom_hline</span>(<span class="dt">yintercept =</span> cutoff, <span class="dt">color =</span> <span class="st">"blue"</span>, <span class="dt">alpha =</span> <span class="fl">0.5</span>) <span class="op">+</span><span class="st"> </span>
<span class="st"> </span><span class="kw">scale_y_continuous</span>(<span class="dt">limits =</span> <span class="kw">c</span>(<span class="dv">0</span>, <span class="dv">1</span>)) <span class="op">+</span><span class="st"> </span>
<span class="st"> </span><span class="kw">ggtitle</span>(<span class="kw">paste0</span>(<span class="st">"Confusion Matrix with cutoff at "</span>, cutoff))
}
<span class="kw">violin_jitter_graph</span>(cutoff, <span class="kw">predict</span>(model_lgr_df2, <span class="dt">data =</span> df2, <span class="dt">type =</span> <span class="st">"response"</span>), df2<span class="op">$</span>test)</code></pre></div>
<p><img src="machinelearningwithR_files/figure-html/confusion_plot2-1.png" width="672" /></p>
<p>The accuracy of our model is slightly improved by using that new cutoff value.</p>
<div id="accounting-for-missing-values" class="section level3">
<h3><span class="header-section-number">4.6.1</span> Accounting for missing values</h3>
<p>The UCI Machine Learning website note that there are no missing values on this dataset. That said, we have to be careful as there are many 0, when it is actually impossible to have such 0.<br />
So before we keep going let’s fill in these values.</p>
<p>The first thing to to is to change these <code>0</code> into <code>NA</code>.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df3 <-<span class="st"> </span>df2
<span class="co">#TODO Find a way to create a function and use map from purrr to do this</span>
df3<span class="op">$</span>glucose[df3<span class="op">$</span>glucose <span class="op">==</span><span class="st"> </span><span class="dv">0</span>] <-<span class="st"> </span><span class="ot">NA</span>
df3<span class="op">$</span>diastolic[df3<span class="op">$</span>diastolic <span class="op">==</span><span class="st"> </span><span class="dv">0</span>] <-<span class="st"> </span><span class="ot">NA</span>
df3<span class="op">$</span>triceps[df3<span class="op">$</span>triceps <span class="op">==</span><span class="st"> </span><span class="dv">0</span>] <-<span class="st"> </span><span class="ot">NA</span>
df3<span class="op">$</span>insulin[df3<span class="op">$</span>insulin <span class="op">==</span><span class="st"> </span><span class="dv">0</span>] <-<span class="st"> </span><span class="ot">NA</span>
df3<span class="op">$</span>bmi[df3<span class="op">$</span>bmi <span class="op">==</span><span class="st"> </span><span class="dv">0</span>] <-<span class="st"> </span><span class="ot">NA</span></code></pre></div>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(visdat)
<span class="kw">vis_dat</span>(df3)</code></pre></div>
<p><img src="machinelearningwithR_files/figure-html/missingdata_pic1-1.png" width="672" /></p>
<p>There are a lot of missing values … too many of them really. If this was really life, it would be important to go back to the drawing board and redisigning the data collection phase.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">model_lgr_df3 <-<span class="st"> </span><span class="kw">glm</span>(test <span class="op">~</span>., <span class="dt">data =</span> df3, <span class="dt">family =</span> <span class="st">"binomial"</span>)
<span class="kw">summary</span>(model_lgr_df3)</code></pre></div>
<pre><code>##
## Call:
## glm(formula = test ~ ., family = "binomial", data = df3)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.7823 -0.6603 -0.3642 0.6409 2.5612
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.004e+01 1.218e+00 -8.246 < 2e-16 ***
## pregnant 8.216e-02 5.543e-02 1.482 0.13825
## glucose 3.827e-02 5.768e-03 6.635 3.24e-11 ***
## diastolic -1.420e-03 1.183e-02 -0.120 0.90446
## triceps 1.122e-02 1.708e-02 0.657 0.51128
## insulin -8.253e-04 1.306e-03 -0.632 0.52757
## bmi 7.054e-02 2.734e-02 2.580 0.00989 **
## diabetes 1.141e+00 4.274e-01 2.669 0.00760 **
## age 3.395e-02 1.838e-02 1.847 0.06474 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 498.10 on 391 degrees of freedom
## Residual deviance: 344.02 on 383 degrees of freedom
## (376 observations deleted due to missingness)
## AIC: 362.02
##
## Number of Fisher Scoring iterations: 5</code></pre>
<p>This leads to a very different results than previously.</p>
<p>Let’s have a look at this new model performance</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">prediction_lgr_df3 <-<span class="st"> </span><span class="kw">predict</span>(model_lgr_df3, <span class="dt">data =</span> df3, <span class="dt">type=</span><span class="st">"response"</span>)
prediction_lgr_df3 <-<span class="st"> </span><span class="kw">if_else</span>(prediction_lgr_df3 <span class="op">></span><span class="st"> </span><span class="fl">0.5</span>, <span class="dv">1</span>, <span class="dv">0</span>)
<span class="co">#prediction_diabetes_lr <- factor(prediction_diabetes_lr)</span>
<span class="co">#levels(prediction_diabetes_lr) <- c("negative", "positive")</span>
<span class="kw">table</span>(df3<span class="op">$</span>test)</code></pre></div>
<pre><code>##
## 0 1
## 500 268</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co">#confusionMatrix(data = prediction_diabetes_lr2, </span>
<span class="co"># reference = df2$test, </span>
<span class="co"># positive = "1")</span></code></pre></div>
</div>
<div id="imputting-missing-values" class="section level3">
<h3><span class="header-section-number">4.6.2</span> Imputting Missing Values</h3>
<p>Now let’s impute the missing values using the <code>simputatiion</code> package. A nice vignette is available <a href="https://cran.r-project.org/web/packages/simputation/vignettes/intro.html">here</a>.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(simputation)
df4 <-<span class="st"> </span>df3
df4 <-<span class="st"> </span><span class="kw">impute_lm</span>(df3, <span class="dt">formula =</span> glucose <span class="op">~</span><span class="st"> </span>pregnant <span class="op">+</span><span class="st"> </span>diabetes <span class="op">+</span><span class="st"> </span>age <span class="op">|</span><span class="st"> </span>test)
df4 <-<span class="st"> </span><span class="kw">impute_rf</span>(df4, <span class="dt">formula =</span> bmi <span class="op">~</span><span class="st"> </span>glucose <span class="op">+</span><span class="st"> </span>pregnant <span class="op">+</span><span class="st"> </span>diabetes <span class="op">+</span><span class="st"> </span>age <span class="op">|</span><span class="st"> </span>test)
df4 <-<span class="st"> </span><span class="kw">impute_rf</span>(df4, <span class="dt">formula =</span> diastolic <span class="op">~</span><span class="st"> </span>bmi <span class="op">+</span><span class="st"> </span>glucose <span class="op">+</span><span class="st"> </span>pregnant <span class="op">+</span><span class="st"> </span>diabetes <span class="op">+</span><span class="st"> </span>age <span class="op">|</span><span class="st"> </span>test)
df4 <-<span class="st"> </span><span class="kw">impute_en</span>(df4, <span class="dt">formula =</span> triceps <span class="op">~</span><span class="st"> </span>pregnant <span class="op">+</span><span class="st"> </span>bmi <span class="op">+</span><span class="st"> </span>diabetes <span class="op">+</span><span class="st"> </span>age <span class="op">|</span><span class="st"> </span>test)
df4 <-<span class="st"> </span><span class="kw">impute_rf</span>(df4, <span class="dt">formula =</span> insulin <span class="op">~</span><span class="st"> </span>. <span class="op">|</span><span class="st"> </span>test)
<span class="kw">summary</span>(df4)</code></pre></div>
<pre><code>## pregnant glucose diastolic triceps
## Min. : 0.000 Min. : 44.00 Min. : 24.00 Min. : 7.0
## 1st Qu.: 1.000 1st Qu.: 99.75 1st Qu.: 64.00 1st Qu.:22.0
## Median : 3.000 Median :117.00 Median : 72.00 Median :29.0
## Mean : 3.845 Mean :121.68 Mean : 72.36 Mean :28.9
## 3rd Qu.: 6.000 3rd Qu.:141.00 3rd Qu.: 80.00 3rd Qu.:35.0
## Max. :17.000 Max. :199.00 Max. :122.00 Max. :99.0
## insulin bmi diabetes age test
## Min. : 14.00 Min. :18.20 Min. :0.0780 Min. :21.00 0:500
## 1st Qu.: 92.73 1st Qu.:27.50 1st Qu.:0.2437 1st Qu.:24.00 1:268
## Median :138.45 Median :32.21 Median :0.3725 Median :29.00
## Mean :155.91 Mean :32.43 Mean :0.4719 Mean :33.24
## 3rd Qu.:192.20 3rd Qu.:36.60 3rd Qu.:0.6262 3rd Qu.:41.00
## Max. :846.00 Max. :67.10 Max. :2.4200 Max. :81.00</code></pre>
<p>Ok we managed to get rid of the NAs. Let’s run a last time our logistic model.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">model_lgr_df4 <-<span class="st"> </span><span class="kw">glm</span>(test <span class="op">~</span><span class="st"> </span>., <span class="dt">data =</span> df4, <span class="dt">family =</span> <span class="st">"binomial"</span>)
<span class="kw">summary</span>(model_lgr_df4)</code></pre></div>
<pre><code>##
## Call:
## glm(formula = test ~ ., family = "binomial", data = df4)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -3.3142 -0.6993 -0.3864 0.7203 2.3773
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -8.639981 0.821457 -10.518 < 2e-16 ***
## pregnant 0.127325 0.032244 3.949 7.85e-05 ***
## glucose 0.030705 0.004143 7.411 1.26e-13 ***
## diastolic -0.006882 0.008691 -0.792 0.42846
## triceps 0.004442 0.014450 0.307 0.75855
## insulin 0.003536 0.001344 2.631 0.00851 **
## bmi 0.081455 0.020825 3.911 9.17e-05 ***
## diabetes 0.838278 0.298054 2.812 0.00492 **
## age 0.009847 0.009698 1.015 0.30991
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 993.48 on 767 degrees of freedom
## Residual deviance: 704.27 on 759 degrees of freedom
## AIC: 722.27
##
## Number of Fisher Scoring iterations: 5</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">prediction_lgr_df4 <-<span class="st"> </span><span class="kw">predict</span>(model_lgr_df4, <span class="dt">data =</span> df4, <span class="dt">type=</span><span class="st">"response"</span>)
prediction_lgr_df4 <-<span class="st"> </span><span class="kw">if_else</span>(prediction_lgr_df4 <span class="op">></span><span class="st"> </span><span class="fl">0.5</span>, <span class="st">"positive"</span>, <span class="st">"negative"</span>)
prediction_lgr_df4 <-<span class="st"> </span><span class="kw">factor</span>(prediction_lgr_df4)
<span class="kw">levels</span>(prediction_lgr_df4) <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"negative"</span>, <span class="st">"positive"</span>)
<span class="co">#table(df4$test, prediction_lgr_df4)</span>
<span class="co">#table(df4$test)</span>
########
<span class="co">#confusionMatrix(data = accuracy_model_lr3, </span>
<span class="co"># reference = df3$test, </span>
<span class="co"># positive = "positive")</span></code></pre></div>
</div>
<div id="roc-and-auc" class="section level3">
<h3><span class="header-section-number">4.6.3</span> ROC and AUC</h3>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">prediction_lgr_df4 <-<span class="st"> </span><span class="kw">predict</span>(model_lgr_df4, <span class="dt">data =</span> df4, <span class="dt">type=</span><span class="st">"response"</span>)
<span class="co">#pr <- prediction(prediction_lgr_df4, df4$test)</span>
<span class="co">#prf <- performance(pr, measure = "tpr", x.measure = "fpr")</span>
<span class="co">#plot(prf)</span></code></pre></div>
<p>Let’s go back to the ideal cut off point that would balance the sensitivity and specificity.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co">#cost_diabetes_perf <- performance(pr, "cost")</span>
<span class="co">#cutoff <- pr@cutoffs[[1]][which.min([email protected][[1]])]</span></code></pre></div>
<p>So for maximum accuracy, the ideal cutoff point is <code>0.487194</code>.<br />
Let’s redo our confusion matrix then and see some improvement.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">prediction_lgr_df4 <-<span class="st"> </span><span class="kw">predict</span>(model_lgr_df4, <span class="dt">data =</span> df4, <span class="dt">type=</span><span class="st">"response"</span>)
prediction_lgr_df4 <-<span class="st"> </span><span class="kw">if_else</span>(prediction_lgr_df4 <span class="op">>=</span><span class="st"> </span>cutoff, <span class="st">"positive"</span>, <span class="st">"negative"</span>)
<span class="co">#confusionMatrix(data = accuracy_model_lr3, </span>
<span class="co"># reference = df3$test, </span>
<span class="co"># positive = "positive")</span></code></pre></div>
<p>Another cost measure that is popular is overall accuracy. This measure optimizes the correct results, but may be skewed if there are many more negatives than positives, or vice versa. Let’s get the overall accuracy for the simple predictions and plot it.</p>
<p>Actually the <code>ROCR</code> package can also give us a plot of accuracy for various cutoff points</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co">#prediction_lgr_df4 <- performance(pr, measure = "acc")</span>
<span class="co">#plot(prediction_lgr_df4)</span></code></pre></div>
<p>Often in medical research for instance, there is a cost in having false negative is quite higher than a false positve.<br />
Let’s say the cost of missing someone having diabetes is 3 times the cost of telling someone that he has diabetes when in reality he/she doesn’t.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co">#cost_diabetes_perf <- performance(pr, "cost", cost.fp = 1, cost.fn = 3)</span>
<span class="co">#cutoff <- pr@cutoffs[[1]][which.min([email protected][[1]])]</span></code></pre></div>
<p>Lastly, in regards to AUC</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co">#auc <- performance(pr, measure = "auc")</span>
<span class="co">#auc <- [email protected][[1]]</span>
<span class="co">#auc</span></code></pre></div>
</div>
</div>
<div id="references-1" class="section level2">
<h2><span class="header-section-number">4.7</span> References</h2>
<ul>
<li><p>The Introduction is from the <a href="https://www.analyticsvidhya.com/blog/2015/11/beginners-guide-on-logistic-regression-in-r/?utm_content=buffer43450&utm_medium=social&utm_source=linkedin.com&utm_campaign=buffer">AV website</a></p></li>
<li><p>Confusion plot. The <a href="http://ethen8181.github.io/machine-learning/unbalanced/unbalanced.html">webpage</a> and the <a href="https://github.com/ethen8181/machine-learning/blob/master/unbalanced/unbalanced_code/unbalanced_functions.R">code</a></p></li>
<li><p>The <a href="http://www.ats.ucla.edu/stat/data/binary.csv">UCLA Institute for Digital Research and Education</a> site where we got the dataset for our first example</p></li>
<li>The <a href="https://archive.ics.uci.edu/ml/datasets/Pima+Indians+Diabetes">UCI Machine learning</a> site where we got the dataset for our second example</li>
<li><p>Function to use ROC with ggplot2 - <a href="http://www.joyofdata.de/blog/illustrated-guide-to-roc-and-auc/">The Joy of Data</a> and <a href="https://github.com/joyofdata/joyofdata-articles/tree/master/roc-auc">here as well</a></p></li>
</ul>
</div>
</div>
</section>
</div>
</div>
</div>
<a href="mlr.html" class="navigation navigation-prev " aria-label="Previous page"><i class="fa fa-angle-left"></i></a>
<a href="softmax-and-multinomial-regressions.html" class="navigation navigation-next " aria-label="Next page"><i class="fa fa-angle-right"></i></a>
</div>
</div>
<script src="libs/gitbook-2.6.7/js/app.min.js"></script>
<script src="libs/gitbook-2.6.7/js/lunr.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-search.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-sharing.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-fontsettings.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-bookdown.js"></script>
<script src="libs/gitbook-2.6.7/js/jquery.highlight.js"></script>
<script>
gitbook.require(["gitbook"], function(gitbook) {
gitbook.start({
"sharing": {
"github": false,
"facebook": true,
"twitter": true,
"google": false,
"linkedin": false,
"weibo": false,
"instapaper": false,
"vk": false,
"all": ["facebook", "google", "twitter", "linkedin", "weibo", "instapaper"]
},
"fontsettings": {
"theme": "white",
"family": "sans",
"size": 2
},
"edit": {
"link": "https://github.com/fderyckel/machinelearningwithr/edit/master/04-logistic_regression.Rmd",
"text": "Suggest edit to this page"
},
"history": {
"link": null,
"text": null
},
"download": null,
"toc": {
"collapse": "section"
}
});
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
var src = "";
if (src === "" || src === "true") src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML";
if (location.protocol !== "file:" && /^https?:/.test(src))
src = src.replace(/^https?:/, '');
script.src = src;
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>