-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation.html
More file actions
1068 lines (933 loc) · 51.3 KB
/
Copy pathvalidation.html
File metadata and controls
1068 lines (933 loc) · 51.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Smile - Model Validation</title>
<meta name="description" content="Statistical Machine Intelligence and Learning Engine">
<!-- Bootstrap 5 + Bootswatch Cerulean -->
<link href="https://cdn.jsdelivr.net/npm/bootswatch@5.3.3/dist/cerulean/bootstrap.min.css" rel="stylesheet">
<link href="css/custom.css" rel="stylesheet">
<!-- Prism syntax highlighting (vendored for offline / file:// viewing) -->
<link href="css/prism.min.css" rel="stylesheet">
<!-- Table of contents -->
<link rel="stylesheet" href="css/pager.css" type="text/css" />
<link rel="stylesheet" href="css/toc.css" type="text/css" />
<!-- Vega-Lite Embed -->
<script src="https://cdn.jsdelivr.net/npm/vega@5"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite@5"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-embed@7"></script>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-57GD08QCML"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-57GD08QCML');
</script>
</head>
<body>
<div class="container site-container">
<header class="site-header">
<div class="masthead">
<p class="lead mb-0">
<a href="index.html" class="masthead-link">
<img src="images/smile.jpg" alt="SMILE logo" class="masthead-logo">
<span class="tagline">SMILE — Statistical Machine Intelligence and Learning Engine</span>
</a>
</p>
</div>
<nav class="navbar navbar-expand-lg navbar-dark site-navbar">
<div class="container-fluid px-0">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbar-collapse"
aria-controls="navbar-collapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="navbar-nav">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">Overview</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="quickstart.html">Quick Start</a></li>
<li><a class="dropdown-item" href="overview.html">What's Machine Learning</a></li>
<li><a class="dropdown-item" href="data.html">Data Processing</a></li>
<li><a class="dropdown-item" href="visualization.html">Data Visualization</a></li>
<li><a class="dropdown-item" href="vegalite.html">Declarative Visualization</a></li>
<li><a class="dropdown-item" href="gallery.html">Gallery</a></li>
<li><a class="dropdown-item" href="faq.html">FAQ</a></li>
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">Supervised Learning</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="classification.html">Classification</a></li>
<li><a class="dropdown-item" href="regression.html">Regression</a></li>
<li><a class="dropdown-item" href="deep-learning.html">Deep Learning</a></li>
<li><a class="dropdown-item" href="feature.html">Feature Engineering</a></li>
<li><a class="dropdown-item" href="validation.html">Model Validation</a></li>
<li><a class="dropdown-item" href="missing-value-imputation.html">Missing Value Imputation</a></li>
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">Unsupervised Learning</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="clustering.html">Clustering</a></li>
<li><a class="dropdown-item" href="vector-quantization.html">Vector Quantization</a></li>
<li><a class="dropdown-item" href="association-rule.html">Association Rule Mining</a></li>
<li><a class="dropdown-item" href="mds.html">Multi-Dimensional Scaling</a></li>
<li><a class="dropdown-item" href="manifold.html">Manifold Learning</a></li>
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">LLM & NLP</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="llm.html">Large Language Model (LLM)</a></li>
<li><a class="dropdown-item" href="nlp.html">Natural Language Processing (NLP)</a></li>
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">Math</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="linear-algebra.html">Linear Algebra</a></li>
<li><a class="dropdown-item" href="statistics.html">Statistics</a></li>
<li><a class="dropdown-item" href="wavelet.html">Wavelet</a></li>
<li><a class="dropdown-item" href="interpolation.html">Interpolation</a></li>
<li><a class="dropdown-item" href="graph.html">Graph Data Structure</a></li>
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">API</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="api/java/index.html" target="_blank" rel="noopener">Java</a></li>
<li><a class="dropdown-item" href="api/scala/index.html" target="_blank" rel="noopener">Scala</a></li>
<li><a class="dropdown-item" href="api/kotlin/index.html" target="_blank" rel="noopener">Kotlin</a></li>
<li><a class="dropdown-item" href="api/json/index.html" target="_blank" rel="noopener">JSON</a></li>
<li><a class="dropdown-item" href="api/clojure/index.html" target="_blank" rel="noopener">Clojure</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link" href="https://mybinder.org/v2/gh/haifengl/smile/notebook?urlpath=lab%2Ftree%2Fshell%2Fsrc%2Funiversal%2Fnotebooks%2Findex.ipynb" target="_blank" rel="noopener">Try It Online</a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://github.com/haifengl/smile" target="_blank" rel="noopener">GitHub</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div id="content" class="row g-4 site-content">
<div class="col-md-3 order-md-last d-none d-md-block">
<div id="sidebar">
<div class="sidebar-toc" style="margin-bottom: 20px;">
<p class="toc-header">Contents</p>
<div id="toc"></div>
</div>
<div id="search">
<script>
(function() {
var cx = '010264411143030149390:ajvee_ckdzs';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:searchbox-only></gcse:searchbox-only>
</div>
</div>
</div>
<div class="col-md-9 order-md-first">
<h1 id="validation-top" class="title">Model Validation</h1>
<p>When training a supervised model, we should always evaluate the goodness of fit of
the model. This helps on model selection and also hyperparameter tuning.
First of all, we should note that the error of the model as measured
on the training data is likely to be lower than the actual generalization error.</p>
<h2 id="metrics">Evaluation Metrics</h2>
<p>Although most supervised learning algorithms try to minimize the empirical error
(regularized or not), we should not use only error rate or accuracy as the objective
measure. For example, if a highly unbalanced data contains 99% positive sample, a naive
algorithm that classifies everything as positive will have 99% accuracy. However,
it is useless.</p>
<p>For classification, Smile has the following evaluation metrics:</p>
<ul>
<li>The <b>accuracy</b> is the proportion of true results (both true positives and
true negatives) in the population.</li>
<li>The <b>sensitivity</b> or <b>true positive rate</b> (TPR) (also called <b>hit rate</b>, <b>recall</b>)
is a statistical measures of the performance of a binary classification test.
Sensitivity is the proportion of actual positives which are correctly identified as such.
<pre class="language-markup"><code class="language-markup">
TPR = TP / P = TP / (TP + FN)
</code></pre>
</li>
<li>The <b>specificity</b> (SPC) or <b>true negative rate</b> is a statistical measures of the performance
of a binary classification test. Specificity measures the proportion
of negatives which are correctly identified.
<pre class="language-markup"><code class="language-markup">
SPC = TN / N = TN / (FP + TN) = 1 - FPR
</code></pre>
</li>
<li>The <b>precision</b> or <b>positive predictive value</b> (PPV) is ratio of true positives
to combined true and false positives, which is different from sensitivity.
<pre class="language-markup"><code class="language-markup">
PPV = TP / (TP + FP)
</code></pre>
</li>
<li>The <b>false discovery rate</b> (FDR) is ratio of false positives
to combined true and false positives, which is actually 1 - precision.
<pre class="language-markup"><code class="language-markup">
FDR = FP / (TP + FP)
</code></pre>
</li>
<li><b>Fall-out, false alarm rate, or false positive rate</b> (FPR) is
<pre class="language-markup"><code class="language-markup">
FPR = FP / N = FP / (FP + TN)
</code></pre>
Fall-out is actually Type I error and closely related to specificity (1 - specificity).</li>
<li><p>The <b>F-score</b> (or <b>F-score</b>) considers both the precision and the recall of the test
to compute the score. The traditional or balanced F-score (F1 score) is the harmonic mean of
precision and recall, where an F1 score reaches its best value at 1 and worst at 0.</p>
<p>The general formula involves a positive real β so that F-score measures
the effectiveness of retrieval with respect to a user who attaches β times
as much importance to recall as precision.</p></li>
</ul>
<p>In Smile, the class label 1 is regarded as positive while 0 as negative. Note that
not all metrics can be applied to multi-class data. If one applies such a metric
(e.g. specificity and sensitivity) on multi-class data regardlessly, the results may
not make sense and all others are regarded as negative. Note that in these situations,
only label 1 is regarded as positive and any other values are treated as negative class.</p>
<p>The below example shows how to calculate the accuracy of a multi-class model.</p>
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#java_1" type="button" role="tab">Java</button></li>
<li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#scala_1" type="button" role="tab">Scala</button></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade" role="tabpanel" id="scala_1">
<div class="code" style="text-align: left;">
<pre class="language-scala"><code class="language-scala">
val segTrain = read.arff("data/weka/segment-challenge.arff")
val segTest = read.arff("data/weka/segment-test.arff")
val model = randomForest("class" ~ ".", segTrain)
val pred = model.predict(segTest)
smile> accuracy(segTest("class").toIntArray(), pred)
res5: Double = 0.9728395061728395
</code></pre>
</div>
</div>
<div class="tab-pane fade show active" role="tabpanel" id="java_1">
<div class="code" style="text-align: left;">
<pre class="language-java"><code class="language-java">
var segTrain = Read.arff("data/weka/segment-challenge.arff");
var segTest = Read.arff("data/weka/segment-test.arff");
var model = RandomForest.fit(Formula.lhs("class"), segTrain);
var pred = model.predict(segTest);
smile> Accuracy.of(segTest.column("class").toIntArray(), pred)
$161 ==> 0.9617283950617284
</code></pre>
</div>
</div>
</div>
<p>Sensitivity and specificity are closely related to the concepts of type I and type II errors.
For any test, there is usually a trade-off between the metrics. This trade-off
can be represented graphically using an ROC curve. When using normalized units, the area under
the ROC curve is equal to the probability that a classifier will rank a
randomly chosen positive instance higher than a randomly chosen negative
one (assuming 'positive' ranks higher than 'negative').</p>
<p>The following example calculates various metrics for a binary classification problem.</p>
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#java_2" type="button" role="tab">Java</button></li>
<li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#scala_2" type="button" role="tab">Scala</button></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade" role="tabpanel" id="scala_2">
<div class="code" style="text-align: left;">
<pre class="language-scala"><code class="language-scala">
val toyTrain = read.csv("data/classification/toy200.txt", delimiter="\t", header=false)
val toyTest = read.csv("data/classification/toy20000.txt", delimiter="\t", header=false)
val x = toyTrain.select(1, 2).toArray()
val y = toyTrain.column(0).toIntArray()
val model = logit(x, y, 0.1, 0.001)
val testx = toyTest.select(1, 2).toArray()
val testy = toyTest.column(0).toIntArray()
val pred = testx.map(model.predict(_))
smile> accuracy(testy, pred)
res7: Double = 0.81435
smile> recall(testy, pred)
res8: Double = 0.7828
smile> sensitivity(testy, pred)
res9: Double = 0.7828
smile> specificity(testy, pred)
res10: Double = 0.8459
smile> fallout(testy, pred)
res11: Double = 0.15410000000000001
smile> fdr(testy, pred)
res12: Double = 0.16447859963710107
smile> f1(testy, pred)
res13: Double = 0.808301925757654
// Calculate posteriori probability for AUC computation.
val posteriori = new Array[Double](2)
val prob = testx.map { x =>
model.predict(x, posteriori)
posteriori(1)
}
smile> auc(testy, prob)
res17: Double = 0.8650958
</code></pre>
</div>
</div>
<div class="tab-pane fade show active" role="tabpanel" id="java_2">
<div class="code" style="text-align: left;">
<pre class="language-java"><code class="language-java">
var toyTrain = Read.csv("data/classification/toy200.txt", CSVFormat.DEFAULT.withDelimiter('\t'));
var toyTest = Read.csv("data/classification/toy20000.txt", CSVFormat.DEFAULT.withDelimiter('\t'));
var x = toyTrain.select(1, 2).toArray();
var y = toyTrain.column(0).toIntArray();
var model = LogisticRegression.fit(x, y, 0.1, 0.001, 100);
var testx = toyTest.select(1, 2).toArray();
var testy = toyTest.column(0).toIntArray();
var pred = Arrays.stream(testx).mapToInt(xi -> model.predict(xi)).toArray();
smile> Accuracy.of(testy, pred)
$171 ==> 0.81435
smile> Recall.of(testy, pred)
$172 ==> 0.7828
smile> Sensitivity.of(testy, pred)
$173 ==> 0.7828
smile> Specificity.of(testy, pred)
$174 ==> 0.8459
smile> Fallout.of(testy, pred)
$175 ==> 0.15410000000000001
smile> FDR.of(testy, pred)
$176 ==> 0.16447859963710107
smile> FScore.F1.score(testy, pred)
$177 ==> 0.808301925757654
// Calculate posteriori probability for AUC computation.
var posteriori = new double[2];
var prob = Arrays.stream(testx).mapToDouble(xi -> {
model.predict(xi, posteriori);
return posteriori[1];
}).toArray();
smile> AUC.of(testy, prob)
$180 ==> 0.8650958
</code></pre>
</div>
</div>
</div>
<p>For regression, Smile has the following evaluation metrics:</p>
<ul>
<li>MSE (mean squared error) and RMSE (root mean squared error).</li>
<li>MAD (mean absolute deviation error).</li>
<li>RSS (residual sum of squares).</li>
</ul>
<h2 id="out-of-sample">Out-of-sample Evaluation</h2>
<p>The generalization error (also known as the out-of-sample error) is
a measure of how accurately an algorithm is able to predict outcome
values for previously unseen data. Ideally, test data should be
statistically independent of training data.
But in practice, we usually have only one historical dataset and
the evaluation of a learning algorithm may be sensitive to sampling error.
In what follows, we discuss various testing mechanisms.</p>
<p>We provide both Java and Scala helper functions for testing. The Java helper
functions are the static methods of the class <a href="api/java/smile/validation/Validation.html"><code>smile.validation.Validation</code></a>.
The Scala one are in the package object of <a href="api/scala/smile/validation/index.html"><code>smile.validation</code></a> and
can be accessed directly in the Shell.</p>
<h3 id="hold-out">Hold-out Testing</h3>
<p>Hold-out testing assume that all data
samples are independently and identically distributed (this is also
the basic assumption of most learning algorithms).
A part of the data is held out for testing. Many benchmark data
contain a separate test dataset.</p>
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#java_3" type="button" role="tab">Java</button></li>
<li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#scala_3" type="button" role="tab">Scala</button></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade" role="tabpanel" id="scala_3">
<div class="code" style="text-align: left;">
<pre class="language-scala"><code class="language-scala">
object validate {
def classification[T <: AnyRef, M <: Classifier[T]]
(x: Array[T], y: Array[Int], testx: Array[T], testy: Array[Int])
(trainer: => (Array[T], Array[Int]) => M): ClassificationValidation[M]
def classification[M <: DataFrameClassifier]
(formula: Formula, train: DataFrame, test: DataFrame)
(trainer: => (Formula, DataFrame) => M): ClassificationValidation[M]
def regression[T <: AnyRef, M <: Regression[T]]
(x: Array[T], y: Array[Double], testx: Array[T], testy: Array[Double])
(trainer: => (Array[T], Array[Double]) => M): RegressionValidation[M]
def regression[M <: DataFrameRegression]
(formula: Formula, train: DataFrame, test: DataFrame)
(trainer: => (Formula, DataFrame) => M): RegressionValidation[M]
}
</code></pre>
</div>
</div>
<div class="tab-pane fade show active" role="tabpanel" id="java_3">
<div class="code" style="text-align: left;">
<pre class="language-java"><code class="language-java">
public class ClassificationValidation {
public static <T, M extends Classifier<T>> ClassificationValidation<M>
of(T[] x, int[] y, T[] testx, int[] testy,
BiFunction<T[], int[], M> trainer);
public static <M extends DataFrameClassifier> ClassificationValidation<M>
of(Formula formula, DataFrame train, DataFrame test,
BiFunction<Formula, DataFrame, M> trainer);
}
public class RegressionValidation {
public static <T, M extends Regression<T>> RegressionValidation<M>
of(T[] x, double[] y, T[] testx, double[] testy,
BiFunction<T[], double[], M> trainer);
public static <M extends DataFrameRegression> RegressionValidation<M>
of(Formula formula, DataFrame train, DataFrame test,
BiFunction<Formula, DataFrame, M> trainer);
}
</code></pre>
</div>
</div>
</div>
<p>The above Scala methods takes a code block to train the model and apply it on the test data.
These methods return the trained model and print out various metrics.</p>
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#java_4" type="button" role="tab">Java</button></li>
<li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#scala_4" type="button" role="tab">Scala</button></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade" role="tabpanel" id="scala_4">
<div class="code" style="text-align: left;">
<pre class="language-scala"><code class="language-scala">
val segTrain = read.arff("data/weka/segment-challenge.arff")
val segTest = read.arff("data/weka/segment-test.arff")
val model = randomForest("class" ~ ".", segTrain)
val pred = model.predict(segTest)
smile> ConfusionMatrix.of(segTest("class").toIntArray(), pred)
val res10: smile.validation.metric.ConfusionMatrix =
ROW=truth and COL=predicted
class 0 | 124 | 0 | 0 | 0 | 1 | 0 | 0 |
class 1 | 0 | 110 | 0 | 0 | 0 | 0 | 0 |
class 2 | 3 | 0 | 117 | 1 | 1 | 0 | 0 |
class 3 | 1 | 0 | 0 | 109 | 0 | 0 | 0 |
class 4 | 1 | 0 | 6 | 2 | 117 | 0 | 0 |
class 5 | 0 | 0 | 0 | 0 | 0 | 94 | 0 |
class 6 | 0 | 0 | 1 | 2 | 0 | 0 | 120 |
</code></pre>
</div>
</div>
<div class="tab-pane fade show active" role="tabpanel" id="java_4">
<div class="code" style="text-align: left;">
<pre class="language-java"><code class="language-java">
var segTrain = Read.arff("data/weka/segment-challenge.arff");
var segTest = Read.arff("data/weka/segment-test.arff");
var formula = Formula.lhs("class");
var model = RandomForest.fit(formula, segTrain);
var pred = model.predict(segTest);
smile> ConfusionMatrix.of(formula.y(segTest).toIntArray(), pred)
$187 ==> ROW=truth and COL=predicted
class 0 | 124 | 0 | 0 | 0 | 1 | 0 | 0 |
class 1 | 0 | 110 | 0 | 0 | 0 | 0 | 0 |
class 2 | 3 | 0 | 115 | 1 | 3 | 0 | 0 |
class 3 | 2 | 0 | 0 | 106 | 2 | 0 | 0 |
class 4 | 2 | 0 | 10 | 6 | 108 | 0 | 0 |
class 5 | 0 | 0 | 0 | 0 | 0 | 94 | 0 |
class 6 | 2 | 0 | 1 | 0 | 0 | 0 | 120 |
</code></pre>
</div>
</div>
</div>
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#scala_5" type="button" role="tab">Scala</button></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade show active" role="tabpanel" id="scala_5">
<div class="code" style="text-align: left;">
<pre class="language-scala"><code class="language-scala">
val toyTrain = read.csv("data/classification/toy200.txt", delimiter="\t", header=false)
val toyTest = read.csv("data/classification/toy20000.txt", delimiter="\t", header=false)
val x = toyTrain.select(1, 2).toArray()
val y = toyTrain.column(0).toIntArray()
val testx = toyTest.select(1, 2).toArray()
val testy = toyTest.column(0).toIntArray()
smile> validate.classification(x, y, testx, testy) { case (x, y) => lda(x, y) }
val res13: smile.validation.ClassificationValidation[smile.classification.LDA] =
{
fit time: 360.135 ms,
score time: 22.309 ms,
validation data size: 20000,
error: 3755,
accuracy: 81.23%,
sensitivity: 78.28%,
specificity: 84.17%,
precision: 83.18%,
F1 score: 80.66%,
MCC: 62.56%,
AUC: 86.35%,
log loss: 0.4999
}
smile> validate.classification(x, y, testx, testy) { case (x, y) => logit(x, y, 0.1, 0.001) }
val res14: smile.validation.ClassificationValidation[smile.classification.LogisticRegression] =
{
fit time: 3.960 ms,
score time: 4.046 ms,
validation data size: 20000,
error: 3713,
accuracy: 81.44%,
sensitivity: 78.28%,
specificity: 84.59%,
precision: 83.55%,
F1 score: 80.83%,
MCC: 63.00%,
AUC: 86.51%,
log loss: 0.4907
}
</code></pre>
</div>
</div>
</div>
<h3 id="out-of-bag">Out-of-bag Error</h3>
<p>Out-of-bag (OOB) error, also called out-of-bag estimate, is a method of measuring
the prediction error of random forests, boosted decision trees, and other machine
learning models utilizing bootstrap aggregating to sub-sample data sampled used
for training. OOB is the mean prediction error on each training sample <code>x<sub>i</sub></code>, using
only the trees that did not have <code>x<sub>i</sub></code> in their bootstrap sample.</p>
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#java_6" type="button" role="tab">Java</button></li>
<li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#scala_6" type="button" role="tab">Scala</button></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade" role="tabpanel" id="scala_6">
<div class="code" style="text-align: left;">
<pre class="language-scala"><code class="language-scala">
val iris = read.arff("data/weka/iris.arff");
val rf = smile.classification.randomForest("class" ~ ".", iris)
println(s"OOB metrics = ${rf.metrics}")
</code></pre>
</div>
</div>
<div class="tab-pane fade show active" role="tabpanel" id="java_6">
<div class="code" style="text-align: left;">
<pre class="language-java"><code class="language-java">
var iris = Read.arff("data/weka/iris.arff");
var rf = smile.classification.RandomForest.fit(Formula.lhs("class"), iris);
System.out.println("OOB metrics = " + rf.metrics());
</code></pre>
</div>
</div>
</div>
<p>Subsampling allows one to define an out-of-bag estimate of the prediction performance
improvement by evaluating predictions on those observations which were not used
in the building of the next base learner. Out-of-bag estimates help avoid the
need for an independent validation dataset, but often underestimate actual
performance improvement and the optimal number of iterations.</p>
<h2 id="cross-validation">Cross Validation</h2>
<p>In <code>k</code>-fold cross validation, the dataset is divided into <code>k</code> random partitions.
We treat each of the <code>k</code> partition like a hold-out set, train a model on
the rest of data, and measure the quality of the model on the held-out.
The overall performance is taken to be the average of the performance
on all <code>k</code> partitions.</p>
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#java_7" type="button" role="tab">Java</button></li>
<li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#scala_7" type="button" role="tab">Scala</button></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade" role="tabpanel" id="scala_7">
<div class="code" style="text-align: left;">
<pre class="language-scala"><code class="language-scala">
object cv {
def classification[T <: AnyRef, M <: Classifier[T]](k: Int, x: Array[T], y: Array[Int])
(trainer: => (Array[T], Array[Int]) => M): ClassificationValidations[M]
def classification[M <: DataFrameClassifier](k: Int, formula: Formula, data: DataFrame)
(trainer: => (Formula, DataFrame) => M): ClassificationValidations[M]
def regression[T <: AnyRef, M <: Regression[T]](k: Int, x: Array[T], y: Array[Double])
(trainer: => (Array[T], Array[Double]) => M): RegressionValidations[M]
def regression[M <: DataFrameRegression](k: Int, formula: Formula, data: DataFrame)
(trainer: => (Formula, DataFrame) => M): RegressionValidations[M]
}
</code></pre>
</div>
</div>
<div class="tab-pane fade show active" role="tabpanel" id="java_7">
<div class="code" style="text-align: left;">
<pre class="language-java"><code class="language-java">
public class CrossValidation {
public static <T, M extends Classifier<T>> ClassificationValidations<M>
classification(int k, T[] x, int[] y, BiFunction<T[], int[], M> trainer);
public static <M extends DataFrameClassifier> ClassificationValidations<M>
classification(int k, Formula formula, DataFrame data, BiFunction<Formula, DataFrame, M> trainer);
public static <T, M extends Regression<T>> RegressionValidations<M>
regression(int k, T[] x, double[] y, BiFunction<T[], double[], M> trainer);
public static <M extends DataFrameRegression> RegressionValidations<M>
regression(int k, Formula formula, DataFrame data, BiFunction<Formula, DataFrame, M> trainer);
}
</code></pre>
</div>
</div>
</div>
<p>When no metrics are provided, the methods use accuracy or R2 by default
for classification or regression, respectively.</p>
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#java_8" type="button" role="tab">Java</button></li>
<li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#scala_8" type="button" role="tab">Scala</button></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade" role="tabpanel" id="scala_8">
<div class="code" style="text-align: left;">
<pre class="language-scala"><code class="language-scala">
smile> cv.classification(10, "class" ~ ".", iris) { case (formula, data) => smile.classification.cart(formula, data) }
val res16: smile.validation.ClassificationValidations[smile.classification.DecisionTree] =
{
fit time: 1.966 ms ± 1.764,
score time: 0.024 ms ± 0.024,
validation data size: 15 ± 0,
error: 1 ± 0,
accuracy: 95.33% ± 3.22,
cross entropy: 0.1858 ± 0.0729
}
</code></pre>
</div>
</div>
<div class="tab-pane fade show active" role="tabpanel" id="java_8">
<div class="code" style="text-align: left;">
<pre class="language-java"><code class="language-java">
smile> var cv = CrossValidation.classification(10, Formula.lhs("class"), iris, (formula, data) -> DecisionTree.fit(formula, data));
cv ==> {
fit time: 0.823 ms ± 0.471,
score time: 0.016 ms ± 0.015,
validation data size: 15 ± 0,
error: 1 ± 1,
accuracy: 94.00% ± 6.63,
cross entropy: 0.2473 ± 0.1981
}
</code></pre>
</div>
</div>
</div>
<p>On the Iris data, the accuracy estimation of 10-fold cross validation
is about 84.7%. You may get different number because of the random partitions.</p>
<p>A special case is the leave-one-out cross validation that uses a single observation
from the original sample as the validation data, and the remaining
observations as the training data. This is repeated such that each
observation in the sample is used once as the validation data.
Leave-one-out cross-validation is
usually very expensive from a computational point of view because of the
large number of times the training process is repeated.</p>
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#java_9" type="button" role="tab">Java</button></li>
<li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#scala_9" type="button" role="tab">Scala</button></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade" role="tabpanel" id="scala_9">
<div class="code" style="text-align: left;">
<pre class="language-scala"><code class="language-scala">
object loocv {
def classification[T <: AnyRef, M <: Classifier[T]](x: Array[T], y: Array[Int])
(trainer: => (Array[T], Array[Int]) => M): ClassificationMetrics
def classification[M <: DataFrameClassifier](formula: Formula, data: DataFrame)
(trainer: => (Formula, DataFrame) => M): ClassificationMetrics
def regression[T <: AnyRef, M <: Regression[T]](x: Array[T], y: Array[Double])
(trainer: => (Array[T], Array[Double]) => M): RegressionMetrics
def regression[M <: DataFrameRegression](formula: Formula, data: DataFrame)
(trainer: => (Formula, DataFrame) => M): RegressionMetrics
}
</code></pre>
</div>
</div>
<div class="tab-pane fade show active" role="tabpanel" id="java_9">
<div class="code" style="text-align: left;">
<pre class="language-java"><code class="language-java">
public class LOOCV {
public static <T, M extends Classifier<T>> ClassificationMetrics
classification(T[] x, int[] y, BiFunction<T[], int[], M> trainer);
public static <M extends DataFrameClassifier> ClassificationMetrics
classification(Formula formula, DataFrame data, BiFunction<Formula, DataFrame, M> trainer);
public static <T, M extends Regression<T>> RegressionMetrics
regression(T[] x, double[] y, BiFunction<T[], double[], M> trainer);
public static <M extends DataFrameRegression> RegressionMetrics
regression(Formula formula, DataFrame data, BiFunction<Formula, DataFrame, M> trainer);
}
</code></pre>
</div>
</div>
</div>
<p>On the Iris data, the accuracy estimation of LOOCV is 85.33%,
which is higher than that of 10-fold cross validation. This
is because more data is used for training and less for testing.</p>
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#java_10" type="button" role="tab">Java</button></li>
<li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#scala_10" type="button" role="tab">Scala</button></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade" role="tabpanel" id="scala_10">
<div class="code" style="text-align: left;">
<pre class="language-scala"><code class="language-scala">
smile> loocv.classification(x, y) { case (x, y) => lda(x, y) }
val res17: smile.validation.ClassificationMetrics =
{
fit time: 0.148 ms,
score time: 0.003 ms,
validation data size: 200,
error: 39,
accuracy: 80.50%,
sensitivity: 81.00%,
specificity: 80.00%,
precision: 80.20%,
F1 score: 80.60%,
MCC: 61.00%,
AUC: 88.19%,
log loss: 0.4915
}
</code></pre>
</div>
</div>
<div class="tab-pane fade show active" role="tabpanel" id="java_10">
<div class="code" style="text-align: left;">
<pre class="language-java"><code class="language-java">
smile> var x = iris.drop("class").toArray();
x ==> double[150][] { double[4] { 5.099999904632568, 3. ... 68, 1.7999999523162842 } }
smile> var loocv = LOOCV.classification(x, y, (x, y) -> LDA.fit(x, y));
loocv ==> {
fit time: 1.967 ms,
score time: 0.014 ms,
validation data size: 150,
error: 22,
accuracy: 85.33%,
cross entropy: 0.4803
}
</code></pre>
</div>
</div>
</div>
<h2 id="bootstrap">Bootstrap</h2>
<p>Bootstrap is a general tool for assessing statistical accuracy. The basic
idea is to randomly draw data with replacement from the training data,
each bootstrap sample set has the same size as the original training set.
In the bootstrap set, the expected ratio of unique instances is
approximately <code>1 − 1/e ≈ 63.2%</code>. This process is done many
times (say <code>k = 100</code>), producing <code>k</code> bootstrap datasets.
Then we fit the model to each of the bootstrap datasets and examine
the behavior of the fits over the <code>k</code> replications.</p>
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#java_11" type="button" role="tab">Java</button></li>
<li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#scala_11" type="button" role="tab">Scala</button></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade" role="tabpanel" id="scala_11">
<div class="code" style="text-align: left;">
<pre class="language-scala"><code class="language-scala">
object bootstrap {
def classification[T <: AnyRef, M <: Classifier[T]](k: Int, x: Array[T], y: Array[Int])
(trainer: => (Array[T], Array[Int]) => M): ClassificationValidations[M]
def classification[M <: DataFrameClassifier](k: Int, formula: Formula, data: DataFrame)
(trainer: => (Formula, DataFrame) => M): ClassificationValidations[M]
def regression[T <: AnyRef, M <: Regression[T]](k: Int, x: Array[T], y: Array[Double])
(trainer: => (Array[T], Array[Double]) => M): RegressionValidations[M]
def regression[M <: DataFrameRegression](k: Int, formula: Formula, data: DataFrame)
(trainer: => (Formula, DataFrame) => M): RegressionValidations[M]
}
</code></pre>
</div>
</div>
<div class="tab-pane fade show active" role="tabpanel" id="java_11">
<div class="code" style="text-align: left;">
<pre class="language-java"><code class="language-java">
public class Bootstrap {
public static <T, M extends Classifier<T>> ClassificationValidations<M>
classification(int k, T[] x, int[] y, BiFunction<T[], int[], M> trainer);
public static <M extends DataFrameClassifier> ClassificationValidations<M>
classification(int k, Formula formula, DataFrame data, BiFunction<Formula, DataFrame, M> trainer);
public static <T, M extends Regression<T>> RegressionValidations<M>
regression(int k, T[] x, double[] y, BiFunction<T[], double[], M> trainer);
public static <M extends DataFrameRegression> RegressionValidations<M>
regression(int k, Formula formula, DataFrame data, BiFunction<Formula, DataFrame, M> trainer);
}
</code></pre>
</div>
</div>
</div>
<p>On the Iris data, the accuracy estimation of 100 bootstraps
is about 83.7%, which is slightly lower than that of 10-fold cross validation.</p>
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#java_12" type="button" role="tab">Java</button></li>
<li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#scala_12" type="button" role="tab">Scala</button></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade" role="tabpanel" id="scala_12">
<div class="code" style="text-align: left;">
<pre class="language-scala"><code class="language-scala">
smile> bootstrap.classification(100, x, y) { case (x, y) => lda(x, y) }
val res18: smile.validation.ClassificationValidations[smile.classification.LDA] =
{
fit time: 0.184 ms ± 0.176,
score time: 0.213 ms ± 0.194,
validation data size: 73 ± 5,
error: 15 ± 3,
accuracy: 79.54% ± 4.39,
sensitivity: 81.47% ± 7.98,
specificity: 78.69% ± 9.88,
precision: 78.90% ± 8.98,
F1 score: 79.46% ± 4.47,
MCC: 60.36% ± 7.79,
AUC: 87.88% ± 3.24,
log loss: 0.5004 ± 0.0328
}
</code></pre>
</div>
</div>
<div class="tab-pane fade show active" role="tabpanel" id="java_12">
<div class="code" style="text-align: left;">
<pre class="language-java"><code class="language-java">
smile> Bootstrap.classification(100, x, y, (x, y) -> LDA.fit(x, y))
$43 ==> {
fit time: 0.057 ms ± 0.020,
score time: 0.163 ms ± 0.236,
validation data size: 55 ± 4,
error: 9 ± 3,
accuracy: 83.96% ± 4.68,
cross entropy: 0.4847 ± 0.0530
}
</code></pre>
</div>
</div>
</div>
<p>The bootstrap distribution of a parameter-estimator has been used to
calculate confidence intervals for its population-parameter.
If the bootstrap distribution of an estimator
is symmetric, then percentile confidence-interval are often used;
such intervals are appropriate especially for median-unbiased estimators
of minimum risk (with respect to an absolute loss function).
Otherwise, if the bootstrap distribution is non-symmetric, then percentile
confidence-intervals are often inappropriate.</p>
<p>The bootstrap distribution and the sample may disagree systematically,
in which case bias may occur. Bias in the
bootstrap distribution will lead to bias in the confidence-interval.</p>
<h2 id="hyperparameter-tuning">Hyperparameter Tuning</h2>
<p>A hyperparameter is a parameter whose value is set before the
learning process begins. By contrast, the values of other
parameters are derived via training. Hyperparameters can be
classified as model hyperparameters, that cannot be inferred
while fitting the machine to the training set because they
refer to the model selection task, or algorithm hyperparameters, that
in principle have no influence on the performance of the model but
affect the speed and quality of the learning process. For example,
the topology and size of a neural network are model hyperparameters,
while learning rate and mini-batch size are algorithm hyperparameters.</p>
<p>In Smile, <code>Hyperparameters</code> class provides two generic
approaches to sampling search candidates. With <code>add()</code>
methods, the user can define a parameter space with a specified
distribution (a fixed value, an array of values, or a range).
The method <code>grid()</code> exhaustively considers all parameter
combinations, while <code>random()</code> generates a stream of
random candidates.</p>
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#java_13" type="button" role="tab">Java</button></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade show active" role="tabpanel" id="java_13">
<div class="code" style="text-align: left;">
<pre class="language-java"><code class="language-java">
import smile.io.*;
import smile.data.formula.Formula;
import smile.validation.*;
import smile.classification.RandomForest;
var hp = new Hyperparameters()
.add("smile.random.forest.trees", 100) // a fixed value
.add("smile.random.forest.mtry", new int[] {2, 3, 4}) // an array of values to choose
.add("smile.random.forest.max.nodes", 100, 500, 50); // range [100, 500] with step 50
var train = Read.arff("data/weka/segment-challenge.arff");
var test = Read.arff("data/weka/segment-test.arff");
var formula = Formula.lhs("class");
var testy = formula.y(test).toIntArray();
hp.grid().forEach(prop -> {
var model = RandomForest.fit(formula, train, prop);
var pred = model.predict(test);
System.out.println(prop);
System.out.format("Accuracy = %.2f%%%n", (100.0 * Accuracy.of(testy, pred)));
System.out.println(ConfusionMatrix.of(testy, pred));
});
</code></pre>
</div>
</div>
</div>
<p>While grid search is popular, random search has the benefit to choose
a budget independent of the number of parameters and possible values.
Note that <code>rand()</code> returns a stream that never ends.
Therefore, one should use the <code>limit()</code> method to decide
how many configurations to test.</p>
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#java_14" type="button" role="tab">Java</button></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade show active" role="tabpanel" id="java_14">
<div class="code" style="text-align: left;">
<pre class="language-java"><code class="language-java">
hp.random().limit(20).forEach(prop -> {
var model = RandomForest.fit(formula, train, prop);
var pred = model.predict(test);
System.out.println(prop);
System.out.format("Accuracy = %.2f%%%n", (100.0 * Accuracy.of(testy, pred)));
System.out.println(ConfusionMatrix.of(testy, pred));
});
</code></pre>
</div>
</div>
</div>