-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMachine_learning_Classification.html
1074 lines (904 loc) · 38.3 KB
/
Machine_learning_Classification.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>AIV classification with machine learning</title>
<script src="site_libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="site_libs/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/default.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<style type="text/css">
h1 {
font-size: 34px;
}
h1.title {
font-size: 38px;
}
h2 {
font-size: 30px;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 18px;
}
h5 {
font-size: 16px;
}
h6 {
font-size: 12px;
}
.table th:not([align]) {
text-align: left;
}
</style>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
code {
color: inherit;
background-color: rgba(0, 0, 0, 0.04);
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
</style>
<style type="text/css">
/* padding for bootstrap navbar */
body {
padding-top: 51px;
padding-bottom: 40px;
}
/* offset scroll position for anchor links (for fixed navbar) */
.section h1 {
padding-top: 56px;
margin-top: -56px;
}
.section h2 {
padding-top: 56px;
margin-top: -56px;
}
.section h3 {
padding-top: 56px;
margin-top: -56px;
}
.section h4 {
padding-top: 56px;
margin-top: -56px;
}
.section h5 {
padding-top: 56px;
margin-top: -56px;
}
.section h6 {
padding-top: 56px;
margin-top: -56px;
}
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #ffffff;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script>
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark it active
menuAnchor.parent().addClass('active');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
background: white;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "";
border: none;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
background-color: transparent;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
@media print {
.toc-content {
/* see https://github.com/w3c/csswg-drafts/issues/4434 */
float: right;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
}
.tocify .list-group-item {
border-radius: 0px;
}
.tocify-subheader {
display: inline;
}
.tocify-subheader .tocify-item {
font-size: 0.95em;
}
</style>
</head>
<body>
<div class="container-fluid main-container">
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row-fluid">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"></a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="index.html">Home</a>
</li>
<li>
<a href="method-development-and-validation.html">LC-MS/MS</a>
</li>
<li>
<a href="AIV_profile_analysis.html">AIV amino acids</a>
</li>
<li>
<a href="Machine_learning_Classification.html">Machine learning</a>
</li>
<li>
<a href="ShinyML.html">Interactive Shiny</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">AIV classification with machine learning</h1>
</div>
<p><br/></p>
<p><strong>Object naming</strong>:</p>
<p>df.XXX: a data.frame or tibble object; e.g., df.all.data<br />
df.modelname…: a data frame or tibble containing tidied results from a model prediction vs actual<br />
mat.XXX: a matrix object; e.g., mat.content<br />
pltXXX: a plot object; e.g., plt.univariate.boxplot.dot<br />
mdl.trained.XXXX: model from training set; e.g., mdl.trained.LDA<br />
mdl.fitted.XXX: object with fitted results output from a trained model; e.g., mdl.fitted.LDA<br />
mdl.XXX: a model object; e.g., mdl.LDA<br />
fitted.XXX: predicted class, e.g. fitted.logistic.elasticNet<br />
cf.XXX: confusion table; e.g., cf.counts.LDA<br />
func.XXX: defined functions; e.g., func.boxplot.Site()</p>
<p><br/></p>
<div id="packages" class="section level1">
<h1><span class="header-section-number">1</span> Packages</h1>
<pre class="r"><code># functional packages
library(readxl)
# Machine learning packages
library(MASS)
library(rsample)
library(viridis)
library(glmnet)
library(caret)
library(rpart.plot) # for classification tree plot
library(randomForest)
library(e1071)
library(ComplexHeatmap)
# The core package collection
# load last, so as the key functions are not masked by others; but instead masking others if any
library(tidyverse)</code></pre>
<pre class="r"><code>set.seed(19911110)</code></pre>
</div>
<div id="data" class="section level1">
<h1><span class="header-section-number">2</span> Data</h1>
<pre class="r"><code># Read amino acid content dataset
path = "/Users/Boyuan/Desktop/My publication/16. HILIC amino acid machine learning to J. Chroma A/Publish-ready files/AIV free amino acids content.xlsx"
df.content= read_excel(path , sheet = "content in AIV (mg.100g DW-1)")
# select needed columns and tidy up
df.content = df.content %>% select(Name, Category, Site) %>%
mutate(strata.group = paste(Category, Site, sep = "_")) %>%
cbind(df.content %>% select(23:ncol(df.content))) %>%
as_tibble()
# categories
unique.categories = df.content$Category %>% unique()
# category colors
color.category = c("Black", "Steelblue", "Firebrick" , "Darkgreen")
names(color.category) = unique.categories</code></pre>
</div>
<div id="define-functions" class="section level1">
<h1><span class="header-section-number">3</span> Define functions</h1>
<div id="train-test-split" class="section level2">
<h2><span class="header-section-number">3.1</span> Train-test split</h2>
<div id="statified-sampling" class="section level3">
<h3><span class="header-section-number">3.1.1</span> Statified sampling</h3>
<pre class="r"><code># strata group
unique.categories.site = df.content$strata.group %>% unique()
# Define function doing stratified sampling based on category-site combination
func.stratifiedSampling = function(trainingRatio = 0.7){
index.train = c()
for (a in unique.categories.site){
df.content.i = df.content %>% filter(strata.group == a)
index.train.i = sample(df.content.i$Name, size = (trainingRatio * nrow(df.content.i)) %>% floor())
index.train = c(index.train, index.train.i)
}
df.train = df.content %>% filter(Name %in% index.train)
df.test = df.content %>% filter(! Name %in% index.train)
list.learn = list(df.train, df.test)
return(list.learn)
}
# demo
# df.learn = func.stratifiedSampling(trainingRatio = .5)
# In practice, the trainingRatio is manuall changed by citing arguments from higher level function (see below)
# the split ratio in convenient practice should never be changed in this sampling function</code></pre>
</div>
<div id="normalization" class="section level3">
<h3><span class="header-section-number">3.1.2</span> Normalization</h3>
<pre class="r"><code># input list: 1st: training set; 2nd, test set; i.e., the output of func.stratifiedSampling
func.normalize.trainTest = function(list) {
mat.train = list[[1]] %>% dplyr::select(-c(Name, Category, Site, strata.group, `Data File`)) %>% as.matrix()
mat.test = list[[2]] %>% dplyr::select(-c(Name, Category, Site, strata.group, `Data File`)) %>% as.matrix()
# mean vector computed from training set (as single column matrix)
meanVector.train = apply(mat.train, 2, mean) %>% as.matrix()
# diagonol matrix, with standard deviation inverse
mat.inverse.sd.diaganol = apply(mat.train, 2, sd) %>% diag() %>% solve()
# Reserve column names
colnames(mat.inverse.sd.diaganol) = colnames(mat.train)
# ones vector, as single column matrix, length = # observation units of TRAINING set
vector.ones.train = rep(1, nrow(mat.train)) %>% as.matrix()
# Compute normalized training dataset
mat.train.scaled = (mat.train - vector.ones.train %*% t(meanVector.train)) %*% mat.inverse.sd.diaganol
# Use built-in scale function to double check computation
# Used for trouble shooting purpose; comment out to keep console cleanness when running code
# mat.train.scaled.test = mat.train %>% scale(center = T, scale = T)
# if ((mat.train.scaled - mat.train.scaled.test ) %>% sum() %>% round(10) == 0){
# cat("Computation is correct!")
# } else{
# cat("Computation may be incorrect. Further examination is required!")
# }
# Normalize test dataset using training-set mean vector and standard deviation diagonal matrix
# ones vector, as single column matrix, length = # observation units of TESTING set
vector.ones.test = rep(1, nrow(mat.test)) %>% as.matrix()
mat.test.scaled = (mat.test - vector.ones.test %*% t(meanVector.train)) %*% mat.inverse.sd.diaganol
# Complete two matrices with category labels, and convert to tibble
df.train.scaled = cbind(data.frame(Category = list[[1]]$Category), mat.train.scaled) %>% as_tibble()
df.test.scaled = cbind(data.frame(Category = list[[2]]$Category), mat.test.scaled) %>% as_tibble()
return(list(df.train.scaled, df.test.scaled))
}
# demo
# func.stratifiedSampling(trainingRatio = .6) %>% func.normalize.trainTest()</code></pre>
</div>
<div id="chaining-prior-two-functions" class="section level3">
<h3><span class="header-section-number">3.1.3</span> Chaining prior two functions</h3>
<pre class="r"><code># Define a third function: chaining the prior two functions together
# 1) stratified sampling into training and test set
# 2) normalize training set, and normalize test set based on training mean vector and standard deviation
func.strata.Norm.trainTest = function(trainingRatio = 0.7, scaleData = T){
if(scaleData == T){
func.stratifiedSampling(trainingRatio = trainingRatio) %>%
func.normalize.trainTest() %>% return()
} else {
func.stratifiedSampling(trainingRatio = trainingRatio) %>% return()
}
}
# demo: 1> func.strata.Norm.trainTest(); # default 0.7 train-test split ratio
# 2> func.strata.Norm.trainTest(trainingRatio = .5) # manually change train-test split ratio</code></pre>
</div>
</div>
<div id="prediction-table-tidy-up" class="section level2">
<h2><span class="header-section-number">3.2</span> Prediction table tidy up</h2>
<div id="confusion-matrix" class="section level3">
<h3><span class="header-section-number">3.2.1</span> Confusion matrix</h3>
<pre class="r"><code># Define two function: tidy up confusion tables (contingency table and stats)
# 1) For contigency table
func.tidy.cf.contigencyTable = function(inputTable, ModelName){
inputTable %>% as.data.frame() %>%
spread(key = Reference, value = Freq) %>%
mutate(Model = ModelName) %>%
return()
}
# demo: cf.counts.LDA %>% func.tidy.cf.contigencyTable()</code></pre>
</div>
<div id="summary-statistics" class="section level3">
<h3><span class="header-section-number">3.2.2</span> Summary statistics</h3>
<pre class="r"><code># 2) For stats table based on each category
func.tidy.cf.statsTable = function(inputTable, ModelName){
cbind(Category = rownames(inputTable), inputTable %>% as_tibble()) %>%
mutate(Category = str_remove(Category, pattern = "Class: ")) %>%
mutate(Model = ModelName) %>%
return()
}</code></pre>
<pre class="r"><code># 3) For overal stats table
func.tidy.cf.statsOveral = function(vector, modelName){
d = data.frame(Accuracy = vector[1], AccuracyLower = vector[3],
AccuracyUpper = vector[4], Model = modelName) %>% as_tibble()
return(d)
}</code></pre>
</div>
<div id="most-votes" class="section level3">
<h3><span class="header-section-number">3.2.3</span> Most votes</h3>
<pre class="r"><code>func.mostVotes = function(vector){
x = vector %>% table() %>% sort() %>% rev()
names(x)[1] %>% return()
}</code></pre>
</div>
</div>
</div>
<div id="machine-learning" class="section level1">
<h1><span class="header-section-number">4</span> Machine learning</h1>
<div id="traintest-split" class="section level2">
<h2><span class="header-section-number">4.1</span> 70/30 train/test split</h2>
<pre class="r"><code># Now, let's set up the training and testing set.
# When needed for certain algorithm, when hyper-parameters are tuned, the training set is further split into validations sets using cross-validation method.
df.learn = func.strata.Norm.trainTest(trainingRatio = .7, scaleData = T)
df.train = df.learn[[1]]
df.test = df.learn[[2]]</code></pre>
<p><strong>Note here that the training set is scaled, and the testing set is also scaled using the mean and covariance matrix of the testing set!</strong></p>
<p>Despite Differences in algorithms per se, the workflow is roughly the same: train the model, test performance on the teset set, and tidy up the confusion matrix. Regardless such similarityit and the possibility of wrapping different algorithms into one overal function, in this work each algorithm is written in a rather independant manner. Redundant as this truely is, this practice is rewarded by easy understanding of each algorithm section, which could be read as a more or less standalone method; meanwhile, this practice provides rapid access for trouble shooting.</p>
</div>
<div id="linear-discriminant-analysis-lda" class="section level2">
<h2><span class="header-section-number">4.2</span> Linear discriminant analysis (LDA)</h2>
<pre class="r"><code># model train
mdl.trained.LDA = lda(Category ~., data = df.train)
# predict on test set, with equal prior probability
mdl.fitted.LDA = predict(mdl.trained.LDA, newdata = df.test, prior = rep(1/4, 4))
fitted.LDA = mdl.fitted.LDA$class # here we overwrite the prior fitted.LDA object
cf.LDA = confusionMatrix(data = fitted.LDA, reference = df.test$Category, mode = "everything")
# confusion table
cf.counts.LDA = cf.LDA$table %>% func.tidy.cf.contigencyTable(ModelName = "LDA")
# Summary stats table
cf.stats.LDA = cf.LDA$byClass %>% func.tidy.cf.statsTable(ModelName = "LDA") </code></pre>
</div>
<div id="quadratic-discriminant-analysis" class="section level2">
<h2><span class="header-section-number">4.3</span> Quadratic discriminant analysis</h2>
<pre class="r"><code># model train
mdl.QDA = qda(Category ~., data = df.train)
# predict on test set, with equal prior probability
mdl.fitted.QDA = predict(mdl.QDA, newdata = df.test, prior = rep(1/4, 4))
fitted.QDA = mdl.fitted.QDA$class
cf.QDA = confusionMatrix(data = fitted.QDA, reference = df.test$Category, mode = "everything")
# confusion matrix
cf.counts.QDA = cf.QDA$table %>% func.tidy.cf.contigencyTable(ModelName = "QDA")
# summary results
cf.stats.QDA = cf.QDA$byClass %>% func.tidy.cf.statsTable(ModelName = "QDA")</code></pre>
<p>With 0.5 split ratio, console would pop up error “rank deficiency in group Mustard”. QDA estimates the covariance matrix for each population, and requries more data input. Mustard is the category with the smallest size of observation units. While LDA assumes equal covariance matrix for all populations, and takes a pooled covaraince matrix, and thus requires much less data input for parameter estimation. In fact, LDA does a fairly nice job when trained with only 10% of data.</p>
</div>
<div id="regularized-logistic-regression" class="section level2">
<h2><span class="header-section-number">4.4</span> Regularized logistic regression</h2>
<pre class="r"><code># cross validation
cv.mdl.logistic.ridge = cv.glmnet(x = df.train[, -1] %>% as.matrix(), y = df.train$Category,
family = "multinomial", alpha = 0)
cv.mdl.logistic.elasticNet = cv.glmnet(x = df.train[, -1] %>% as.matrix(), y = df.train$Category,
family = "multinomial", alpha = 0.5)
cv.mdl.logistic.lasso = cv.glmnet(x = df.train[, -1] %>% as.matrix(), y = df.train$Category,
family = "multinomial", alpha = 1)
par(mfrow = c(1, 3))
plot(cv.mdl.logistic.ridge, main = "Ridge", line = 2)
plot(cv.mdl.logistic.elasticNet, main = "Elastic Net (alpha = 0.5)", line = 2)
plot(cv.mdl.logistic.lasso, main = "Lasso", line = 2)</code></pre>
<p><img src="Machine_learning_Classification_files/figure-html/unnamed-chunk-14-1.png" width="672" /></p>
<pre class="r"><code>par(mfrow = c(1, 1))</code></pre>
<pre class="r"><code># check model coefficients
x = coef(cv.mdl.logistic.elasticNet, s = "lambda.min")
df.logisticNets.coefficients =
data.frame(x[[1]] %>% as.matrix(), x[[2]] %>% as.matrix(),
x[[3]] %>% as.matrix(), x[[4]] %>% as.matrix())
colnames(df.logisticNets.coefficients) = names(x)
# df.logisticNets.coefficients</code></pre>
<pre class="r"><code># Prediction with train-test split, a formal test of model efficiency
# Define function for performing regularized logistic with different alpha values
func.regularizedLogistic = function(
input.alpha, # control ridge, lasso, or between
ModelName # model type as extra column note in the confusion table output
){
# train with 10-fold cross validation
cv.mdl.logistic = cv.glmnet(x = df.train[, -1] %>% as.matrix(), y = df.train$Category,
family = "multinomial", alpha = input.alpha, nfolds = 10)
# predict with test set
fitted.logistic =
predict(cv.mdl.logistic, newx = df.test[, -1] %>% as.matrix(),
s = cv.mdl.logistic$lambda.1se, type = "class") %>% c() %>%
factor(levels = sort(unique.categories), ordered = T) # Note: important to sort unique.categories!
# wrap up prediction results
cf.logistic = confusionMatrix(data = fitted.logistic, reference = df.test$Category)
cf.counts.logistic = cf.logistic$table %>% func.tidy.cf.contigencyTable(ModelName = ModelName)
cf.stats.logistic = cf.logistic$byClass %>% func.tidy.cf.statsTable(ModelName = ModelName)
return(list(cf.counts.logistic, cf.stats.logistic, fitted.logistic, cf.logistic))
}
# Test upon different alpha values (important to note that alpha is not a hyper-parameter to optimize!)
# func.regularizedLogistic(input.alpha = 0, ModelName = "Ridge")
# func.regularizedLogistic(input.alpha = 1, ModelName = "Lasso")
# func.regularizedLogistic(input.alpha = 0.5, ModelName = paste("ElasticNet, α = 0.5") )
# We'remore interested in the elastic net results
list.logistic = func.regularizedLogistic(input.alpha = 0.5, ModelName = paste("EN") )
cf.counts.ElasticNet =list.logistic[[1]]
cf.stats.ElasticNet = list.logistic[[2]]
fitted.ElasticNet = list.logistic[[3]]
cf.EN = list.logistic[[4]]</code></pre>
</div>
<div id="random-forest" class="section level2">
<h2><span class="header-section-number">4.5</span> Random forest</h2>
<pre class="r"><code># Predict with train-test split
colnames(df.train) = make.names(colnames(df.train))
colnames(df.test) = make.names(colnames(df.test))
# set up training model and test accuracy
mdl.randomForest = randomForest(Category ~., data = df.train, ntree = 500, mtry = 5)
fitted.randomForest = predict(mdl.randomForest, newdata = df.test)
# set up confusion table
cf.randomForest = confusionMatrix(data = fitted.randomForest,
reference = df.test$Category,
mode = "everything")
# confusion matrix
cf.counts.randomForest = cf.randomForest$table %>%
func.tidy.cf.contigencyTable(ModelName = "RF")
# Summary stats
cf.stats.randomForest = cf.randomForest$byClass %>%
func.tidy.cf.statsTable(ModelName = "RF")
# cf.counts.randomForest
# cf.stats.randomForest</code></pre>
</div>
<div id="support-vector-machine" class="section level2">
<h2><span class="header-section-number">4.6</span> Support vector machine</h2>
<div id="cross-validation" class="section level3">
<h3><span class="header-section-number">4.6.1</span> Cross-validation</h3>
<pre class="r"><code># Tune hyper-parameters
svm.gamma = 10^(seq(-5, 2, by = 1))
svm.cost = 10^(seq(-2, 5, by = 1))
cv.svm = df.train %>%
vfold_cv(strata = Category, v = 5) %>%
mutate(train = map(.x = splits, .f = ~training(.x) ),
validate = map(.x = splits, .f = ~testing(.x) )) %>%
select(-splits) %>%
crossing(gamma = svm.gamma, cost = svm.cost) %>%
mutate(hyper = map2(.x = gamma, .y = cost, .f = ~list(.x, .y))) %>% # 1st gamma; 2nd cost
# set up model CV tuning hyper-params
mutate(model = map2(.x = train, .y = hyper,
.f = ~svm(x = .x[, -1], y = .x[[1]], gamma = .y[[1]], cost = .y[[2]] ) )) %>%
# predict on validation set
# note that here the CV is performed in a somewhat loose manner as the train-validation folds have been normalized upstream prior to train-validation split
mutate(fitted.validate = map2(.x = model, .y = validate,
.f = ~predict(.x, newdata = .y[, -1] )),
actual.validate = map(.x = validate, .f = ~.x[[1]] %>% factor(ordered = F)),
accuracy = map2_dbl(.x = fitted.validate , .y = actual.validate,
.f = ~sum(.x == .y)/length(.x)))
cv.svm.summary = cv.svm %>%
group_by(gamma, cost) %>%
summarise(accuracy.mean = mean(accuracy) * 100,
accuracy.sd = sd(accuracy) * 100 ) %>%
arrange(desc(accuracy.mean))</code></pre>
<pre class="r"><code>cv.svm.summary %>%
ggplot(aes(x = gamma, y = cost, z = accuracy.mean)) +
geom_tile(aes(fill = accuracy.mean)) +
scale_fill_viridis(option = "A", alpha = .9) +
# stat_contour(color = "grey", size = .5) +
coord_fixed() +
theme(panel.grid.minor = element_line(colour = "black", size = 2),
panel.grid.major = element_blank()) +
scale_x_log10(breaks = svm.gamma, labels = log10(svm.gamma)) +
scale_y_log10(breaks = svm.cost, labels = log10(svm.cost)) +
labs(x = "gamma, 10 ^ X", y = "cost, 10 ^ X", title = "SVM Radial Kernel") +
geom_text(aes(label = accuracy.mean %>% round(1) ), color = "black")</code></pre>
<p><img src="Machine_learning_Classification_files/figure-html/unnamed-chunk-19-1.png" width="768" /></p>
</div>
<div id="train-by-entire-training-set" class="section level3">
<h3><span class="header-section-number">4.6.2</span> Train by entire training set</h3>
<pre class="r"><code>mdl.svm = svm(x = df.train[, -1], y = df.train$Category,
gamma = cv.svm.summary$gamma[1],
cost = cv.svm.summary$cost[1])
# predict
fitted.svm = predict(mdl.svm, newdata = df.test[, -1])
# confusion matrix
cf.svm = confusionMatrix(
data = fitted.svm, reference = df.test$Category, mode = "everything")
# confusion matrix
cf.counts.svm = cf.svm$table %>%
func.tidy.cf.contigencyTable(ModelName = "SVM")
# summary stats
cf.stats.svm = cf.svm$byClass %>%
func.tidy.cf.statsTable(ModelName = "SVM")</code></pre>
</div>
</div>
<div id="naive-bayes-benchmark" class="section level2">
<h2><span class="header-section-number">4.7</span> Naive Bayes (benchmark)</h2>
<pre class="r"><code># train
mdl.Bayes = naiveBayes(x = df.train[, -1], y = df.train$Category)
# predict
fitted.Bayes = predict(mdl.Bayes, newdata = df.test, type = "class")
# confusion matrix
cf.Bayes = confusionMatrix(
data = fitted.Bayes, reference = df.test$Category, mode = "everything")
# confusion matrix
cf.counts.Bayes = cf.Bayes$table %>%
func.tidy.cf.contigencyTable(ModelName = "NB")
# summary stats
cf.stats.Bayes = cf.Bayes$byClass %>%
func.tidy.cf.statsTable(ModelName = "NB")</code></pre>
</div>
</div>
<div id="test-results" class="section level1">
<h1><span class="header-section-number">5</span> Test results</h1>
<div id="wrap-up" class="section level2">
<h2><span class="header-section-number">5.1</span> Wrap up</h2>
<pre class="r"><code>unique.models = factor(
c("LDA", "QDA", "EN", "RF", "SVM", "NB", "Most voted"), ordered = T)</code></pre>
<pre class="r"><code># Summary of all machine learning techniques ----
# Sample wise prediction of all models and most voted
df.actual.vs.fit = data.frame(
"Actual" = df.test$Category,
"LDA" = fitted.LDA,
"QDA" = fitted.QDA,
"EN" = fitted.ElasticNet,
"RF" = fitted.randomForest,
"SVM" = fitted.svm,
"NB" = fitted.Bayes)
df.actual.vs.fit = df.actual.vs.fit %>% as_tibble() %>%
mutate(Actual = factor(Actual, ordered = F))
df.actual.vs.fit = df.actual.vs.fit %>%
mutate(most.voted = apply(df.actual.vs.fit %>% select(-Actual),
MARGIN = 1, func.mostVotes))
# Most voted confusion matrix
cf.mostVoted = confusionMatrix(data = df.actual.vs.fit$most.voted %>% factor(),
reference = df.actual.vs.fit$Actual %>% factor(), mode = "everything")
cf.counts.MostVoted = cf.mostVoted$table %>%
func.tidy.cf.contigencyTable(ModelName = "Most voted")
cf.stats.MostVoted = cf.mostVoted$byClass %>%
func.tidy.cf.statsTable(ModelName = "Most voted")</code></pre>
<pre class="r"><code># Summary of all machine learning techniques
df.confusionMatrix.all = cf.counts.LDA %>% rbind(cf.counts.QDA) %>%
rbind(cf.counts.ElasticNet) %>% # rbind(cf.counts.CART) %>%
rbind(cf.counts.randomForest) %>% rbind(cf.counts.svm) %>%
rbind(cf.counts.Bayes) %>% rbind(cf.counts.MostVoted) %>% as_tibble()
# tidy up the confusion matrix combined
df.confusionMatrix.all.tidy = df.confusionMatrix.all %>%
# tidy up
gather(-c(Prediction, Model), key = reference, value = counts) %>%
# convert AIVs category into ordered factor
mutate(reference = factor(reference, levels = unique.categories, ordered = T),
Prediction = factor(Prediction, levels = unique.categories %>% rev(), ordered = T)) %>%
# change model order in the dataset
mutate(Model = factor(Model, levels = unique.models, ordered = T)) %>%
arrange(Model, reference, Prediction) %>%
mutate(Diaganol = Prediction == reference)</code></pre>
<pre class="r"><code># assign color to correct / incorrect prediction
diag = df.confusionMatrix.all.tidy %>%
filter(Diaganol == F)
df.confusionMatrix.all.tidy = diag %>%
mutate(color = ifelse(counts == 0, "Grey", "Firebrick")) %>%
rbind(df.confusionMatrix.all.tidy %>% filter(Diaganol == T) %>%
mutate(color = "steelblue"))</code></pre>
</div>
<div id="confusion-matrix-1" class="section level2">
<h2><span class="header-section-number">5.2</span> Confusion matrix</h2>
<pre class="r"><code># Visualize confusion matrix
df.confusionMatrix.all.tidy %>%
ggplot(aes(x = reference, y = Prediction)) +
facet_wrap(~Model, nrow = 2) +
# off diaganol incorrect prediction
geom_label(data = df.confusionMatrix.all.tidy %>% filter(color == "Firebrick"),
aes(label = counts),
fill = "firebrick", alpha = .3, size = 6) +
# diaganol correct prediction
geom_label(data = df.confusionMatrix.all.tidy %>% filter(color == "steelblue"),
aes(label = counts),
fill = "Steelblue", alpha = .3, size = 6) +
# zero counts
geom_label(data = df.confusionMatrix.all.tidy %>% filter(color == "Grey"),
aes(label = counts),
size = 6, color = "grey") +
theme_bw() +
theme(axis.text.x = element_text(angle = 90, vjust = .8, hjust = .8, color = "black", size = 12),
axis.text.y = element_text(color = "black", size = 12),
axis.title = element_text(size = 14, colour = "black"),
strip.background = element_blank(),
strip.text = element_text(face = "bold", size = 14),
panel.border = element_rect(color = "black", size = 1),
title = element_text(face = "bold")) +
labs(x = "\nReference", y = "Prediction\n") +
ggtitle("Confusion Matrix") +
coord_fixed(ratio = 1)</code></pre>
<p><img src="Machine_learning_Classification_files/figure-html/unnamed-chunk-26-1.png" width="1152" /></p>
</div>
<div id="sample-wise-heatmap" class="section level2">
<h2><span class="header-section-number">5.3</span> Sample-wise heatmap</h2>
<pre class="r"><code># Sample-wise comparison between models
fitted.ElasticNet = func.regularizedLogistic(input.alpha = 0.5, ModelName = "Elastic Net")[[3]]
df.actual.vs.fit = data.frame(
"Actual" = df.test$Category,
"Linear discriminant" = fitted.LDA,
"Quadratic discriminant" = fitted.QDA,
"Elastic net" = fitted.ElasticNet,
# "CART" = fitted.CART,
"Random forest" = fitted.randomForest,
"Support vector machine" = fitted.svm,
"Naive Bayes" = fitted.Bayes)
df.actual.vs.fit = df.actual.vs.fit %>% as_tibble() %>%
mutate(Actual = factor(Actual, ordered = F))
# df.actual.vs.fit
# most votes
func.mostVotes = function(vector){
x = vector %>% table() %>% sort() %>% rev()
names(x)[1] %>% return()
}
df.actual.vs.fit = df.actual.vs.fit %>%
mutate('Most voted' = apply(df.actual.vs.fit %>% select(-Actual),
MARGIN = 1, func.mostVotes))</code></pre>
<pre class="r"><code># Heatmap of sample-wise predicted result
plt.heatmap.machineLearning =
df.actual.vs.fit %>% arrange(Actual) %>%
as.matrix() %>% t() %>%
Heatmap(col = color.category,
heatmap_legend_param = list(
title = "Category", title_position = "leftcenter",
nrow = 1,
labels_gp = gpar(fontsize = 11)),
rect_gp = gpar(col = "white", lwd = 0.1))
draw(plt.heatmap.machineLearning,
heatmap_legend_side = "bottom")</code></pre>
<p><img src="Machine_learning_Classification_files/figure-html/unnamed-chunk-28-1.png" width="960" /></p>
</div>
<div id="summary-statistics-1" class="section level2">
<h2><span class="header-section-number">5.4</span> Summary statistics</h2>
<pre class="r"><code># Set up summary statistics
df.stats = cf.stats.LDA %>% rbind(cf.stats.QDA) %>%
rbind(cf.stats.ElasticNet) %>% rbind(cf.stats.randomForest) %>%
rbind(cf.stats.svm) %>% rbind(cf.stats.Bayes) %>% rbind(cf.stats.MostVoted) %>%
select(Category, Model, Precision, Recall, F1) %>%
gather(-c(1:2), key = metrics, value = values) %>%
mutate(Model = factor(Model, levels = unique.models, ordered = T))
df.stats.overal = func.tidy.cf.statsOveral(cf.LDA$overall, modelName = "LDA") %>%
rbind(func.tidy.cf.statsOveral(cf.QDA$overall, modelName = "QDA")) %>%
rbind(func.tidy.cf.statsOveral(cf.EN$overall, modelName = "EN")) %>%
rbind(func.tidy.cf.statsOveral(cf.randomForest$overall, modelName = "RF")) %>%
rbind(func.tidy.cf.statsOveral(cf.svm$overall, modelName = "SVM")) %>%
rbind(func.tidy.cf.statsOveral(cf.Bayes$overall, modelName = "NB")) %>%
rbind(func.tidy.cf.statsOveral(cf.mostVoted$overall, modelName = "Most voted")) %>%
mutate(Model = factor(Model, levels = unique.models, ordered = T))</code></pre>
<p>The overal accuracy of the model is in bold, with corresponding 95% confidence interval shown in following line.</p>
<pre class="r"><code>plt.summaryStats =
df.stats %>% ggplot(aes(x = Category, y = values, color = metrics)) +
geom_segment(aes( xend = Category, y = 0.5, yend = values),
position = position_dodge(0.5)) +
geom_point(size = 4, position = position_dodge(.3), alpha = .9) +
facet_wrap(~Model, nrow = 1) +
theme_bw() +
theme(legend.position = "bottom",
legend.title = element_text(size = 11),
legend.text = element_text(size = 11),
strip.text = element_text(face = "bold", size = 12),
strip.background = element_blank(),
axis.text.x = element_text(angle = 90, hjust = 1, colour = "black", size = 11),
axis.text.y = element_text(colour = "black", size = 11),
axis.title = element_text(size = 11)) +
coord_cartesian(ylim = c(0.65, 1)) +
scale_color_brewer(palette = "Accent") +
# overal stats
geom_text(data = df.stats.overal,
aes(x = 2.5, y = 0.7, label = round(Accuracy, 3) * 100),
color = "black", fontface = "bold", size = 5) +
geom_text(data = df.stats.overal,
aes(x = 2.5, y = 0.66,
label = paste(round(AccuracyLower, 3) * 100, " ~ ",
round(AccuracyUpper, 3) * 100)),
color = "black", size = 5)
plt.summaryStats </code></pre>
<p><img src="Machine_learning_Classification_files/figure-html/unnamed-chunk-30-1.png" width="1152" /></p>
</div>
</div>