-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathSmart_Process_Analytics.py
1984 lines (1417 loc) · 131 KB
/
Smart_Process_Analytics.py
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
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 19 00:56:16 2020
@author: Weike (Vicky) Sun [email protected]/[email protected]
(c) 2020 Weike Sun, all rights reserved
"""
import pandas as pd
import numpy as np
from dataset_property_new import nonlinearity_assess, collinearity_assess, residual_analysis, nonlinearity_assess_dynamic
from sklearn.preprocessing import StandardScaler
import matplotlib as mpl
mpl.style.use('default')
import warnings
warnings.filterwarnings('ignore')
"""
Decision Tree for Smart Process Analytics
"""
"""
Create Data Block
"""
print("""----------------------------------------------------
Please provide the following information using 'Yes=1' or 'No=0'
----------------------------------------------------""")
if_have_testing_data = int(input("Do you have a specific testing dataset you want to test? "))
if_time_series = int(input("The data is time-series? "))
if_interpretable = int(input("Do you require the model to be interpretable? "))
if_continuity = int(input("Do you require the model to be contiuous? e.g., use the model for an optimizer. "))
if_grouped = int(input("Is there any grouping in your measurements? e.g., replicated measurements. "))
if not if_grouped:
group =None
if_spectra = int(input("Spectral data? "))
if_plot_interrogation = int(input("Do you want to visualize the data interrogation results? "))
if_time = int(input("Do you have time for nested cross-validation? "))
if_robust = int(input("Do you prioritize robustness over accuracy? "))
print('')
print("""----------------------------------------------------
Please provide the following information using 'Yes=1', 'No=0', or 'Unknown=2'
---------------------------------------------------- """)
if_enough = int(input("Do you think you have enough data to characterize the underlying process complexity? "))
if_nonlinear = int(input("Do you believe your model should be nonlinear? For spectral data, the linear model is used. "))
if if_spectra:
if_nonlinear = 0
if_multicollinear= int(input("Do you believe there is siginificant collinearity in your data? "))
if_dynamic = int(input("Do you believe the dynamic model is neccessary? "))
if if_dynamic != 0 and if_time_series == 0:
print('Warining*Your data is not time series data, so only static model should be considered.*')
if_dynamic = 0
if_stability = int(input("Do you require information of model stability given enough time? "))
print('')
print("""----------------------------------------------------
Please provide the file name, e.g., mydata.txt:
----------------------------------------------------""")
Data_name = input("Name of your data file (Should have dimension N x (m+1), last column for predicted variable) ")
#load data
if Data_name[-3:] == 'txt':
if int(input('Is there delimiter (,) in your txt file? ')):
Data = np.loadtxt(Data_name, delimiter=',')
else:
Data = np.loadtxt(Data_name)
elif Data_name[-3:] == 'lsx':
Data = pd.read_excel(Data_name, header = None)
Data = np.array(Data)
else:
print("Please convert data type to '.txt' or '.xlsx'")
X_original = Data[:,0:-1]
y_original = Data[:,-1].reshape(-1,1)
m = np.shape(X_original)[1]
N = np.shape(X_original)[0]
if if_have_testing_data:
Test_data_name = input("Please provide test dataset name: ")
if Test_data_name[-3:] == 'txt':
if int(input('Is there delimiter (,) in your txt file? ')):
Test_data = np.loadtxt(Test_data_name, delimiter = ',')
else:
Test_data = np.loadtxt(Test_data_name)
elif Test_data_name[-3:] == 'lsx':
Test_data = pd.read_excel(Test_data_name, header = None)
Test_data = np.array(Test_data)
else:
print("Please convert test data type to '.txt' or '.xlsx'")
X_test_original = Test_data[:,0:-1]
y_test_original = Test_data[:,-1].reshape(-1,1)
N_test = np.shape(X_test_original)[0]
else:
X_test_original = None
y_test_original = None
"""
Assess Data Property
"""
round_number = 0
print('')
print("""----------------------------------------------------
Please provide the following information to assess data [Yes:1 No:0]:
----------------------------------------------------""")
if int(input("Is there any categorical variable in your X? ")):
cat = list(map(int,input("Enter a series of indicator for which variable is categorical: e.g., 1 0 0 represents the 1st variable is a categorical variable. ").strip().split()))[:m]
else:
cat = None
if int(input("Do you have varaibles names you want to use in the figures? [Yes 1 No 0]: ")):
xticks = list(map(str,input("Enter a series of x variable name: e.g., x1 x2 x3. ").strip().split()))[:m]
yticks = list(input("Enter the name of y variable: ").strip().split())[:1]
else:
xticks = None
yticks = None
if int(input("Do you have a significance level to use? ")):
alpha = float(input("Provide the significance level: "))
else:
alpha = 0.01
if if_nonlinear == 2:
if_nonlinear = nonlinearity_assess(X_original, y_original, if_plot_interrogation, cat = cat,alpha = alpha, difference = 0.4, xticks = xticks, yticks = yticks, round_number = round_number)
if if_nonlinear == 0 and if_dynamic == 1:
lag = int(input('The lag number you want to use to assess nonlinear dyanmics: '))
if_nonlinear_dynamic = nonlinearity_assess_dynamic(X_original, y_original, if_plot_interrogation, alpha = alpha, difference = 0.4, xticks = xticks, yticks = yticks, round_number = round_number,lag= lag)
if if_nonlinear_dynamic ==1:
if_nonlinear = 1
if if_multicollinear == 2:
if_multicollinear = int(collinearity_assess(X_original, y_original, if_plot_interrogation, xticks = xticks, yticks = yticks, round_number = round_number))
"""
Select the Model
"""
if int(input('Do you have a specific model in the data analytical traingle that you want to use? ')):
model_name = list(map(str,input('Please provide the model name: [ALVEN/SVR/RF/EN/SPLS/RR/PLS or DALVEN or RNN or SS]. Note you can not test static and dynamic model at the same time. If you put in the static model name and then there is significant dynamics in the residual and you did not answer 0 to "do you want a dynamic model", the dyanmic model will be tested automatically after that. ').strip().split()))
else:
print('')
print("""----------------------------------------------------
Based on the information of data characteristics, the following methods are selected:
----------------------------------------------------""")
model_name = None
if if_nonlinear == 1:
if if_dynamic == 0 or if_dynamic == 2:
print('The nonlinear model is selected:')
if if_enough == 0:
print('Because you have limited data, ALVEN is recommonded.')
model_name = ['ALVEN']
elif if_interpretable == 1:
print('Because you would like an interpretable model, ALVEN is recommonded.')
model_name = ['ALVEN']
elif if_continuity == 1:
print('Because you ask for continuity, ALVEN/SVR are recommonded.')
model_name = ['ALVEN','SVR']
else:
print('The nonlinear models, ALVEN/SVR/RF, will be tested.')
model_name = ['ALVEN','SVR','RF']
if if_dynamic == 1:
print('The nonlinear dynamic model is selected:')
if if_enough == 0 :
print('Because you have limited data, DALVEN is recommonded.')
model_name = ['DALVEN']
elif if_interpretable == 1:
print('Because you would like an interpretable model, DALVEN is recommonded.')
model_name = ['DALVEN']
else:
print('Because you have engough data and do not require interpretability, RNN is recommonded.')
model_name = ['RNN']
else:
if if_dynamic == 0 or if_dynamic ==2:
if if_multicollinear == 0:
print('There is no significant nonlinearity and multicollinearity in the data, OLS is recommonded.')
model_name = ['OLS']
else:
if if_spectra:
print('Because you have spectral data, RR/PLS are recommonded.')
model_name = ['RR','PLS']
elif if_interpretable:
print('Because you want interpretability, EN/SOLS are recommonded.')
model_name = ['EN','SPLS']
else:
print('There is significant multicollinearity, EN/SPLS/RR/PLS are recommonded.')
model_name = ['EN','SPLS','RR','PLS']
else:
print('There is significant dynamics and multicolinearity, CVA/SSARX/MOSEP are recommonded.')
model_name = ['SS']
"""
Select Cross-Validation Strategy
"""
nested_flag = 0
cv_method = None
one_std = 0
grouped = 0
if 'OLS' in model_name:
print("")
print('OLS is selected, no cross-validation is needed.')
elif int(input('Do you have a specific cross-validation method that you want to use? ')):
cv_method = input('Please provide the name of cross-validation method: ')
if if_grouped:
grouped = 1
print('Since you have grouped data, please provide the group lable of each variable in a Nx1 format.')
group_name = input('Please provide the file name of the label: (e.g. label.txt) ')
if group_name[-3:] == 'txt':
if int(input('Is there delimiter (,) in your txt file? ')):
group = np.loadtxt(group_name, delimiter=',')
else:
group = np.loadtxt(group_name)
elif group_name[-3:] == 'lsx':
group = pd.read_excel(group_name, header = None)
group = np.array(group)
else:
print("Please convert data type to '.txt' or '.xlsx'")
if if_robust==1:
one_std = 1
if if_stability ==1:
nested_flag = 1
else:
print('')
print("""----------------------------------------------------
Based on the information of data attributes, the cross-validation strategy is selected as:
----------------------------------------------------""")
if if_dynamic != 1:
if not if_grouped:
if if_enough == 1:
cv_method = 'Single'
print('Single validation set is used.')
else:
if if_time == 1:
if if_stability == 1:
if if_robust == 1:
cv_method = 'Re_KFold'
nested_flag = 1
one_std = 1
print('Nested CV with repeated KFold in inner loop and one-std rule is selected')
else:
cv_method = 'Re_KFold'
nested_flag = 1
print('Nested CV with repeated KFold in inner loop is selected')
else:
if if_robust == 1:
if int(input('Do you want to select beweent KFold/MC/Re_KFold? default: Re_Kfold. ')):
cv_method = input('Plese provide the CV method name: ')
one_std = 1
print(cv_method + ' with one-std rule is selected.')
else:
one_std = 1
cv_method = 'Re_KFold'
print('Repeated KFold with one-std rule is selected.')
else:
if int(input('Do you want to select beweent KFold/MC/Re_KFold? default: Re_Kfold. ')):
cv_method = input('Plese provide the CV method name: ')
print(cv_method + ' is selected.')
else:
cv_method = 'Re_KFold'
print('Repated KFold is selected.')
else:
if if_robust == 1:
if int(input('Do you want to select beweent KFold/MC/Re_KFold? default: Re_Kfold. ')):
cv_method = input('Plese provide the CV method name: ')
one_std = 1
print(cv_method + ' with one-std rule is selected.')
else:
one_std = 1
cv_method = 'Re_KFold'
print('Repeated KFold with one-std rule is selected.')
else:
if int(input('Do you want to select beweent KFold/MC/Re_KFold? default: Re_Kfold. ')):
cv_method = input('Plese provide the CV method name: ')
print(cv_method + ' is selected.')
else:
cv_method = 'Re_KFold'
print('Repated KFold is selected.')
else:
grouped = 1
print('Since you have grouped data, please provide the group lable of each variable in a Nx1 format.')
group_name = input('Please provide the file name of the label: (e.g. label.txt) ')
if group_name[-3:] == 'txt':
if int(input('Is there delimiter (,) in your txt file? ')):
group = np.loadtxt(group_name, delimiter=',')
else:
group = np.loadtxt(group_name)
elif group_name[-3:] == 'lsx':
group = pd.read_excel(group_name, header = None)
group = np.array(group)
else:
print("Please convert data type to '.txt' or '.xlsx'")
if if_enough == 1:
cv_method = 'Single_group'
print('Single grouped CV is selected')
else:
if if_time == 1:
if if_stability == 1:
if if_robust == 1:
one_std = 1
nested_flag = 1
cv_method = 'GroupKFold'
print('Nested grouped Kfold with one std rule is selected.')
else:
nested_flag = 1
cv_method = 'GroupKFold'
print('Nested grouped Kfold is selected.')
else:
if if_robust == 1:
one_std = 1
cv_method = 'GroupKFold'
print('Grouped Kfold with one std rule is selected.')
else:
cv_method = 'GroupKFold'
print('Grouped Kfold is selected.')
else:
if if_robust == 1:
one_std = 1
cv_method = 'GroupKFold'
print('Grouped Kfold with one std rule is selected.')
else:
cv_method = 'GroupKFold'
print('Grouped Kfold is selected.')
else:
if model_name == ['SS']:
print('MATLAB/ADAPTx packges with information criterion will be used')
else:
if if_enough == 1:
cv_method = 'Single_ordered'
print('Single validation is used for time series modeling.')
else:
if if_time:
if if_robust:
cv_method = 'Timeseries'
one_std = 1
print('Cross-validation for time series with one std rule is selected.')
else:
cv_method = 'Timeseries'
print('Cross-validation for time series is selected.')
else:
cv_method = 'IC'
print('Information criteria is selected.')
if if_robust:
one_std = 1
print('')
print("""----------------------------------------------------
Start Model Fitting
----------------------------------------------------""")
round_number = 1
from copy import deepcopy
########################### data preprocessing
X=deepcopy(X_original)
y=deepcopy(y_original)
scaler_x = StandardScaler(with_mean=True, with_std=True)
scaler_x.fit(X)
X_scale = scaler_x.transform(X)
scaler_y = StandardScaler(with_mean=True, with_std=True)
scaler_y.fit(y)
y_scale = scaler_y.transform(y)
if X_test_original is not None:
X_test = deepcopy(X_test_original)
y_test = deepcopy(y_test_original)
X_test_scale = scaler_x.transform(X_test)
y_test_scale = scaler_y.transform(y_test)
else:
X_test = X
y_test = y
X_test_scale =X_scale
y_test_scale =y_scale
############################ model fitting 1st round
fitting_result = {}
if 'OLS' in model_name:
from regression_models import OLS_fitting
final_model, model_params, mse_train, mse_test, yhat_train, yhat_test = OLS_fitting(X_scale, y_scale, X_test_scale, y_test_scale, 0)
fitting_result['OLS'] = {'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test}
selected_model = 'OLS'
yhat_test = scaler_y.inverse_transform(yhat_test)
_, if_dynamic = residual_analysis(X_test, y_test, yhat_test, alpha = alpha, round_number = round_number)
if if_dynamic != 0:
print('The first round static fitting is done, check if nonlinear model is neccesarry')
if if_dynamic:
print('There is significant dynamic in the residual, dyanmic model will be fitted in the 2nd round')
round_number = 2
else:
print('--------------Analysis Is Done--------------')
else:
print('--------------Analysis Is Done--------------')
elif if_dynamic == 2:
if not one_std:
#use static cross-validation for this round and traditional cv
import cv_final as cv
K_fold = int(input('Number of K-fold you want to use, or the fold number you want to use in single validation 1/K, if not known input 5: '))
Nr = int(input('Number of repetition (if have in CV) you want to use, if not known input 10: '))
alpha_num = int(input('Number of penalty weight you want to consider in RR/EN/ALVEN, if not known input 20: '))
if not nested_flag:
print('------Model Construction------')
val_err = np.zeros(len(model_name))
index = 0
fitting1_result_trial = {}
for model_index in model_name:
if model_index == 'ALVEN':
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val, final_list = cv.CV_mse(model_index, X, y, X_test, y_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num, label_name=True)
fitting1_result_trial[model_index] = {'model_hyper':model_hyper,'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val':MSE_val, 'final_list':final_list}
val_err[index] = MSE_val
elif model_index == 'SVR' or model_index == 'RF':
model_hyper,final_model, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv.CV_mse(model_index, X_scale, y_scale, X_test_scale, y_test_scale, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
fitting1_result_trial[model_index] = {'model_hyper':model_hyper,'final_model':final_model, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val':MSE_val}
val_err[index] = MSE_val
else:
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv.CV_mse(model_index, X_scale, y_scale, X_test_scale, y_test_scale, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
fitting1_result_trial[model_index] = {'model_hyper':model_hyper,'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val': MSE_val}
val_err[index] = MSE_val
index += 1
if len(model_name) > 1:
print('Select the best model from the small candidate pool based on validation error:')
selected_model = model_name[np.argmin(val_err)]
print('*****'+selected_model + ' is selected.'+'*****')
else:
selected_model = model_name[0]
fitting_result[selected_model]=fitting1_result_trial[selected_model]
yhat_test = scaler_y.inverse_transform(fitting_result[selected_model]['yhat_test'])
_, if_dynamic = residual_analysis(X_test, y_test, yhat_test, alpha = alpha, round_number = round_number)
print('The first round static fitting is done, check if nonlinear model is neccesarry')
if if_dynamic:
print('There is significant dynamic in the residual, dyanmic model will be fitted in the 2nd round')
round_number = 2
else:
print('--------------Analysis Is Done--------------')
else:
print('Nested CV is used and the model selection if necessary is based on testing set in the outter loop')
if not grouped:
num_outter = int(input('How many number of outter loop you want to use in Nested CV? if not known input 10: '))
print('------Model Construction------')
from sklearn.model_selection import train_test_split
test_nest_err = np.zeros((len(model_name),num_outter))
for index_out in range(num_outter):
X_nest, X_nest_test, y_nest, y_nest_test = train_test_split(X, y, test_size=1/K_fold, random_state= index_out)
X_nest_scale, X_nest_scale_test, y_nest_scale, y_nest_scale_test = train_test_split(X_scale, y_scale, test_size=1/K_fold, random_state= index_out)
index = 0
for model_index in model_name:
if model_index == 'ALVEN':
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val, final_list = cv.CV_mse(model_index, X_nest, y_nest, X_nest_test, y_nest_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num, label_name=True)
test_nest_err[index,index_out] = mse_test
elif model_index == 'SVR' or model_index == 'RF':
model_hyper,final_model, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv.CV_mse(model_index, X_nest_scale, y_nest_scale, X_nest_scale_test, y_nest_scale_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
test_nest_err[index,index_out] = mse_test
else:
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv.CV_mse(model_index, X_nest_scale, y_nest_scale, X_nest_scale_test, y_nest_scale_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
test_nest_err[index,index_out] = mse_test
index += 1
print('The nested CV testing MSE result:')
import matplotlib.pyplot as plt
plt.figure()
pos = [i+1 for i in range(len(model_name))]
ax=plt.subplot(111)
plt.violinplot(np.transpose(test_nest_err))
ax.set_xticks(pos)
ax.set_xticklabels(model_name)
ax.set_title('Testing MSE distribution using nested CV')
if len(model_name) > 1:
print('Select the best model from the small candidate pool based on nested test error:')
selected_model = model_name[np.argmin(np.mean(test_nest_err,axis=1))]
print('*****'+selected_model + ' is selected.*****')
else:
selected_model = model_name[0]
print('Final model fitting')
if selected_model == 'ALVEN':
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val, final_list = cv.CV_mse(selected_model, X, y, X_test, y_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num, label_name=True)
fitting_result[selected_model] = {'model_hyper':model_hyper,'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val':MSE_val, 'final_list':final_list}
elif selected_model == 'SVR' or selected_model == 'RF':
model_hyper,final_model, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv.CV_mse(selected_model, X_scale, y_scale, X_test_scale, y_test_scale, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
fitting_result[selected_model] = {'model_hyper':model_hyper,'final_model':final_model, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val':MSE_val}
else:
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv.CV_mse(selected_model, X_scale, y_scale, X_test_scale, y_test_scale, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
fitting_result[selected_model] = {'model_hyper':model_hyper,'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val': MSE_val}
yhat_test = scaler_y.inverse_transform(yhat_test)
_, if_dynamic = residual_analysis(X_test, y_test, yhat_test, alpha = alpha, round_number = round_number)
print('The first round static fitting is done, check if nonlinear model is neccesarry')
if if_dynamic:
print('There is significant dynamic in the residual, dyanmic model will be fitted in the 2nd round')
round_number = 2
else:
print('--------------Analysis Is Done--------------')
else:
from sklearn.model_selection import LeaveOneGroupOut
print('Leave one group out will be used in the outer loop')
print('------Model Construction------')
test_nest_err = np.zeros((len(model_name), len(np.unique(group))))
logo = LeaveOneGroupOut()
index_out = 0
for train, test in logo.split(X, y.flatten(), groups=group.flatten()):
index = 0
for model_index in model_name:
if model_index == 'ALVEN':
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val, final_list = cv.CV_mse(model_index, X[train], y[train], X[test], y[test], cv_type = cv_method, group = group[train], K_fold = K_fold, Nr= Nr, alpha_num=alpha_num, label_name=True)
test_nest_err[index,index_out] = mse_test
elif model_index == 'SVR' or model_index == 'RF':
model_hyper,final_model, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv.CV_mse(model_index, X_scale[train], y_scale[train], X_scale[test], y_scale[test], cv_type = cv_method, group = group[train], K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
test_nest_err[index,index_out] = mse_test
else:
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv.CV_mse(model_index, X_scale[train], y_scale[train], X_scale[test], y_scale[test], cv_type = cv_method, group = group[train], K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
test_nest_err[index,index_out] = mse_test
index += 1
index_out +=1
print('The nested CV testing MSE result:')
import matplotlib.pyplot as plt
plt.figure()
pos = [i+1 for i in range(len(model_name))]
ax=plt.subplot(111)
plt.violinplot(np.transpose(test_nest_err))
ax.set_xticks(pos)
ax.set_xticklabels(model_name)
ax.set_title('Testing MSE distribution using nested CV')
if len(model_name) > 1:
print('Select the best model from the small candidate pool based on nested test error:')
selected_model = model_name[np.argmin(np.mean(test_nest_err,axis=1))]
print('*****'+selected_model + ' is selected.*****')
else:
selected_model = model_name[0]
print('------Final model fitting-------')
if selected_model == 'ALVEN':
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val, final_list = cv.CV_mse(selected_model, X, y, X_test, y_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num, label_name=True)
fitting_result[selected_model] = {'model_hyper':model_hyper,'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val':MSE_val, 'final_list':final_list}
elif selected_model == 'SVR' or selected_model == 'RF':
model_hyper,final_model, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv.CV_mse(selected_model, X_scale, y_scale, X_test_scale, y_test_scale, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
fitting_result[selected_model] = {'model_hyper':model_hyper,'final_model':final_model, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val':MSE_val}
else:
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv.CV_mse(selected_model, X_scale, y_scale, X_test_scale, y_test_scale, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
fitting_result[selected_model] = {'model_hyper':model_hyper,'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val': MSE_val}
yhat_test = scaler_y.inverse_transform(yhat_test)
_, if_dynamic = residual_analysis(X_test, y_test, yhat_test, alpha = alpha, round_number = round_number)
print('The first round static fitting is done, check if nonlinear model is neccesarry')
if if_dynamic:
print('There is significant dynamic in the residual, dyanmic model will be fitted in the 2nd round')
round_number = 2
else:
print('--------------Analysis Is Done--------------')
else:
#use static cross-validation for this round and traditional cv
import cv_final_onestd as cv_std
K_fold = int(input('Number of K-fold you want to use, or the fold number you want to use in single validation 1/K, if not known input 5: '))
Nr = int(input('Number of repetition (if have in CV) you want to use, if not known input 10: '))
alpha_num = int(input('Number of penalty weight you want to consider in RR/EN/ALVEN, if not known input 20: '))
if not nested_flag:
print('------Model Construction------')
val_err = np.zeros(len(model_name))
index = 0
fitting1_result_trial = {}
for model_index in model_name:
if model_index == 'ALVEN':
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val, final_list = cv_std.CV_mse(model_index, X, y, X_test, y_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num, label_name=True)
fitting1_result_trial[model_index] = {'model_hyper':model_hyper,'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val':MSE_val, 'final_list':final_list}
val_err[index] = MSE_val
elif model_index == 'SVR' or model_index == 'RF':
model_hyper,final_model, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv_std.CV_mse(model_index, X_scale, y_scale, X_test_scale, y_test_scale, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
fitting1_result_trial[model_index] = {'model_hyper':model_hyper,'final_model':final_model, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val':MSE_val}
val_err[index] = MSE_val
else:
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv_std.CV_mse(model_index, X_scale, y_scale, X_test_scale, y_test_scale, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
fitting1_result_trial[model_index] = {'model_hyper':model_hyper,'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val': MSE_val}
val_err[index] = MSE_val
index += 1
if len(model_name) > 1:
print('Select the best model from the small candidate pool based on validation error:')
selected_model = model_name[np.argmin(val_err)]
print('*****'+selected_model + ' is selected.'+'*****')
else:
selected_model = model_name[0]
fitting_result[selected_model]=fitting1_result_trial[selected_model]
yhat_test = scaler_y.inverse_transform(fitting_result[selected_model]['yhat_test'])
_, if_dynamic = residual_analysis(X_test, y_test, yhat_test, alpha = alpha, round_number = round_number)
print('The first round static fitting is done, check if nonlinear model is neccesarry')
if if_dynamic:
print('There is significant dynamic in the residual, dyanmic model will be fitted in the 2nd round')
round_number = 2
else:
print('--------------Analysis Is Done--------------')
else:
print('Nested CV is used and the model selection if necessary is based on testing set in the outter loop')
if not grouped:
num_outter = int(input('How many number of outter loop you want to use in Nested CV? if not known input 10: '))
print('------Model Construction------')
from sklearn.model_selection import train_test_split
test_nest_err = np.zeros((len(model_name),num_outter))
for index_out in range(num_outter):
X_nest, X_nest_test, y_nest, y_nest_test = train_test_split(X, y, test_size=1/K_fold, random_state= index_out)
X_nest_scale, X_nest_scale_test, y_nest_scale, y_nest_scale_test = train_test_split(X_scale, y_scale, test_size=1/K_fold, random_state= index_out)
index = 0
for model_index in model_name:
if model_index == 'ALVEN':
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val, final_list = cv_std.CV_mse(model_index, X_nest, y_nest, X_nest_test, y_nest_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num, label_name=True)
test_nest_err[index,index_out] = mse_test
elif model_index == 'SVR' or model_index == 'RF':
model_hyper,final_model, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv_std.CV_mse(model_index, X_nest_scale, y_nest_scale, X_nest_scale_test, y_nest_scale_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
test_nest_err[index,index_out] = mse_test
else:
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv_std.CV_mse(model_index, X_nest_scale, y_nest_scale, X_nest_scale_test, y_nest_scale_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
test_nest_err[index,index_out] = mse_test
index += 1
print('The nested CV testing MSE result:')
import matplotlib.pyplot as plt
plt.figure()
pos = [i+1 for i in range(len(model_name))]
ax=plt.subplot(111)
plt.violinplot(np.transpose(test_nest_err))
ax.set_xticks(pos)
ax.set_xticklabels(model_name)
ax.set_title('Testing MSE distribution using nested CV')
if len(model_name) > 1:
print('Select the best model from the small candidate pool based on nested test error:')
selected_model = model_name[np.argmin(np.mean(test_nest_err,axis=1))]
print('*****'+selected_model + ' is selected.*****')
else:
selected_model = model_name[0]
print('Final model fitting')
if selected_model == 'ALVEN':
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val, final_list = cv_std.CV_mse(selected_model, X, y, X_test, y_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num, label_name=True)
fitting_result[selected_model] = {'model_hyper':model_hyper,'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val':MSE_val, 'final_list':final_list}
elif selected_model == 'SVR' or selected_model == 'RF':
model_hyper,final_model, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv_std.CV_mse(selected_model, X_scale, y_scale, X_test_scale, y_test_scale, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
fitting_result[selected_model] = {'model_hyper':model_hyper,'final_model':final_model, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val':MSE_val}
else:
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv_std.CV_mse(selected_model, X_scale, y_scale, X_test_scale, y_test_scale, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
fitting_result[selected_model] = {'model_hyper':model_hyper,'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val': MSE_val}
yhat_test = scaler_y.inverse_transform(yhat_test)
_, if_dynamic = residual_analysis(X_test, y_test, yhat_test, alpha = alpha, round_number = round_number)
print('The first round static fitting is done, check if nonlinear model is neccesarry')
if if_dynamic:
print('There is significant dynamic in the residual, dyanmic model will be fitted in the 2nd round')
round_number = 2
else:
print('--------------Analysis Is Done--------------')
else:
from sklearn.model_selection import LeaveOneGroupOut
print('Leave one group out will be used in the outer loop')
print('------Model Construction------')
test_nest_err = np.zeros((len(model_name), len(np.unique(group))))
logo = LeaveOneGroupOut()
index_out = 0
for train, test in logo.split(X, y.flatten(), groups=group.flatten()):
index = 0
for model_index in model_name:
if model_index == 'ALVEN':
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val, final_list = cv_std.CV_mse(model_index, X[train], y[train], X[test], y[test], cv_type = cv_method, group = group[train], K_fold = K_fold, Nr= Nr, alpha_num=alpha_num, label_name=True)
test_nest_err[index,index_out] = mse_test
elif model_index == 'SVR' or model_index == 'RF':
model_hyper,final_model, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv_std.CV_mse(model_index, X_scale[train], y_scale[train], X_scale[test], y_scale[test], cv_type = cv_method, group = group[train], K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
test_nest_err[index,index_out] = mse_test
else:
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv_std.CV_mse(model_index, X_scale[train], y_scale[train], X_scale[test], y_scale[test], cv_type = cv_method, group = group[train], K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
test_nest_err[index,index_out] = mse_test
index += 1
index_out +=1
print('The nested CV testing MSE result:')
import matplotlib.pyplot as plt
plt.figure()
pos = [i+1 for i in range(len(model_name))]
ax=plt.subplot(111)
plt.violinplot(np.transpose(test_nest_err))
ax.set_xticks(pos)
ax.set_xticklabels(model_name)
ax.set_title('Testing MSE distribution using nested CV')
if len(model_name) > 1:
print('Select the best model from the small candidate pool based on nested test error:')
selected_model = model_name[np.argmin(np.mean(test_nest_err,axis=1))]
print('*****'+selected_model + ' is selected.*****')
else:
selected_model = model_name[0]
print('------Final model fitting-------')
if selected_model == 'ALVEN':
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val, final_list = cv_std.CV_mse(selected_model, X, y, X_test, y_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num, label_name=True)
fitting_result[selected_model] = {'model_hyper':model_hyper,'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val':MSE_val, 'final_list':final_list}
elif selected_model == 'SVR' or selected_model == 'RF':
model_hyper,final_model, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv_std.CV_mse(selected_model, X_scale, y_scale, X_test_scale, y_test_scale, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
fitting_result[selected_model] = {'model_hyper':model_hyper,'final_model':final_model, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val':MSE_val}
else:
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv_std.CV_mse(selected_model, X_scale, y_scale, X_test_scale, y_test_scale, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
fitting_result[selected_model] = {'model_hyper':model_hyper,'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val': MSE_val}
yhat_test = scaler_y.inverse_transform(yhat_test)
_, if_dynamic = residual_analysis(X_test, y_test, yhat_test, alpha = alpha, round_number = round_number)
print('The first round static fitting is done, check if nonlinear model is neccesarry')
if if_dynamic:
print('There is significant dynamic in the residual, dyanmic model will be fitted in the 2nd round')
round_number = 2
else:
print('--------------Analysis Is Done--------------')
elif if_dynamic == 0:
if not one_std:
#use static cross-validation for this round and traditional cv
import cv_final as cv
K_fold = int(input('Number of K-fold you want to use, or the fold number you want to use in single validation 1/K, if not known input 5: '))
Nr = int(input('Number of repetition (if have in CV) you want to use, if not known input 10: '))
alpha_num = int(input('Number of penalty weight you want to consider in RR/EN/ALVEN, if not known input 20: '))
if not nested_flag:
print('------Model Construction------')
val_err = np.zeros(len(model_name))
index = 0
fitting1_result_trial = {}
for model_index in model_name:
if model_index == 'ALVEN':
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val, final_list = cv.CV_mse(model_index, X, y, X_test, y_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num, label_name=True)
fitting1_result_trial[model_index] = {'model_hyper':model_hyper,'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val':MSE_val, 'final_list':final_list}
val_err[index] = MSE_val
elif model_index == 'SVR' or model_index == 'RF':
model_hyper,final_model, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv.CV_mse(model_index, X_scale, y_scale, X_test_scale, y_test_scale, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
fitting1_result_trial[model_index] = {'model_hyper':model_hyper,'final_model':final_model, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val':MSE_val}
val_err[index] = MSE_val
else:
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv.CV_mse(model_index, X_scale, y_scale, X_test_scale, y_test_scale, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
fitting1_result_trial[model_index] = {'model_hyper':model_hyper,'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val': MSE_val}
val_err[index] = MSE_val
index += 1
if len(model_name) > 1:
print('Select the best model from the small candidate pool based on validation error:')
selected_model = model_name[np.argmin(val_err)]
print('*****'+selected_model + ' is selected.'+'*****')
else:
selected_model = model_name[0]
fitting_result[selected_model]=fitting1_result_trial[selected_model]
yhat_test = scaler_y.inverse_transform(fitting_result[selected_model]['yhat_test'])
residual_analysis(X_test, y_test, yhat_test, alpha = alpha, round_number = round_number)
print('--------------Analysis Is Done--------------')
else:
print('Nested CV is used and the model selection if necessary is based on testing set in the outter loop')
if not grouped:
num_outter = int(input('How many number of outter loop you want to use in Nested CV? if not known input 10: '))
print('------Model Construction------')
from sklearn.model_selection import train_test_split
test_nest_err = np.zeros((len(model_name),num_outter))
for index_out in range(num_outter):
X_nest, X_nest_test, y_nest, y_nest_test = train_test_split(X, y, test_size=1/K_fold, random_state= index_out)
X_nest_scale, X_nest_scale_test, y_nest_scale, y_nest_scale_test = train_test_split(X_scale, y_scale, test_size=1/K_fold, random_state= index_out)
index = 0
for model_index in model_name:
if model_index == 'ALVEN':
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val, final_list = cv.CV_mse(model_index, X_nest, y_nest, X_nest_test, y_nest_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num, label_name=True)
test_nest_err[index,index_out] = mse_test
elif model_index == 'SVR' or model_index == 'RF':
model_hyper,final_model, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv.CV_mse(model_index, X_nest_scale, y_nest_scale, X_nest_scale_test, y_nest_scale_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
test_nest_err[index,index_out] = mse_test
else:
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv.CV_mse(model_index, X_nest_scale, y_nest_scale, X_nest_scale_test, y_nest_scale_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
test_nest_err[index,index_out] = mse_test
index += 1
print('The nested CV testing MSE result:')
import matplotlib.pyplot as plt
plt.figure()
pos = [i+1 for i in range(len(model_name))]
ax=plt.subplot(111)
plt.violinplot(np.transpose(test_nest_err))
ax.set_xticks(pos)
ax.set_xticklabels(model_name)
ax.set_title('Testing MSE distribution using nested CV')
if len(model_name) > 1:
print('Select the best model from the small candidate pool based on nested test error:')
selected_model = model_name[np.argmin(np.mean(test_nest_err,axis=1))]
print('*****'+selected_model + ' is selected.*****')
else:
selected_model = model_name[0]
print('Final model fitting')
if selected_model == 'ALVEN':
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val, final_list = cv.CV_mse(selected_model, X, y, X_test, y_test, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num, label_name=True)
fitting_result[selected_model] = {'model_hyper':model_hyper,'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val':MSE_val, 'final_list':final_list}
elif selected_model == 'SVR' or selected_model == 'RF':
model_hyper,final_model, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv.CV_mse(selected_model, X_scale, y_scale, X_test_scale, y_test_scale, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
fitting_result[selected_model] = {'model_hyper':model_hyper,'final_model':final_model, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val':MSE_val}
else:
model_hyper,final_model, model_params, mse_train, mse_test, yhat_train, yhat_test, MSE_val = cv.CV_mse(selected_model, X_scale, y_scale, X_test_scale, y_test_scale, cv_type = cv_method, group = group, K_fold = K_fold, Nr= Nr, alpha_num=alpha_num)
fitting_result[selected_model] = {'model_hyper':model_hyper,'final_model':final_model, 'model_params':model_params, 'mse_train':mse_train, 'mse_test':mse_test, 'yhat_train':yhat_train, 'yhat_test':yhat_test, 'MSE_val': MSE_val}
yhat_test = scaler_y.inverse_transform(yhat_test)
residual_analysis(X_test, y_test, yhat_test, alpha = alpha, round_number = round_number)
print('--------------Analysis Is Done--------------')
else:
from sklearn.model_selection import LeaveOneGroupOut
print('Leave one group out will be used in the outer loop')
print('------Model Construction------')
test_nest_err = np.zeros((len(model_name), len(np.unique(group))))
logo = LeaveOneGroupOut()
index_out = 0
for train, test in logo.split(X, y.flatten(), groups=group.flatten()):