-
Notifications
You must be signed in to change notification settings - Fork 0
/
LemonMLscript.html
1649 lines (1408 loc) · 74.5 KB
/
LemonMLscript.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>Lemon Juice Classification</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>
<script src="site_libs/htmlwidgets-1.5.1/htmlwidgets.js"></script>
<script src="site_libs/plotly-binding-4.9.1/plotly.js"></script>
<script src="site_libs/typedarray-0.1/typedarray.min.js"></script>
<link href="site_libs/crosstalk-1.0.0/css/crosstalk.css" rel="stylesheet" />
<script src="site_libs/crosstalk-1.0.0/js/crosstalk.min.js"></script>
<link href="site_libs/plotly-htmlwidgets-css-1.49.4/plotly-htmlwidgets.css" rel="stylesheet" />
<script src="site_libs/plotly-main-1.49.4/plotly-latest.min.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;
}
</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="ICEplots.html">ICE plots</a>
</li>
<li>
<a href="LemonMLscript.html">Machine Learning Script</a>
</li>
<li>
<a href="Shiny_App_Script.html">Shiny App Script</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">Lemon Juice Classification</h1>
<h4 class="date">3/23/2020</h4>
<br>
<p>Below is documented the R script constructed for data analysis in the original work
<a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC9261826/"><strong>
Assessment of lemon juice quality and adulteration by ultra-high performance liquid chromatography/triple quadrupole mass spectrometry with interactive and interpretable machine learning</strong></a>
published in <em>Journal of Food and Drug Analysis</em>.
</p>
<p>The R code has been built with reference to <a href="https://r4ds.hadley.nz/">R for Data Science (2e)</a>, and the
official documentation of <a href="https://www.tidyverse.org/">tidyverse</a>, and <a href="https://www.databrewer.co/"><strong>DataBrewer.co</strong></a>.
See breakdown of modules below:</p>
<ul>
<li><p><strong>Data visualization</strong> with <strong>ggplot2</strong> (<a href="https://www.databrewer.co/R/visualization/introduction">tutorial</a>
of the fundamentals; and <a href="https://www.databrewer.co/R/gallery">data
viz. gallery</a>).</p></li>
<li><p><a href="https://www.databrewer.co/R/data-wrangling"><strong>Data
wrangling</strong> </a> with the following packages: <a href="https://www.databrewer.co/R/data-wrangling/tidyr/introduction"><strong>tidyr</strong></a>,
transform (e.g., pivoting) the dataset into tidy structure; <a href="https://www.databrewer.co/R/data-wrangling/dplyr/0-introduction"><strong>dplyr</strong></a>,
the basic tools to work with data frames; <a href="https://www.databrewer.co/R/data-wrangling/stringr/0-introduction"><strong>stringr</strong></a>,
work with strings; <a href="https://www.databrewer.co/R/data-wrangling/regular-expression/0-introduction"><strong>regular
expression</strong></a>: search and match a string pattern; <a href="https://www.databrewer.co/R/data-wrangling/purrr/introduction"><strong>purrr</strong></a>,
functional programming (e.g., iterating functions across elements of
columns); and <a href="https://www.databrewer.co/R/data-wrangling/tibble/introduction"><strong>tibble</strong></a>,
work with data frames in the modern tibble structure.</p></li>
</ul>
<br>
</div>
<div id="basic-setup" class="section level1">
<h1><span class="header-section-number">1</span> Basic setup</h1>
<pre class="r"><code>library(readxl)
library(rebus)
library(stringr)
library(ggrepel)
library(gridExtra)
library(cowplot)
library(RColorBrewer)
library(viridis)
library(ggcorrplot)
library(ggsci)
library(plotly)
# machine learning packages
library(glmnet)
library(MASS)
library(e1071)
library(rsample)
library(randomForest)
# finally load tidyverse avoiding key functions from being masked
library(tidyverse)</code></pre>
<pre class="r"><code>set.seed(2020)</code></pre>
<pre class="r"><code>theme_set(theme_bw() +
theme(strip.background = element_blank(),
strip.text = element_text(face = "bold", size = 11),
legend.text = element_text(size = 10),
legend.title = element_blank(),
axis.text = element_text(size = 11, colour = "black"),
title = element_text(colour = "black", face = "bold"),
axis.title = element_text(size = 12)))
# global color set
color.types = c("firebrick", "steelblue", "darkgreen")
names(color.types) = c("adulterated_L_J", "authentic_L_J", "lemonade")</code></pre>
</div>
<div id="raw-data-tidy-up" class="section level1">
<h1><span class="header-section-number">2</span> Raw data tidy up</h1>
<pre class="r"><code>path = "/Users/Boyuan/Desktop/My publication/14. Lemon juice (Weiting)/publish ready files/June 2020/Supplementary Material-June-C.xlsx"
d = read_excel(path, sheet = "Final data", range = "A1:R82")
d = d %>% filter(!code %in% c(54:57)) # No. 54-57 belongs to comemrcially sourced lemon juices
# Replace special values
vectorReplace = function(x, searchPattern){
replaceWith = NA
if (searchPattern == "T.") {
# arbitrarily replace Trace level as one fifth of the minimum
replaceWith = ((as.numeric(x) %>% min(na.rm = T)) / 5) %>% as.character()
} else if (searchPattern == "n.d.") {
# arbitrarily set non-detected level as content being zero
replaceWith = "0"
} else if (searchPattern == "LOD") {
# for content whose UV absorption beyond instrument limit, set as double of the maximum value
replaceWith = ((as.numeric(x) %>% max(na.rm = T)) * 2) %>% as.character()
}
if (is.na(replaceWith)) { return(x) } else { # only performnce replacement when with special values
x = str_replace_all(x, pattern = searchPattern, replacement = replaceWith)
return(x)
}
}
dd = d[, -c(1:4)]
dd = apply(dd, 2, vectorReplace, searchPattern = "T.")
dd = apply(dd, 2, vectorReplace, searchPattern = "n.d.")
dd = apply(dd, 2, vectorReplace, searchPattern = "LOD") %>% as_tibble()
d = cbind(d[, c(1:4)], # sample id information
apply(dd, 2, as.numeric) %>% as_tibble()) %>% # content in numeric values
as_tibble()
# convert code into ordered factor, in descending order of 1, 2, 3....
d$code = d$code %>% factor(levels = d$code, ordered = T)
d$code = d$code %>% factor(levels = rev(d$code), ordered = T)</code></pre>
</div>
<div id="exploratory-data-analysis-eda" class="section level1">
<h1><span class="header-section-number">3</span> Exploratory data analysis (EDA)</h1>
<div id="distribution-plot" class="section level2">
<h2><span class="header-section-number">3.1</span> Distribution plot</h2>
<pre class="r"><code>plt.contentDistribution = d %>% gather(-c(1:4), key = compounds, value = content) %>%
ggplot(aes(x = content, fill = type, color = type)) +
geom_density(alpha = .2) +
facet_wrap(~compounds, scales = "free", nrow = 3) +
theme(legend.position = c(.9, .15))
plt.contentDistribution</code></pre>
<p><img src="LemonMLscript_files/figure-html/unnamed-chunk-5-1.png" width="960" /></p>
</div>
<div id="feature-correlation-plot" class="section level2">
<h2><span class="header-section-number">3.2</span> feature correlation plot</h2>
<pre class="r"><code>func.plotCorrelation = function(whichType, title){
d %>% filter(type == whichType) %>%
select(-c(1:4)) %>% cor() %>%
ggcorrplot(hc.order = T, method = "circle", colors = c("Firebrick", "white", "Steelblue") %>% rev()) +
coord_equal() + theme(axis.text = element_text(colour = "black"), title = element_text(face = "bold"))
}
func.plotCorrelation(whichType = "authentic_L_J") + ggtitle("Correlation matrix - Authentic lemon juice")</code></pre>
<p><img src="LemonMLscript_files/figure-html/unnamed-chunk-6-1.png" width="672" /></p>
<pre class="r"><code>func.plotCorrelation(whichType = "lemonade") + ggtitle("Correlation matrix - Commercial lemonade beverages")</code></pre>
<p><img src="LemonMLscript_files/figure-html/unnamed-chunk-6-2.png" width="672" /></p>
</div>
<div id="pca" class="section level2">
<h2><span class="header-section-number">3.3</span> PCA</h2>
<pre class="r"><code>mat.scaled = d %>% select(-c(code, Sample, type, character)) %>% scale()
cov.matrix = cov(mat.scaled)
eigens = eigen(cov.matrix) # eigenvectors and values of covariance matrix
eigen.values = eigens$values
eigen.vectorMatrix = eigens$vectors
PC = mat.scaled %*% eigen.vectorMatrix # principle component matrix
colnames(PC) = paste0("PC", 1:ncol(PC)) # add PC's as column names
PC = d.PC = cbind(d[, 1:4], PC) %>% as_tibble()
PC %>% ggplot(aes(x = PC1, y = PC2, color = type)) +
geom_point(position = position_jitter(.1, .1), shape = 21, fill = "white") +
# geom_text(aes(label = code)) +
scale_color_startrek() +
labs(x = paste0("PC1, ", round(eigen.values[1]/sum(eigen.values)* 100, 1), "% explained"),
y = paste0("PC2, ", round(eigen.values[2]/sum(eigen.values)* 100, 1), "% explained")) +
coord_equal()</code></pre>
<p><img src="LemonMLscript_files/figure-html/unnamed-chunk-7-1.png" width="768" /></p>
<pre class="r"><code># 3D PCA
# link: https://rpubs.com/Boyuan/lemon_juice_3D_PCA
plot_ly(PC, x = ~ PC1, y = ~PC2, z = ~PC3, color = ~ type) %>%
add_markers() %>%
layout(title = '3D Interactive PCA',
scene = list(
xaxis = list(title = paste0("PC1, ", round(eigen.values[1]/sum(eigen.values)* 100, 1), "% explained")),
yaxis = list(title = paste0("PC2, ", round(eigen.values[2]/sum(eigen.values)* 100, 1), "% explained")),
zaxis = list(title = paste0("PC3, ", round(eigen.values[3]/sum(eigen.values)* 100, 1), "% explained"))
)
)</code></pre>
<div id="htmlwidget-5d05eac75555269eefd0" style="width:768px;height:768px;" class="plotly html-widget"></div>
<script type="application/json" data-for="htmlwidget-5d05eac75555269eefd0">{"x":{"visdat":{"10eff7e72ab29":["function () ","plotlyVisDat"]},"cur_data":"10eff7e72ab29","attrs":{"10eff7e72ab29":{"x":{},"y":{},"z":{},"color":{},"alpha_stroke":1,"sizes":[10,100],"spans":[1,20],"type":"scatter3d","mode":"markers","inherit":true}},"layout":{"margin":{"b":40,"l":60,"t":25,"r":10},"title":"3D Interactive PCA","scene":{"xaxis":{"title":"PC1, 38.1% explained"},"yaxis":{"title":"PC2, 13.4% explained"},"zaxis":{"title":"PC3, 9.9% explained"}},"hovermode":"closest","showlegend":true},"source":"A","config":{"showSendToCloud":false},"data":[{"x":[1.29245608021602,0.247327318026684,-2.56149506852184,1.02216854811322,1.02144854861423,0.221324174361603,-0.349045041869286,-0.38581323603689,-1.4821455186857,-2.37404641039611,-2.47684985252583,-3.72650845128052,0.153931476992609,-0.941729558563705,-1.50068529531973,-2.10972450438429,-2.64980884826357,2.13613894537144,-2.37418031730669,0.478180094023784,1.845971833046,-1.45374887861705,1.19418232583957,1.91430361040799,0.066834320382271,1.2127175590955,1.76579567376996],"y":[0.695526168184717,0.590944665242343,-4.1645585667584,1.13948649493847,1.04367370014434,1.38230502942391,-1.98630912501223,1.93770321135043,2.36212232905973,2.14999681352786,2.34829500113664,2.18440733827298,2.75578768016132,3.13716969340722,3.00971177877454,2.81693148679536,1.91489823211499,-1.06640858061311,-2.80357152637204,-0.748953948325587,-1.05436264362873,-2.33095577365992,0.00625489147679137,-0.325453367664005,-1.10722803571808,-0.0557751287201965,0.467505744789272],"z":[-0.153272397784193,-1.07588827668465,4.68854824204557,0.786203717659978,0.029601316090255,0.219153679839619,-3.60423289888726,1.2676637692362,0.708759504389941,1.53239208288905,1.28333869274744,0.31955812246784,1.06207167374108,0.748548555977624,0.877678989830995,1.23804936420199,0.0231827277148735,2.34709583631241,0.298763599570472,-0.868563972996611,1.19368249250316,0.431635919627839,0.141387674072584,1.72946532281876,0.424389806543768,-0.570694829818461,0.0592676898020226],"type":"scatter3d","mode":"markers","name":"adulterated_L_J","marker":{"color":"rgba(102,194,165,1)","line":{"color":"rgba(102,194,165,1)"}},"textfont":{"color":"rgba(102,194,165,1)"},"error_y":{"color":"rgba(102,194,165,1)"},"error_x":{"color":"rgba(102,194,165,1)"},"line":{"color":"rgba(102,194,165,1)"},"frame":null},{"x":[1.11105606348818,0.603039915546309,1.21353582832768,-1.35787019158325,0.19225080551594,-1.21246667581881,-1.45178082404376,-5.68026361836666,-3.16377269996762,-5.02990803003648,-4.96543833095703,-6.93055161425824,-3.2136386608419,-2.25524613183358,-1.90423074658712,-2.40873185573606,-4.16866825809589,-1.24964086402868,0.185187190398568,-2.99485684015602,0.111484893291767,-0.858635390662749,-1.54239194864953,2.07225720546971,1.83438570934901,1.77479111647483],"y":[-0.0859376154201105,-0.142252660854825,0.339587586095071,-0.152230195818979,0.345390365706661,0.260723038277785,-0.00618989387332358,-3.30564951725206,0.580460783900814,-0.00170437349004221,-2.46999529348503,0.183283634350539,-0.808450531398731,-0.558153587576732,-0.36941259219531,-1.77940596421968,-0.563238916320843,0.390317817157598,0.475794889065444,0.429704166707622,0.422730012901104,-0.0546266942913341,0.785547893407879,-0.920957728673648,-0.666756609984423,0.169127635494428],"z":[-0.817328459989141,-0.858211461675529,-0.629340350344767,-2.09800451069364,-1.18016988208466,-1.52645098158561,-1.4207164898772,-0.0830469642365655,-2.06787066093538,-1.90858964613215,-0.3866152999683,1.25046058688634,0.720261245486266,0.527260458222733,0.329804314863947,-0.544993314502189,0.557635333107548,-0.665821738241084,-0.782414382679238,-1.09934787994972,-0.993179712086061,-0.412911159184163,-0.747363795423164,2.28559867183411,1.56272953670896,0.0752991087137491],"type":"scatter3d","mode":"markers","name":"authentic_L_J","marker":{"color":"rgba(252,141,98,1)","line":{"color":"rgba(252,141,98,1)"}},"textfont":{"color":"rgba(252,141,98,1)"},"error_y":{"color":"rgba(252,141,98,1)"},"error_x":{"color":"rgba(252,141,98,1)"},"line":{"color":"rgba(252,141,98,1)"},"frame":null},{"x":[2.05714649351934,2.38757879319326,1.98706631927528,2.46898400690317,1.73913538312126,2.45951764380522,2.38254770319144,2.34711033045327,2.30378739310736,1.75433161273427,1.96369864134024,2.10522487111011,2.21860197339323,2.04435906039219,2.0544860415976,2.215836416796,2.68064964050441,2.25770659306511,1.49205524911911,1.67135779863506,1.90309179689125,2.3097740202158,1.98329764936216,2.31575899554558],"y":[0.423955238003994,0.00123198464260368,-0.700231723171998,0.556190798634687,-0.359181579935747,0.890399063146194,-0.108716821513531,0.395998235607263,0.463757866049253,-0.567813941502302,-0.870631862914607,-0.134451071866694,0.0869403450654771,-0.699917351924463,-0.0693727358762944,-0.0841103318097234,-1.84151340759914,0.334099918173264,-1.29982933293597,-1.17283776144364,-0.368996368680066,-0.588016740559321,-0.74470679201939,-0.339094836108358],"z":[-0.00271240614489784,-0.365869855855512,0.601645728672797,0.612065746738997,-0.35782594284662,0.883021326687573,-0.421366100870039,-0.225735328927382,-0.0744704279938564,-0.649403277140523,-0.977850240900579,-0.786210754766569,-0.226044698531477,-0.224402923208373,-0.615530933647594,-0.473465885341308,2.06979052487044,-0.17176827268735,-0.583666225719361,-1.24209006725691,-0.399331584083848,0.290684984898261,-0.249974151851627,-0.633948204241613],"type":"scatter3d","mode":"markers","name":"lemonade","marker":{"color":"rgba(141,160,203,1)","line":{"color":"rgba(141,160,203,1)"}},"textfont":{"color":"rgba(141,160,203,1)"},"error_y":{"color":"rgba(141,160,203,1)"},"error_x":{"color":"rgba(141,160,203,1)"},"line":{"color":"rgba(141,160,203,1)"},"frame":null}],"highlight":{"on":"plotly_click","persistent":false,"dynamic":false,"selectize":false,"opacityDim":0.2,"selected":{"opacity":1},"debounce":0},"shinyEvents":["plotly_hover","plotly_click","plotly_selected","plotly_relayout","plotly_brushed","plotly_brushing","plotly_clickannotation","plotly_doubleclick","plotly_deselect","plotly_afterplot","plotly_sunburstclick"],"base_url":"https://plot.ly"},"evals":[],"jsHooks":[]}</script>
</div>
<div id="lda-full-data" class="section level2">
<h2><span class="header-section-number">3.4</span> LDA (full data)</h2>
<div id="scatterplot" class="section level3">
<h3><span class="header-section-number">3.4.1</span> Scatterplot</h3>
<pre class="r"><code>d2 = cbind(type = d$type, mat.scaled %>% as.tibble()) %>% as_tibble()
# LDA model
EDA.mdl.lda = lda(data = d2, type ~., prior = rep(1/3, 3))
EDA.lda = cbind(type.predicted = predict(EDA.mdl.lda)$class, # labels predicted
type.actual = d2$type, # labels actual
code = d$code, # unique sequential sample code
predict(EDA.mdl.lda)$x %>% as_tibble() ) %>% # 1st and 2nd discriminant
mutate(status = type.predicted == type.actual) %>%
as_tibble()
# EDA.lda
# actual separation
plt.lda.actual = EDA.lda %>%
ggplot(aes(x = LD1, y = LD2, col = type.actual)) +
# confidence ellipse as background
stat_ellipse(level = .8, linetype = "dashed") +
# add sample labels
geom_text(aes(label = code), fontface = "bold", size = 3) +
labs(title = "Actual classification") +
# theme
theme(legend.position = "bottom") +
scale_color_manual(values = color.types) +
scale_fill_manual(values = color.types)
# plt.lda.actual
# predicted separation
plt.lda.predicted =
# correct prediction
EDA.lda %>% filter(status == T) %>%
ggplot(aes(x = LD1, y = LD2, col = type.predicted)) +
# confidence ellipse as background
stat_ellipse(level = .8, linetype = "dashed") +
# add sample labels
geom_text(aes(label = code), fontface = "bold", size = 3) +
labs(title = "Predicted classification") +
# false prediction
geom_label_repel(data = EDA.lda %>% filter(status == F),
aes(label = code, fill = type.predicted),
color = "white", fontface = "bold", label.size = 0) + # no border line
# theme
theme(legend.position = "bottom") +
scale_color_manual(values = color.types) +
scale_fill_manual(values = color.types) +
annotate(geom = "text", label = "Squared numbers indicate \nincorrect predictions.",
x = 1.5, y = 2.1, fontface = "bold", size = 2.5)
# plt.lda.predicted</code></pre>
<pre class="r"><code>plt.lda.scatterPlot = plot_grid(plt.lda.actual, plt.lda.predicted, nrow = 1,
labels = c("A", "B"))
plt.lda.scatterPlot</code></pre>
<p><img src="LemonMLscript_files/figure-html/unnamed-chunk-10-1.png" width="1152" /></p>
</div>
<div id="decision-boundary" class="section level3">
<h3><span class="header-section-number">3.4.2</span> Decision boundary</h3>
<pre class="r"><code># mark decision boundary based on full data
LDcenter = EDA.lda %>%
group_by(type.actual) %>%
summarise(LD1.mean = mean(LD1), LD2.mean = mean(LD2))
LDcenter.adulterated = LDcenter[1, 2:3]
LDcenter.authentic = LDcenter[2, 2:3]
LDcenter.commercial = LDcenter[3, 2:3]
LD1.min = EDA.lda$LD1 %>% min()
LD1.max = EDA.lda$LD1 %>% max()
LD2.min = EDA.lda$LD2 %>% min()
LD2.max = 2.5 # EDA.lda$LD2 %>% max()
gridDensity = 100
grid.LD1 = seq(LD1.min, LD1.max, length.out = gridDensity)
grid.LD2 = seq(LD2.min, LD2.max, length.out = (LD2.max - LD2.min) / (LD1.max - LD1.min) * gridDensity )
grid.LD = expand.grid(LD1 = grid.LD1, LD2 = grid.LD2)
dist.adulterated = grid.LD %>% apply(1, function(x) ( (x - LDcenter.adulterated)^2 ) %>% sum() )
dist.authentic = grid.LD %>% apply(1, function(x) ( (x - LDcenter.authentic)^2 ) %>% sum() )
dist.commercial = grid.LD %>% apply(1, function(x) ( (x - LDcenter.commercial)^2 ) %>% sum() )
grid.LD = grid.LD %>%
mutate(dist.adulterated = dist.adulterated,
dist.authentic = dist.authentic,
dist.commercial = dist.commercial)
grid.LD = grid.LD %>%
mutate(boundary = apply(grid.LD[, 3:5], MARGIN = 1, FUN = which.min) %>% as.character())
grid.LD$boundary = grid.LD$boundary %>% str_replace(pattern = "1", replacement = "adulterated_L_J")
grid.LD$boundary = grid.LD$boundary %>% str_replace(pattern = "2", replacement = "authentic_L_J")
grid.LD$boundary = grid.LD$boundary %>% str_replace(pattern = "3", replacement = "lemonade")
# Redraw LDA scatter plot with decision boundary
plt.lda.boundary = grid.LD %>% rename(type.actual = boundary) %>%
ggplot(aes(x = LD1, y = LD2, color = type.actual)) +
geom_point(alpha = .2, shape = 19, size = .5) +
# geom_point(data = EDA.lda, inherit.aes = T) +
# confidence ellipse as background
stat_ellipse(data = EDA.lda, level = .8, linetype = "dashed") +
# add sample labels
geom_text(data = EDA.lda, aes(label = code), fontface = "bold", size = 3) +
geom_label(data = EDA.lda %>% filter(status != T), size = 3,
aes(label = code), label.r = unit(.5, "lines")) +
# theme
scale_color_manual(values = color.types) +
scale_fill_manual(values = color.types) +
theme(legend.position = "bottom", panel.grid = element_blank())
plt.lda.boundary</code></pre>
<p><img src="LemonMLscript_files/figure-html/unnamed-chunk-11-1.png" width="672" /></p>
<pre class="r"><code># grid.arrange(plt.lda.predicted, plt.lda.boundary, nrow = 2)</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="training-cross-validation-testing" class="section level2">
<h2><span class="header-section-number">4.1</span> Training & cross validation & testing</h2>
<div id="training-set" class="section level3">
<h3><span class="header-section-number">4.1.1</span> Training set</h3>
<pre class="r"><code># Data preparation
colnames(d) = colnames(d) %>% make.names() # ensure column names are suitable for ML
d$type = d$type %>% as.factor()
trainTest.split = d %>% initial_split(strata = "type", prop = .7, sed)
# training set
trainingSet.copy = training(trainTest.split) # as a copy of the training set
trainingSet = trainingSet.copy %>% select(-c(code, Sample, character)) # for machine learning training
trainingSet.scaled = trainingSet[, -1] %>% scale() %>% as_tibble() %>% # normalized data
mutate(type = trainingSet$type) %>% # add type
select(ncol(trainingSet), 1:(ncol(trainingSet)-1)) # put type as first column
# mean and standard deviation of each feature, for normalization of the test set
mean.vector = trainingSet[, -1] %>% apply(2, mean)
sd.vector = trainingSet[, -1] %>% apply(2, sd)</code></pre>
</div>
<div id="testing-set" class="section level3">
<h3><span class="header-section-number">4.1.2</span> Testing set</h3>
<pre class="r"><code># testing set, normalized based on mean and standard deviation of the training set
testingSet.copy = testing(trainTest.split) # as a copy of the testing set with additional sample info
testingSet = testingSet.copy %>% select(-c(code, Sample, character))
testingSet.scaled = testingSet %>% select(-type) %>% scale(center = mean.vector, scale = sd.vector) %>%
as_tibble() %>% mutate(type = testingSet$type) %>% # add actual type of the test set
select(ncol(testingSet), 1:(ncol(testingSet)-1)) # put type as first column</code></pre>
</div>
<div id="cross-validation-cv-folds" class="section level3">
<h3><span class="header-section-number">4.1.3</span> Cross-validation (CV) folds</h3>
<pre class="r"><code># CV-fold of the training set, for hyperparameter tune & model performance comparison
trainingSet.cv = trainingSet %>%
vfold_cv(v = 5) %>%
mutate(train = map(.x = splits, .f = ~training(.x)),
validate = map(.x = splits, .f = ~testing(.x)))
# scale training and validation fold (based on the corresponding training fold)
trainingSet.cv.scaled = trainingSet.cv %>%
mutate(train.mean = map(.x = train, .f = ~ apply(.x[, -1], 2, mean)),
train.sd = map(.x = train, .f = ~ apply(.x[, -1], 2, sd)),
# wrap mean and std into a list: 1st mean; 2nd std (or instead use pmap function for succinct coding)
train.mean.sd = map2(.x = train.mean, .y = train.sd, .f = ~list(.x, .y)),
# normalize training; note type as the last column
train.scaled = map(.x = train, .f = ~ .x[, -1] %>% scale() %>% as_tibble() %>% mutate(type = .x$type) ),
# normalize validation fold based corresponding training fold; note type as the last column
validate.scaled = map2(.x = validate, .y = train.mean.sd,
.f = ~ .x[, -1] %>% scale(center = .y[[1]], scale = .y[[2]]) %>% as_tibble() %>% mutate(type = .x$type) ),
# actual validation result
validate.actual = map(.x = validate.scaled, .f = ~.x$type)
) %>%
select(-c(train, validate, train.mean, train.sd, splits))
trainingSet.cv.scaled</code></pre>
<pre><code>## # A tibble: 5 x 5
## id train.mean.sd train.scaled validate.scaled validate.actual
## <chr> <named list> <named list> <named list> <named list>
## 1 Fold1 <list [2]> <tibble [44 × 15]> <tibble [11 × 15]> <fct [11]>
## 2 Fold2 <list [2]> <tibble [44 × 15]> <tibble [11 × 15]> <fct [11]>
## 3 Fold3 <list [2]> <tibble [44 × 15]> <tibble [11 × 15]> <fct [11]>
## 4 Fold4 <list [2]> <tibble [44 × 15]> <tibble [11 × 15]> <fct [11]>
## 5 Fold5 <list [2]> <tibble [44 × 15]> <tibble [11 × 15]> <fct [11]></code></pre>
</div>
</div>
<div id="support-vector-machine-svm" class="section level2">
<h2><span class="header-section-number">4.2</span> Support vector machine (SVM)</h2>
<div id="cv" class="section level3">
<h3><span class="header-section-number">4.2.1</span> CV</h3>
<div id="radial-kernal" class="section level4">
<h4><span class="header-section-number">4.2.1.1</span> Radial kernal</h4>
<pre class="r"><code># Support vector machine -----
# Radial kernal
gammaTune = 10^seq(from = -6, to = 2, by = .5)
costTune.radial = 10^seq(from = -2, to = 5, by = .5)
d.CV.SVM.radial = trainingSet.cv.scaled %>%
# factorial combination of gamma and cost to tune
crossing(gamma = gammaTune, cost = costTune.radial) %>%
mutate(hyperParameter = map2(.x = gamma, .y = cost, .f = ~list(.x, .y) ),
# cross validation, set up model for each training fold
model = map2(.x = train.scaled, .y = hyperParameter,
.f = ~svm(data = .x, type ~., gamma = .y[[1]], cost = .y[[2]],
type = "C-classification", kernel = "radial")),
validate.fitted = map2(.x = model, .y = validate.scaled, .f = ~predict(.x, .y)))
# Def func. comparing validation fold actual label vs. fitted label
func.cv.prediction = function(dataset){
dataset %>% mutate(
# Note that "validate.fitted" term is outside the function, separately specified by different models due to syntax difference
# Note that the term "validate.fitted" should be used uniformly across different ML methods
# actual vs. predicted of the validation set
validate.fitted.vs.actual = map2(.x = validate.fitted, .y = validate.actual, .f = ~ .x == .y ),
accuracy = map_dbl(.x = validate.fitted.vs.actual, .f = ~ round(sum(.x) / length(.x) * 100, 3) ))
}
# predict on validation fold using prior defined function
d.CV.SVM.radial = d.CV.SVM.radial %>% func.cv.prediction()
# summarize radial kernel CV result
d.tune.svm.radial = d.CV.SVM.radial %>%
group_by(gamma, cost) %>%
summarise(accuracy.mean = mean(accuracy),
accuracy.sd = sd(accuracy)) %>%
arrange(desc(accuracy.mean))
d.tune.svm.radial</code></pre>
<pre><code>## # A tibble: 255 x 4
## # Groups: gamma [17]
## gamma cost accuracy.mean accuracy.sd
## <dbl> <dbl> <dbl> <dbl>
## 1 0.1 3.16 80.0 17.5
## 2 0.1 1 78.2 15.2
## 3 0.0316 10 76.4 19.9
## 4 0.1 10 76.4 18.9
## 5 0.01 31.6 74.5 17.5
## 6 0.0316 31.6 74.5 17.5
## 7 0.1 31.6 74.5 17.5
## 8 0.1 100 74.5 19.7
## 9 0.1 316. 74.5 19.7
## 10 0.1 1000 74.5 19.7
## # … with 245 more rows</code></pre>
<pre class="r"><code># Func. def: plotting SVM hyper-parameter tuning result
func.plot.tune.HyperParam = function( data, hyper1, hyper2){
# hyper 1 = "gamma" for radial, or "degree" for polynomial; hyper2 = "cost" for SVM
data %>% ggplot(aes_string(x = hyper1, y = hyper2, 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())
}
plt.svm.tune.radial =
d.tune.svm.radial %>% func.plot.tune.HyperParam(hyper1 = "gamma", hyper2 = "cost") +
scale_x_log10(breaks = gammaTune, labels = log10(gammaTune) ) +
scale_y_log10(breaks = costTune.radial, labels = log10(costTune.radial) ) +
labs(x = "gamma, 10 ^ X", y = "cost, 10 ^ X", title = "SVM Radial Kernel")
plt.svm.tune.radial</code></pre>
<p><img src="LemonMLscript_files/figure-html/unnamed-chunk-15-1.png" width="672" /></p>
</div>
<div id="polynomial-kenel" class="section level4">
<h4><span class="header-section-number">4.2.1.2</span> Polynomial kenel</h4>
<pre class="r"><code>polynomialDegree = 2:7
costTune.polynomial = 10^seq(from = -2, to = 5, by = .5)
d.CV.SVM.polynomial = trainingSet.cv.scaled %>%
# factorial combination of polynomial degree and cost to tune
crossing(degree = polynomialDegree, cost = costTune.polynomial) %>%
mutate(hyperParameter = map2(.x = degree, .y = cost, .f = ~list(.x, .y) ),
# cross validation, set up model for each training fold
model = map2(.x = train.scaled, .y = hyperParameter,
.f = ~svm(data = .x, type ~., degree = .y[[1]], cost = .y[[2]],
type = "C-classification", kernel = "polynomial")),
validate.fitted = map2(.x = model, .y = validate.scaled, .f = ~predict(.x, .y)))
# predict on validation fold using prior defined function
d.CV.SVM.polynomial = d.CV.SVM.polynomial %>% func.cv.prediction()
# summarize tune result of polynomial kernel
d.tune.svm.polynomial = d.CV.SVM.polynomial %>%
group_by(degree, cost) %>%
summarise(accuracy.mean = mean(accuracy),
accuracy.sd = sd(accuracy)) %>%
arrange(desc(accuracy.mean))
d.tune.svm.polynomial</code></pre>
<pre><code>## # A tibble: 90 x 4
## # Groups: degree [6]
## degree cost accuracy.mean accuracy.sd
## <int> <dbl> <dbl> <dbl>
## 1 3 10 74.5 11.9
## 2 3 31.6 69.1 13.8
## 3 3 100 69.1 10.4
## 4 3 316. 69.1 10.4
## 5 3 1000 69.1 10.4
## 6 3 3162. 69.1 10.4
## 7 3 10000 69.1 10.4
## 8 3 31623. 69.1 10.4
## 9 3 100000 69.1 10.4
## 10 5 100 69.1 13.8
## # … with 80 more rows</code></pre>
<pre class="r"><code># plot tune result of polynomial kernel
plt.svm.tune.polynomial =
d.tune.svm.polynomial %>% func.plot.tune.HyperParam(hyper1 = "degree", hyper2 = "cost") +
scale_x_continuous(breaks = polynomialDegree) +
scale_y_log10(breaks = costTune.polynomial, labels = log10(costTune.polynomial) ) +
labs(x = "Degree", y = "Cost, 10 ^ X", title = "SVM Polynomial Kernel")
plt.svm.tune.polynomial</code></pre>
<p><img src="LemonMLscript_files/figure-html/unnamed-chunk-16-1.png" width="672" /></p>
</div>
<div id="linear-kernel" class="section level4">
<h4><span class="header-section-number">4.2.1.3</span> Linear kernel</h4>
<pre class="r"><code>costTune.linear = 10^seq(from = -2, to = 5, by = .5)
d.CV.SVM.linear = trainingSet.cv.scaled %>%
crossing(cost = costTune.linear) %>%
mutate(model = map2(.x = train.scaled, .y = cost,
.f = ~svm(data = .x, type ~., cost = .y,
type = "C-classification", kernel = "linear")),
validate.fitted = map2(.x = model, .y = validate.scaled, .f = ~predict(.x, .y)))
d.CV.SVM.linear = d.CV.SVM.linear %>% func.cv.prediction()
d.tune.svm.linear = d.CV.SVM.linear %>%
group_by(cost) %>%
summarise(accuracy.mean = mean(accuracy),
accuracy.sd = sd(accuracy)) %>%
arrange(desc(accuracy.mean))
d.tune.svm.linear</code></pre>
<pre><code>## # A tibble: 15 x 3
## cost accuracy.mean accuracy.sd
## <dbl> <dbl> <dbl>
## 1 0.316 63.6 18.2
## 2 1 63.6 20.3
## 3 3.16 63.6 20.3
## 4 0.1 61.8 14.9
## 5 10 56.4 17.5
## 6 31.6 56.4 17.5
## 7 100 56.4 17.5
## 8 316. 56.4 19.7
## 9 0.0316 54.5 17.0
## 10 1000 54.5 20.3
## 11 3162. 50.9 23.7
## 12 10000 50.9 23.7
## 13 31623. 50.9 23.7
## 14 100000 50.9 23.7
## 15 0.01 41.8 19.9</code></pre>
<pre class="r"><code>d.tune.svm.linear %>% ggplot(aes(x = cost, y = accuracy.mean)) +
geom_bar(stat = "identity", alpha = .8) + geom_point() + geom_line() +
scale_x_log10() </code></pre>
<p><img src="LemonMLscript_files/figure-html/unnamed-chunk-17-1.png" width="672" /></p>
<pre class="r"><code>k1 = d.tune.svm.radial[1, 3:4] %>% mutate(kernel = "radial")
k2 = d.tune.svm.polynomial[1, 3:4] %>% mutate(kernel = "polynomial") # best degree 3
k3 = d.tune.svm.linear[1, 2:3] %>% mutate(kernel = "linear")
rbind(k1, k2, k3)</code></pre>
<pre><code>## # A tibble: 3 x 3
## accuracy.mean accuracy.sd kernel
## <dbl> <dbl> <chr>
## 1 80.0 17.5 radial
## 2 74.5 11.9 polynomial
## 3 63.6 18.2 linear</code></pre>
<pre class="r"><code>cv.svm = k1 %>% mutate(model = "SVM")</code></pre>
</div>
</div>
<div id="training-testing" class="section level3">
<h3><span class="header-section-number">4.2.2</span> Training & testing</h3>
<pre class="r"><code>mdl.svm = svm(data = trainingSet.scaled, type ~.,
gamma = d.tune.svm.radial$gamma[1], cost = d.tune.svm.radial$cost[1],
kernel = "radial", type = "C-classification")
accuracy.training.svm = sum(predict(mdl.svm) == trainingSet.scaled$type) / nrow(trainingSet.scaled)*100
cat("Accuracy on the training set is", accuracy.training.svm, "%.")</code></pre>
<pre><code>## Accuracy on the training set is 96.36364 %.</code></pre>
<pre class="r"><code>accuracy.testing.svm = sum(predict(mdl.svm, newdata = testingSet.scaled) == testingSet.scaled$type) / nrow(testingSet.scaled) *100
cat("Accuracy on the testing set is", accuracy.testing.svm, "%.")</code></pre>
<pre><code>## Accuracy on the testing set is 81.81818 %.</code></pre>
<pre class="r"><code># confusion matrix
predict.SVM = predict(mdl.svm, newdata = testingSet.scaled)
# Def. func: converting confusion table into tibble format
func.tidyConfusionTable = function(table, modelName){
tb = table %>% as.data.frame() %>% spread(Var2, value = Freq) %>% mutate(model = modelName)
colnames(tb) = colnames(tb) %>% str_extract(pattern = one_or_more(WRD) )
return(tb)
}
cf.svm = table(predict.SVM, testingSet.scaled$type) %>%
func.tidyConfusionTable(modelName = "SVM")</code></pre>
</div>
</div>
<div id="linear-discriminant-analysis-lda" class="section level2">
<h2><span class="header-section-number">4.3</span> Linear discriminant analysis (LDA)</h2>
<div id="cv-1" class="section level3">
<h3><span class="header-section-number">4.3.1</span> CV</h3>
<pre class="r"><code># Cross validation performance (checking performance only, not for hyper-param tune)
d.CV.LDA = trainingSet.cv.scaled %>%
mutate(model = map(.x = train.scaled, .f = ~lda(data = .x, type ~ ., prior = rep(1/3, 3))),
validate.fitted = map2(.x = model, .y = validate.scaled, .f = ~predict(.x, newdata = .y)$class)) %>%
func.cv.prediction()
cv.LDA = data.frame(accuracy.mean = d.CV.LDA$accuracy %>% mean(),
accuracy.sd = d.CV.LDA$accuracy %>% sd()) %>%
mutate(model = "LDA")</code></pre>
</div>
<div id="training-testing-1" class="section level3">
<h3><span class="header-section-number">4.3.2</span> Training & testing</h3>
<pre class="r"><code># set up model on entire training set
mdl.lda = lda(data = trainingSet.scaled, type ~., prior = rep(1/3, 3))
# Prediction on the training set
accuracy.training.LDA = sum(predict(mdl.lda)$class == trainingSet.scaled$type) / nrow(trainingSet.scaled) * 100
cat("Accuracy on the training set by Linear Discriminant Analysis is", accuracy.training.LDA, "%." )</code></pre>
<pre><code>## Accuracy on the training set by Linear Discriminant Analysis is 83.63636 %.</code></pre>
<pre class="r"><code># Prediction on the testing set
fitted.lda = predict(mdl.lda, newdata = testingSet.scaled)
predict.LDA = fitted.lda$class
cf.lda = table(predict.LDA, testingSet.scaled$type) %>%
func.tidyConfusionTable(modelName = "LDA")
accuracy.testing.lda = sum(predict(mdl.lda, newdata = testingSet.scaled)$class == testingSet.scaled$type) / nrow(testingSet.scaled) * 100
cat("Accuracy on the testing set by Linear Discriminant Analysis is", accuracy.testing.lda, "%.")</code></pre>
<pre><code>## Accuracy on the testing set by Linear Discriminant Analysis is 81.81818 %.</code></pre>
<pre class="r"><code># probability distribution sample-wise
d.prob.lda = fitted.lda$posterior %>% as_tibble() %>% mutate(model = "LDA")</code></pre>
</div>
</div>
<div id="random-forest" class="section level2">
<h2><span class="header-section-number">4.4</span> Random forest</h2>
<div id="cv-2" class="section level3">
<h3><span class="header-section-number">4.4.1</span> CV</h3>
<pre class="r"><code>featuresTune = 2:8