forked from ornlpmcp/ASCENDS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ascends.py
1461 lines (1180 loc) · 59 KB
/
ascends.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
from __future__ import print_function
# In[1]:
import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter("ignore")
import os
import numpy as np
import tensorflow as tf
import random as rn
os.environ['KMP_DUPLICATE_LIB_OK']='True'
from keras import regularizers
from keras.datasets import mnist
from keras.layers import Dense, Dropout
from keras.models import Sequential
from keras.optimizers import RMSprop
from pandas.plotting import scatter_matrix
from pprint import pprint
from sklearn import linear_model
from sklearn import preprocessing
from sklearn import svm
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import f_regression
from sklearn.feature_selection import SelectFromModel
from sklearn.feature_selection import SelectKBest
from sklearn.gaussian_process.kernels import WhiteKernel, ExpSineSquared
from sklearn.isotonic import IsotonicRegression
from sklearn.kernel_ridge import KernelRidge
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RidgeClassifier
from sklearn.linear_model import SGDRegressor
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import r2_score
from sklearn.model_selection import cross_val_predict
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RandomizedSearchCV
from sklearn.neighbors import KNeighborsRegressor
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import Normalizer
from sklearn.preprocessing import StandardScaler
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import KFold
from sklearn.preprocessing import LabelEncoder
import configparser
import csv
import datetime
import glob
import keras
import math
import matplotlib
#matplotlib.use("TkAgg")
from matplotlib import pyplot as plt
import os
import pandas as pd
import pickle
import random
import sys
import time
import traceback
from minepy import MINE
from sklearn.linear_model import LogisticRegression
from os import path
from pathlib import PurePath
from tensorflow.python.util import deprecation
import tensorflow as tf
import multiprocessing
deprecation._PRINT_DEPRECATION_WARNINGS = False
config = tf.ConfigProto()
#config.gpu_options.per_process_gpu_memory_fraction = 0.5 # maximun alloc gpu50% of MEM
#config.gpu_options.allow_growth = True #allocate dynamically
#config = tf.ConfigProto( device_count = {'GPU': 2 , 'CPU':4 } )
sess = tf.Session(config=config)
keras.backend.set_session(sess)
#os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
os.environ['TF_CPP_MIN_VLOG_LEVEL'] = '2'
def save_test_data(predictions, actual_values, filename):
df_predictions = pd.DataFrame(predictions, columns=['predictions'])
df_actual_values = pd.DataFrame(actual_values, columns=['actual_values'])
df = df_predictions.join(df_actual_values)
df.to_csv(filename)
# In[3]:
def load_header(csv_file, print_out = False):
# Loading headers
headers = pd.read_csv(csv_file,header=None, nrows=1).values[0]
idx_to_key = {}
key_to_idx = {}
for i in range(0, len(headers)):
idx = i
key = headers[i]
key_to_idx[key] = idx
idx_to_key[idx] = key
if print_out is True:
print(idx_to_key)
return headers, idx_to_key, key_to_idx
def model_name(model_abbr):
model_name = None
if(model_abbr =='RF'):
model_name = 'Random Forest'
elif(model_abbr =='NET'):
model_name = 'Neural Network'
elif(model_abbr =='LR'):
model_name = 'Linear Regression'
elif(model_abbr =='LRC'):
model_name = 'Logistic Regression'
elif(model_abbr =='RG'):
model_name = 'Ridge'
elif(model_abbr =='KR'):
model_name = 'Kernel Ridge'
elif(model_abbr =='BR'):
model_name = 'Bayesian Ridge'
elif(model_abbr =='SVM'):
model_name = 'Support Vector Machine'
elif(model_abbr =='NN'):
model_name = 'k-Nearest Neighbor'
return model_name
# In[4]:
def data_load_shuffle(csv_file, input_col, cols_to_remove, target_col, random_state=0, delimiter = ',', map_all = None):
data = pd.read_csv(csv_file, delimiter = delimiter)
data_df = data[data[target_col].notnull()]
if cols_to_remove is not None:
for col in cols_to_remove:
del data_df[col]
data_df_shuffle = data_df.sample(frac=1, random_state=random_state)
if input_col is not None:
data_df_shuffle = data_df_shuffle[input_col+[target_col]]
data_df = data_df[input_col+[target_col]]
y_train = pd.DataFrame(data_df_shuffle[target_col])
# training set is without target column
del data_df_shuffle[target_col]
x_train = data_df_shuffle.copy()
headers, idx_to_key, key_to_idx = load_header(csv_file)
cols_to_remove_ = []
headers = list(headers)
header_y = target_col
if cols_to_remove is not None:
for col in cols_to_remove:
headers.remove(col)
headers.remove(target_col)
# dataframe to numpy array
x_train_original = x_train
y_train = y_train.values
x_train = x_train.values
# reshaping target values
y_train = y_train.reshape(y_train.shape[0],1)
if input_col is not None:
header_x = np.array(input_col)
else:
header_x = np.array(headers)
key_idx = -1
if map_all is not None:
for key in map_all.keys():
for i in range(0, len(header_x)):
if header_x[i]==key:
key_idx = i
break
if key_idx!=-1:
for item in x_train:
item[key_idx] = map_all[key][item[key_idx]]
if map_all is not None:
for key in map_all.keys():
if header_y==key:
new_y_train = []
for item in y_train:
item = [map_all[key][item[0]]]
new_y_train.append(item)
y_train = np.array(new_y_train)
for key in map_all.keys():
data_df[key] = data_df[key].map(map_all[key])
x_train = x_train.astype('float32')
y_train = y_train.astype('float32')
return data_df, x_train, y_train, header_x, header_y
def correlation_analysis_all(data_df, target_col, top_k=10, file_to_save = None, save_chart = None, only_pcc= False, feature_selection_file = None):
if feature_selection_file == None:
print("* correlation_analysis_all")
pcc = data_df.corr()[target_col]
if(len(pcc)<top_k):
top_k=len(pcc)
print("Computing PCC, PCC_SQRT ..")
pcc = pcc.sort_values(ascending = False).dropna()
pcc = pcc.rename("PCC")
try:
del pcc[target_col]
except:
pass
pcc_sqrt = pcc.apply(lambda x: np.sqrt(x* x))
pcc_sqrt = pcc_sqrt.sort_values(ascending = False).dropna()
pcc_sqrt = pcc_sqrt.rename("PCC_SQRT")
MICs = []
MASs = []
MEVs = []
MCNs = []
MCN_generals = []
GMICs = []
TICs = []
print("Computing all other metrics ..")
if only_pcc==False or only_pcc=='False':
for col in data_df.columns:
print(" - computing for ", col, "...")
if col!=target_col:
x = data_df[col].values
y = data_df[target_col].values
mine = MINE()
mine.compute_score(x,y)
MICs.append((col,mine.mic()))
MASs.append((col,mine.mas()))
MEVs.append((col,mine.mev()))
MCNs.append((col,mine.mcn(0)))
MCN_generals.append((col,mine.mcn_general()))
GMICs.append((col,mine.gmic()))
TICs.append((col,mine.tic()))
top_k_pcc = list(pcc.keys())[:top_k]
top_k_pcc_sqrt = list(pcc_sqrt.keys())[:top_k]
top_k_mic = [tup[0] for tup in sorted(MICs, key=lambda tup: tup[1], reverse = True)[:top_k]]
top_k_mas = [tup[0] for tup in sorted(MASs, key=lambda tup: tup[1], reverse = True)[:top_k]]
top_k_mev = [tup[0] for tup in sorted(MEVs, key=lambda tup: tup[1], reverse = True)[:top_k]]
top_k_mcn = [tup[0] for tup in sorted(MCNs, key=lambda tup: tup[1], reverse = True)[:top_k]]
top_k_mcn_general = [tup[0] for tup in sorted(MCN_generals, key=lambda tup: tup[1], reverse = True)[:top_k]]
top_k_gmic = [tup[0] for tup in sorted(GMICs, key=lambda tup: tup[1], reverse = True)[:top_k]]
top_k_tic = [tup[0] for tup in sorted(TICs, key=lambda tup: tup[1], reverse = True)[:top_k]]
mic_df = pd.DataFrame([tup[1] for tup in MICs],columns=['MIC'],index=[tup[0] for tup in MICs])
mas_df = pd.DataFrame([tup[1] for tup in MASs],columns=['MAS'],index=[tup[0] for tup in MASs])
mev_df = pd.DataFrame([tup[1] for tup in MEVs],columns=['MEV'],index=[tup[0] for tup in MEVs])
mcn_df = pd.DataFrame([tup[1] for tup in MCNs],columns=['MCN'],index=[tup[0] for tup in MCNs])
mcn_general_df = pd.DataFrame([tup[1] for tup in MCN_generals],columns=['MCN_general'],index=[tup[0] for tup in MCN_generals])
gmic_df = pd.DataFrame([tup[1] for tup in GMICs],columns=['GMIC'],index=[tup[0] for tup in GMICs])
tic_df = pd.DataFrame([tup[1] for tup in TICs],columns=['TIC'],index=[tup[0] for tup in TICs])
if only_pcc==False or only_pcc=='False':
final_report = mic_df.join(mas_df).join(mev_df).join(mcn_df).join(mcn_general_df).join(gmic_df).join(tic_df).sort_index().join(pcc_sqrt).join(pcc)
else:
pcc_sqrt = pd.DataFrame(pcc_sqrt)
final_report = pcc_sqrt.join(pcc)
if file_to_save is not None:
# save to correlation report
final_report.to_csv(file_to_save)
if save_chart is not None:
for col in final_report.keys():
ax = final_report[col].sort_values(ascending=False).plot(kind='bar',alpha=0.8)
ax.set_ylabel(col+" (target_col = '"+target_col+"')", fontsize=12)
plt.axhline(0, color='k')
plt.savefig(save_chart)
plt.close()
fs_dict = {'PCC':top_k_pcc,'PCC_SQRT':top_k_pcc_sqrt,'MIC':top_k_mic,'MAS':top_k_mas,'MEV':top_k_mev,'MCN':top_k_mcn,'MCN_general':top_k_mcn_general,'GMIC':top_k_gmic,'TIC':top_k_tic}
else:
final_report = pd.read_csv(feature_selection_file)
top_k_pcc = list(final_report.sort_values(by=['PCC'], ascending=False).T.values[0])[:top_k]
top_k_pcc_sqrt = list(final_report.sort_values(by=['PCC_SQRT'], ascending=False).T.values[0])[:top_k]
top_k_mic = list(final_report.sort_values(by=['MIC'], ascending=False).T.values[0])[:top_k]
top_k_mas = list(final_report.sort_values(by=['MAS'], ascending=False).T.values[0])[:top_k]
top_k_mev = list(final_report.sort_values(by=['MEV'], ascending=False).T.values[0])[:top_k]
top_k_mcn = list(final_report.sort_values(by=['MCN'], ascending=False).T.values[0])[:top_k]
top_k_mcn_general = list(final_report.sort_values(by=['MCN_general'], ascending=False).T.values[0])[:top_k]
top_k_gmic = list(final_report.sort_values(by=['GMIC'], ascending=False).T.values[0])[:top_k]
top_k_tic = list(final_report.sort_values(by=['TIC'], ascending=False).T.values[0])[:top_k]
fs_dict = {'PCC':top_k_pcc,'PCC_SQRT':top_k_pcc_sqrt,'MIC':top_k_mic,'MAS':top_k_mas,'MEV':top_k_mev,'MCN':top_k_mcn,'MCN_general':top_k_mcn_general,'GMIC':top_k_gmic,'TIC':top_k_tic}
if file_to_save is not None:
# save to correlation report
final_report.to_csv(file_to_save)
if save_chart is not None:
for col in final_report.keys()[1:]:
ax = final_report[col].sort_values(ascending=False).plot(kind='bar',alpha=0.8)
ax.set_ylabel(col+" (target_col = '"+target_col+"')", fontsize=12)
plt.axhline(0, color='k')
plt.savefig(save_chart)
plt.close()
return fs_dict, final_report
# In[6]:
def default_model_parameters_classifier():
model_parameters = {
'scaler_option':'StandardScaler', \
'rf_n_estimators': '100', 'rf_max_features': 'auto', 'rf_max_depth': 'None', \
'rf_min_samples_split': '2', 'rf_min_samples_leaf': '1', 'rf_bootstrap': 'True', \
'rf_criterion':'gini','rf_min_weight_fraction_leaf':'0.','rf_max_leaf_nodes':'None',\
'rf_min_impurity_decrease':'0.',\
'nn_n_neighbors': '5', 'nn_weights': 'uniform', 'nn_algorithm': 'auto', 'nn_leaf_size': '30', 'nn_p': '2',\
'nn_metric':'minkowski','nn_metric_params':'None',
'rg_alpha':'1','rg_fit_intercept':'True','rg_normalize':'False','rg_max_iter':'None','rg_tol':'0.001','rg_class_weight':'None','rg_solver':'auto','svm_kernel': 'rbf', \
'svm_degree': '3', 'svm_coef0': '0.0', 'svm_tol': '1e-3', 'svm_c': '1.0', \
'svm_gamma': 'auto', \
'svm_decision_function_shape':'ovr', \
'net_structure':'16 16 16',\
'net_layer_n':'3',\
'net_dropout': '0.0',\
'net_l_2': '0.01',\
'net_learning_rate': '0.01',\
'net_epochs': '100',\
'net_batch_size': '2',\
}
return model_parameters
def default_model_parameters():
model_parameters = {
'scaler_option':'StandardScaler', \
'rf_n_estimators': '100', 'rf_max_features': 'auto', 'rf_max_depth': 'None', \
'rf_min_samples_split': '2', 'rf_min_samples_leaf': '1', 'rf_bootstrap': 'True', \
'rf_criterion':'mse','rf_min_weight_fraction_leaf':'0.','rf_max_leaf_nodes':'None',\
'rf_min_impurity_decrease':'0.',\
'nn_n_neighbors': '5', 'nn_weights': 'uniform', 'nn_algorithm': 'auto', 'nn_leaf_size': '30', 'nn_p': '2',\
'nn_metric':'minkowski','nn_metric_params':'None',\
'kr_alpha': '1', 'kr_kernel': 'linear', 'kr_gamma': 'None', 'kr_degree': '3', 'kr_coef0': '1', \
'br_n_iter': '300', 'br_alpha_1': '1.2e-6', 'br_alpha_2': '1.e-6', 'br_tol': '1.e-3', \
'br_lambda_1': '1.e-6', 'br_lambda_2': '1.e-6', 'br_compute_score': 'False', 'br_fit_intercept': 'True', \
'br_normalize':'False',\
'svm_kernel': 'rbf', \
'svm_degree': '3', 'svm_coef0': '0.0', 'svm_tol': '1e-3', 'svm_c': '1.0', \
'svm_epsilon': '0.1', 'svm_shrinking': 'True', 'svm_gamma': 'auto', \
'net_structure':'16 16 16',\
'net_layer_n':'3',\
'net_dropout': '0.0',\
'net_l_2': '0.01',\
'net_learning_rate': '0.01',\
'net_epochs': '100',\
'net_batch_size': '2',\
}
return model_parameters
def load_model_parameter_from_file(filename):
config = configparser.RawConfigParser()
config.read(filename)
model_parameters = {}
for key in config['HYPERPARAMETERS']:
model_parameters[key] = config["HYPERPARAMETERS"][key]
return model_parameters
# In[7]:
def fix_value(val, val_type):
if val is None or val=='None':
return None
elif val=='auto':
return val
else:
if(val_type=='float'):
return float(val)
elif(val_type=='str'):
return str(val)
elif(val_type=='int'):
return int(val)
elif(val_type=='bool'):
return str2bool(val)
elif val_type=='PurePath':
return PurePath(val)
else:
return val
def define_model_classifier(model_type, model_parameters, x_header_size, random_state = None):
if model_type == "LRC":
model = Pipeline([
('classification', LogisticRegression())
])
elif model_type == "RF":
model = Pipeline([
('classification', RandomForestClassifier(n_estimators = int(model_parameters['rf_n_estimators']),
max_features = fix_value(model_parameters['rf_max_features'],'int'),
max_depth = fix_value(model_parameters['rf_max_depth'],'int'),
min_samples_split = int(model_parameters['rf_min_samples_split']),
min_samples_leaf = int(model_parameters['rf_min_samples_leaf']),
bootstrap = str2bool(model_parameters['rf_bootstrap']),
criterion = model_parameters['rf_criterion'],
random_state = random_state,
min_weight_fraction_leaf = float(model_parameters['rf_min_weight_fraction_leaf']),
max_leaf_nodes = fix_value(model_parameters['rf_max_leaf_nodes'],'int'),
min_impurity_decrease = float(model_parameters['rf_min_impurity_decrease']),
))])
elif model_type == "NN":
model = Pipeline([
('classification', KNeighborsClassifier(n_neighbors = int(model_parameters['nn_n_neighbors']),
weights = model_parameters['nn_weights'],
algorithm = model_parameters['nn_algorithm'],
leaf_size = int(model_parameters['nn_leaf_size']),
metric = model_parameters['nn_metric'],
metric_params = fix_value(model_parameters['nn_metric_params'],'str'),
p = int(model_parameters['nn_p'])))
])
elif model_type == "RG":
model = Pipeline([
('classification', RidgeClassifier(alpha = float(model_parameters['rg_alpha']),
fit_intercept = fix_value(model_parameters['rg_fit_intercept'],'bool'),
normalize = fix_value(model_parameters['rg_normalize'],'bool'),
max_iter = fix_value(model_parameters['rg_max_iter'],'int'),
tol = float(model_parameters['rg_tol']),
class_weight = fix_value(model_parameters['rg_class_weight'],'str'),
solver = fix_value(model_parameters['rg_solver'],'str')))
])
elif model_type == "SVM":
model = Pipeline([
('classification', svm.SVC(kernel = model_parameters['svm_kernel'],
degree = int(model_parameters['svm_degree']),
coef0 = float(model_parameters['svm_coef0']),
tol = float(model_parameters['svm_tol']),
C = float(model_parameters['svm_c']),
gamma = fix_value(model_parameters['svm_gamma'],'float'),
decision_function_shape = model_parameters['svm_decision_function_shape']
))
])
return model
def define_model_regression(model_type, model_parameters, x_header_size, random_state = None):
if model_type == "LR":
model = Pipeline([
('regression', LinearRegression())
])
elif model_type == "RF":
model = Pipeline([
('regression', RandomForestRegressor(n_estimators = int(model_parameters['rf_n_estimators']),
max_features = fix_value(model_parameters['rf_max_features'],'int'),
max_depth = fix_value(model_parameters['rf_max_depth'],'int'),
min_samples_split = int(model_parameters['rf_min_samples_split']),
min_samples_leaf = int(model_parameters['rf_min_samples_leaf']),
bootstrap = str2bool(model_parameters['rf_bootstrap']),
criterion = model_parameters['rf_criterion'], random_state = random_state,
min_weight_fraction_leaf = float(model_parameters['rf_min_weight_fraction_leaf']),
max_leaf_nodes = fix_value(model_parameters['rf_max_leaf_nodes'],'int'),
min_impurity_decrease = float(model_parameters['rf_min_impurity_decrease']),
))])
elif model_type == "NN":
model = Pipeline([
('regression', KNeighborsRegressor(n_neighbors = int(model_parameters['nn_n_neighbors']),
weights = model_parameters['nn_weights'],
algorithm = model_parameters['nn_algorithm'],
leaf_size = int(model_parameters['nn_leaf_size']),
metric = model_parameters['nn_metric'],
metric_params = fix_value(model_parameters['nn_metric_params'],'str'),
p = int(model_parameters['nn_p'])))
])
elif model_type == "BR":
model = Pipeline([
('regression', linear_model.BayesianRidge(n_iter = int(model_parameters['br_n_iter']),
alpha_1 = float(model_parameters['br_alpha_1']),
alpha_2 = float(model_parameters['br_alpha_2']),
tol = float(model_parameters['br_tol']),
lambda_1 = float(model_parameters['br_lambda_1']),
lambda_2 = float(model_parameters['br_lambda_2']),
compute_score = fix_value(model_parameters['br_compute_score'],'bool'),
normalize = fix_value(model_parameters['br_normalize'],'bool'),
fit_intercept = fix_value(model_parameters['br_fit_intercept'],'bool')))
])
elif model_type == "SVM":
model = Pipeline([
('regression', svm.SVR(kernel = model_parameters['svm_kernel'],
degree = int(model_parameters['svm_degree']),
coef0 = float(model_parameters['svm_coef0']),
tol = float(model_parameters['svm_tol']),
C = float(model_parameters['svm_c']),
gamma = fix_value(model_parameters['svm_gamma'],'float'),
epsilon = float(model_parameters['svm_epsilon']),
))
])
# 'kr_alpha': '1', 'kr_kernel': 'linear', 'kr_gamma': 'None', 'kr_degree': '3', 'kr_coef0': '1', \
elif model_type == "KR":
model = Pipeline([
('regression', KernelRidge(alpha = int(model_parameters['kr_alpha']),
kernel = fix_value(model_parameters['kr_kernel'],'str'),
gamma = fix_value(model_parameters['kr_gamma'],'str'),
degree = int(model_parameters['kr_degree']),
coef0 = int(model_parameters['kr_coef0']),))
])
return model
# In[8]:
def rescale_x(scaler_option, x_train):
scale = None
if scaler_option=='False':
x_train_ = x_train
elif scaler_option == "MinMaxScaler":
scale = preprocessing.MinMaxScaler()
x_train_ = scale.fit_transform(x_train)
elif scaler_option == "MaxAbsScaler":
scale = preprocessing.MaxAbsScaler()
x_train_ = scale.fit_transform(x_train)
elif scaler_option == "RobustScaler":
scale = preprocessing.RobustScaler()
x_train_ = scale.fit_transform(x_train)
elif scaler_option == "QuantileTransformer":
scale = preprocessing.QuantileTransformer()
x_train_ = scale.fit_transform(x_train)
elif scaler_option == "Normalizer":
scale = preprocessing.Normalizer()
x_train_ = scale.fit_transform(x_train)
else:
scale = preprocessing.StandardScaler()
x_train_ = scale.fit_transform(x_train)
return x_train_, scale
# In[9]:
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
def cross_val_predict_net_classifier(model, x_train, y_train, epochs=1000, batch_size=8, verbose = 0, scaler_option='StandardScaler', num_of_folds = 5, num_of_class = 2, force_to_proceed = False, accuracy_threshold = 0.5, fast_tune = True):
x_trains, y_trains, x_tests, y_tests = split_data(x_train, y_train, num_of_folds=num_of_folds)
predictions_total = []
actual_values_total = []
for j in range(0, num_of_folds):
print(" Evaluating fold(%d) ..."%(j))
start_time = time.time()
x_train_, scale = rescale_x(scaler_option, x_trains[j])
# This is the change
if scale is not None:
x_test_ = scale.transform(x_tests[j])
else:
x_test_ = x_tests[j]
dummy_y = keras.utils.to_categorical(y_trains[j], num_classes=num_of_class, dtype='float32')
history = model.fit(x_train_, dummy_y,
batch_size=batch_size,
epochs=epochs,
verbose=verbose)
predictions = model.predict_classes(x_test_)
actual_values = y_tests[j]
actual_values = actual_values.reshape(actual_values.shape[0],)
accuracy= evaluate_classifier(predictions, actual_values)
if force_to_proceed == False:
if accuracy<accuracy_threshold:
return [],[]
print(" accuracy = %8.3f "%(accuracy))
predictions_total+=list(predictions)
actual_values_total+=list(actual_values)
if fast_tune==True:
print("* Fast tuning enabled. so we only test 1 fold, and move on ..")
break
return np.array(predictions_total), np.array(actual_values_total)
def cross_val_predict_net(model, x_train, y_train, epochs=1000, batch_size=8, verbose = 0, scaler_option='StandardScaler', num_of_folds = 5, force_to_proceed= False, fast_tune=True):
x_trains, y_trains, x_tests, y_tests = split_data(x_train, y_train, num_of_folds=num_of_folds)
predictions_total = []
actual_values_total = []
for j in range(0, num_of_folds):
print(" Evaluating fold(%d) ..."%(j))
start_time = time.time()
x_train_, scale = rescale_x(scaler_option, x_trains[j])
# This is the change
if scale is not None:
x_test_ = scale.transform(x_tests[j])
else:
x_test_ = x_tests[j]
history = model.fit(x_train_, y_trains[j],
batch_size=batch_size,
epochs=epochs,
verbose=verbose)
predictions = model.predict(x_test_)
actual_values = y_tests[j]
MAE, R2 = evaluate(predictions, actual_values)
print(" MAE = %8.3f R2 = %8.3f ..."%(MAE, R2))
if force_to_proceed == False:
if R2<0:
return [],[]
predictions_total+=list(predictions)
actual_values_total+=list(actual_values)
if fast_tune==True:
print("* Fast tuning enabled. so we only test 1 fold, and move on ..")
break
return np.array(predictions_total), np.array(actual_values_total)
def save_parameters(model_parameters, filename):
f = open(filename,'w')
f.write("[HYPERPARAMETERS]\n\n")
for key in model_parameters.keys():
f.write(str(key)+" = "+str(model_parameters[key])+"\n")
f.close()
def save_args(model_args,filename):
f = open(filename,'w')
f.write("[ARGUMENTS]\n\n")
for key in model_args.keys():
f.write(str(key)+" = "+str(model_args[key])+"\n")
f.close()
def save_metadata(model_args, model_stats,filepath):
if path.exists(filepath):
meta=pd.read_csv(filepath,index_col=0)
else:
meta=pd.DataFrame(columns=["session","model_args","model_stats"])
size=len(meta.index)+1
meta=meta.append(pd.DataFrame(data=[[size,model_args,model_stats]],columns=["session","model_args","model_stats"]))
meta.to_csv(filepath)
return size
def train_and_predict(model, x_train, y_train, scaler_option, num_of_folds=5):
x_train_, scale = rescale_x(scaler_option, x_train)
y_train_ = y_train.reshape(y_train.shape[0],)
predictions = cross_val_predict(model, x_train_, y_train_, cv=num_of_folds)
actual_values = y_train_
return predictions, actual_values
def get_session(project_file):
if path.exists(project_file / "metadata.csv"):
meta=pd.read_csv(project_file / "metadata.csv")
else:
return 1
return len(meta.index)+1
# In[10]:
def train_and_save_net_classifier(model, tag, input_cols, target_col, x_train, y_train, scaler_option, accuracy=None, path_to_save = '.', num_of_folds=5, epochs=100, batch_size=2, num_of_class = 2):
if accuracy is None:
print('* Model has not been evaluated. Evaluation initiated via %d-fold cross validation'%(num_of_folds))
predictions, actual_values = cross_val_predict_net_classifier(model, epochs=epochs, batch_size=batch_size, x_train = x_train, y_train = y_train, verbose = 0, scaler_option = scaler_option, num_of_folds = num_of_folds, num_of_class = num_of_class, fast_tune = False)
accuracy = evaluate_classifier(predictions, actual_values)
x_train_, scale = rescale_x(scaler_option, x_train)
dummy_y = keras.utils.to_categorical(y_train, num_classes=num_of_class, dtype='float32')
print('* Training initiated ..')
model.fit(x_train_, dummy_y, epochs=epochs, batch_size=batch_size)
print('* Training done.')
model_dict = {}
model_dict['tag'] = tag
model_dict['model'] = model
model_dict['model_abbr'] = 'NET'
model_dict['input_cols'] = input_cols
model_dict['target_col'] = target_col
model_dict['accuracy'] = accuracy
model_dict['fitted_scaler_x'] = scale
output_file = PurePath(path_to_save) / (tag)
#print(model_dict)
print("* Trained model saved to file:", str(output_file))
output = open(output_file, 'wb')
pickle.dump(model_dict, output)
def train_and_save_net(model, tag, input_cols, target_col, x_train, y_train, scaler_option, MAE=None, R2=None, path_to_save = '.', num_of_folds=5, epochs=100, batch_size=2):
if MAE is None or R2 is None:
print('* Model has not been evaluated. Evaluation initiated via %d-fold cross validation'%(num_of_folds))
predictions, actual_values = cross_val_predict_net(model, epochs=epochs, batch_size=batch_size, x_train = x_train, y_train = y_train, verbose = 0, scaler_option = scaler_option, fast_tune = False)
MAE, R2 = evaluate(predictions, actual_values)
x_train_, scale = rescale_x(scaler_option, x_train)
print('* Training initiated ..')
model.fit(x_train_, y_train, epochs=epochs, batch_size=batch_size)
print('* Training done.')
model_dict = {}
model_dict['tag'] = tag
model_dict['model'] = model
model_dict['model_abbr'] = 'NET'
model_dict['input_cols'] = input_cols
model_dict['target_col'] = target_col
model_dict['MAE'] = MAE
model_dict['R2'] = R2
model_dict['fitted_scaler_x'] = scale
output_file = PurePath(path_to_save) / (tag)
#print(model_dict)
print("* Trained model saved to file:", str(output_file))
output = open(output_file, 'wb')
pickle.dump(model_dict, output)
def train_and_save_classifier(model, tag, model_abbr, input_cols, target_col, x_train, y_train, scaler_option, accuracy=None, path_to_save = '.', num_of_folds=5):
x_train_, scale = rescale_x(scaler_option, x_train)
y_train_ = y_train.reshape(y_train.shape[0],)
if accuracy is None:
print('* Model has not been evaluated. Evaluation initiated via %d-fold cross validation'%(num_of_folds))
predictions = cross_val_predict(model, x_train_, y_train_, cv=num_of_folds)
actual_values = y_train_
accuracy = evaluate_classifier(predictions, actual_values)
print('* Training initiated ..')
model.fit(x_train_, y_train_)
print('* Training done.')
actual_values = y_train_
model_dict = {}
model_dict['tag'] = tag
model_dict['model'] = model
model_dict['model_abbr'] = model_abbr
model_dict['input_cols'] = input_cols
model_dict['target_col'] = target_col
model_dict['accuracy'] = accuracy
model_dict['fitted_scaler_x'] = scale
output_file = PurePath(path_to_save) / (tag)
#print(model_dict)
print("* Trained model saved to file:", str(output_file))
output = open(output_file, 'wb')
pickle.dump(model_dict, output)
def train_and_save(model, tag, model_abbr, input_cols, target_col, x_train, y_train, scaler_option, MAE=None, R2=None, path_to_save = '.', num_of_folds=5):
x_train_, scale = rescale_x(scaler_option, x_train)
y_train_ = y_train.reshape(y_train.shape[0],)
if MAE is None or R2 is None:
print('* Model has not been evaluated. Evaluation initiated via %d-fold cross validation'%(num_of_folds))
predictions = cross_val_predict(model, x_train_, y_train_, cv=num_of_folds)
actual_values = y_train_
MAE, R2 = evaluate(predictions, actual_values)
print('* Training initiated ..')
model.fit(x_train_, y_train_)
print('* Training done.')
actual_values = y_train_
model_dict = {}
model_dict['tag'] = tag
model_dict['model'] = model
model_dict['model_abbr'] = model_abbr
model_dict['input_cols'] = input_cols
model_dict['target_col'] = target_col
model_dict['MAE'] = MAE
model_dict['R2'] = R2
model_dict['fitted_scaler_x'] = scale
output_file = PurePath(path_to_save) / ((tag))
#print(model_dict)
print("* Trained model saved to file:", str(output_file))
output = open(output_file, 'wb')
pickle.dump(model_dict, output)
def evaluate_classifier(predictions, actual_values):
correct = 0
wrong = 0
for i in range(0,len(predictions)):
if predictions[i]==actual_values[i]:
correct+=1
else:
wrong+=1
accuracy = float(correct)/(float(correct)+float(wrong))
return accuracy
def evaluate(predictions, actual_values):
try:
MAE = mean_absolute_error(predictions,actual_values)
R2 = r2_score(actual_values, predictions, multioutput='variance_weighted')
except Exception as e:
MAE = -1
R2 = -1
return MAE, R2
def save_comparison_chart(predictions, actual_values, filename):
plt.close()
min_val = min(predictions)
max_val = max(actual_values)
plt.xlabel('Predicted Value')
plt.ylabel('Actual Value')
plt.ylim([min_val, max_val])
plt.xlim([min_val, max_val])
plt.grid(True)
plt.scatter(predictions,actual_values)
t = np.arange(min_val, max_val, 0.01)
line, = plt.plot(t, t, lw=1)
if type(filename)==str:
filename = PurePath(filename)
if not os.path.exists(filename.parent): os.makedirs(filename.parent)
plt.savefig(filename)
plt.close()
# In[13]:
def add_key_to_params(tag, params):
tag = tag.lower()
parameters = {}
for key in params.keys():
parameters[(tag+'_'+key).lower()] = params[key]
return parameters
# In[14]:
def hyperparameter_tuning_classifier(tag, x_train, y_train, num_of_folds, scaler_option, n_iter=100, random_state=0, verbose=1):
rf_n_estimators = [int(x) for x in np.linspace(start = 10, stop = 1000, num = 20)]
rf_max_features = list(range(1,x_train.shape[1]))
rf_max_depth = [int(x) for x in np.linspace(1, 32, 32)]
rf_max_depth.append(None)
rf_min_samples_split = [int(x) for x in np.linspace(start = 2, stop = 15, num = 20)]
rf_min_samples_leaf = [int(x) for x in np.linspace(start = 2, stop = 15, num = 20)]
rf_bootstrap = ['True', 'False']
rf_criterion = ['gini']
rf_min_weight_fraction_leaf = [float(x) for x in np.linspace(start = 0, stop = 1.e-5, num = 10)]
rf_max_leaf_nodes = [2, 5, 10, 50, 100]
rf_min_impurity_decrease = [float(x) for x in np.linspace(start = 0, stop = 1.e-5, num = 10)]
rf_random_grid = {'n_estimators': rf_n_estimators,
'max_features': rf_max_features,
'max_depth': rf_max_depth,
'min_samples_split': rf_min_samples_split,
'min_samples_leaf': rf_min_samples_leaf,
'bootstrap': rf_bootstrap,
'criterion': rf_criterion,
'min_weight_fraction_leaf': rf_min_weight_fraction_leaf,
'max_leaf_nodes': rf_max_leaf_nodes,
'min_impurity_decrease': rf_min_impurity_decrease}
nn_n_neighbors = [int(x) for x in np.linspace(start = 2, stop = 15, num = 10)]
nn_weights = ['uniform', 'distance']
nn_algorithm = ['auto','ball_tree','kd_tree','brute']
nn_leaf_size = [1,2,3,4,5]
nn_p = [int(x) for x in np.linspace(start = 1, stop = 5, num = 5)]
nn_metric = ['minkowski']
nn_metric_params = [None]
nn_random_grid = {'n_neighbors': nn_n_neighbors,
'weights': nn_weights,
'algorithm': nn_algorithm,
'leaf_size': nn_leaf_size,
'metric': nn_metric,
'metric_params': nn_metric_params,
'p': nn_p}
rg_alpha = [float(x) for x in np.linspace(start = 0, stop = 10, num = 10)]
rg_fit_intercept = ['True', 'False']
rg_max_iter = [100, 500, 1000, None]
rg_tol = [float(x) for x in np.linspace(start = 1.e-5, stop = 1.e-2, num = 20)]
rg_class_weight = [None,'balanced']
rg_normalize = ['True', 'False']
rg_solver = ['auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg', 'sag', 'saga']
rg_random_grid = {'max_iter': rg_max_iter,
'alpha': rg_alpha,
'fit_intercept': rg_fit_intercept,
'tol': rg_tol,
'class_weight': rg_class_weight,
'normalize': rg_normalize,
'solver': rg_solver
}
svm_kernel = ['rbf', 'poly','linear','sigmoid']
svm_gamma = ['auto', 0.001, 0.01, 0.1, 1]
svm_degree = [1, 2, 3]
svm_coef0 = [0, 1, 2, 3]
svm_tol = [float(x) for x in np.linspace(start = 1.e-4, stop = 1.e-2, num = 20)]
#svm_C = [float(x) for x in np.linspace(start = 0.001, stop = 3000, num = 100)]
svm_C = [0.001, 0.01, 0.1, 1, 10]
svm_decision_function_shape = ['ovr','ovo']
svm_random_grid = {'kernel': svm_kernel,
'degree': svm_degree,
'gamma' : svm_gamma,
'coef0': svm_coef0,
'tol': svm_tol,
'C' : svm_C,
'decision_function_shape':svm_decision_function_shape}
if tag=='RF':
estimator = RandomForestClassifier()
random_grid = rf_random_grid
elif tag=='NN':
estimator = KNeighborsClassifier()
random_grid = nn_random_grid
elif tag=='RG':
estimator = RidgeClassifier()
random_grid = rg_random_grid
elif tag=='SVM':
estimator = svm.SVC()
random_grid = svm_random_grid
else:
estimator = None
tuned_parameters = None
if estimator is not None:
model = RandomizedSearchCV(
estimator = estimator,
param_distributions = random_grid,
n_iter = n_iter,
cv = num_of_folds,
verbose=verbose,
random_state=random_state,
n_jobs = multiprocessing.cpu_count())
x_train_, scale = rescale_x(scaler_option, x_train)
y_train_ = y_train.reshape(y_train.shape[0],)
model.fit(x_train_, y_train_)
tuned_parameters = add_key_to_params(tag, model.best_params_)
tuned_parameters['scaler_option'] = scaler_option
return tuned_parameters