-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuildModel.m
More file actions
3619 lines (2618 loc) · 159 KB
/
Copy pathBuildModel.m
File metadata and controls
3619 lines (2618 loc) · 159 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
(* ::Package:: *)
(* ::Input::Initialization:: *)
BuildModel[]:=Module[{output="Process Terminated",phasenumber,datain, file, phaser, phanum, flag, indata0, darkblue,indata,tag1,initems,
path, readin, sheet, allNames, allTrainingData, allnamesimage, response0, response, windowaddress1, windowaddress2, windowaddress3,
predictor, criterion, leng,numb, initemsimage, predictorNames, criterionName, alldataimage, completeimage, univariateimage,
bivariateimage,distributionimage, correlationmatrix, correlationchart, size1, size2,summaryimage, projectname,projectname0,
timeconstraint0, timeconstraint, evolutions0, evolutions, judge1, start, paretofront, developedModels, totaltime,
quality0, quality, interestingModels, interestimage, linearModels, freeformModels, linearimage, freeformimage, fontsize,
dimensionimage, combinationiamge, archivedimage, archivedModels, judge, presenceimage,metavariableimage, anEnsemble,
ensembleimage, ensembleinpareto,performanceimage,outlierIndices,comparisonimage,nicheimage, phenotype, createdModel,
estimatedModel, estimatedValues, observedValues, comparedimage, pairs, pairs2,j,startingtime, finishingtime,realtime,
xaxes, poarrows,midline,judgement,lesspairs,morepairs,bprights,bpwrongs,rightrate, LL,MM,LM,ML,rwdata,
realchecker, pairvec, pairs1, nullchecker1, bmlist0, bmitems0,newdim, nullcheckout, joineddata,joineditems, joinedname,
modelcount0,modelcount, modelcountD, modelcountA, imodelcount,fontsize2,judgebackG, traditionalForm, eachfunction, wholefunction,
cstat, cstatres, nullchecker2, nullflag, alltrainingsIP, allnamesIP, starttime, endtime, expectedduration,consumedtime,
NFindFile2, filename,valimeth0,valimeth, selectpara0, selectpara, splitratio, crossnumb0, crossnumb, testsize, trainsize, trainpos, hotraindata, hotestdata,foldsize, foldbag, ii, randpos, randorder, foldnumb, samplesize, blockbag, testpos,
rsquare, PredictedTestValues, ObservedTestValues, TrainData, TestData, TestPairs, allTestIP, estimatedTestValues, observedTestValues, testpairs, testpairs1, testpairs2, testcstatres, testcstat, testxaxes, testpoarrows, testmidline, testjudgement, testcomparedimage, lesstestpairs, moretestpairs, testLL, testMM, testLM, testML, testbprights, testbpwrongs, testrightrate, testrwdata, testrsquare, estimatedTrainValues, trainrsquare, randcage, jj, observedTrainValues, trainpairs, trainpairs1, trainpairs2,
traincstatres, traincstat, trainxaxes,trainpoarrows, trainmidline, trainjudgement, traincomparedimage, lesstrainpairs, moretrainpairs, trainLL, trainMM, trainLM, trainML, trainbprights, trainbpwrongs, trainrightrate, trainrwdata,triplebag,triplebagOM,
seed, seednumber0, seednumber, trainingcases, testcases ,loolen, i, partTrainingData, partTestData, fulltime, paretofront2,archivedbag,traindatabag, testdatabag, modelbag,paretobag,interestingbag,imagebag, countbag, presencebag, ensemblebag,
createdbag,allTrainingIP, allNamesIP, partTrainingIP, partTestIP, partNamesIP, estimatedValue,observedValue,pair,
roundedValue,judged,looresult,criteria, traditionalbag, allbag, partbag, pairbag, pairbag2, pair2, pospos,
posneg, negpos, negneg, ppvalue,npvalue, sensvalue, specvalue, accuvalue, fvalue, cvalue, testLabels, modelValues,
theta, thRange, aROCs, AUCvalue,theta0, ROCcurve, rocFuncs, rocFuncTips, ROCgraph,numbers, model, opts,CreateStandaloneModel,
minmax, monitors, limits0, limits, minP, maxP, Anumb, Pnumb, firstModels, firstcount, Smodels, Cnumb, Lnumb,
deltaC, deltaL,finalquality,usedvariables, variablebox, topfive,vect,bestbag,bestfive,
presencefinalimage,presencefinalimage15, presencefinalimage10, presencefinalimage5, presencefinal,
finaltopfive, minnumb, wrongcases, rightwrong, scores,summary, labeling, now0,future0,future4,future8,AUCvalue2,rocvalues,allinterestingModels,allEnsemble,allensembleimage,allensembleinpareto,alloutlierIndices,allperformanceimage,allcomparisonimage,allnicheimage,allphenotype,allcreatedModel,allestimatedModel,alltraditionalForm,allestimatedValues,allobservedValues,allpairs,allpairs1,allpairs2,allcstatres,allcstat,alljudgement,allcomparedimage,allrwdata,allrsquare,alljoineddata,alljoineditems,alljoinedname,precision, recall,allFvalue,allvariables, Nof1, mypercent, Nof0, subsetsize, alltestLabels, allmodelValues, allaROCs, allROCcurve, allAUCvalue, allrocFuncs, allrocFuncTips,allrocvalues,allROCgraph,
allroundedValues, allpairs3, allresult, allrightwrong, allscores, allsummary, cmdata, rightcases,paretofrontlinear,paretofrontfree,
correlationchartloo0,correlationchartloo, looscores, looscore, lootext, lootexts,loograph, version, error, errorbag,errorminmax,
errortext,errorgraph, evolutionStrategyLOO, robustModelLOO, selectionStrategyLOO, subsetsizefunc, numRec,
evolutionStrategyHO, robustModelHO, selectionStrategyHO, benchmark, corecount, future, findstartpoint, rawmodels,startgradient,
darkgreen, fitindex0, fitindex, inquiry, quartetbag, totalbag, totalnames, remainingtime, timelag, lm, x, rsquared, labels,
alllm, allrsquared,qualityflag,paretofront1, nsjudge0,nsjudge, liststandout,listnormout, allTrainingData0, allNames0,
explanatdata, targetdata, graphS, graphN,presencefinalimage20, graphO,allgraph, partgraph, allmodels, partmodels,
allarchivedModels, allprojectname, partprojectname, importantvariables, dominantvariables, top20variables, top15variables, top10variables, top5variables,
trainlines, testlines, traintestpos, usefulvariables, coeffvalues, coefftable, numbcoefftable, minpercent0, minpercent, heads, unionh,
cutoff0, cutoff ,classes
},
(* BuildModel version 3.0.1 2021.12.24 Monitor off *)
version="BuildModel version 3.0.1 made on December 24th, 2021";
(* Set the currrent directory where the notebook you are running BuildModel[] on is saved as the working directory *)
SetDirectory[NotebookDirectory[]];
corecount=$ProcessorCount;
Global`CORECOUNT=corecount;
(* Hypterparameter Settings for LOO method *)
evolutionStrategyLOO=BalancedGP;
robustModelLOO=True;
selectionStrategyLOO=ParetoFrontSelect;
(* startgradient=0.85; *)
(* Hypterparameter Settings for Hold-out method *)
evolutionStrategyHO=BalancedGP;
robustModelHO=True;
selectionStrategyHO=ParetoFrontSelect;
(* Parameter Setting *)
deltaC=1; deltaL=0.01;minnumb=100;
startingtime=Now[[1]];Global`STARTINGTIME=startingtime;
darkblue=RGBColor[0, 0.0376287, 0.760174];
darkgreen=RGBColor[0, 0.676539, 0];
windowaddress1={{Automatic, 10},{Automatic, 10}};
windowaddress2={{Automatic, 250},{Automatic , 350}};
windowaddress3={{Automatic, 150},{Automatic, 10}};
size1=650; size2=900;fontsize=16;fontsize2=20;
(* SubSetSizefunction *)
subsetsizefunc[numRec_]:=With[{sizeCand=33 + 8215/(5.3+numRec)-2.3N@Log[numRec]},If[numRec<100, 100, sizeCand]];
(* NFindFile2 *)
NFindFile2[filename_]:= Module[{judge0, judge11,judge2, judge3,out, choice,readables, existQ, existN, existP, alljudges, exist1,exist2,exist3, exist4},
judge0=FindFile[ToString[filename]];
judge11=FindFile[StringJoin[ ToString[filename], ".xls"]];
judge2=FindFile[StringJoin[ToString[filename],".xlsx" ]];
judge3=FindFile[StringJoin[ToString[filename],".csv" ]];
alljudges={judge0,judge11,judge2,judge3};
existQ=Map[ #=!=$Failed&, alljudges];
existN=Count[existQ, True];
existP=NPosition[ existQ, True];
Label["choiceagain"];
Which[
existN===0,
readables=$Path; PB[];Print[Style[StringForm["\[FilledDiamond] The file `` was not found. \n\nCheck if `` is located in the following folders where Mathematica can read.:\n
$Path = ``\n\nThese paths can be identified by evaluating $Path.", filename, filename, readables],14]];PB[];
out=$Failed,
existN===1,
out=Part[alljudges, existP[[1]]],
existN===2,
exist1=alljudges[[existP[[1]]]]; exist2= alljudges[[existP[[2]]]];
choice= InputString[StringForm["Two files were found:\n`` and ``\n Type 1 for ``, Type 2 for ``\n\nPress OK to select the FIRST file ``\nType end to quit.",
exist1,exist2, exist1, exist2, exist1], WindowMargins-> {{Automatic, 10},{Automatic,10}}];
Which[choice==="1"||choice==="",out= exist1, choice==="2", out=exist2,choice==="end"||choice==="quit", Goto["endingbuildmodel"],
True, ErrorMessage["error"]; Goto["choiceagain"]],
existN===3,
exist1=alljudges[[existP[[1]]]]; exist2= alljudges[[existP[[2]]]]; exist3=alljudges[[existP[[3]]]];
choice= InputString[StringForm["Three files were found:\n``, `` and ``\n Type 1 for ``, Type 2 for ``, Type 3 for ``\n\nPress OK to select the FIRST file ``\nType end to quit.",
exist1, exist2, exist3, exist1, exist2, exist3, exist1 ]];
Which[choice==="1"||choice==="",out= exist1, choice==="2", out=exist2,choice==="3", out=exist3, choice==="end"||choice==="quit", Goto["endingbuildmodel"],
True, ErrorMessage["error"]; Goto["choiceagain"]],
existN===4,
exist1=alljudges[[existP[[1]]]]; exist2= alljudges[[existP[[2]]]]; exist3=alljudges[[existP[[3]]]];exist4=alljudges[[existP[[4]]]];
choice= InputString[StringForm["Four files were found:\n``, ``, `` and ``\n Type 1 for ``, Type 2 for ``, Type 3 for ``, Type 4 for ``\n\nPress OK to select the FIRST file ``\nType end to quit.",
exist1, exist2, exist3,exist1, exist1, exist2, exist3,exist4, exist1 ]];
Which[choice==="1"||choice==="",out= exist1, choice==="2", out=exist2,choice==="3", out=exist3, choice==="4", out=exist4,choice==="end"||choice==="quit", Goto["endingbuildmodel"],
True, ErrorMessage["error"]; Goto["choiceagain"]],
True, ErrorMessage["Unexpected choice error"]; Goto["choiceagain"]
];
out
];
(* NFindFile3 *)
NFindFile3[filename_]:= Module[{judge0, judge11,judge2, judge3,out, choice,readables, existQ, existN, existP, alljudges, exist1,exist2,exist3, exist4},
(* NFindFile3 only checks if the file exits or not. *)
judge0=FindFile[ToString[filename]];
judge11=FindFile[StringJoin[ ToString[filename], ".xls"]];
judge2=FindFile[StringJoin[ToString[filename],".xlsx" ]];
judge3=FindFile[StringJoin[ToString[filename],".csv" ]];
alljudges={judge0,judge11,judge2,judge3};
existQ=Map[ #=!=$Failed&, alljudges];
existN=Count[existQ, True];
existP=NPosition[ existQ, True];
Which[
existN===0,
readables=$Path; PB[];Print[Style[StringForm["\[FilledDiamond] The file `` was not found. \n\nCheck if `` is located in the following folders where Mathematica can read.:\n
$Path = ``\n\nThese paths can be identified by evaluating $Path.", filename, filename, readables],14]];PB[];
out=False,
existN>= 1,
out=True,
True, ErrorMessage["Unexpected choice error"]; out = False
];
out
];
(* Create Standalone Model *)
CreateStandaloneModel[model:(_GPModel | _ModelEnsemble), opts___?OptionQ] := Module[
{inputVars, expression},
inputVars = DataVariables /. {opts} /. ModelPersonality@model;
expression = ModelPhenotype[model, opts];
Function@@{inputVars, expression}
];
(* DataIn function *)
datain[file_]:= Module[ {paths, out1={}, raw, len, i0, f, vec, data,item, csvQ},
paths=NFindFile2[file];raw=Import[paths];
len=Length[raw];csvQ=If[paths=!=$Failed&&StringTake[paths,-3]==="csv", 1, 0, 0];CSVQ=csvQ;
f[vec_]:= If[ Union[ vec] ==={Null}, Null, vec];
Which[raw===$Failed,
ErrorMessage[StringForm["The `` was not found.", file]];
out1="nofilefound"; Goto["ends"],
csvQ===1,
data=IntactComplement[ Map[ f,cleandata[Rest[raw ]]], {Null}];
Clear[Global`DATA];Global`DATA=data;
item=Numberings[First[raw]];
Clear[Global`ITEMS]; Global`ITEMS=item;
out1={1,{item, data}},
len===1,
data=IntactComplement[ Map[ f,cleandata[Rest[raw[[1]] ]]], {Null}];
Clear[Global`DATA];Global`DATA=data;
item=Numberings[First[raw[[1]]]];
Clear[Global`ITEMS]; Global`ITEMS=item;
out1={1,{item, data}},
len>= 2,
Clear[Global`DATA, Global`ITEMS];
For[i0=1, i0<= len, i0++,
data[i0]=Complement[ Map[ f,cleandata[Rest[raw[[i0]] ]]], {Null}];
Global`DATA[i0]=data[i0];
item[i0]=Numberings[First[raw[[i0]]]];
Global`ITEMS[i0]=item[i0];
AppendTo[out1,{item[i0], data[i0]}]
]; out1={len, out1},
True,
ErrorMessage["Unexpected DataIn error"]; out1="nofilefound"; Goto["ends"]
];
Label["ends"];
out1
];
(* Real Cheker *)
realchecker[pairvec_]:= Module[ {checknumb, vectors, rscore, rpos},
checknumb[vectors_]:= If[ NumberQ[vectors[[1]]]&&NumberQ[vectors[[2]]], 1, 0];
rscore=Map[ checknumb, pairvec];
rpos=NPosition[ rscore, 1];
Part[ pairvec, rpos]
];
(* Null Checker *)
nullchecker1[bmlist0_, bmitems0_]:=Module[ {nclen, ji, nbag, nline, nlout, nljudge, allmeans, address1, func, bpos, bmean, rules1, realpos, allmedians, address2, rules2, ncleng, mbag, mline,realrow, emptyrow, emptyitems, bmlist, bmitems, nullcounts, allcounts, nullpercent},
nbag={};mbag={};
func[bpos_,bmean_]:={bpos-> bmean[[bpos[[2]]]]};
Global`BMLIST0=bmlist0;Global`BMITEMS0=bmitems0;
ncleng=Length[Transpose[bmlist0]];
(* \:7a7a\:306e\:5217\:306e\:51e6\:7406 *)
For[ji=1, ji<= ncleng, ji++,
mline=Transpose[bmlist0][[ji]];
AppendTo[mbag, If[Union[Map[NumberQ, mline]]==={False}, 1, 0, 0]]
];
If[MemberQ[mbag, 1]===False, bmlist=bmlist0; bmitems=bmitems0;Goto["nextphase"]];
realrow=NPosition[mbag, 0]; emptyrow=NPosition[mbag,1];
bmlist=Transpose[Part[Transpose[bmlist0], realrow]];Global`INTERLIST=bmlist;
bmitems=Part[ bmitems0, realrow];
emptyitems=MakeTwin[emptyrow,Part[ bmitems0, emptyrow]];
Print[Style[StringForm["\[EmptyDiamond] Completely empty or non-numeric rows were excluded.\n Their row numbers and item names are ``.", emptyitems], Bold, 15, Red]];
Print[" "];
Label["nextphase"];
nclen=Length[bmlist];
nlout={bmlist,bmitems};
(* \:7a7a\:306e\:30bb\:30eb\:306e\:51e6\:7406 *)
For[ ji=1, ji<= nclen, ji++,
nline=bmlist[[ji]];
AppendTo[nbag, If[Union[Map[NumberQ, nline]]==={True}, 0, 1, 1]]
];Global`NBAG=nbag;
If[MemberQ[nbag, 1]===False, Goto["ncending"]];
Global`NBAG=nbag;Global`BMLIST=bmlist;
nullcounts= Count[Map[ NumberQ,Flatten@bmlist],False];Global`NULLCOUNTS=nullcounts;
allcounts=Length@Flatten@bmlist;Global`ALLCOUNTS=allcounts;
nullpercent=NF[100.nullcounts/allcounts];Global`NULLPERCENT=nullpercent;
Label["nljudgeagain"];
nljudge=InputString[StringForm["``% of cells in the dataset are empty.\nPress OK to replace empty cell with median value of the row.\n\nType a to replace empty cell with average value of the row.\nType n to leave empty cells as they are.\nType x to excluede those columns.\nType end to quit.", nullpercent], WindowMargins->{{Automatic,10}, {Automatic, 10}}];
allmeans=Map[ NMean, Transpose[bmlist]];Global`ALLMEANS=allmeans;
allmedians=Map[ NMedian, Transpose[bmlist]];Global`ALLMEDIANS=allmedians;
Which[
nljudge==="end"||nljudge==="end", nlout="terminated";Goto["ncending"],
nljudge==="x",
realpos=NPosition[nbag, 0];Global`REALPOS=realpos;
nlout={Part[bmlist, realpos],bmitems};
Print[Style["Columns that contain non-numeric cells were excluded.",15, Purple, Bold]];
Print[Style[StringForm["\[EmptyDiamond] Initial N of columns = ``, Final N of columns = ``", nclen, Length[nlout[[1]]]], 15,Bold]];
Print[" "],
nljudge==="a"&&Union[Map[NumberQ, allmeans]]==={True},
address1=Position[Map[NumberQ, bmlist,{2}], False];Global`ADDRESS1=address1;
rules1=Flatten[Map[ func[#,allmeans ]&, address1],1];Global`RULES1=rules1;
nlout={ReplacePart[bmlist, rules1],bmitems};
Print[Style["\[EmptyDiamond] Non-numeric cells were replaced with average values of the row.", 15,Purple, Bold]];
Print[" "],
nljudge===""&&Union[Map[NumberQ, allmedians]]==={True},
address2=Position[Map[NumberQ, bmlist,{2}], False];
rules2=Flatten[Map[ func[#,allmedians]&, address2],1];
nlout={ReplacePart[bmlist, rules2],bmitems};
Print[Style["\[EmptyDiamond] Non-numeric cells were replaced with median values of the row.",15, Purple, Bold]];
Print[" "],
nljudge==="n",
Print[Style["\[EmptyDiamond] Empty cells were left unchanged.",15,Bold]];
Print[" "];Goto["ncending"],
nljudge==="a"&&Union[Map[NumberQ, allmeans]]=!={True},
ErrorMessage["Type in again, because some rows have no numeric value.",15, Purple, Bold];Goto["nljudgeagain"],
nljudge===""&&Union[Map[NumberQ, allmedians]]=!={True},
ErrorMessage["Type in again, because some rows have no numeric value."];Goto["nljudgeagain"],
True,
ErrorMessage["Type in, again."];Goto["nljudgeagain"]
];
Label["ncending"];
nlout
];
(* non-numeric cells \:3092\:6570\:5b57\:3067\:7f6e\:304d\:63db\:3048\:308b *)
nullchecker2[bmlist0_, bmitems0_]:=Module[ {nclen, ji, nbag, nline, nlout, nljudge, allmeans, address1, func, bpos, bmean, rules1, realpos, allmedians, address2, rules2, ncleng, mbag, mline,realrow, emptyrow, emptyitems, bmlist, bmitems, nullcounts, allcounts, nullpercent},
nbag={};mbag={};
func[bpos_,bmean_]:={bpos-> bmean[[bpos[[2]]]]};
Global`BMLIST0=bmlist0;Global`BMITEMS0=bmitems0;
ncleng=Length[Transpose[bmlist0]];
(* \:7a7a\:306e\:5217\:306e\:51e6\:7406 *)
For[ji=1, ji<= ncleng, ji++,
mline=Transpose[bmlist0][[ji]];
AppendTo[mbag, If[Union[Map[NumberQ, mline]]==={False}, 1, 0, 0]]
];
If[MemberQ[mbag, 1]===False, bmlist=bmlist0; bmitems=bmitems0;Goto["nextphase"]];
realrow=NPosition[mbag, 0]; emptyrow=NPosition[mbag,1];
bmlist=Transpose[Part[Transpose[bmlist0], realrow]];Global`INTERLIST=bmlist;
bmitems=Part[ bmitems0, realrow];
emptyitems=MakeTwin[emptyrow,Part[ bmitems0, emptyrow]];
Print[Style[StringForm["\[EmptyDiamond] Completely empty or non-numeric rows were excluded.\n Their row numbers and item names are ``.", emptyitems], Bold, 15, Red]];
Print[" "];
Label["nextphase"];
nclen=Length[bmlist];
nlout={bmlist,bmitems};
(* \:7a7a\:306e\:30bb\:30eb\:306e\:51e6\:7406 *)
For[ ji=1, ji<= nclen, ji++,
nline=bmlist[[ji]];
AppendTo[nbag, If[Union[Map[NumberQ, nline]]==={True}, 0, 1, 1]]
];Global`NBAG=nbag;
If[MemberQ[nbag, 1]===False, Goto["ncending"]];Global`NBAG=nbag;
Global`BMLIST=bmlist;
nullcounts=Count[ Map[NumberQ,Flatten@bmlist], False];Global`NULLCOUNTS=nullcounts;
allcounts=Length@Flatten@bmlist;Global`ALLCOUNTS=allcounts;
nullpercent=NF[100.nullcounts/allcounts];Global`NULLPERCENT=nullpercent;
Label["nljudgeagain"];
nljudge=InputString[StringForm["``% of cells in the dataset are empty.\nTo test the accuracy of the created model on the training data, non-numeric cells must be replaced with a number.\n\nPress OK to replace empty cell with median value of the row.\nType a to replace empty cell with average value of the row.\nType x to excluede those columns.\nType end to quit.", nullpercent], WindowMargins->{{Automatic,10}, {Automatic, 10}}];
allmeans=Map[ NMean, Transpose[bmlist]];Global`ALLMEANS=allmeans;
allmedians=Map[ NMedian, Transpose[bmlist]];Global`ALLMEDIANS=allmedians;
Which[
nljudge==="end"||nljudge==="end", nlout="terminated";Goto["ncending"],
nljudge==="x",
realpos=NPosition[nbag, 0];Global`REALPOS=realpos;
nlout={Part[bmlist, realpos],bmitems};
Print[Style["Columns that contain non-numeric cells were excluded.",15, Purple, Bold]];
Print[Style[StringForm["\[EmptyDiamond] Initial N of columns = ``, Final N of columns = ``", nclen, Length[nlout[[1]]]], 15,Bold]];
Print[" "],
nljudge==="a"&&Union[Map[NumberQ, allmeans]]==={True},
address1=Position[Map[NumberQ, bmlist,{2}], False];Global`ADDRESS1=address1;
rules1=Flatten[Map[ func[#,allmeans ]&, address1],1];Global`RULES1=rules1;
nlout={ReplacePart[bmlist, rules1],bmitems};
Print[Style["\[EmptyDiamond] Non-numeric cells were replaced with average values of the row.", 15,Purple, Bold]];
Print[" "],
nljudge===""&&Union[Map[NumberQ, allmedians]]==={True},
address2=Position[Map[NumberQ, bmlist,{2}], False];
rules2=Flatten[Map[ func[#,allmedians]&, address2],1];
nlout={ReplacePart[bmlist, rules2],bmitems};
Print[Style["\[EmptyDiamond] Non-numeric cells were replaced with median values of the row.",15, Purple, Bold]];
Print[" "],
nljudge==="a"&&Union[Map[NumberQ, allmeans]]=!={True},
ErrorMessage["Type in again, because some rows have no numeric value.",15, Purple, Bold];Goto["nljudgeagain"],
nljudge==="m"&&Union[Map[NumberQ, allmedians]]=!={True},
ErrorMessage["Type in again, because some rows have no numeric value."];Goto["nljudgeagain"],
True,
ErrorMessage["Type in, again."];Goto["nljudgeagain"]
];
Label["ncending"];
nlout
];
phaser[phanum_]:= Module[ {phas, phaseboard, conts},
phaseboard=CreateWindow[WindowSize -> {500, 180}, WindowMargins -> windowaddress2, WindowTitle -> "Phase names"];
conts=Cell["Phase 1 Patient data\nPhase 2 Group selection\nPhase 3 Component selection\nPhase 4 Parameter setting\nPhase 5 Data loading\nPhase 6 Data analysis & plotting", FontSize -> 20];
NotebookWrite[phaseboard,conts];
Label["phasagain"];
phas=InputString[StringForm["Type in a phase NUMBER to return\nfrom `` to ``\nType end to quit", 1, phanum], WindowMargins-> windowaddress1];
NotebookClose[phaseboard];
Which[ phas==="end"||phas==="quit", flag="terminated";Goto["endinglabodata"],
IntegerQ[ToExpression[phas]]&& 1 <=ToExpression[phas]<= phanum, Goto[StringJoin["phase", phas]],
True, ErrorMessage["Type in, again"];Goto["phasagain"]
];
];
topfive[vect_]:=Which[ListQ[vect]===False, {{Null,Null}}, Length@vect<5, vect[[All,2]],Length@vect>= 5, Take[vect,5][[All,2]], True, {{Null,Null}}];
(* a function to find out the starting values of QualityBox *)
findstartpoint[rawmodels_]:=Module[{QB0, QB1, QB2,medians, ratio, medians2, startpoint,allgrads,nears, lenpos, lencands, lenlens, startpoint0},
QB0=Map[ModelQuality, rawmodels];
QB1=Map[{#[[1]],100#[[2]]}&, QB0];
medians=Map[NMedian, Transpose@QB1];
ratio=medians[[2]]/medians[[1]];
QB2=Map[ {ratio*#[[1]],#[[2]]}&, QB1];
(* medians2=Map[NMedian, Transpose@QB2]; *)
allgrads=Map[ #[[2]]/#[[1]]&, QB2];
nears=Nearest[ allgrads, fitindex, Round[0.2Length@rawmodels]];
lenpos=Flatten@Map[NPosition[allgrads,#]&, nears];
lencands=Part[QB2, lenpos];
lenlens=Map[Norm, lencands];
startpoint0=lencands[[Last@NPosition[lenlens, NMin@lenlens]]];
startpoint={startpoint0[[1]]/ratio,startpoint0[[2]]/100};
startpoint
];
(* Load DataModeler *)
(* <<"DataModeler`"; *)
(* --------- PHASE 0 -------------------------------------------- Set Up --------------------------------------------------- -*)
SetUp[];
Print[ ];
(* start of body of program *)
(* ------- PHASE 1 ----------------------------------------------Reading in raw data-------------------------------------------------- *)
Label["phase1"];phasenumber=1; Global`PHASENUMBER=1;
Print[Style["\[FilledSquare]\:3000Building functions with Symbolic regression",Bold, Purple,fontsize2]];
Print[Style[StringForm["\[FilledDiamond] ``", version],Bold,fontsize, Blue]];
Print[ ];
Print[ ];
Print[Style["\t\[EmptySquare]\:3000Phase 1 Reading in data",Bold, Purple,fontsize2]];
Print[ ];
Print[Style[StringForm["Starting time: date ``.``.`` time ``.``.``",
startingtime[[1]],startingtime[[2]],startingtime[[3]],startingtime[[4]],startingtime[[5]],Round@startingtime[[6]]], Bold, fontsize]];
Label["indataagain"];
indata0=InputString[Style["[Inevitable Data]\nType in a FILE NAME of spread sheet, like data(.xlsx).\nOr type in an expression of DATA in Mathematica.\nPress OK to use DATA as an input data.\nType p to use the PREVIOUS data.\nType u to use the PREIVOUS FILTERED data.\nType end to quit",darkblue], WindowMargins -> windowaddress1];
If[indata0==="end"||indata0==="quit",flag="terminated";Goto["endinglabodata"]];
Global`INDATA0=indata0;
(* tag1=0: indata & initems, separately, tag1=1: Excel file *)
Which[
indata0===""&&ListQ[Global`DATA],
indata=Global`DATA; tag1=0,
ListQ[ToExpression[indata0]]&&NameQ[indata0],
indata=ToExpression[indata0]; tag1=0,
indata0==="p" && ListQ[Global`INDATA]&&IntegerQ[Global`TAG1]&&ListQ[Global`INITEMS], indata=Global`INDATA; tag1=Global`TAG1; initems=Global`INITEMS;indata0=Global`INDATA0; Goto["pass1"],
MemberQ[{"y", "u"}, indata0]&& ListQ[Global`INDATA1]&&IntegerQ[Global`TAG1]&&ListQ[Global`INITEMS], indata1=Global`INDATA1; tag1=Global`TAG1; initems=Global`INITEMS;indata0=Global`INDATA0; Print[Style[StringForm["Patient data name: ``, its dimensions: ``", If[indata0==="", "DATA", indata0], Dimensions[indata1]],fontsize,Bold]];Goto["pass2"],
indata0==="end"||indata0==="quit",flag="terminated";Goto["endinglabodata"],
path=NFindFile3[indata0]; path===True,
readin=datain[indata0];tag1=1;Global`RAWREADIN=readin;
Which[
readin[[1]]===1,
{initems, indata}=readin[[2]](*; initems=AddDots[initems] *),
NumberQ[readin[[1]]]&&readin[[1]]>= 2,
For[i=1, i<= readin[[1]], i++,
Print[StringForm["Sheet ``", i]];
Print[readin[[2, i,1]]]
];Print[" "];
Label["sheetagain"];
sheet=Input[StringForm["Type in a NUMBER of the sheet for analysis\n\nPress OK to select the FIRST sheet\nType end to quit."], Null,WindowMargins-> windowaddress3];
Which[
IntegerQ[sheet]&&1<= sheet<=readin[[1]],
{initems, indata}={readin[[2,sheet,1]], readin[[2,sheet,2]]}(* ;initems=AddDots[initems] *),
sheet===Null,
{initems, indata}={readin[[2,1,1]], readin[[2,1,2]]}(* ;initems=AddDots[initems] *),
ToString[sheet]==="end"||ToString[sheet]==="quit",
flag="terminated";Goto["endinglabodata"],
True, ErrorMessage["Type in, again."];Goto["sheetagain"]
]
],
True,ErrorMessage["Type in a file name or an expression, again."];Goto["indataagain"]
];PATH=path;Global`READIN=readin;TAG1=tag1;
Label["initemsagain"];
If[ tag1===0,
initems=InputString[Style["[Inevitable Data]\nType in an expression of COLUMN NAMES Numbered\nof the original data\nPress OK to use ITEMS as colum names\n\nType r to return to a previous phase.\nType end to quit.",darkblue], WindowMargins-> windowaddress1];
Which[ initems===""&&ListQ[Global`ITEMS], initems=Global`ITEMS,
initems==="end"||initems==="quit", flag="terminated";Goto["endinglabodata"],
ListQ[ToExpression[initems]], initems=ToExpression[Map[ ToExpression, initems]],
initems==="r"||initems==="b", phaser[phasenumber],
True, ErrorMessage["Type in, again."];Goto["initemsagain"]
];
(* initems=AddDots[initems]; *)
];
Global`INDATA=indata; Global`INITEMS=initems;Global`INDATA0=indata0;
Label["pass1"];
Print[Style[StringForm["Patient data name: ``, its dimensions: ``", If[indata0==="", "DATA", indata0], Dimensions[indata]],Bold,fontsize]];
leng=Length[initems]; numb=Length[indata]; Global`LENG=leng;
Print[" "];
If[leng===1, ErrorMessage["There must be more than one row in the data set."];Goto["endingbuildmodel"]];
(* ------- PHASE 2 -------Data Definition------------------------------------------------------------- *)
Print[Style["\t\[EmptySquare]\:3000Phase 2 Data Definition",Bold,Purple,fontsize2]];
Label["phase2"];phasenumber=2; Global`PHASENUMBER=2;
Label["response"];
Print[Style[StringForm["The origianl colum labels:"],fontsize,Bold]];
initemsimage=DisplayForm[FrameBox[ initems]];
Print[ initemsimage];
Print[" "];
response0=InputString[Style["Type in a colum NUMBER of the RESPONSE variable.\nPress OK to use the LAST column for the response.\n\nType r to return to a previous phase.\nType end to quit.",darkblue], WindowMargins->windowaddress1];
response=ToExpression[response0];
Which[
response0==="end"||response0==="quit", flag="terminated"; Goto["endingbuildmodel"],
response0==="r"||response0==="b", phaser[phasenumber],
response0==="", response=leng;criterion=indata[[All, leng]]; predictor=indata[[All, Range[1, leng-1]]];
allNames=initems[[All,2]]; allTrainingData=indata; predictorNames=Drop[initems, -1][[All,2]]; criterionName=Last[initems][[2]],
IntegerQ[response]&&1<= response<= leng, criterion=indata[[All, response]]; predictor= Transpose[ Drop[ Transpose[indata], {response}]];
criterionName= initems[[All,2]][[response]];allNames=Join[ Drop[initems[[All,2]], {response}], {criterionName}];
allTrainingData=Fuse[ predictor, criterion] ,
True, ErrorMessage["Type in, again."]; Goto["response"]
];
Global`CRITERION=criterion; Global`PREDICTOR=predictor;Global`CRITERIONNAME=criterionName; Global`PREDICTORNAMES=predictorNames;
Global`ALLNAMES=allNames; Global`ALLTRAININGDATA=allTrainingData;
criterionkinds=Union[criterion];Global`CRITERIONKINDS=criterionkinds;
allnamesimage=DisplayForm[FrameBox[ allNames]];
alldataimage=DisplayForm[FrameBox[ Short[allTrainingData, 100]]];
Print[Style[StringForm["\[FilledDiamond] allNames (The last variable `` is a target response)", criterionName],fontsize, Bold]];
Print[ allnamesimage];
Print[Style["\[FilledDiamond] allTrainingData (The last column is a response variable, the others are explanatory variables)",fontsize, Bold]];
Print[alldataimage];
Print["\t(The above output is suppressed below 100 lines.)"];
Print[" "];
Print[" "];
heads=Sort[allNames]; unionh=Sort[Union[allNames]];
If[ SameQ[heads, unionh]===False,
Print[Style[StringForm["\[FilledDiamond]\:3000The following item names are overlapping in the dataset: ``", Delete[ heads, Map[Part[#,1]&, Map[Position[heads,#]&,unionh]]]], Bold,16]];
Print[Style[StringForm["The ITEMS NAMES must be UNIQUE with each other."],Bold,16]];
Print[Style[StringForm["The process is terminated."],Bold,Red,16]];Goto["endingbuildmodel"]];
(* ------- PHASE 3 -------Interpolation of Empty cells and Rescaling data ---------------------------------------- *)
Print[Style["\t\[EmptySquare]\:3000Phase 3 Interpolation of Empty Cells",Bold,Purple,fontsize2]];
Label["phase3"];phasenumber=3; Global`PHASENUMBER=3;
Print[" "];
Print[Style["\[FilledDiamond] Data Completeness Check",Bold,fontsize]];
completeimage=DataCompletenessMap[
allTrainingData,
PlotRange->Automatic
];
Print[completeimage];Global`COMPLETEIMAGE=completeimage;
Print[" "];
(* \:866b\:98df\:3044\:30c7\:30fc\:30bf\:306e\:88dc\:9593 *)
Global`ALLTRAININGDATA1=allTrainingData;Global`ALLNAMES1=allNames;
nullcheckout=nullchecker1[allTrainingData, allNames];
If[nullcheckout==="terminated", Goto["endingbuildmodel"]];
{allTrainingData, allNames}=nullcheckout;
Global`ALLTRAININGDATA2=allTrainingData;Global`ALLNAMES2=allNames;
If[ Dimensions[allTrainingData][[2]]=!=Length[allNames],ErrorMessage["Unknown nullchecker error. Row lengths do not match."];Goto["endingbuildmodel"]];
criterion=allTrainingData[[All,Dimensions[allTrainingData][[2]]]];Global`NEWCRITERION=criterion;
(* Real Data for analysis after modifying empty cells *)
Global`ALLTRAININGDATA=allTrainingData;Global`ALLNAMES=allNames;
(* \:5206\:6790\:5bfe\:8c61: allTrainingData, allNames *)
(* target varialbe \:306f\:3001allTrainingData\:306e\:6700\:7d42\:5217 *)
If[
Global`ALLTRAININGDATA1=!=Global`ALLTRAININGDATA2,
Print[Style["\[FilledDiamond] 1. New Data Completeness Check",Bold,fontsize]];
completeimage=DataCompletenessMap[
allTrainingData,
PlotRange->Automatic
];
Print[completeimage];
Print[" "]; newdim=Dimensions[allTrainingData];
Print[Style[StringForm["\[FilledSquare] N of columns = ``, n of rows = ``", newdim[[1]], newdim[[2]]], Purple, 15, Bold]];
Print[Style[StringForm["\[FilledSquare] Selected variables (the last one is the response varialbe:\n ``", Numberings[allNames]], 15, Bold]];
Print[" "],
newdim=Dimensions[allTrainingData];
Print[Style[StringForm["\[FilledSquare] N of columns = ``, n of rows = ``", newdim[[1]], newdim[[2]]], Purple, 15, Bold]];
Print[Style[StringForm["\[FilledSquare] Selected variables (the last one is the response varialbe:\n ``", Numberings[allNames]], 15, Bold]];
];
(* Exporting the interpolated data *)
Print[" "];
Print[Style[StringForm["\[FilledDiamond]\:3000Exporting the Dataset for the Analysis after Interporated if necessary."], Bold, 16, Blue]];
Print[" "];
ExportExcel3[allTrainingData, Numberings@allNames, "DatasetAfterNullCheck"];
Print[" "];
(* Rescaling: Standardization & Normalization *)
Label["nsagain"];
nsjudge0=InputString["Do you RESCALE the explanatory variables?\nPress OK or type 0 to go WITHOUT rescaling.\nType 1 or s to STANDARDEIZE them with mean 0 and SD 1.\nType 2 or n to NORMALIZE them between 0 and 1.\n\nType end to quit.",WindowMargins-> windowaddress1];
nsjudge=ToExpression@nsjudge0;
Which[
nsjudge0===""||nsjudge0==="0",
nsjudge=0,
nsjudge0==="1",
Null,
nsjudge0==="s",
nsjudge=1,
nsjudge0==="2",
Null,
nsjudge0==="n",
nsjudge=2,
nsjudge0==="end"||nsjudge0==="quit", Goto["endingbuildmodel"],
True, ErrorMessage["Type in, again."];Goto["nsagain"]
];
If[MemberQ[Map[NumericQ,Flatten@allTrainingData],False],
Print[" "];Print[Style[StringForm["\[FilledSquare] There are some NON-NUMERIC cells in the data."], Bold, Red, 15]];Print[" "]];
Which[
nsjudge===0,
Print[" "];
Print[Style[StringForm["\[EmptyDiamond] The explanatory variables are used in the ORIGINAL SCALE."], Bold,Blue, 14]];
Print[" "],
nsjudge===1,
{allTrainingData0, allNames0}={allTrainingData, allNames};
Global`ALLTRAININGDATA0=allTrainingData0; Global`ALLNAMES0=allNames0;
explanatdata=Map[Drop[#,-1]&, allTrainingData];targetdata=Map[Last,allTrainingData];
Global`EXPLANATDATA=explanatdata; Global`TARGETDATA=targetdata;
liststandout=ListStandardize[explanatdata, Numberings@Drop[allNames,-1]];
allTrainingData=Fuse[liststandout[[1]], targetdata];
Global`ALLTRAININGDATAS=allTrainingData;
Print[Style[StringForm["\[FilledDiamond] The explanatory variables are used in the STANDARDIZED SCALE with the average as 0 and the standard deviation as 1."], Bold,Blue, 16]];
Print[Style[StringForm["\[EmptyDiamond] The explanatory variables have been STANDARDIZED."], Bold,16]];
Print[" "];
Print[Style[StringForm["\[EmptySquare] The Plot of Origianl Distributions of variables"], Bold,16]];
graphO=ListPlot[allTrainingData0, ImageSize-> 750, PlotRange-> All, PlotMarkers->Automatic, AxesLabel-> {Style["Explanatory\nVariable", 15],Style["Original\nValue",15]},
TicksStyle->Directive["Label", 14,Bold]];
Print@graphO;
Print[" "];
Print[Style[StringForm["\[EmptySquare] The Plot of Distributions of Standarzed variables"], Bold,16]];
graphS=ListPlot[allTrainingData, ImageSize-> 750, PlotRange-> All, PlotMarkers->Automatic, AxesLabel-> {Style["Explanatory\nVariable", 15],Style["Standardized\nValue",15]},
TicksStyle->Directive["Label", 14,Bold]];
Print@graphS;
Print[" "],
nsjudge===2,
{allTrainingData0, allNames0}={allTrainingData, allNames};
Global`ALLTRAININGDATA0=allTrainingData0; Global`ALLNAMES0=allNames0;
explanatdata=Map[Drop[#,-1]&, allTrainingData];targetdata=Map[Last,allTrainingData];
Global`EXPLANATDATA=explanatdata; Global`TARGETDATA=targetdata;
listnormout=ListNormalize[explanatdata, Numberings@Drop[allNames,-1]];
allTrainingData=Fuse[listnormout[[1]], targetdata];
Global`ALLTRAININGDATAN=allTrainingData;
Print[Style[StringForm["\[FilledDiamond] The explanatory variables are used in the NORMALIZED SCALE that are scaled between 0 and 1."], Bold,Blue, 16]];
Print[Style[StringForm["\[EmptyDiamond] The explanatory variables have been NORMALIZED."], Bold,16]];
Print[" "];
Print[Style[StringForm["\[EmptySquare] The Plots of Origianl Distributions of variables"], Bold,16]];
graphO=ListPlot[allTrainingData0, ImageSize-> 750, PlotRange-> All, PlotMarkers->Automatic, AxesLabel-> {Style["Explanatory\nVariable", 15],Style["Original\nValue",15]},
TicksStyle->Directive["Label", 14,Bold]];
Print@graphO;
Print[" "];
Print[Style[StringForm["\[EmptySquare] The Plots of Distributions of Normalized variables"], Bold,16]];
graphN=ListPlot[allTrainingData, ImageSize-> 750, PlotRange-> All, PlotMarkers->Automatic, AxesLabel-> {Style["Explanatory\nVariable", 15],Style["Normalized\nValue",15]},
TicksStyle->Directive["Label", 14,Bold]];
Print@graphN;
Print[" "],
True,
ErrorMessage["Unexpected Rescaling Error"];Goto["endingbuildmodel"]
];
(* Exporting the rescaled data *)
If[ nsjudge=!=0,
Print[" "];
Print[Style[StringForm["\[FilledDiamond]\:3000Exporting the Dataset for the Analysis after Rescaling if necessary."], Bold, 16, Blue]];
Print[" "];
ExportExcel3[allTrainingData, Numberings@allNames, "DatasetAfterRescaling"];
];
Print[" "];
(* ------- PHASE 4 ------- Selection of Validation Method ---------------------------------------------------------------- *)
Print[" "];
Print[" "];
Print[Style["\t\[EmptySquare]\:3000Phase 4 Validation Method",Bold,Purple,fontsize2]];
Label["phase3"];phasenumber=4; Global`PHASENUMBER=4;
Print[" "];
Print[Style["\[FilledDiamond] Selection of Validation Method",Bold,fontsize]];
Print[" "];
(* Selection from Hold-out method, Cross validation method or No division *)
Label["valimeth"];
valimeth0=InputString[Style[StringForm["\[FilledSquare] VALIDATION method\nPress OK or type h to use HOLD-OUT method to split data into Training data and Test data.\nType l (el) or o (ou) to use LEAVE-ONE-OUT method.\nType n not to divide data into them.\nType end to quit."]], WindowMargins-> windowaddress1];
(* Type k to use K-FOLD CROSS VALIDATION method (NOT READY).\n*)
Which[
valimeth0==="end"||valimeth0==="quit", Goto["endingbuildmodel"],
valimeth0===""||valimeth0==="h",
valimeth=1;
Print[Style[StringForm["\t\[EmptyDiamond] Validataion method: Hold-out Validation method was selected."], Bold, fontsize, Blue]],
valimeth0==="o"||valimeth0==="l"||valimeth0==="L",
valimeth = 2;
Print[Style[StringForm["\t\[EmptyDiamond] Validataion method: Leave-One-Out Cross Validation method was selected."], Bold, fontsize, Blue]],
(* valimeth0==="k",
valimeth = 3;
Print[Style[StringForm["\t\[EmptyDiamond] Validataion method: K-Fold Cross Validation method was selected."], Bold, fontsize, Blue]], *)
valimeth0 === "n",
valimeth = 0;
Print[Style[StringForm["\t\[EmptyDiamond] Validataion method: No validation."], Bold, fontsize, Blue]],
True,
ErrorMessage["Type in, again."];
Goto["valimeth"]
];Global`VALIMETH=valimeth;
PB[];
PB[];
PB[];
(* Setting the parameter of slitting or folding *)
Which[
valimeth===0,
Print[Style[StringForm["\[EmptyDiamond] All the raw data is used for both training data and test data without divided."],Bold,fontsize]];Goto["skip"],
valimeth===1,
(* Hold out method *)
Label["selectagain"];
selectpara0=InputString["\[FilledSquare] HOLD=OUT method\nPress OK to set Training data : Test data = 7 : 3.\nType a NUMBER for a TEST SIZE Between 0\:301c1.\n\nType end to quit.", WindowMargins-> windowaddress1];
selectpara=ToExpression[selectpara0];
Which[selectpara0==="end"||selectpara0==="quit",Goto["endingbuildmodel"],
selectpara0==="", splitratio=0.3,
NumberQ[selectpara]&&0<selectpara<1,
splitratio =selectpara,
True, ErrorMessage["Type in, again."];Goto["selectagain"]
]; Print[Style[StringForm["\[FilledSquare] The hold-out method was chosen.\n\[EmptyDiamond] All the raw data was split into training data and test data with `` : `` ratio.", 1-splitratio, splitratio],Bold,fontsize]];
Global`SPLITRATIO=splitratio,
valimeth===2,
(* Leave-One-Out Cross validation *)
Goto["LOOmethod"],
valimeth===3,
(* k-Fold Cross validation method *)
ErrorMessage["NOT PROGRAMMED YET."];Goto["endingbuildmodel"];
Label["crossagain"];
crossnumb0=InputString["Press OK to do 5-FOLD CROSS VALIDATION.\nType an INTEGER (2 or more) for a number of blocks.\n\nType end to quit.", WindowMargins-> windowaddress1];
crossnumb=ToExpression[crossnumb0];
Which[crossnumb0==="end"||crossnumb0==="quit", Goto["endingbuildmodel"],
crossnumb0==="", foldnumb=5,
IntegerQ[crossnumb]&&1<crossnumb,
foldnumb =crossnumb,
True, ErrorMessage["Type in, again."];Goto["crossagain"]
] ;
Print[Style[StringForm["\[FilledSquare] The cross-validation method was chosen.\n\[EmptyDiamond] All the raw data was divided into `` blocks.", foldnumb],Bold,fontsize]];
Global`FOLDNUMB=foldnumb,
True,
ErrorMessage["Unexpected valimth error"];Goto["endingbuildmodel"]
];
Print[" "];
(* Selecting specific data into each subgroup for validation *)
Label["seedagain"];
seednumber0=InputString["Press OK to use RandomInteger[10000] as a SEED.\n\nType in an INTEGER for a seed.\nType f to FIX the seed for RANDOMIATION (seed=0).\nType end to quit.",WindowMargins-> windowaddress1];
seednumber=ToExpression[seednumber0];
Which[seednumber0==="end"||seednumber0==="quit", Goto["endingbuildmodel"],
seednumber0==="f", seed=0,
IntegerQ@seednumber, seed=seednumber,
seednumber0===""||seednumber0==="r", seed=RandomInteger[10000],
True, Print["Type an integer or n, again"];Goto["seedagain"]
];
Print[" "];
(* training data and test data specified by randomization *)
samplesize=Length@allTrainingData;
randorder=NRandomSample[Range@samplesize, samplesize, seed];
Print[Style[StringForm["\[FilledSquare] The seed for randomization is ``.", seed], 16, Bold,Red]];
Print[" "];
Global`SAMPLESIZE=samplesize;
Global`RANDORDER=randorder;
Label["skip"];
Which[
valimeth===1,
(* Hold out method *)
testsize=Floor[splitratio*samplesize];
trainsize=samplesize-testsize;
Global`TESTSIZE=testsize; Global`TRAINSIZE=trainsize;
trainpos=Take[randorder, trainsize];
testpos=Drop[ randorder, trainsize];
Print[Style[StringForm["\[FilledDiamond] The position of test data is `` with a randomization seed number ``.\nThe whole position of test data is shown by TESTPOS\nThe whole position of training data is shown by TRAINPOS.", Short[testpos], seed], 16]];
Print[" "];
Global`TRAINPOS=trainpos; Global`TESTPOS=testpos;
trainlines=MakeTwin[trainpos , Table[1, {Length@trainpos}]];
testlines=MakeTwin[testpos, Table[0, {Length@testpos}]];
traintestpos=Sort[Join[trainlines,testlines], #1[[1]]<= #2[[1]]&];
Global`TRAINLINES=trainlines; Global`TESTLINES=testlines;
Global`TRAINTESTPOS=traintestpos;
hotraindata=Part[allTrainingData, trainpos];
hotestdata=Part[allTrainingData, testpos];
Global`HOTRAINDATA=hotraindata; Global`HOTESTDATA=hotestdata;
Global`TRAINSAMPLES=hotraindata; Global`TESTSAMPLES=hotestdata;
Print[Style[StringForm["\[FilledDiamond]\:3000Hold-out method: Traing data N = ``, Test data N = `` (`` : ``)", Length@hotraindata, Length@hotestdata, 1-splitratio, splitratio], Bold, 15]];
Print[Style["They are expression as TRAINSAMPLES and TESTSAMPLES.", Bold, fontsize]];
PB[];
ExportExcel3[traintestpos, Numberings@{"CaseNo","TrainingData"}, "TrainingdataPosition"];
Print[Style[StringForm["\[FilledDiamond]\:3000The positions of traingdata and testdata with a randomization seed number ``\n\tare exported in the Excel file, TraingindataPositioin.", seed],Bold, 15, Red]];
PB[];
ExportExcel2[hotraindata, Numberings@allNames, "Trainingdataset"];
ExportExcel2[hotestdata, Numberings@allNames, "Testdataset"];
Print[Style[StringForm["\[FilledDiamond]\:3000Trainingdata and Testdata for the Hold-Out method are expressed as TRAINSAMPLES and TESTSAMPLES.\n\tThey are exported in the Excel file, Trainingdataset and Testdataset."],Bold, 15, Red]];
PB[],
valimeth===3,
(* k-fold Cross validation method *)
foldsize=Round@(samplesize/foldnumb);
foldbag={};blockbag={};
randcage[1]:= randorder;Global`RANDCAGE[1]=randcage[1];
For[ii=1, ii<= foldnumb-1, ii++,
randpos[ii]=RandomSample[randcage[ii], foldsize];
AppendTo[foldbag, randpos[ii]];
AppendTo[blockbag,{ii, Part[allTrainingData, randpos[ii]]}];
randcage[ii+1]=IntactComplement[randcage[ii],randpos[ii]] ];
AppendTo[foldbag, randcage[foldnumb]];AppendTo[blockbag, {foldnumb, Part[allTrainingData, randcage[foldnumb]]}];
Global`FOLDBAG=foldbag;Global`BLOCKBAG=blockbag;
Print[Style[StringForm["\[FilledDiamond]\:3000``-fold Cross Validation method: The data was divided into `` blocks. The case counts in them are ``, respectively.",foldnumb, foldnumb, Map[Length,foldbag]], Bold, fontsize]];
Print[Style[StringForm["The `` folds of data blocks are expressed as BLOCKBAG.", foldnumb], Bold, fontsize]]
];
Print[" "];
(* Designation of selected dataset to TrainData with allNames as item names *)
Which[
valimeth===0,
(* No validation *)
TrainData=allTrainingData;
TestData={},
valimeth===1,
(* Hold-out method *)
TrainData=hotraindata;
TestData=hotestdata,
valimeth===3,
(* k-fold cross validation *)
TrainData=Drop[blockbag,-1];
TestData=Take[blockbag,-1],
True,
ErrorMessage["Unexpected valimeth designation error"];Goto["endingbuildmodel"]
];
Global`P4TRAINDATA=TrainData;
Global`P4TESTDATA =TestData;
(* ------- PHASE 5 -------Exploring Data---------------------------------------------------------------- *)