-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtoolkit.py
1785 lines (1432 loc) · 77.6 KB
/
toolkit.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
# package specific imports
from typing import Literal
import Visualisation as vis
import matplotlib.pyplot as plt
## python imports
import pickle
import logging, sys # for logging
from typing import Callable
from collections import Counter
from joblib import Parallel, delayed, cpu_count # for parallel processing
from tqdm import tqdm # for progress bar
# external imports
import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
# import random forest regression model
from sklearn.ensemble import RandomForestRegressor
# import support vector machine regression model
from sklearn.svm import SVR
# import elastic net regression model
from sklearn.linear_model import ElasticNet
# import simple mlp regression model
from sklearn.neural_network import MLPRegressor
# import xgb regression model
from xgboost import XGBRegressor
# import k nearest neighbors regression model
from sklearn.neighbors import KNeighborsRegressor
## feature selection
# import feature selection
from sklearn.feature_selection import SelectKBest, f_regression
import shap
from sklearn.base import BaseEstimator, TransformerMixin
import pandas as pd
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectKBest, f_regression, mutual_info_regression
from sklearn.model_selection import KFold
from sklearn.metrics import mean_squared_error, accuracy_score
from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
from sklearn.base import clone
import sklearn_relief as sr
# hyperparameter tuning
from sklearn.model_selection import GridSearchCV
## validation
from sklearn.metrics import r2_score
from scipy.stats import pearsonr
class FirstQuantileImputer(BaseEstimator, TransformerMixin):
def __init__(self):
super().__init__()
self.quantile_ = None
def fit(self, X, y=None):
self.quantile_ = X.quantile(0.25)
return self
def transform(self, X, y=None, return_df=False):
q = self.quantile_
for col in X.columns:
hi_bound = q[col]
if np.isnan(hi_bound):
hi_bound = q.dropna().min()
vals = np.random.uniform(0, hi_bound, size=X[col].isna().sum())
X.loc[X[col].isna(), col] = vals
if return_df:
return X
return X.values
class FeatureTransformer:
def __init__(self):
'''
chains a series of transform functions and selection functions together,
with the assumption that the transform/selection functions are independent of each other
'''
self.transform_functions = {}
self.selection_function = {}
def add_selection_function(self, name: str, selection_function, function_kwargs: dict = {}):
self.selection_function[name] = {'selection_function': selection_function, 'args': function_kwargs}
def get_selection_function(self, name: str):
return self.selection_function[name]['selection_function']
def get_selection_function_args(self, name: str):
return self.selection_function[name]['args']
def get_selection_function_names(self):
return self.selection_function.keys()
def remove_selection_function(self, name: str):
self.selection_function.pop(name)
def add_transform_function(self, name: str, transform_function, function_kwargs: dict = {}):
self.transform_functions[name] = {'transform_function': transform_function, 'args': function_kwargs}
def get_transform_function(self, name: str):
return self.transform_functions[name]['transform_function']
def get_transform_function_args(self, name: str):
return self.transform_functions[name]['args']
def get_transform_function_names(self):
return self.transform_functions.keys()
def remove_transform_function(self, name: str):
self.transform_functions.pop(name)
def run_all_transform(self, X_train, y_train):
'''
Input:
X_train: pandas dataframe, training data
y_train: pandas series, training label
X_test: pandas dataframe, test data
Output:
X_train: pandas dataframe, the training data after all transform functions
y_train: pandas series, the training label after all transform functions
X_test: pandas dataframe, the test data after all transform functions
'''
for name in self.transform_functions.keys():
transform_function = self.get_transform_function(name)
transform_args = self.get_transform_function_args(name)
X_train, y_train = transform_function(X_train, y_train, **transform_args)
return X_train, y_train
def run_selection_function(self, X_train, y_train):
'''
Input:
X_train: pandas dataframe, training data
y_train: pandas series, training label
X_test: pandas dataframe, test data
Output:
selected_features: list of strings, the selected features, selected features should only be based on X_train
Strings are used instead of indices because it guarantees subset selection while maintain stability as
the indices of the features may change after an feature selection function
sel_train: pandas dataframe, the training data after feature selection
sel_test: pandas dataframe, the test data after feature selection
'''
for name in self.selection_function.keys():
selection_function = self.get_selection_function(name)
selection_args = self.get_selection_function_args(name)
selected_features, sel_train = selection_function(X_train, y_train, **selection_args)
return selected_features, sel_train
def run(self, X_train, y_train):
'''
Simply run all the transform functions and selection functions
'''
X_train, y_train = self.run_all_transform(X_train, y_train)
selected_features, sel_train = self.run_selection_function(X_train, y_train)
return selected_features, sel_train
class Powerkit:
def __init__(self, feature_data: pd.DataFrame, label_data: pd.Series) -> None:
self.feature_data = feature_data
self.label_data = label_data
self.cv_split_size = 0.1
self.conditions = {} # dict of dict obj, dict has the following structure:
# {
# 'condition': str,
# 'condition_to_get_feature_importance': bool,
# 'pipeline_function': Callable,
# 'pipeline_args': dict,
# 'eval_function': Callable,
# 'eval_args': dict
# }
def add_condition(self, condition: str, get_importance: bool, pipeline_function: Callable, pipeline_args: dict, eval_function: Callable, eval_args: dict):
# if condition already exists, raise error
if condition in self.conditions.keys():
raise ValueError(f'condition {condition} already exists')
self.conditions[condition] = {'condition': condition,
'condition_to_get_feature_importance': get_importance,
'pipeline_function': pipeline_function,
'pipeline_args': pipeline_args,
'eval_function': eval_function,
'eval_args': eval_args}
def remove_condition(self, condition: str):
# if condition does not exist, raise error
if condition not in self.conditions.keys():
raise ValueError(f'condition {condition} does not exist')
self.conditions.pop(condition)
def generate_rng_list(self, n_rng):
rng_list = np.random.randint(0, 100000, size=n_rng)
return rng_list
def _abstract_run_single(self,
condition: str,
condition_to_get_feature_importance: bool,
rng: int,
pipeline_function: Callable,
pipeline_args: dict,
eval_function: Callable,
eval_args: dict,
verbose: bool = False
):
'''
enforces only on how the data is split and a generic df structure with
the first column being 'condition'.
The rest of the columns are up to the methods `pipeline_function` and `eval_function` to decide. They effectively make up the actual condition and additional return values.
pipeline function takes in the following arguments:
X_train: pandas dataframe, training data
y_train: pandas series, training label
pipeline_args: dict, the rest of the arguments
it's possible that eval_function require information from pipeline_function. Usually it is a trained model.
In which case the pipeline_function must return a dict variable called `pipeline_components`
which contains the information needed for eval_function
eval_function takes in the following arguments:
X_test: pandas dataframe, test data
y_test: pandas series, test label
eval_args: dict | None, the rest of the arguments
pipeline_components: dict | None, the information needed for eval_function, if not needed, eval_info is None
things should be returned for each run:
feature importance: a tuple, of (feature_name, score) for each feature which represents the relative importance of the feature
model performance [OPTIONAL]: measured either by accuracy, correlation, etc, depending on the eval_function, if not provided, return None.
model performance can be used to calculated an adjusted feature importance metric, e.g. by multiplying the feature importance by the model performance. It can also be used as a proxy to evaluate the generalizability of the model.
final return value:
results: dict = {'rng': rng, 'condition': condition, 'feature_importance': feature_importance, 'model_performance': model_performance}
'''
# initialize the final returns
final_returns = {}
final_returns['rng'] = rng
final_returns['condition'] = condition
# split the data and go through the pipeline
X_train, X_test, y_train, y_test = train_test_split(self.feature_data, self.label_data, test_size=self.cv_split_size, random_state=rng)
pipeline_comps = pipeline_function(X_train, y_train, rng, **pipeline_args)
eval_returns = eval_function(X_test, y_test, pipeline_components=pipeline_comps, **eval_args)
# update the final returns
final_returns.update(eval_returns)
if not condition_to_get_feature_importance:
final_returns.pop('feature_importance')
return final_returns
def _abstract_run(self, rng_list: list, n_jobs: int, verbose: bool = False, conditions=None):
if conditions is None:
conditions = self.conditions
if n_jobs == 1:
# use normal loop syntax for verbose printing
data_collector = []
for rng in tqdm(rng_list, disable=not verbose):
for condition in conditions:
data = self._abstract_run_single(condition,
self.conditions[condition]['condition_to_get_feature_importance'],
rng,
self.conditions[condition]['pipeline_function'],
self.conditions[condition]['pipeline_args'],
self.conditions[condition]['eval_function'],
self.conditions[condition]['eval_args'],
verbose=verbose
)
data_collector.append(data)
else:
# use joblib to parallelize the process, disable verbose printing
data_collector = Parallel(n_jobs=n_jobs)(delayed(self._abstract_run_single)(condition,
self.conditions[condition]['condition_to_get_feature_importance'],
rng,
self.conditions[condition]['pipeline_function'],
self.conditions[condition]['pipeline_args'],
self.conditions[condition]['eval_function'],
self.conditions[condition]['eval_args'],
verbose=False
)
for rng in rng_list
for condition in conditions)
df = pd.DataFrame(data_collector)
return df
def run_all_conditions(self, rng_list: list, n_jobs: int, verbose: bool = False):
df = self._abstract_run(rng_list, n_jobs, verbose)
return df
def run_selected_condition(self, condition: str, rng_list: list, n_jobs: int, verbose: bool = False):
if condition not in self.conditions.keys():
raise ValueError(f'condition {condition} does not exist')
df = self._abstract_run(rng_list, n_jobs, verbose, conditions=[condition])
return df
def get_mean_contribution(self, df, condition, col_name='feature_importance', adjust_for_accuracy=False, accuracy_col_name='model_performance', **kwargs):
'''
Use adjust_for_accuracy ONLY when the distribution of the model performance is similar to that of the feature importance
'''
# filter the dataframe by condition
df = df[df['condition'] == condition]
feature_importance = df[col_name]
rngs = df['rng']
accuracies = df[accuracy_col_name]
data_collector = []
# for each row in the feature importance column, append tuple (feature_name, score) to a list
accuracy_tuples = []
for fi_row, rng_row, accuracies in zip(feature_importance, rngs, accuracies):
for feature_name, score in zip(fi_row[0], fi_row[1]):
data_collector.append({'iteration_no': rng_row, 'feature_names': feature_name, 'scores': score})
if adjust_for_accuracy:
accuracy_tuples.append((feature_name, accuracies))
# convert the list to a dataframe
feature_importance_df = pd.DataFrame(data_collector)
# if adjust_for_accuracy is False, set accuracy_tuples to None
if not adjust_for_accuracy:
accuracy_tuples = None
# calculate the mean contribution for each feature
contribution = get_mean_contribution_general(feature_importance_df, adjust_for_accuracy=adjust_for_accuracy, accuracy_scores=accuracy_tuples, **kwargs)
return contribution
def run_until_consensus(self, condition: str,
rel_tol: float = 0.01, abs_tol: float = 0.001, max_iter: int = 100,
use_std: bool = False,
feature_importance_col_name: str = 'feature_importance',
model_performance_col_name: str = 'model_performance',
n_jobs: int = 1, verbose: bool = False, verbose_level: int = 1,
return_meta_df: bool = False,
crunch_factor=1):
'''
Input:
condition: str, the condition to run
rel_tol: float, the relative tolerance to use for consensus run
abs_tol: float, the absolute tolerance to use for consensus run
max_iter: int, the maximum number of iterations to run
use_std: bool, whether to use standard deviation as the metric for consensus run, if False, use average absolute difference
n_jobs: int, the number of jobs to use for parallel processing
verbose: bool, whether to print verbose information
verbose_level: int, the level of verbose information to print, 0 for no verbose, 1 for basic information, 2 for intermediate information, 3 for all information
return_meta_df: bool, whether to return the meta dataframe which contains the information for each iteration
Output:
rng_list: list of int, the rng list used for consensus run
total_df: pandas dataframe, the dataframe containing the results for each iteration
meta_df: pandas dataframe, the dataframe containing the meta information for each iteration, only returned if return_meta_df is True
'''
rng_list = []
current_tol = 1e10
abs_diff = 1e10
current_contrib = 0
prev_contrib = 0
meta_results = []
total_df = pd.DataFrame()
early_break = False
while current_tol > rel_tol and abs_diff > abs_tol and len(rng_list) < max_iter:
if early_break:
break
n_rngs = (n_jobs if n_jobs != -1 else cpu_count()) * crunch_factor
rngs = self.generate_rng_list(n_rngs)
if verbose and verbose_level >= 3:
print(f'running condition {condition} with rng {rngs}')
verbose_at_run = False
if verbose and verbose_level >= 2:
verbose_at_run = True
df = self.run_selected_condition(condition, rng_list=rngs, n_jobs=n_jobs, verbose=verbose_at_run)
# create a mini df for each iteration
for rng in rngs:
mini_df = df[df['rng'] == rng]
# print(mini_df.shape)
if verbose and verbose_level >= 3:
print(f'finished running condition {condition} with rng {rng}')
if mini_df is None:
raise ValueError(f'no df is returned for condition {condition}')
total_df = pd.concat([total_df, mini_df], axis=0)
if verbose and verbose_level >= 3:
print(f'finished concatenating df for condition {condition} with rng {rng}')
if isinstance(prev_contrib, int):
if verbose and verbose_level >= 3:
print(f'prev_contrb is 0, setting prev_contrb to current_contrib')
prev_contrib = self.get_mean_contribution(total_df, condition, strict_mean=0, col_name=feature_importance_col_name)
# strict mean = 0, sum only at the end
if verbose and verbose_level >= 1:
print(f'prev_contrib: {list(prev_contrib.index[:5])}')
print(f'current iteration: {len(rng_list)} current_tol: {current_tol:4f}, abs_diff: {abs_diff:6f}, performance: {df[model_performance_col_name].mean():2f}')
else:
current_contrib = self.get_mean_contribution(total_df, condition, strict_mean=0, col_name=feature_importance_col_name)
# print the first five features in one line by converting to list
if verbose and verbose_level >= 1:
print(f'current_contrib: {list(current_contrib.index[:5])}')
diff = prev_contrib.copy()
diff['scores'] = prev_contrib['scores'] - current_contrib['scores']
abs_diff = np.abs(diff['scores']).sum()
abs_prev = np.abs(prev_contrib['scores']).sum()
if verbose and verbose_level >= 3:
# print(f'{prev_contrib}, {current_contrib}')
print(f'total abs prev: {abs_prev}, total abs current: {abs_diff}')
current_tol = 1 - (abs_prev - abs_diff) / abs_prev
prev_contrib = current_contrib
if verbose and verbose_level >= 1:
print(f'current iteration: {len(rng_list)} current_tol: {current_tol:4f}, abs_diff: {abs_diff:6f}, abs_prev: {abs_prev:2f}, performance: {total_df[model_performance_col_name].mean():2f}')
meta_results.append([len(rng_list), current_tol, abs_diff, abs_prev, total_df[model_performance_col_name].mean()])
rng_list.append(rng)
if current_tol <= rel_tol or abs_diff <= abs_tol or len(rng_list) >= max_iter:
early_break = True
break
if verbose and verbose_level >= 0:
# display in one line
print(f'Consensus Run: condition {condition} is done in {len(rng_list)} iterations')
if current_tol >= rel_tol:
print(f'Consensus Run under condition {condition} is NOT converged within {rel_tol} relative tolerance')
if abs_diff >= abs_tol:
print(f'Consensus Run under condition {condition} is NOT converged within {abs_tol} absolute tolerance')
if len(rng_list) >= max_iter:
print(f'WARNING: Consensus Run under condition {condition} is not converged within {max_iter} iterations')
# create a dataframe for meta results
meta_df = pd.DataFrame(meta_results, columns=['iteration', 'current_tol', 'abs_diff', 'abs_prev', 'perf'])
if return_meta_df:
return rng_list, total_df, meta_df
return rng_list, total_df
### pipeline functions
'''
'''
### evaluation functions
'''
'''
class Toolkit:
def __init__(self, feature_data: pd.DataFrame, label_data: pd.Series) -> None:
'''
Toolkit contains config parameters and the cleaned dataset for the analysis
'''
self.feature_data = feature_data
self.label_data = label_data
self.conditions = [], # each element: string, e.g. 'all', 'random', 'network'
self.conditions_to_get_feature_importance = [] # each element: bool, True or False
self.matched_functions = [] # each element: function, the function to use for feature selection
self.extra_args_for_functions = []
self.models_used = []
self.model_identifier = []
self.model_hyperparameters = []
self.rng_list = []
self.cv_split_size = 0.1
self.max_feature_save_size = 1000
self.verbose = False
def add_condition(self, condition, condition_to_get_feature_importance, matched_function, extra_args_for_function):
'''
Input:
condition: string, the condition to test, e.g. 'all', 'random', 'network'
condition_to_get_feature_importance: boolean, whether to get feature importance for this condition
matched_function: function, the function to use for feature selection
best practice is to use FeatureTransformer to wrap the function, call FeatureTransformer.run()
extra_args_for_function: tuple, the extra arguments to pass to the function
Example Usage:
`toolkit.add_condition('all', False, FeatureTransformer.run(), (,))`
The above example adds a condition called 'all', feature importance will not be calculated,
the feature selection function is FeatureTransformer.run(), and the extra arguments are empty
'''
self.conditions.append(condition)
self.conditions_to_get_feature_importance.append(condition_to_get_feature_importance)
self.matched_functions.append(matched_function)
self.extra_args_for_functions.append(extra_args_for_function)
def add_model(self, model, model_identifer, model_hyperparameters):
self.models_used.append(model)
self.model_identifier.append(model_identifer)
self.model_hyperparameters.append(model_hyperparameters)
def set_rng_list(self, rng_list):
self.rng_list = rng_list
def generate_rng_list(self, n_rng):
self.rng_list = np.random.randint(0, 100000, size=n_rng)
def _generic_run_single(self,
condition,
condition_to_get_feature_importance,
matched_function,
extra_arg,
model_str,
single_model_hyperparameters,
rng,
verbose=False):
if verbose:
print(f'running {model_str} with seed {rng} under {condition} conditions')
X_train, X_test, y_train, y_test = train_test_split(self.feature_data, self.label_data, test_size=self.cv_split_size, random_state=rng)
selected_features, sel_train, sel_test = matched_function(X_train, y_train, X_test, *extra_arg)
model = get_model_from_string(model_str, **single_model_hyperparameters)
model.fit(sel_train, y_train)
y_pred = model.predict(sel_test)
score = mean_squared_error(y_test, y_pred)
corr, p_val = pearsonr(y_test, y_pred)
r_squared = r2_score(y_test, y_pred)
shap_values = None
if condition_to_get_feature_importance:
shap_values = get_shap_values(model, model_str, sel_train, sel_test)
if verbose:
print(f'--- result: prediction correlation {corr}, p-value {p_val}, r-squared {r_squared}')
# if sel_train and sel_test are too big, they will not be saved
if sel_train.shape[1] > self.max_feature_save_size:
sel_train = None
if sel_test.shape[1] > self.max_feature_save_size:
sel_test = None
return [rng, model_str, condition, selected_features,
score, corr, p_val, r_squared, shap_values,
sel_train, sel_test, y_test, y_pred]
def _generic_run(self,
conditions_to_test,
conditions_to_get_feature_importance,
matched_functions,
extra_args,
models_used,
models_hyperparameters,
rng_list=None,
n_jobs=1,
verbose=True,
):
if rng_list is None:
rng_list = self.rng_list
if len(self.rng_list) == 0:
raise ValueError('Toolkit: rng_list is empty, please set it or generate it')
if n_jobs == 1:
data_collector = []
for m, model_str in enumerate(models_used):
for rng in rng_list:
for j, condition in enumerate(conditions_to_test):
data = self._generic_run_single(condition,
conditions_to_get_feature_importance[j],
matched_functions[j],
extra_args[j],
model_str,
models_hyperparameters[m],
rng,
verbose=verbose)
data_collector.append(data)
else:
# use joblib to parallelize the process
data_collector = Parallel(n_jobs=n_jobs)(delayed(self._generic_run_single)(condition,
conditions_to_get_feature_importance[j],
matched_functions[j],
extra_args[j],
model_str,
models_hyperparameters[m],
rng,
verbose=False)
for m, model_str in enumerate(models_used)
for rng in rng_list
for j, condition in enumerate(conditions_to_test))
if verbose:
print('### All models ran')
df = pd.DataFrame(data_collector, columns=['rng', 'model', 'exp_condition', 'selected_features',
'mse', 'corr', 'p_val', 'r_squared', 'shap_values',
'X_train', 'X_test', 'y_test', 'y_pred'])
return df
def run_selected_condition(self, condition, rng_list=None, n_jobs=1, verbose=False):
modified_conditions = []
modify_index = None
for i, c in enumerate(self.conditions):
if condition in c:
modified_conditions.append(c)
modify_index = i
break
# if no condition is found, return None
if len(modified_conditions) == 0:
print(f"WARNING: no condition is found for {condition}")
print(f'available conditions are {self.conditions}')
return None
modified_conditions_to_get_feature_importance = [self.conditions_to_get_feature_importance[modify_index]]
modified_matched_functions = [self.matched_functions[modify_index]]
modified_extra_args_for_functions = [self.extra_args_for_functions[modify_index]]
df = self._generic_run(modified_conditions,
modified_conditions_to_get_feature_importance,
modified_matched_functions,
modified_extra_args_for_functions,
self.models_used,
self.model_hyperparameters,
rng_list=rng_list,
n_jobs=n_jobs,
verbose=verbose)
return df
def run_selected_model(self, model_identifier, rng_list=None, n_jobs=1, verbose=False):
modified_model_identifiers = []
modified_model_hyperparameters_index = None
for i, m in enumerate(self.model_identifier):
if model_identifier in m:
modified_model_identifiers.append(m)
modified_model_hyperparameters_index = i
break
# if no model is found, return None
if len(modified_model_identifiers) == 0:
print(f"WARNING: no model is found for identifier {model_identifier}")
print(f'Available model identifiers are {self.model_identifier}')
return None
modified_model_hyperparameters = [self.model_hyperparameters[modified_model_hyperparameters_index]]
modified_model_used = [self.models_used[modified_model_hyperparameters_index]]
df = self._generic_run(self.conditions,
self.conditions_to_get_feature_importance,
self.matched_functions,
self.extra_args_for_functions,
modified_model_used,
modified_model_hyperparameters,
rng_list=rng_list,
n_jobs=n_jobs,
verbose=verbose)
return df
def run_selected_condition_and_model(self, condition, model_identifier, rng_list=None, n_jobs=1, verbose=False):
modified_conditions = []
modify_index = None
for i, c in enumerate(self.conditions):
if condition in c:
modified_conditions.append(c)
modify_index = i
break
# if no condition is found, return None
if len(modified_conditions) == 0:
print(f"WARNING: no condition is found for {condition}")
print(f'available conditions are {self.conditions}')
return None
modified_model_identifiers = []
modified_model_hyperparameters_index = None
for i, m in enumerate(self.model_identifier):
if model_identifier in m:
modified_model_identifiers.append(m)
modified_model_hyperparameters_index = i
break
# if no model is found, return None
if len(modified_model_identifiers) == 0:
print(f"WARNING: no model is found for identifier {model_identifier}")
print(f'Available model identifiers are {self.model_identifier}')
return None
modified_model_hyperparameters = [self.model_hyperparameters[modified_model_hyperparameters_index]]
modified_model_used = [self.models_used[modified_model_hyperparameters_index]]
modified_conditions_to_get_feature_importance = [self.conditions_to_get_feature_importance[modify_index]]
modified_matched_functions = [self.matched_functions[modify_index]]
modified_extra_args_for_functions = [self.extra_args_for_functions[modify_index]]
df = self._generic_run(modified_conditions,
modified_conditions_to_get_feature_importance,
modified_matched_functions,
modified_extra_args_for_functions,
modified_model_used,
modified_model_hyperparameters,
rng_list=rng_list,
n_jobs=n_jobs,
verbose=verbose)
return df
def run_all(self, rng_list=None, n_jobs=1, verbose=False):
df = self._generic_run(self.conditions,
self.conditions_to_get_feature_importance,
self.matched_functions,
self.extra_args_for_functions,
self.models_used,
self.model_hyperparameters,
rng_list=rng_list,
n_jobs=n_jobs,
verbose=verbose)
return df
def run_until_consensus(self, condition: str,
rel_tol: float = 0.01,
abs_tol: float = 0.001,
max_iter: int = 100,
n_jobs=1, verbose=True, verbose_level=1, return_meta_df=False):
rng_list = []
current_tol = 1e10
abs_diff = 1e10
current_contrib = 0
prev_contrib = 0
meta_results = []
total_df = pd.DataFrame()
while current_tol > rel_tol and abs_diff > abs_tol and len(rng_list) < max_iter:
rng = np.random.randint(0, 10000000)
rng_list.append(rng)
rng_list_to_run = [rng]
if verbose and verbose_level >= 3:
print(f'running condition {condition} with rng {rng}')
verbose_at_run = False
if verbose and verbose_level >= 2:
verbose_at_run = True
df = self.run_selected_condition(condition, rng_list=rng_list_to_run, n_jobs=n_jobs, verbose=verbose_at_run)
if verbose and verbose_level >= 3:
print(f'finished running condition {condition} with rng {rng}')
if df is None:
raise ValueError(f'no df is returned for condition {condition}')
else:
total_df = pd.concat([total_df, df], axis=0)
if verbose and verbose_level >= 3:
print(f'finished concatenating df for condition {condition} with rng {rng}')
if isinstance(prev_contrib, int):
if verbose and verbose_level >= 3:
print(f'prev_contrb is 0, setting prev_contrb to current_contrib')
prev_contrib = get_mean_contribution(total_df, condition, absolute_value=True, strict_mean=0)
# strict mean = 0, sum only at the end
else:
current_contrib = get_mean_contribution(total_df, condition, absolute_value=True, strict_mean=0)
# print the first five features in one line by converting to list
if verbose and verbose_level >= 1:
print(f'current_contrib: {list(current_contrib.index[:5])}')
if verbose and verbose_level >= 3:
# print(f'{prev_contrib}, {current_contrib}')
print(f'total abs prev: {get_abs_sum_for_feature_contributions(prev_contrib)}, total abs current: {get_abs_sum_for_feature_contributions(current_contrib)}')
diff = get_diff_between_feature_contributions(current_contrib, prev_contrib)
abs_diff = get_abs_sum_for_feature_contributions(diff)
abs_prev = get_abs_sum_for_feature_contributions(prev_contrib)
current_tol = 1 - (abs_prev - abs_diff) / abs_prev
prev_contrib = current_contrib
if verbose and verbose_level >= 1:
print(f'current iteration: {len(rng_list)} current_tol: {current_tol:4f}, abs_diff: {abs_diff:6f}, abs_prev: {abs_prev:2f}, corr: {df["corr"].mean():2f}')
meta_results.append([len(rng_list), current_tol, abs_diff, abs_prev, df['corr'].mean()])
if verbose and verbose_level >= 0:
# display in one line
print(f'Consensus Run: condition {condition} is done in {len(rng_list)} iterations')
if current_tol >= rel_tol:
print(f'Consensus Run under condition {condition} is NOT converged within {rel_tol} relative tolerance')
if abs_diff >= abs_tol:
print(f'Consensus Run under condition {condition} is NOT converged within {abs_tol} absolute tolerance')
if len(rng_list) >= max_iter:
print(f'WARNING: Consensus Run under condition {condition} is not converged within {max_iter} iterations')
# create a dataframe for meta results
meta_df = pd.DataFrame(meta_results, columns=['iteration', 'current_tol', 'abs_diff', 'abs_prev', 'corr'])
if return_meta_df:
return rng_list, total_df, meta_df
return rng_list, total_df
def get_model_from_string(model_name, **kwargs):
if model_name == 'ElasticNet':
return ElasticNet(**kwargs)
elif model_name == 'RandomForestRegressor':
return RandomForestRegressor(**kwargs)
elif model_name == 'SVR':
return SVR(**kwargs)
elif model_name == 'MLPRegressor':
return MLPRegressor(**kwargs)
elif model_name == 'XGBRegressor':
return XGBRegressor(**kwargs)
elif model_name == 'KNeighborsRegressor':
return KNeighborsRegressor(**kwargs)
else:
raise ValueError(f'{model_name} is not supported')
def get_shap_values(model, model_str, train_data, test_data):
if model_str == 'RandomForestRegressor':
explainer = shap.TreeExplainer(model, train_data)
elif model_str == 'ElasticNet':
explainer = shap.LinearExplainer(model, train_data)
elif model_str == 'XGBRegressor':
explainer = shap.TreeExplainer(model, train_data)
# TODO: tensorflow error for this one, fix
# elif model_str == 'MLPRegressor':
# explainer = shap.DeepExplainer(model, train_data)
else:
explainer = shap.KernelExplainer(model.predict, train_data)
shap_values = explainer.shap_values(test_data)
return shap_values
### Hyperparameter Tuning of Models
'''
All hyperparameter tuning methods should take in the following arguments:
X: pandas dataframe | numpy array, the data to perform feature selection on
y: pandas series | numpy array, the label
cv: int, the number of folds for cross validation
n_jobs: int, the number of jobs to run in parallel, usually set to 1
All feature selection methods should return the following:
params: dict, the best parameters for the model
'''
def hypertune_svr(X: pd.DataFrame, y: pd.Series, cv=5, n_jobs=1):
'''
Input:
X: pandas dataframe, the training data
y: pandas series, the training label
Output:
best_params: dict, the best parameters for the model
'''
# define the parameter values that should be searched
kernel_range = {'kernel': ['linear', 'poly', 'rbf', 'sigmoid']}
# instantiate and fit the grid
grid = GridSearchCV(SVR(), kernel_range, cv=cv, scoring='r2', n_jobs=n_jobs)
grid.fit(X, y)
# view the complete results
# print(grid.cv_results_)
# examine the best model
# print(grid.best_score_)
# print(grid.best_params_)
return grid.best_params_, grid.best_score_, grid.cv_results_
def hypertune_ann(X: pd.DataFrame, y: pd.Series, cv=5, n_jobs=1):
'''
Input:
X: pandas dataframe, the training data
y: pandas series, the training label
Output:
best_params: dict, the best parameters for the model
'''
# define the parameter values that should be searched
hidden_layer_sizes_range = [(i,) for i in range(1, 100, 10)]
hidden_layer_sizes_range += [(i, i) for i in range(1, 100, 10)]
hidden_layer_sizes_range += [(i, i, i) for i in range(1, 100, 10)]
learning_rate_range = ['constant', 'invscaling', 'adaptive']
param_grid = dict(hidden_layer_sizes=hidden_layer_sizes_range,
learning_rate=learning_rate_range)
# instantiate and fit the grid
grid = GridSearchCV(MLPRegressor(max_iter=10000), param_grid, cv=cv, scoring='r2', n_jobs=n_jobs)
grid.fit(X, y)
# view the complete results
# print(grid.cv_results_)
# examine the best model
# print(grid.best_score_)
# print(grid.best_params_)
return grid.best_params_, grid.best_score_, grid.cv_results_
### Feature Selection Methods
'''
All feature selection methods should take in the following arguments:
X: pandas dataframe | numpy array, the data to perform feature selection on
y: pandas series | numpy array, the label
k: int, the number of features to select, -1 if all features should be selected
*args: extra arguments
All feature selection methods should return the following:
selected_features: list of strings or list of ints representing the indices of the selected features
scores: list of floats | ints, the scores associated with each selected feature
'''
def ensemble_percentile_threshold(X: pd.DataFrame, y: pd.Series, k: int,
methods: list, method_kwargs: list, method_cutoffs_way: list,
alpha=0.05, shuffled_iters=1000, n_jobs=1, stable_seeds=True, verbose=1):
'''
Given a set of feature selection methods, select features which has alpha < 0.05 in any of the methods
when compared to feature score distributions based on randomly shuffled label data.
Input:
X: pandas dataframe, the training data
y: pandas series, the training label
k: int, the number of features to select, always set to -1, k is not used in this method
method: list of functions, the list of feature selection methods to use
method_kwargs: list of dicts, the list of extra arguments for each feature selection method
method_cutoffs_way: list of strings, "one_way" or "two_way", the way to determine the cutoff for each method
threshold: float, the threshold to select features scores
shuffled_iters: int, the number of iterations to shuffle the label data
n_jobs: int, the number of jobs to run in parallel
stable_seeds: bool, whether to use stable seeds for reproducibility, stable seeds simply range from 0 to shuffled_iters
'''
if len(methods) != len(method_kwargs) or len(methods) != len(method_cutoffs_way):
raise ValueError('methods, method_kwargs, and method_cutoffs_way should have the same length')
# create a list of shuffled labels
if stable_seeds:
random_seeds = list(range(shuffled_iters))
else:
random_seeds = np.random.randint(-100000000, 100000000, size=shuffled_iters)
shuffled_label_data = [y.sample(frac=1, random_state=seed) for seed in random_seeds]
df_above_threshold_list = []
i = 0
while i < len(methods):
method, method_kwarg, method_cutoff_way = methods[i], method_kwargs[i], method_cutoffs_way[i]
all_scores = get_shuffled_scores(shuffled_label_data, X, method, method_kwarg, n_jobs=n_jobs, verbose=verbose)
all_scores = [score for score in all_scores if not np.isnan(score)]
if method_cutoff_way == 'one_way':
percentile_cutoff = 100 - alpha * 100
threshold = np.percentile(all_scores, percentile_cutoff)
# print(f'percentile cutoff: {percentile_cutoff}, threshold: {threshold}')