-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathEDA_v4.py
1714 lines (1520 loc) · 78 KB
/
EDA_v4.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
#!/usr/bin/env python
import sys
sys.path.insert(0,'./lib')
import pandas as pd
import numpy as np
import util
import os
import shutil
from shutil import copyfile
from pprint import pprint, pformat
import re
import copy
from sklearn.preprocessing import LabelEncoder,OneHotEncoder
from xgboost import XGBClassifier, XGBRFClassifier, XGBRegressor
from xgboost import plot_importance
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import log_loss, f1_score, accuracy_score, r2_score, make_scorer, confusion_matrix, precision_recall_fscore_support
from scipy.optimize import minimize_scalar, minimize
from sklearn.model_selection import PredefinedSplit, GridSearchCV, ParameterGrid, StratifiedKFold
import gzip
import pickle
import datetime as dt
import scipy.stats as ss
from configjson import CONFIG
import json
#import impute
import sklearn.feature_extraction.text as fet
from nltk import word_tokenize
from nltk import corpus
from nltk.stem import WordNetLemmatizer
import warnings
warnings.simplefilter("ignore")
import itertools
SEED=int(CONFIG.get('Seed',42))
np.random.seed(SEED)
if os.environ.get('NLTK_DATA')!='./nltk_data':
util.error_msg('need to first run: export NLTK_DATA="./nltk_data" ')
EVAL_ENV='EVAL'
if os.getenv("AICROWD_TEST_DATA_PATH") is None:
EVAL_ENV='AICROWD'
import argparse as arg
opt=arg.ArgumentParser(description='Phase2-Approval Prediction')
opt.add_argument('-p','--hyperparameter', default=False, action='store_true', help='hyperparameter tuning')
opt.add_argument('-e','--estimator', default=False, action='store_true', help='estimator tuning')
opt.add_argument('-i','--impute_model', default=False, action='store_true', help='impute RF model')
opt.add_argument('-r','--recreate', default=False, action='store_true', help='recreate feature matrix')
opt.add_argument('-d','--debug', default=False, action='store_true', help='recreate feature matrix')
opt.add_argument('-s','--sort', default=False, action='store_true', help='sort features')
opt.add_argument('-k','--stacking', default=False, action='store_true', help='stacking')
args=opt.parse_args()
TAG=json.dumps(CONFIG)
TAG=re.sub('[{} "]', '', re.sub('false', '0', re.sub('true', '1', TAG)))
TAG=re.sub(',Feature.*','',TAG)
print(">>>>>>>>>TAG:", TAG, ">>", EVAL_ENV)
if EVAL_ENV=='EVAL':
OUTPUT="."
else:
OUTPUT=os.path.join('tags', re.sub('-', 'm', re.sub(',', '_', re.sub(r'[a-z:]', '', TAG))))
os.makedirs(OUTPUT, exist_ok=True)
copyfile('configjson.py', os.path.join(OUTPUT, 'configjson.py'))
print(">>>>>>>>>Folder:", OUTPUT)
if EVAL_ENV=='EVAL':
# in docker eval environment
TRAIN_FILE= os.path.join(os.getenv("AICROWD_TRAIN_DATA_PATH"),'training_data_2015_split_on_outcome.csv')
TEST_FILE= os.getenv("AICROWD_TEST_DATA_PATH")
SUBMISSION_FILE=os.getenv("AICROWD_PREDICTIONS_OUTPUT_PATH")
RECREATE=True
CORE=4
elif EVAL_ENV=='AICROWD':
###RECREATE=not os.path.exists(os.path.join(OUTPUT, 'feature_matrix.pkl.gz'))
RECREATE=False
TRAIN_FILE='/shared_data/data/training_data/training_data_2015_split_on_outcome.csv'
TEST_FILE='/shared_data/data/test_data_sample/testing_phase2_release_small.csv'
if not os.path.exists(TEST_FILE):
TEST_FILE = 'testing_phase2_release.csv'
#TEST_FILE = 'testing_phase2_release_small.csv'
if not os.path.exists(TRAIN_FILE):
TRAIN_FILE = 'training_data_2015_split_on_outcome.csv'
SUBMISSION_FILE=os.path.join(OUTPUT, "submit.csv")
EVAL_ENV=False
CORE=36
#XXXXXXX
#CONFIG={'RemoveTrivialDrugs':True,'RemoveTerminated':False,'SetTerminatedToZero':False,'Model':'XGB','Validate':'2014Only'}
LOWER_BOUND=0.01
UPPER_BOUND=0.99
###TARGET_RATIO=0.15
TARGET_RATIO=float(CONFIG.get('TargetRatio',0.15))
FIX_20182019=CONFIG['FixYear']
DRUGKEY_AUGMENTATION=CONFIG['DrugindiMax']
WEIGHT_BY_DRUGKEY=True
WEIGHT_BY_OUTCOME=False
DRUGKEYS=['drugkey','indicationkey']
# Some drugs appear often in the training set
TRIVIAL_DRUGS=[1627, 1798, 1803, 4232, 5440, 7350, 11435, 14311, 15034, 15816, 18087, 19577, 23997, 26475, 28941, 34480, 111814]
TRIVIAL_OUTCOME={1627: 0.0, 1798: 0.0, 1803: 0.0, 4232: 1.0, 5440: 0.0, 7350: 1.0, 11435: 0.0, 13517: 0.9316239316239316, 14236: 0.07692307692307693, 14311: 0.0, 15034: 0.0, 15816: 1.0, 18087: 0.029850746268656716, 19577: 0.02857142857142857, 23997: 1.0, 26475: 0.0, 28941: 0.0, 34480: 0.0, 111814: 1.0}
#(40, 26, 26, 30, 21, 103, 26, 117, 26, 36, 25, 32, 67, 35, 36, 44, 25, 34, 21)
REMOVE_TRIVIAL_DRUGS=CONFIG['RemoveTrivialDrugs']
REMOVE_TERMINATED=CONFIG['RemoveTerminated']
FIX_TRIVIAL_DRUGS=False
SET_TERMINATED_TO_ZERO=CONFIG['SetTerminatedToZero']
MODEL_SELECTION=CONFIG['Model']
VALIDATION_MODE=CONFIG['Validate']
SAMPLE_WEIGHT=CONFIG['SampleWeight']
# one: 1, sqrt: 1/sqrt(n), inverse: 1/n
if SAMPLE_WEIGHT not in ('ONE','SQRT', 'INV', 'DIONE', 'DISQRT', 'DIINV'):
util.error_msg('Unsupported SAMPLE_WEIGHT!')
# We currently don't know how to handle imputing other than MEAN
# RF approach can be applied to train, but tricky for test
IMPUTE=CONFIG['Impute']
HYPERPARAMETER=False #CONFIG['Hyper']
SCALE_POS_WEIGHT=CONFIG['PosScale']
if EVAL_ENV=='EVAL':
HYPERPARAMETER=False
HYPERPARAMETER=args.hyperparameter
ONLY_TUNE_ESTIMATOR=args.estimator
IMPUTE_MODEL=args.impute_model
if EVAL_ENV=='EVAL':
HYPERPARAMETER=ONLY_TUNE_ESTIMATOR=False
IMPUTE_MODEL=False
elif ONLY_TUNE_ESTIMATOR:
HYPERPARAMETER=ONLY_TUNE_ESTIMATOR=True
if IMPUTE_MODEL: RECREATE=True
if args.recreate or args.debug: RECREATE=True
if HYPERPARAMETER:
if ONLY_TUNE_ESTIMATOR:
if MODEL_SELECTION in ('XGB'):
if not os.path.exists('hyperparameter.json'):
util.error_msg('Missing: hyperparameter.json')
else:
if not os.path.exists(os.path.join(OUTPUT, 'hyperparameter.range.json')):
if MODEL_SELECTION in ('XGB'):
copyfile("params/hyperparameter.range.json", os.path.join(OUTPUT, 'hyperparameter.range.json'))
elif MODEL_SELECTION=='RF':
copyfile("params/hyperparameter.range.rf.json", os.path.join(OUTPUT, 'hyperparameter.range.json'))
def myToken(s): return re.split('[|,]',s)
class Dump:
"""Utility for save/load object to/from a pickle file, the file is gzipped
"""
@staticmethod
def save(obj, pkl_filename):
with gzip.open(pkl_filename, 'wb') as f:
pickle.dump(obj, f)
@staticmethod
def load(pkl_filename):
if not os.path.exists(pkl_filename):
util.error_msg('File not exist: '+pkl_filename)
with gzip.open(pkl_filename, 'rb') as f:
return pickle.load(f)
@staticmethod
def load_json(json_filename):
if not os.path.exists(json_filename):
util.error_msg('File not exist: '+json_filename)
with open(json_filename) as f:
data=json.load(f)
return data
@staticmethod
def save_json(data, json_filename):
with open(json_filename, "w") as f:
data=json.dump(data, f)
return data
class EDA:
def __init__(self, impute=IMPUTE, recreate=True):
self.EPS=1e-6
self.QUANTILE =0.25 # use to normalize ratio
self.IMPUTE=impute
# impute can be MEAN (or median), ML (machine learning method)
# missing value exists in duration, age, accrual columns
# target or text columns no need for EDA plotting
self.s_out=f'M{MODEL_SELECTION}_V{VALIDATION_MODE}_SW{SAMPLE_WEIGHT}_I{IMPUTE}_SD{SEED}'
self.OUTCOME = 'outcome'
self.YEAR='intphaseendyear'
self.NEW_YEAR='YEAR'
if not recreate:
self.train, self.test, param=Dump.load(os.path.join(OUTPUT, 'feature_matrix.pkl.gz'))
self.feature_cols=param['feature_cols']
self.filter_datasets()
self.ratio=param['ratio']
self.ratio_in_terminate=param['ratio_in_terminate']
print("Ratio:", self.ratio, "Ratio in Terminated:", self.ratio_in_terminate, "Features:", len(self.feature_cols))
print("Number of Features:", len(self.feature_cols))
return
self.train= pd.read_csv(TRAIN_FILE)
# add TRAIN column, as we may need to merge train+test and split them for feature engineering
# (requiring all historical data)
self.test=pd.read_csv(TEST_FILE)
print('# in test set:',len(self.test))
self.train.rename2({k:k.lower() for k in self.train.header()})
self.test.rename2({k:k.lower() for k in self.test.header()})
self.train['TRAIN']=True
self.test['TRAIN']=False
self.train['test_idx']=-1
self.test['test_idx']=self.test.index.values
# fix years first!
self.fix_phase_year(self.YEAR, self.NEW_YEAR)
if False: # identify problematic columns
for s in self.train.header():
if s!=self.OUTCOME and not s in self.test.header():
print("EDA> Delete feature not in test:", s)
self.drop_col(s)
elif np.all(self.train[s].isnull()):
#
print("EDA> Delete feature of all NaN:", s)
self.drop_col(s)
elif not np.any(self.train[s].isnull()) and self.train[s].nunique()==1:
# DrugCountryName, looks like a bug
if s=='TRAIN': continue
print("EDA> Delete feature of unique value:", s, self.train.loc[0, s])
self.drop_col(s)
elif s=='unnamed: 0':
if 'unnamed: 0' in self.train.header():
self.train.drop('unnamed: 0', axis=1, inplace=True)
if 'unnamed: 0' in self.test.header():
self.test.drop('unnamed: 0', axis=1, inplace=True)
if EVAL_ENV=='EVAL':
self.test[self.OUTCOME]=0
elif self.OUTCOME not in self.test.header():
self.test[self.OUTCOME]=0
#NEED TO MAKE SURE TRAIN AND TEST HAVE THE SAME COLUMNS IN THE SAME ORDER
COLUMNS=sorted(['YEAR', 'drugkey', 'indicationkey', 'outcome', 'intduration', 'inttargetaccrual', 'intactualaccrual', 'intidentifiedsites', 'intsponsorid_approval_drugkey_indicationkey', 'intsponsorid_failure_drugkey_indicationkey', 'intpersonid_approval_drugkey_indicationkey', 'intpersonid_failure_drugkey_indicationkey', 'intsponsorid_p1_intclinicaltrialids', 'intsponsorid_p1_completed_intclinicaltrialids', 'intsponsorid_p1_terminated_intclinicaltrialids', 'intsponsorid_p1_positive_intclinicaltrialids', 'intsponsorid_p1_negative_intclinicaltrialids', 'intsponsorid_p2_intclinicaltrialids', 'intsponsorid_p2_completed_intclinicaltrialids', 'intsponsorid_p2_terminated_intclinicaltrialids', 'intsponsorid_p2_positive_intclinicaltrialids', 'intsponsorid_p2_negative_intclinicaltrialids', 'intsponsorid_p3_intclinicaltrialids', 'intsponsorid_p3_completed_intclinicaltrialids', 'intsponsorid_p3_terminated_intclinicaltrialids', 'intsponsorid_p3_positive_intclinicaltrialids', 'intsponsorid_p3_negative_intclinicaltrialids', 'intpersonid_p1_intclinicaltrialids', 'intpersonid_p1_completed_intclinicaltrialids', 'intpersonid_p1_terminated_intclinicaltrialids', 'intpersonid_p1_positive_intclinicaltrialids', 'intpersonid_p1_negative_intclinicaltrialids', 'intpersonid_p2_intclinicaltrialids', 'intpersonid_p2_completed_intclinicaltrialids', 'intpersonid_p2_terminated_intclinicaltrialids', 'intpersonid_p2_positive_intclinicaltrialids', 'intpersonid_p2_negative_intclinicaltrialids', 'intpersonid_p3_intclinicaltrialids', 'intpersonid_p3_completed_intclinicaltrialids', 'intpersonid_p3_terminated_intclinicaltrialids', 'intpersonid_p3_positive_intclinicaltrialids', 'intpersonid_p3_negative_intclinicaltrialids', 'intpriorapproval', 'decminage', 'decmaxage', 'strminageunit', 'strmaxageunit', 'strterminationreason', 'strsponsor','row_id','TRAIN','genericname','test_idx'])
#'intclinicaltrialid'
META_DATA=['row_id','TRAIN','outcome','drugkey','indicationkey',self.NEW_YEAR, 'indication_groupkey', 'test_idx']
#'strterminationreason','strsponsor'])
cols_multilabel=[#'originkey',
'mediumdescription',
'strregulatorystatus',
'strtherapeuticarea',
'strdesignkeyword',
'strdiseasetype',
'strmechanismofaction',
'drugdeliveryroutedescription',
'drugtarget',
'therapydescription',
'strpatientsegment',
'strsponsortype',
'strlocation',
'strterminationreason'
]
cols_freetext=[
#'strpatientpopulation',
#'strprimaryendpoint',
#'strexclusioncriteria',
#'strstudydesign'
]
#, 'strregulatorystatus', 'strtherapeuticarea', 'strdesignkeyword', 'strdiseasetype', 'strmechanismofaction', 'drugdeliveryroutedescription', 'drugtarget', 'strpatientpopulation', 'strprimaryendpoint', 'strexclusioncriteria', 'strstudydesign', 'genericname', 'therapydescription', 'strpatientsegment', 'strsponsortype', 'strlocation', 'mediumdescription', 'originkey']
COLUMNS+=cols_multilabel
COLUMNS+=cols_freetext
#COLUMNS=[x for x in COLUMNS if self.train.col_type(x)!='s']
COLUMNS=util.unique2(COLUMNS)
self.train=self.train[COLUMNS].copy()
self.test=self.test[COLUMNS].copy()
self.COLUMNS=COLUMNS
self.nan_cols=['intduration', 'inttargetaccrual', 'intactualaccrual'] #, 'decminage', 'decmaxage']
if IMPUTE_MODEL:
# create impute models, save into ./impute.pkl.gz
self.impute_model_validate(self.nan_cols)
self.impute_model(self.nan_cols)
exit()
if IMPUTE!="MEAN":
self.impute_runtime()
#for x in self.nan_cols:
# print(x, self.test[x].isnull().sum())
#exit()
# Trivial drugs
FIND_TRIVIAL=False
if FIND_TRIVIAL:
cnt=self.train.groupby('drugkey').size()
pos=self.train.groupby('drugkey')[self.OUTCOME].sum()
out=[]
outcome={}
for k,v in cnt.items():
if v>=20 and (pos[k]/v>=0.90 or pos[k]/v<=0.10):
out.append((k, pos[k]/v, v))
outcome[k]=pos[k]/v
drugkey, prob, cnt=zip(*out)
print(list(drugkey))
print(outcome)
exit()
t=self.train[self.OUTCOME].value_counts()
self.ratio=self.train.outcome.sum()/len(self.train)
print("Overall approval ratio: ", self.ratio)
ratio=self.train.groupby(self.NEW_YEAR)[self.OUTCOME].sum()/self.train.groupby(self.NEW_YEAR).size()
print("Approval ratio by year: ")
pprint(ratio)
#print("======== numeric features ", self.train.shape, self.test.shape)
self.fix_multilabel(cols_multilabel)
print("======== added multilabel features ", len(cols_multilabel),self.train.shape, self.test.shape,len([x for x in self.train.columns for y in cols_multilabel if y+':' in x]))
#self.fix_freetext(cols_freetext,coef_cut=0.02,n_cut=None)
##print("======== added free text features ", len(cols_freetext),self.train.shape, self.test.shape)
self.fix_terminate_reason('strterminationreason')
self.ratio_in_terminate=self.train[self.train['hopeful']<0][self.OUTCOME].mean()
print("Approval ratio in terminated records:", self.ratio_in_terminate)
self.filter_datasets()
#print("\n".join(self.train.header()))
self.fix_age_col('decminage','strminageunit', 'decmaxage','strmaxageunit')
self.fix_accrual('inttargetaccrual', 'intactualaccrual')
self.fix_duration('intduration')
self.fix_identifiedsites('intidentifiedsites')
self.fix_prior_approval('intpriorapproval')
#self.fix_generic_name('genericname')
self.fix_sponsor_cluster()
#self.phase_performance(entity="sponsor", phase="p1", previous=5)
#self.phase_performance(entity="sponsor", phase="p2", previous=5)
#self.phase_performance(entity="sponsor", phase="p3", previous=5)
#self.phase_performance(entity="sponsor", phase="p1", previous=3)
#self.phase_performance(entity="sponsor", phase="p2", previous=3)
#self.phase_performance(entity="sponsor", phase="p3", previous=3)
# previous==0 must be at the last, as it modified the raw columns
self.phase_performance(entity="sponsor", phase="p1")
self.phase_performance(entity="sponsor", phase="p2")
self.phase_performance(entity="sponsor", phase="p3")
self.phase_performance(entity="person", phase="p1")
self.phase_performance(entity="person", phase="p2")
self.phase_performance(entity="person", phase="p3")
#self.overall_performance(entity="sponsor", previous=5)
#self.overall_performance(entity="sponsor", previous=3)
self.overall_performance(entity="sponsor")
self.overall_performance(entity="person")
self.fix_indication_key("indicationkey")
self.fix_indication_group("indicationkey")
self.fix_drug_key('drugkey')
self.downcast_dtypes(self.train)
self.downcast_dtypes(self.test)
self.feature_cols=util.read_list('feature_cols.txt')
self.feature_cols=[x for x in self.feature_cols if x!='']
REMOVE_FEATURES=False
if REMOVE_FEATURES:
t_rank=pd.read_csv(os.path.join(OUTPUT, 'FeatureRanking.csv'))
# keep top 50 features
n_TOP=30
print("KEEPING >>>>>>>>>>>>>>")
for x in t_rank[:n_TOP].Feature:
print(x)
print("REMOVING >>>>>>>>>>>>>>")
for x in t_rank[n_TOP:].Feature:
print(x)
exit()
REDUNDANT_FEATURES=False
if REDUNDANT_FEATURES:
t_rank=pd.read_csv(os.path.join(OUTPUT, 'FeatureRanking.csv'))
#t_rank=pd.read_csv('notes/FeatureRanking.all265.csv')
c_seen={}
S_cols=[]
for x in t_rank.Feature:
s_root=re.sub(r'(_prev_.yers)?(_rank)?_norm(_by_year)?', '', x)
if s_root in c_seen: continue
#print(x)
c_seen[s_root]=True
S_cols.append(x)
# remove highly correlated features
m=self.train[S_cols].values
r,c=m.shape
R=np.corrcoef(m, rowvar=0)
cols_del=[]
cols_keep=[]
for i in range(c):
if S_cols[i] in cols_del: continue
cols_keep.append(S_cols[i])
print(S_cols[i])
rm=[ (S_cols[j], R[i,j]) for j in range(i+1,c) if R[i, j]>=0.95 ]
for x in rm:
if x[0] not in cols_del: cols_del.append(x[0])
#print(">>>", S_cols[i], x)
print("Left:", len(cols_keep), "Removed:", len(t_rank)-len(cols_keep))
exit()
REDUNDANT_MultiFEATURES=False # remove identical multilabel features
if REDUNDANT_MultiFEATURES:
##S_cols=util.read_list('features/feature_cols.multi607.txt')
S_cols=util.read_list('features/feature_cols.n75_m399.txt')
# remove highly correlated features
m=self.train[S_cols].values
r,c=m.shape
cols_del=[]
cols_keep=[]
out={}
for i in range(c):
ci=S_cols[i]
if ci in cols_del: continue
cols_keep.append(ci)
#print(S_cols[i])
rm=[ S_cols[j] for j in range(i+1,c) if np.all(m[:,i] == m[:,j]) ]
if len(rm) > 0:
out[ci]=[]
for x in rm:
if x not in cols_del: cols_del.append(x)
#print(">>>", S_cols[i], x)
out[ci].append(x)
##Dump.save_json(out, 'features/Redundant_multicols.json')
##with open(f'features/feature_cols.multi_rmRd{len(cols_keep)}.txt', 'w') as f_col:
## f_col.writelines("%s\n" % c for c in cols_keep)
print("Left:", len(cols_keep), "Removed:", len(cols_del))
exit()
if EVAL_ENV!='EVAL':
FOUND_BAD=False
print("SEARCH for UNEXPECTED NEW FEATURES:")
for x in self.train.header():
if x in META_DATA and x!='YEAR': continue
if self.train.col_type(x)!='s' and x not in self.feature_cols:
FOUND_BAD=True
print(x)
if FOUND_BAD:
print("There are new features!")
else:
print("No unexpected new feature, good!")
s_file=os.path.join(OUTPUT, 'feature_matrix.pkl.gz')
self.train=self.train[ util.unique2(META_DATA+self.feature_cols) ].copy()
self.test=self.test[ util.unique2(META_DATA+self.feature_cols) ].copy()
Dump.save([self.train, self.test, {'ratio':self.ratio, 'ratio_in_terminate':self.ratio_in_terminate, 'feature_cols':self.feature_cols}], s_file)
print(os.path.join(OUTPUT, "feature_matrix.pkl.gz"))
copyfile(os.path.join(OUTPUT,"feature_matrix.pkl.gz"), "feature_matrix.pkl.gz")
CHECK_CORRELATION=False
if CHECK_CORRELATION:
self.check_correlation()
exit()
print("Number of Features:", len(self.feature_cols))
def downcast_dtypes(self, df):
"""Save 50% of memory usage"""
float_cols = [c for c in df if df[c].dtype == "float64"]
int_cols = [c for c in df if df[c].dtype in ["int64", "int32"] and c not in ['drugkey','indicationkey','row_id']]
df[float_cols] = df[float_cols].astype(np.float32)
df[int_cols] = df[int_cols].astype(np.int16)
return df
def fix_generic_name(self, col):
data=self.merge_datasets()
data[col]=data[col].apply(lambda x: -1 if (pd.isnull(x) or x=='') else (1 if re.search(r'^[a-zA-Z ,]+$', str(x)) is not None else 0))
self.split_datasets(data)
def fix_sponsor_cluster_(self):
ids=set(util.read_list('cluster_low.txt'))
self.train['sponsor_class']=self.train.row_id.isin(ids).astype(int)
self.test['sponsor_class']=self.train.row_id.isin(ids).astype(int)
def fix_sponsor_cluster(self):
cluster_ids=util.read_csv('sponsor_cluster.csv')
cols=['intsponsorid_p2_positive_intclinicaltrialids','intsponsorid_p2_intclinicaltrialids']
X=cluster_ids[cols].values
max_X=np.max(X, axis=0)
X=X/max_X
y=cluster_ids['cluster_id'].values
from sklearn.neighbors import KNeighborsClassifier
knn=KNeighborsClassifier(n_neighbors=1)
knn.fit(X, y)
X_train=self.train[cols].values/max_X
self.train['sponsor_class']=knn.predict(X_train)
X_test=self.test[cols].values/max_X
self.test['sponsor_class']=knn.predict(X_test)
# year 1990 means nan, there are too few items for the year <=2001, so let's change the years
def fix_phase_year(self, yr_col, newyr_col):
self.train[newyr_col]=self.train[yr_col].apply(lambda x: 2001 if x<=2001 else x)
self.train[newyr_col]=self.train[newyr_col]
# we set
#self.test[newyr_col]=2015-2000
self.test[newyr_col]=self.test[yr_col]
# maybe set 2019 as 2018 as there are not many records there?
self.test[newyr_col]=self.test[newyr_col].clip(2001, 2025)
def overall_performance(self, entity="sponsor", previous=0):
# sponsor/person
QUANTILE=0.1
col_pos="int{}id_approval_drugkey_indicationkey".format(entity)
col_neg="int{}id_failure_drugkey_indicationkey".format(entity)
col_tot="int{}id_total_drugkey_indicationkey".format(entity)
col_ratio="int{}id_postive.pct_drugkey_indicationkey".format(entity)
if previous>0:
if entity!='sponsor':
print("ERROR> only have sponsor id for previous!=0")
exit()
col_entity='strsponsor'
col_newtot=col_tot+"_prev_{}yrs".format(previous)
col_newpos=col_pos+"_prev_{}yrs".format(previous)
col_newneg=col_neg+"_prev_{}yrs".format(previous)
col_newratio=col_ratio+"_prev_{}yrs".format(previous)
data=self.merge_datasets()
if previous==0:
data[col_tot]=data[col_pos]+data[col_neg]
# when calculate percentage, we need to add enough dummie counts to avoid high percentage due to few counts
dummie=data.groupby(self.NEW_YEAR)[col_tot].quantile(QUANTILE).clip(1, np.inf)
X=data[self.NEW_YEAR].map(dummie)
data[col_ratio]=((data[col_pos])/(data[col_tot].values+X)).clip(0.0,1.0)
#print(data[col_ratio])
self.rank_normalize_dual(data, col_tot)
self.rank_normalize_dual(data, col_pos)
self.rank_normalize_dual(data, col_neg)
else:
for k,t_v in data.groupby(self.NEW_YEAR):
df=data[data[self.NEW_YEAR]<k-previous+1].copy()
prev_pos=df.groupby(col_entity)[col_pos].max().to_dict()
prev_neg=df.groupby(col_entity)[col_neg].max().to_dict()
pos=(t_v[col_pos]-t_v[col_entity].apply(lambda x: prev_pos.get(x, 0))).clip(0,999999)
neg=(t_v[col_neg]-t_v[col_entity].apply(lambda x: prev_neg.get(x, 0))).clip(0,999999)
tot=pos+neg
dummie=tot.quantile(QUANTILE).clip(1,np.inf)
data.loc[t_v.index, col_newtot]=tot
data.loc[t_v.index, col_newpos]=pos
data.loc[t_v.index, col_newneg]=neg
data.loc[t_v.index, col_newratio]=(pos/(tot+dummie)).clip(0.0,1.0)
self.rank_normalize_dual(data, col_newtot)
self.rank_normalize_dual(data, col_newpos)
self.rank_normalize_dual(data, col_newneg)
self.split_datasets(data)
# we can calculate an overall success rate
# if we calculate POS over years, there are consistent high performers and low performers
def phase_performance(self, entity="sponsor", phase="p1", previous=0):
QUANTILE=0.25
# sponsor/person, p1/p2/p3
col_trials="int{}id_{}_intclinicaltrialids".format(entity, phase)
col_complete="int{}id_{}_completed_intclinicaltrialids".format(entity, phase)
col_terminate="int{}id_{}_terminated_intclinicaltrialids".format(entity, phase)
# b/c there are status unknown, complete+terminate!=trials
col_positive="int{}id_{}_positive_intclinicaltrialids".format(entity, phase)
col_negative="int{}id_{}_negative_intclinicaltrialids".format(entity, phase)
# terminate is not successful, but terminate does not mean negative (not enough enrollment
# there is some data leak in these columns, as it probably aggregate future data
# e.g., by calculate diff of successful trials, we know how many trials are successful in the previous year.
# however, since such data are
# as these counts are accumulative, they grow over years, so we should correct the year-effect
# we get differential data
# we will basically use them to rank entity within each year to create a performance index (PI)
# total number of trails run
col_tot="int{}id_{}_total_intclinicaltrialids".format(entity, phase)
col_inprog="int{}id_{}_progress.pct_intclinicaltrialids".format(entity, phase)
col_comp="int{}id_{}_completed.pct_intclinicaltrialids".format(entity, phase)
col_pos="int{}id_{}_positive.pct_intclinicaltrialids".format(entity, phase)
if previous>0:
if entity!='sponsor':
print("ERROR> only have sponsor id for previous!=0")
exit()
col_entity='strsponsor'
col_tot+="_prev_{}yrs".format(previous)
col_inprog+="_prev_{}yrs".format(previous)
col_comp+="_prev_{}yrs".format(previous)
col_pos+="_prev_{}yrs".format(previous)
data=self.merge_datasets()
data[col_tot]=data[col_trials].copy()
if previous==0:
# when calculate percentage, we need to add enough dummie counts to avoid high percentage due to few counts
dummie=data.groupby(self.NEW_YEAR)[col_tot].quantile(QUANTILE).clip(1, np.inf)
X=data[self.NEW_YEAR].map(dummie)
data[col_inprog]=((data[col_trials]-data[col_complete]-data[col_terminate])/(data[col_trials].values+X)).clip(0.0,1.0)
data['_temp']=data[col_complete]+data[col_terminate]
dummie=data.groupby(self.NEW_YEAR)['_temp'].quantile(QUANTILE).clip(1, np.inf)
X=data[self.NEW_YEAR].map(dummie)
data[col_comp]=((data[col_complete])/(data['_temp'].values+X)).clip(0.0,1.0)
data['_temp']=data[col_positive]+data[col_negative]
dummie=data.groupby(self.NEW_YEAR)['_temp'].quantile(QUANTILE).clip(1, np.inf)
X=data[self.NEW_YEAR].map(dummie)
data[col_pos]=((data[col_positive])/(data['_temp'].values+X)).clip(0.0,1.0)
data.drop([col_tot,'_temp'], axis=1, inplace=True)
else:
for k,t_v in data.groupby(self.NEW_YEAR):
#print(k, previous)
df=data[data[self.NEW_YEAR]<k-previous+1].copy()
prev_tot=df.groupby(col_entity)[col_trials].max().to_dict()
tot=(t_v[col_trials]-t_v[col_entity].apply(lambda x: prev_tot.get(x, 0))).clip(0, 999999)
prev_comp=data[data[self.NEW_YEAR]<k-previous+1].groupby(col_entity)[col_complete].max().to_dict()
comp=(t_v[col_complete]-t_v[col_entity].apply(lambda x: prev_comp.get(x, 0))).clip(0, 999999)
prev_term=df.groupby(col_entity)[col_terminate].max().to_dict()
term=(t_v[col_terminate]-t_v[col_entity].apply(lambda x: prev_term.get(x, 0))).clip(0, 999999)
inprog=(tot-comp-term).clip(0, 999999)
prev_pos=df.groupby(col_entity)[col_positive].max().to_dict()
pos=(t_v[col_positive]-t_v[col_entity].apply(lambda x: prev_pos.get(x, 0))).clip(0, 999999)
prev_neg=df.groupby(col_entity)[col_negative].max().to_dict()
neg=(t_v[col_negative]-t_v[col_entity].apply(lambda x: prev_neg.get(x, 0))).clip(0, 999999)
data.loc[t_v.index, col_tot]=tot
dummie=tot.quantile(QUANTILE).clip(1, np.inf)
data.loc[t_v.index, col_inprog]=inprog/(tot+dummie)
tmp=comp+term
dummie=tmp.quantile(QUANTILE).clip(1, np.inf)
data.loc[t_v.index, col_comp]=comp/(tmp+dummie)
tmp=pos+neg
dummie=tmp.quantile(QUANTILE).clip(1, np.inf)
data.loc[t_v.index, col_pos]=pos/(tmp+dummie)
if previous>0:
self.rank_normalize_dual(data, col_tot)
self.rank_normalize_dual(data, col_inprog)
self.rank_normalize_dual(data, col_comp)
self.rank_normalize_dual(data, col_pos)
if previous==0:
self.rank_normalize_dual(data, col_trials)
self.rank_normalize_dual(data, col_complete)
self.rank_normalize_dual(data, col_terminate)
self.rank_normalize_dual(data, col_positive)
self.rank_normalize_dual(data, col_negative)
self.split_datasets(data)
#drug id is useful, two drug accounts have over 100 trials each
# fludarabine, oxaliplatin, the are concentrated on some years (what happened???)
# they are 100% approved and can get hints from prior approvals
# need to check drug overlap between train and test
# test has a drug that appear a lot, but not much in training
# so we may need to down weight, so that each drug is treated equally in the training?
def fix_drug_key(self, drug_col):
# besides outcome, calculate other p1,p2,p3....
QUANTILE=0.15
data=self.merge_datasets()
col_cnt='drug_prior_trial_count'
data[col_cnt]=0.0
col_ratio='drug_prior_trial_positve.pct'
data[col_ratio]=0.0
for k,t_v in data.groupby(self.NEW_YEAR):
k=min(2015, k) # since we need to access OUTCOME file and OUTCOME is not available for records >=2015
df=data[data[self.NEW_YEAR]<k].copy() # <k has not count, don't do <=k, which include current year
# then you peak into the outcome of the current year
if len(df)==0: continue
cnt=df.groupby(drug_col).size()
data.loc[t_v.index, col_cnt]=t_v[drug_col].apply(lambda x: cnt.get(x, 0))
#test dataset will not have outcome vaues
#underestimate positive ratios, but nothing we can do
pos=df[df[self.OUTCOME]>0.5].groupby(drug_col).size().to_dict()
dummie=max(cnt.quantile(QUANTILE),1)
cnt=cnt.to_dict()
data.loc[t_v.index, col_ratio]=t_v[drug_col].apply(lambda x: pos.get(x, 0)/(cnt.get(x,0)+dummie))
self.rank_normalize_dual(data, col_cnt)
#print(k, sorted(data.header()))
self.split_datasets(data)
def fix_indication_key(self, drug_col):
# besides outcome, calculate other p1,p2,p3....
QUANTILE=0.15
data=self.merge_datasets()
col_cnt='indication_prior_trial_count'
data[col_cnt]=0.0
col_ratio='indication_prior_trial_positve.pct'
data[col_ratio]=0.0
for k,t_v in data.groupby(self.NEW_YEAR):
k=min(2015, k) # since we need to access OUTCOME file and OUTCOME is not available for records >=2015
df=data[data[self.NEW_YEAR]<k].copy() # <k has not count, don't do <=k, which include current year
# then you peak into the outcome of the current year
if len(df)==0: continue
cnt=df.groupby(drug_col).size()
data.loc[t_v.index, col_cnt]=t_v[drug_col].apply(lambda x: cnt.get(x, 0))
#test dataset will not have outcome vaues
#underestimate positive ratios, but nothing we can do
pos=df[df[self.OUTCOME]>0.5].groupby(drug_col).size().to_dict()
dummie=max(cnt.quantile(QUANTILE),1)
cnt=cnt.to_dict()
data.loc[t_v.index, col_ratio]=t_v[drug_col].apply(lambda x: pos.get(x, 0)/(cnt.get(x,0)+dummie))
self.rank_normalize_dual(data, col_cnt)
#print(k, sorted(data.header()))
self.split_datasets(data)
def fix_indication_group(self, ind_col):
t=pd.read_csv('countvec/indicationkey2group.csv', delimiter="|")
c_map={}
for k,t_v in t.groupby('IndicationKey'):
grpid=t_v.IndicationGroupKey.tolist()
if len(grpid)==1:
c_map[k]=grpid[0]
else:
grpid=[x for x in grpid if x!=24]
c_map[k]=min(grpid)
data=self.merge_datasets()
indgrp_col='indication_groupkey'
data[indgrp_col]=data[ind_col].map(c_map)
QUANTILE=0.15
col_cnt='indicationgrp_prior_trial_count'
data[col_cnt]=0.0
col_ratio='indicationgrp_prior_trial_positve.pct'
data[col_ratio]=0.0
for k,t_v in data.groupby(self.NEW_YEAR):
k=min(2015, k) # since we need to access OUTCOME file and OUTCOME is not available for records >=2015
df=data[data[self.NEW_YEAR]<k].copy() # <k has not count, don't do <=k, which include current year
# then you peak into the outcome of the current year
if len(df)==0: continue
cnt=df.groupby(indgrp_col).size()
data.loc[t_v.index, col_cnt]=t_v[indgrp_col].apply(lambda x: cnt.get(x, 0))
pos=df[df[self.OUTCOME]>0.5].groupby(indgrp_col).size().to_dict()
dummie=max(cnt.quantile(QUANTILE),1)
cnt=cnt.to_dict()
data.loc[t_v.index, col_ratio]=t_v[indgrp_col].apply(lambda x: pos.get(x, 0)/(cnt.get(x,0)+dummie))
self.rank_normalize_dual(data, col_cnt)
#print(k, sorted(data.header()))
enc=OneHotEncoder()
enc.fit(data[[indgrp_col]])
t=pd.read_csv('countvec/indicationgroup.csv', delimiter="|")
t['Name']=t.Name.apply(lambda x: re.sub(r'\W.*$', '', x))
c_name={k:v for k,v in zip(t.IndicationGroupKey, t.Name)}
S_col=["indicationgrp_key_{}_{}".format(int(x), c_name[int(x)]) for x in enc.categories_[0]]
#print(S_col)
m=enc.transform(data[[indgrp_col]]).toarray().astype(int)
r,c=m.shape
for i in range(c):
data[S_col[i]]=m[:,i]
#data.drop(indgrp_col, axis=1, inplace=True)
self.split_datasets(data)
# this is a very important column, [] stands for probably approved before, ['0'] for not approved before
# [] has a much higher success rate
def fix_prior_approval(self, app_col):
c_map={'[]':1, "['0']":0}
def fix(df):
df[app_col]=df[app_col].map(c_map)
df[app_col].fillna(0, inplace=True)
fix(self.train)
fix(self.test)
def fix_terminate_reason(self, col):
data=self.merge_datasets()
def is_positive(s):
s=s.lower().strip()
if s=="": return 0
if 'completed' in s:
if 'positive' in s: return 1
if 'negative' in s: return -1
if 'indeterminate' in s: return 0
if 'terminated' in s:
if re.search(r'(negative|adverse|poor|lack|shift|repriorit|bussiness|other)', s) is not None:
return -1
print(">>unseen terminateion reason>>", s)
return -1
return 0
data[col].fillna('', inplace=True)
data['hopeful']=data[col].apply(lambda x: is_positive(x))
self.split_datasets(data)
def fix_age_col(self, min_age_col, min_unit_col, max_age_col, max_unit_col):
def fix_age(df, age_col, unit_col):
norm={'months':12, 'weeks': 365/7, 'days': 365, 'years':1}
df[age_col]=df.apply(lambda r: np.nan if pd.isnull(r[age_col]) else r[age_col]/norm.get(r[unit_col],1), axis=1)
data=self.merge_datasets()
def fix(df):
fix_age(df, min_age_col, min_unit_col)
fix_age(df, max_age_col, max_unit_col)
df['age_range']=df[max_age_col]-df[min_age_col]
df[min_age_col].fillna(df[min_age_col].mean(), inplace=True)
df[max_age_col].fillna(df[max_age_col].mean(), inplace=True)
df['age_range'].fillna(df['age_range'].mean(), inplace=True)
df['for_baby']=df.apply(lambda r: 1 if (r[min_age_col]<=3 or r[max_age_col]<=3) else 0, axis=1)
df['for_elder']=df.apply(lambda r: 1 if (r[min_age_col]>=65 or r[max_age_col]>=65) else 0, axis=1)
df.drop([min_unit_col, max_unit_col], axis=1, inplace=True)
fix(data)
self.split_datasets(data)
# (act-target)/target, there is a sweet window 0-1. To high is not good somehow, maybe indicating the trial was not well planned
def fix_accrual(self, target_col, actual_col):
QUANTILE=0.25
data=self.merge_datasets()
col='accrual_pct'
#actual_mean=data[actual_col].mean()
#target_mean=data[target_col].mean()
#dummie=data[target_col].quantile(QUANTILE).clip(1, np.inf)
#data[col]=(data[actual_col]-data[target_col])/(data[target_col]+dummie)
#self.split_datasets(data)
#exit()
#data[col]=(data[actual_col]-data[target_col])/data[target_col].clip(100, np.inf)
if True: #self.IMPUTE=='MEAN':
for k,t_v in data.groupby(self.NEW_YEAR):
t_v=t_v.copy()
actual_mean=t_v[actual_col].mean()
target_mean=t_v[target_col].mean()
dummie=t_v[target_col].quantile(QUANTILE).clip(1, np.inf)
t_v[actual_col].fillna(actual_mean, inplace=True)
data.loc[t_v.index, actual_col]=t_v[actual_col]
t_v[target_col].fillna(target_mean, inplace=True)
data.loc[t_v.index, target_col]=t_v[target_col]
data.loc[t_v.index, col]=(t_v[actual_col]-t_v[target_col])/(t_v[target_col]+dummie)
self.rank_normalize_dual(data, 'accrual_pct')
self.rank_normalize_dual(data, target_col)
self.rank_normalize_dual(data, actual_col)
self.split_datasets(data)
# duration grows over the year, so maybe normalize within the year
def fix_duration(self, col):
data=self.merge_datasets()
#dur_mean=t_v[col].mean()
#data[col].fillna(dur_mean, inplace=True)
#self.split_datasets(data)
#exit()
if True: #self.IMPUTE=='MEAN':
for k,t_v in data.groupby(self.NEW_YEAR):
t_v=t_v.copy()
dur_mean=t_v[col].mean()
t_v[col].fillna(dur_mean, inplace=True)
data.loc[t_v.index, col]=t_v[col]
#self.median_center_by_year(data, col)
self.rank_normalize_dual(data, col)
self.split_datasets(data)
# not sure what is identified sites, but it also grows over the year
def fix_identifiedsites(self, col):
data=self.merge_datasets()
#self.median_center_by_year(data, col)
self.rank_normalize_dual(data, col)
self.split_datasets(data)
def rank_normalize(self, df, col, inplace=True):
R=(df[col].values-df[col].mean())/(df[col].std()+self.EPS)
# simply normalized without converting to rank
df[col+"_norm"]=R
R=pd.core.algorithms.rank(df[col].values)
R/=np.sum(~ np.isnan(R))
if inplace:
df[col]=R
else:
df[col+"_rank_norm"]=R
if inplace:
df.rename2({col: col+"_rank_norm"})
def rank_normalize_by_year(self, df, col, inplace=True):
if not inplace:
df[col+"_rank_norm_by_year"]=df[col].copy()
for k,t_v in df.groupby(self.NEW_YEAR):
# take non np.nan values in col and convert them into ranking
R=(t_v[col].values-t_v[col].mean())/(t_v[col].std()+self.EPS)
# simply normalized without converting to rank
df.loc[t_v.index, col+"_norm_by_year"]=R
R=pd.core.algorithms.rank(t_v[col].values)
R/=np.sum(~ np.isnan(R))
R=ss.norm.ppf(np.clip(R, 0.02, 0.98))
if inplace:
df.loc[t_v.index, col]=R
else:
df.loc[t_v.index, col+"_rank_norm_by_year"]=R
if inplace:
df.rename2({col: col+"_rank_norm_by_year"})
def rank_normalize_dual(self, df, col, inplace=True):
self.rank_normalize_by_year(df, col, inplace=False)
#self.rank_normalize(df, col, inplace=inplace)
def filter_datasets(self):
if REMOVE_TRIVIAL_DRUGS:
self.train=self.train[~self.train['drugkey'].isin(TRIVIAL_DRUGS)].copy()
if REMOVE_TERMINATED:
self.train=self.train[self.train.hopeful>=0].copy()
def merge_datasets(self):
self.test[self.OUTCOME].fillna(0, inplace=True)
data=pd.concat([self.train, self.test], ignore_index=True, sort=True)
return data
def split_datasets(self, df):
self.train=df[df.TRAIN].copy()
self.train.index=range(len(self.train))
self.test=df[~df.TRAIN].copy()
self.test.index=range(len(self.test))
#self.test.drop(self.OUTCOME, axis=1, inplace=True)
def check_correlation(self):
types=self.train.col_types()
data=[]
for i,s in enumerate(self.feature_cols):
if types[i]!='s' and s not in ['TRAIN',self.OUTCOME,self.YEAR]:
tmp=self.train[self.train[s].notnull()]
r=np.corrcoef(tmp[[s, self.OUTCOME]].values, rowvar=0)
r=r[0,1]
data.append([s, r, abs(r)])
t=pd.DataFrame(data, columns=['Column','Corr','AbsCorr'])
t.sort_values('AbsCorr', ascending=False, inplace=True)
t.display()
def impute_model_validate(self, nan_cols):
data=self.merge_datasets()
col_feature=[x for x in self.COLUMNS if data.col_type(x)!='s' and x not in [self.OUTCOME,'TRAIN','phaseendyear','drugkey','indicationkey','intclinicaltrialid','row_id']]
KFOLD=5
seed=SEED
kf=StratifiedKFold(n_splits=KFOLD, shuffle=True, random_state=SEED)
out=[]
res=[]
for train_idx,validate_idx in kf.split(data, data[self.NEW_YEAR]):
train=data.iloc[train_idx]
validate=data.iloc[validate_idx]
for col in nan_cols:
clf = XGBRegressor(
objective='reg:linear',
random_state=seed,
seed=seed,
nthread=CORE,
max_depth=6,
learning_rate=0.05,
n_estimators=5000
)
#rf=RandomForestRegressor(n_estimators=200, max_depth=5, n_jobs=CORE, random_state=SEED)
X_cols=[x for x in col_feature if x!=col]
mask=~ train[col].isnull()
my_xtrain=train.loc[mask, X_cols].values
my_ytrain=train.loc[mask, col].values
mask=~ validate[col].isnull()
my_xvalidate=validate.loc[mask, X_cols].values
my_yvalidate=validate.loc[mask, col].values
clf.fit(
my_xtrain,
my_ytrain,
eval_metric='rmse',
eval_set=[(my_xvalidate, my_yvalidate)],
early_stopping_rounds=50
)
Yp_validate=clf.predict(my_xvalidate)
Yp_train=clf.predict(my_xtrain)
n_estimators=len(clf.get_booster().get_dump())
print(">>>Impute Train:", col, "R2:", r2_score(my_ytrain, Yp_train), 'r2(truth):', np.corrcoef(my_ytrain, Yp_train, rowvar=0)[0,1], "estimator:",n_estimators)
res.append({'Col':col,'R2':r2_score(my_ytrain, Yp_train), 'Corr':np.corrcoef(my_ytrain, Yp_train, rowvar=0)[0,1], 'n_estimators':n_estimators})
print(">>>Impute: Validate", col, "R2:", r2_score(my_yvalidate, Yp_validate), 'r2(truth):', np.corrcoef(my_yvalidate, Yp_validate, rowvar=0)[0,1], 'n_estimators',n_estimators)
res.append({'Col':col,'R2':r2_score(my_yvalidate, Yp_validate), 'Corr':np.corrcoef(my_yvalidate, Yp_validate, rowvar=0)[0,1], 'n_estimators':n_estimators})
t1=pd.DataFrame({'True':my_ytrain, 'Pred':Yp_train})
t1['IsTrain']=1
t1['Feature']=col
t2=pd.DataFrame({'True':my_yvalidate, 'Pred':Yp_validate})
t2['IsTrain']=0
t2['Feature']=col
k=int(len(out)/2)
t1['Fold']=k