-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_mol_class.py
1588 lines (1314 loc) · 67.1 KB
/
train_mol_class.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
from __future__ import print_function
import sys
import os
import random
import math
from collections import defaultdict, OrderedDict
from functools import cmp_to_key
import logging
import warnings
import json
import traceback
import datetime
import psutil
import copy
import errno
import numpy as np
from scipy.stats import pearsonr
from sklearn import preprocessing, svm, neighbors
import sklearn.metrics
from sklearn.metrics import precision_recall_curve, roc_auc_score, accuracy_score, average_precision_score, log_loss
from sklearn.metrics.scorer import make_scorer
from sklearn.base import BaseEstimator, TransformerMixin, ClassifierMixin, clone
from sklearn.utils import check_X_y, column_or_1d, check_consistent_length
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.naive_bayes import BernoulliNB, GaussianNB
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.dummy import DummyClassifier
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.externals import joblib
from sklearn.externals.joblib import Memory, Parallel, delayed
from sklearn.exceptions import DataConversionWarning
from sklearn.model_selection import StratifiedKFold, StratifiedShuffleSplit, GridSearchCV, RandomizedSearchCV
from rdkit import Chem
from rdkit.Chem import rdMolDescriptors, AllChem
from rdkit.Chem.Fingerprints import FingerprintMols
from rdkit.Chem.rdMolDescriptors import GetHashedAtomPairFingerprintAsBitVect, GetHashedTopologicalTorsionFingerprintAsBitVect
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def mkdir_p(path):
"""Make directory with parents"""
try:
os.makedirs(path)
return 0
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
return 1
else:
raise
def csv_list(init):
"""auxiliary function to parse comma-delimited command line arguments"""
field = init.split(',')
return [x.strip() for x in field if len(x)]
def mol_to_fp_fun(fp_type, nBits=2048):
"""instantiate fingerprinting function from string"""
if fp_type == 'ecfp4':
return lambda x: AllChem.GetMorganFingerprintAsBitVect(x, 2, nBits=nBits)
if fp_type == 'ecfp6':
return lambda x: AllChem.GetMorganFingerprintAsBitVect(x, 3, nBits=nBits)
if fp_type == 'ecfp12':
return lambda x: AllChem.GetMorganFingerprintAsBitVect(x, 6, nBits=nBits)
if fp_type == 'maccs':
if(nBits != 166):
logging.warning('maccs FP is of a fix size (166). Ignoring nBits=' + str(nBits))
return lambda x: Chem.MACCSkeys.GenMACCSKeys(x)
if fp_type == 'daylight' or fp_type == "path5":
return lambda x: FingerprintMols.FingerprintMol(x, minPath=1, maxPath=5, fpSize=nBits, bitsPerHash=2,
useHs=0, tgtDensity=0.0, minSize=nBits)
if fp_type == 'ap':
return lambda x: GetHashedAtomPairFingerprintAsBitVect(x, nBits=nBits)
if fp_type == 'torsion':
return lambda x: GetHashedTopologicalTorsionFingerprintAsBitVect(x, nBits=nBits)
else:
logging.error('unknown fingerprint type: ' + fp_type)
sys.exit(1)
warnings.filterwarnings("ignore", category=UserWarning, module="matplotlib")
warnings.filterwarnings(action='ignore', category=DataConversionWarning)
warnings.filterwarnings(action='ignore', category=DeprecationWarning)
#warnings.simplefilter("ignore", DeprecationWarning)
mpl_logger = logging.getLogger('matplotlib')
mpl_logger.setLevel(logging.WARNING)
def warn_with_traceback(message, category, filename, lineno, file=None, line=None):
log = file if hasattr(file, 'write') else sys.stderr
traceback.print_stack(file=log)
log.write(warnings.formatwarning(message, category, filename, lineno, line))
warnings.showwarning = warn_with_traceback
def exceptions_str():
return traceback.format_exception_only(
sys.exc_info()[0], sys.exc_info()[1])[0].strip()
# grid of possible hyperparameter settings for optimization
# note: order is significant for 2nd stage local optimization
PARAM_GRID = {
'rf': OrderedDict([
('class_weight', [None, 'balanced']),
('bootstrap', [False, True]),
('max_features', [None, 'sqrt', 'log2']),
('criterion', ['gini', 'entropy']),
('max_depth', [None, 10, 20, 50, 100]),
('min_samples_split', [2, 5, 10, 20, 50]),
('min_samples_leaf', [1, 5, 10, 20, 50]),
('n_estimators', [10, 50, 100, 200, 500]),
]),
'gbm': OrderedDict([
('max_depth', [3, 4, 5, 6, 8]),
('min_samples_split', [2, 5, 10, 20, 50]),
('min_samples_leaf', [1, 5, 10, 20]),
('max_features', [None, 'sqrt', 'log2']),
('criterion', ['mse', 'friedman_mse', 'mae']),
('subsample', [0.3, 0.5, 0.8, 1.0]),
('learning_rate', [0.001, 0.01, 0.05, 0.1, 0.2]),
('n_estimators', [10, 50, 100, 200, 500]),
]),
'xgb': OrderedDict([
('scale_pos_weight', [1, 5, 10, 20]),
('max_depth', [3, 4, 5, 6, 8, 12]),
('min_child_weight', [1, 2, 5, 10]),
('gamma', [0.0, 0.2, 0.5, 1.0]),
('max_delta_step', [0, 1, 5, 10]),
('subsample', [0.5, 0.8, 1.0]),
('colsample_bytree', [0.5, 0.8, 1.0]),
('reg_alpha', [0.0, 1e-4, 1e-3, 1e-2, 0.1, 1.0]),
('reg_lambda', [0.0, 1e-4, 1e-3, 1e-2, 0.1, 1.0]),
('learning_rate', [0.001, 0.01, 0.05, 0.1, 0.2]),
('n_estimators', [10, 50, 100, 200, 500]),
]),
'lr': OrderedDict([
('class_weight', [None, 'balanced']),
('penalty', ['l1', 'l2']),
('C', [0.0001, 0.001, 0.01, 0.1, 1, 10]),
('tol', [1e-5, 1e-4, 1e-3]),
#('max_iter', [200, 1000]),
]),
'svm_lin': OrderedDict([
('class_weight', [None, 'balanced']),
('penalty', ['l1', 'l2']),
('C', [0.0001, 0.001, 0.01, 0.1, 1, 10]),
('tol', [1e-5, 1e-4, 1e-3]),
# Unsupported set of arguments: The combination of penalty='l1' and loss='hinge' is not supported
# 'loss': ['hinge', 'squared_hinge']),
]),
'svm_poly': OrderedDict([
# note: with sigmoid kernel and coef0=10 (and greater), decision function values seemed to
# have offset between cross folds - weird!
('kernel', ['poly']),
('class_weight', [None, 'balanced']),
('degree', [2, 3, 4]),
('coef0', [0.0, 0.1, 1]),
('C', [0.0001, 0.001, 0.01, 0.1, 1, 10]),
('gamma', ['auto', 0.00001, 0.0001, 0.001, 0.01, 0.1, 1, 10]),
('shrinking', [False, True]),
('tol', [1e-4, 1e-3, 1e-2]),
]),
'svm_rbf': OrderedDict([
('kernel', ['rbf']),
('class_weight', [None, 'balanced']),
('C', [0.0001, 0.001, 0.01, 0.1, 1, 10]),
('gamma', ['auto', 0.00001, 0.0001, 0.001, 0.01, 0.1, 1, 10]),
('shrinking', [False, True]),
('tol', [1e-4, 1e-3, 1e-2]),
]),
'svm_sig': OrderedDict([
# note: with sigmoid kernel and coef0=10 (and greater), decision function values seemed to
# have offset between cross folds - weird!
('class_weight', [None, 'balanced']),
('kernel', ['sigmoid']),
('coef0', [0.0, 0.1, 0.5, 1]),
('C', [0.0001, 0.001, 0.01, 0.1, 1, 10]),
('gamma', ['auto', 0.00001, 0.0001, 0.001, 0.01, 0.1, 1, 10]),
('shrinking', [False, True]),
('tol', [1e-4, 1e-3, 1e-2]),
]),
'mlp': OrderedDict([
('alpha', [0.0001, 0.001, 0.01, 0.1, 1.0, 5.0]),
('learning_rate_init', [0.001, 0.01, 0.1]),
('learning_rate', ['constant', 'invscaling', 'adaptive']),
('activation', ['logistic', 'tanh', 'relu']),
('depth', [1, 2, 3]),
('width', ['sqrt', 'log2', 'full']),
('tol', [1e-5, 1e-4, 1e-3]),
]),
}
def get_param_combinations(d):
"""cardinality of cross-product of all options"""
sz = 1
for v in d.values():
sz *= len(v)
return sz
def cmp_mixed(x, y):
"""compare function to sort mixed numeric/string values"""
try:
xf = float(x)
yf = float(y)
return xf - yf
except:
xs = str(x)
ys = str(y)
if xs < ys:
return -1
if xs > ys:
return 1
return 0
# note: did not get matplotlib cycler to work as desired
class PlotCycler(object):
def __init__(self, what='color'):
if what == 'color':
self.cycle = ['r', 'g', 'b', 'm', 'c', 'y', 'k', 'w']
else:
self.cycle = ['-', '--', '-.', ':', ':']
self.pos = 0
def next(self):
pos_last = self.pos
self.pos = (self.pos + 1) % len(self.cycle)
return self.cycle[pos_last]
def core_basename(x):
"""strip off directories and all extensions from filename"""
x = os.path.split(x)[1]
ext = [x, 'dummy']
while len(ext[1]) > 1:
ext = os.path.splitext(ext[0])
return ext[0]
def df_to_csv_append(df, csv_file_path, sep="\t", header=True, overwrite=False, **kwargs):
"""append pandas DataFrame to file"""
if overwrite or not os.path.isfile(csv_file_path):
df.to_csv(csv_file_path, index=False, sep=sep, header=True, **kwargs)
return
df_file = pd.read_csv(csv_file_path, nrows=1, sep=sep)
if len(df.columns) != len(df_file.columns):
raise ValueError("Columns do not match!! Dataframe has " + str(len(df.columns)) +
" columns. CSV file " + csv_file_path + " has " + str(len(df_file.columns)) + " columns.")
elif not (df.columns == df_file.columns).all():
raise Exception("Columns and column order of dataframe and csv file do not match!!")
else:
df.to_csv(csv_file_path, mode='a', index=False, sep=sep, header=False, **kwargs)
class Fingerprinter(BaseEstimator, TransformerMixin):
"""transform a smiles string into one of several possible fingerprint types"""
FP_TYPES = ['ecfp4', 'ecfp6', 'ecfp12', 'maccs', 'daylight', 'ap', 'torsion', 'prop']
def __init__(self, fp_type='ecfp4', fp_size=2048):
if fp_type not in Fingerprinter.FP_TYPES:
raise ValueError('no such fingerprint type: %s' % fp_type)
self.fp_type = fp_type
self.fp_size = fp_size
# avoid warnings from aw_common
if fp_type == 'maccs':
self.fp_size = 166
self.features = None
def get_feature_names(self):
if self.features is None:
raise ValueError('Fingerprinter: need to call fit() before getting feature names')
return self.features
# fit() doesn't do anything, this is a transformer class
def fit(self, X, y=None):
return self
def transform(self, X):
X = np.array(X)
logging.debug('generating %d %s fingerprints' % (len(X), self.fp_type))
# if logging.getLogger().getEffectiveLevel() <= 10:
# for line in traceback.format_stack():
# logging.debug(line.strip())
if self.fp_type == 'prop':
properties = rdMolDescriptors.Properties()
get_fp = properties.ComputeProperties
else:
get_fp = mol_to_fp_fun(self.fp_type, self.fp_size)
fp = []
smiles_used = []
for i in range(len(X)):
try:
mol = Chem.MolFromSmiles(X[i], sanitize=True)
fp.append(list(get_fp(mol)))
smiles_used.append(X[i])
except:
logging.error('For smile: "%s":' % X[i])
logging.error(exceptions_str())
raise
# pass
if self.fp_type == 'prop':
self.features = list(properties.GetPropertyNames())
else:
self.features = [self.fp_type + '_' + str(i) for i in range(len(fp[0]))]
df = pd.DataFrame(fp, columns=self.features)
logging.debug('done fingerprinting %s' % self.fp_type)
return df
def clone_pipeline(pipe_in):
"""clone an sklearn Pipeline object"""
return Pipeline(memory=pipe_in.memory,
steps=[(name, clone(est)) for name, est in pipe_in.steps])
def create_fp(fp_type, fp_size, mem):
"""create a single fingerprint transformer.
- include scaling for molecular properties
"""
if fp_type != 'prop':
return Fingerprinter(fp_type, fp_size)
else:
pipe = Pipeline(memory=mem,
steps=[(fp_type, Fingerprinter(fp_type, fp_size))])
# molecular descriptors can have very different ranges - normalize!
pipe.steps.append(('scale', preprocessing.StandardScaler(copy=True, with_mean=True, with_std=True)))
return pipe
def create_fp_pipe(fp_type, fp_size, mem):
"""instantiate a feature pipeline from string"""
fps = fp_type.split('~')
if len(fps) == 1:
pipe = Pipeline(memory=mem,
steps=[(fp_type, Fingerprinter(fp_type, fp_size))])
if fp_type == 'prop':
# molecular descriptors can have very different ranges - normalize!
pipe.steps.append(('features', preprocessing.StandardScaler(copy=True, with_mean=True, with_std=True)))
else:
combined_features = FeatureUnion([(fp, create_fp(fp, fp_size, mem)) for fp in fps], n_jobs=1)
pipe = Pipeline(memory=mem, steps=[('features', combined_features)])
return pipe, ('prop' not in fps)
def get_feature_names(pipe, pos=-1):
"""
workaround: sklearn Pipeline, StandardScaler classes have not get_feature_names() method :-( ANNOYING
"""
if not isinstance(pipe, (FeatureUnion, Pipeline)) and hasattr(pipe, 'get_feature_names'):
return pipe.get_feature_names()
el = pipe.steps[pos][1]
if isinstance(el, preprocessing.StandardScaler):
return get_feature_names(pipe, pos - 1)
if isinstance(el, FeatureUnion):
features = []
for (name, est, weight) in el._iter():
features.extend(get_feature_names(est))
return features
return get_feature_names(el)
def prepare_pipeline_for_scoring(pipe):
"""
Recursively set all memory in pipe to None; if possible, parallelize classifiers and FeatureUnion
"""
if hasattr(pipe, 'n_jobs'):
pipe.n_jobs = -1
if hasattr(pipe, 'nthread'):
pipe.nthread = -1
if isinstance(pipe, ThresholdTuner):
prepare_pipeline_for_scoring(pipe.classifier)
if isinstance(pipe, Pipeline):
pipe.memory = None
for s in pipe.steps:
prepare_pipeline_for_scoring(s[1])
if isinstance(pipe, FeatureUnion):
for (name, est, weight) in pipe._iter():
prepare_pipeline_for_scoring(est)
class LabelStratificationEncoder(BaseEstimator, TransformerMixin):
"""
encode a target label and an additional stratification column into a fake 'multiclass' target.
Auxiliary class to help with stratification when using sklearn CV classes.
"""
def __init__(self):
self.le = None
def fit(self, strat=None):
if strat is not None and len(strat) > 1:
self.le = preprocessing.LabelEncoder()
self.le.fit(strat)
logging.debug('LabelStratificationEncoder classes: %s, %s' % (self.le.classes_, np.bincount(strat)))
return self
def transform(self, y, strat=None):
if self.le is None or strat is None:
return y
w_trans = self.le.transform(strat)
# use lowest bit for target; assumption: y in [0,1]
res = y + 2 * w_trans
if logging.getLogger().getEffectiveLevel() <= 10:
dist = np.bincount(res).astype(float)
dist /= np.sum(dist)
logging.debug('LabelStratificationEncoder distribution %s' % dist)
return res
def fit_transform(self, y, strat):
self.fit(strat)
return self.transform(y, strat)
def inverse_transform(self, y):
y_trans = np.mod(y, 2)
strat = None
if self.le is not None:
strat = self.le.inverse_transform(y // 2)
return y_trans, strat
class ThresholdTuner(BaseEstimator, ClassifierMixin):
"""wrapper for a classifier to additionally estimate a prediction threshold on held out validation set."""
def __init__(self, classifier, thresh=None, valid_frac=0.0, max_false_positive_rate=.2, random_state=None, stratifier=None):
"""
max_false_positive_rate - adjust threshold so as to have (at most) that many false positives.
"""
self.classifier = classifier
self.thresh = thresh
self.valid_frac = valid_frac
self.max_false_positive_rate = max_false_positive_rate
self.random_state = random_state
self.stratifier = stratifier
if stratifier is not None and not isinstance(stratifier, LabelStratificationEncoder):
raise ValueError('stratifier must be an instance of class LabelStratificationEncoder')
def fit(self, X, y, sample_weight=None, test_filter=None):
"""
Fit the embedded classifier, then estimate a threshold to attain max_false_positive_rate
test_filter: subset index to compute threshold on
"""
X, y = check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'], y_numeric=True, multi_output=False)
w_train = None
w_valid = None
if sample_weight is not None:
sample_weight = column_or_1d(sample_weight)
check_consistent_length(sample_weight, y)
if test_filter is not None:
test_filter = column_or_1d(test_filter)
check_consistent_length(test_filter, y)
# split train set further for validation holdout
if self.valid_frac > 0.0:
cv = StratifiedShuffleSplit(test_size=self.valid_frac, random_state=self.random_state)
for train_idx, valid_idx in cv.split(X, y):
break
X_train = X[train_idx]
y_train = y[train_idx]
X_valid = X[valid_idx][test_filter[valid_idx]]
y_valid = y[valid_idx][test_filter[valid_idx]]
if sample_weight is not None:
w_train = sample_weight[train_idx]
w_valid = sample_weight[valid_idx][test_filter[valid_idx]]
else:
# validate on train
X_train = X
y_train = y
w_train = sample_weight
X_valid = X
y_valid = y
w_valid = sample_weight
if logging.getLogger().getEffectiveLevel() <= 10:
dist_train = np.bincount(y_train).astype(float)
dist_train /= np.sum(dist_train)
dist_valid = np.bincount(y_valid).astype(float)
dist_valid /= np.sum(dist_valid)
logging.debug('distribution train %s - valid %s' % (dist_train, dist_valid))
strat_train = None
strat_valid = None
if self.stratifier is not None:
y_train, strat_train = self.stratifier.inverse_transform(y_train)
y_valid, strat_valid = self.stratifier.inverse_transform(y_valid)
if w_train is not None:
self.classifier.fit(X_train, y_train, w_train)
else:
self.classifier.fit(X_train, y_train)
if self.max_false_positive_rate is not None:
score = score_classifier(self.classifier, X_valid)
fpr, tpr, thresholds = sklearn.metrics.roc_curve(y_valid, score, sample_weight=w_valid)
# note: fpr is increasing
# round for few positives
#pos = np.count_nonzero(y_valid)
assert(fpr[0] <= fpr[-1])
#fpr_target = math.floor(self.max_false_positive_rate * pos)/(1.0 * pos)
self.thresh = np.interp(self.max_false_positive_rate, fpr, thresholds)
return self
def predict_proba(self, X):
return score_classifier(self.classifier, X)
def predict(self, X):
"""compute the score of the embedded classifier, then apply tuned threshold"""
score = score_classifier(self.classifier, X)
return (score > self.thresh).astype(int)
class MLPClassifierWrapper(MLPClassifier):
"""
Wrapper for MLPClassifier.
Purpose: ability to specify width of hidden layers with keywords instead of fixed numbers
"""
def __init__(self, width='sqrt', depth=1,
activation="tanh", # changed!
solver='adam', alpha=0.1,
batch_size='auto', learning_rate="constant",
learning_rate_init=0.01, power_t=0.5, max_iter=10000,
shuffle=True, random_state=None, tol=1e-3,
verbose=False, warm_start=False, momentum=0.9,
nesterovs_momentum=True, early_stopping=False,
validation_fraction=0.1, beta_1=0.9, beta_2=0.999,
epsilon=1e-8):
self.width = width
self.depth = depth
sup = super(MLPClassifier, self)
sup.__init__(hidden_layer_sizes=(100,), activation=activation,
solver=solver, alpha=alpha,
batch_size=batch_size, learning_rate=learning_rate,
learning_rate_init=learning_rate_init, power_t=power_t, max_iter=max_iter, loss='log_loss',
shuffle=shuffle, random_state=random_state, tol=tol,
verbose=verbose, warm_start=warm_start, momentum=momentum,
nesterovs_momentum=nesterovs_momentum, early_stopping=early_stopping,
validation_fraction=validation_fraction, beta_1=beta_1, beta_2=beta_2,
epsilon=epsilon)
def fit(self, X, y, sample_weight=None):
if self.width not in ['sqrt', 'log2', 'full']:
raise ValueError('invalid layer width: %s' % self.width)
n = X.shape[1]
if self.width == 'sqrt':
n = int(math.ceil(math.sqrt(n)))
else:
n = int(math.ceil(math.log2(n)))
self.hidden_layer_sizes = (n) * self.depth
super(MLPClassifier, self).fit(X, y)
# properties of sklearn classifiers
def classifier_has_random_state(method):
return not(method.startswith('knn') or method in ('dummy', 'nb', 'qda'))
def classifier_has_cache_size(method):
return method in ('svm_rbf', 'svm_poly', 'svm_sig')
def classifier_allows_weights(method):
return not(method.startswith('knn') or method in ('qda', 'mlp'))
def get_classifier(method, hyper_param_file=None, binary_features=True, **kwargs):
"""
instantiate an sklearn classifier according to string.
read hyper parameters from hyper_parm_file, if given.
"""
classifier = None
if ((not classifier_has_random_state(method)) or
# workaround: xgb does not allow seed=None
(method == 'xgb' and 'random_state' in kwargs and kwargs['random_state'] is None)):
try:
kwargs.pop('random_state')
except:
pass
if not classifier_has_cache_size(method):
try:
kwargs.pop('cache_size')
except:
pass
if method[:3] == 'knn':
k = int(method[3:])
if binary_features:
metric = 'jaccard'
else:
metric = 'minkowski'
classifier = neighbors.KNeighborsClassifier(k, metric=metric, weights='distance', **kwargs)
elif method == 'lr':
classifier = LogisticRegression(max_iter=200, class_weight='balanced', **kwargs)
elif method == 'rf':
classifier = RandomForestClassifier(n_estimators=200, class_weight='balanced', **kwargs)
elif method == 'gbm':
classifier = GradientBoostingClassifier(n_estimators=200, learning_rate=0.05, **kwargs)
elif method == 'svm_lin':
classifier = svm.LinearSVC(max_iter=10000, dual=False, **kwargs)
elif method == 'svm_poly':
# note: probability computation for svm is expensive and not needed
classifier = svm.SVC(probability=False, kernel='poly', **kwargs)
elif method == 'svm_rbf':
classifier = svm.SVC(probability=False, kernel='rbf', **kwargs)
elif method == 'svm_sig':
classifier = svm.SVC(probability=False, kernel='sigmoid', **kwargs)
elif method == 'ada':
classifier = AdaBoostClassifier(n_estimators=500, **kwargs)
elif method == 'gp':
classifier = GaussianProcessClassifier(**kwargs)
elif method == 'mlp':
classifier = MLPClassifierWrapper(**kwargs)
elif method == 'nb':
if binary_features:
classifier = BernoulliNB(**kwargs)
else:
classifier = GaussianNB(**kwargs)
elif method == 'qda':
classifier = QuadraticDiscriminantAnalysis(**kwargs)
elif method == 'xgb':
from xgboost import XGBClassifier
classifier = XGBClassifier(n_jobs=-1, nthread=-1, **kwargs)
elif method == 'dummy':
classifier = DummyClassifier(strategy='uniform')
else:
raise ValueError('unknown classifier: ' + str(method))
if hyper_param_file is not None:
if not os.path.exists(hyper_param_file):
raise ValueError('requested hyperparameters file not found: %s' % hyper_param_file)
logging.info('reading hyperparameters from file: %s' % hyper_param_file)
hyper_params = json.load(open(hyper_param_file, 'r'))
if 'comment' in hyper_params:
hyper_params.pop('comment')
logging.info(hyper_params)
# remove possible pipeline prefix
hyper_params = dict([(k.split('__')[-1], v) for k, v in hyper_params.items()])
classifier.set_params(**hyper_params)
return classifier
def plot_folds(label_score_weight, dir_out='images', tag='test', plot_type='pr', chosen_thresh=0.0):
"""plot precision-recall or roc curves from multiple cross validation folds"""
# plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b', 'm', 'c', 'y', 'k', 'w'])))
cyc_line = PlotCycler('line')
if plot_type == 'thresh':
plt.title("chosen threshold: %.3f" % chosen_thresh)
first = True
for label, score, weight in label_score_weight:
fpr, tpr, thresholds = sklearn.metrics.roc_curve(label, score, sample_weight=weight)
label_t = None
label_f = None
if first:
label_t = "tpr"
label_f = "fpr"
first = False
l = cyc_line.next()
plt.plot(thresholds, tpr, "b--", label=label_t, linestyle=l)
plt.plot(thresholds, fpr, "g-", label=label_f, linestyle=l)
if chosen_thresh is not None:
plt.plot((chosen_thresh, chosen_thresh), (0.0, 1.0), 'k-')
plt.ylabel("score")
plt.xlabel("decision threshold")
plt.legend(loc='best')
plt.grid(True)
plt.savefig(os.path.join(dir_out, plot_type + '_' + tag + '.png'))
plt.close()
return
elif plot_type == 'violin':
score_max = -1
score_min = 1e10
for ls in label_score_weight:
score_max = max(score_max, max(ls[1]))
score_min = min(score_min, min(ls[1]))
fig, ax = plt.subplots(1, len(label_score_weight))
fold = -1
for label, score, weight in label_score_weight:
fold += 1
ax[fold].violinplot([score[~label], score[label]], showmedians=True)
ax[fold].grid(axis='both')
pearson = pearsonr(label, score)[0]
ax[fold].set_title('%.3f' % pearson)
ax[fold].set_ylim([score_min, score_max])
plt.suptitle('score distributions for %s, pearson =' % tag, fontsize=15)
plt.savefig(os.path.join(dir_out, plot_type + '_' + tag + '.png'))
plt.close()
return
elif plot_type == 'pr':
analyze_func = precision_recall_curve
agg_func = sklearn.metrics.average_precision_score
agg_name = 'ap'
plt.xlabel('recall')
plt.ylabel('precision')
title_prefix = 'precision-recall'
plt.ylim([0.0, 1.05])
plt.xlim([0.0, 1.0])
elif plot_type == 'roc':
def analyze_func(y, x, sample_weight):
fpr, tpr, thresholds = sklearn.metrics.roc_curve(y, x, sample_weight=sample_weight)
return tpr, fpr, thresholds
agg_func = sklearn.metrics.roc_auc_score
agg_name = 'area'
plt.xlabel('false positive rate')
plt.ylabel('true positive rate')
title_prefix = 'roc'
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
else:
raise ValueError('unknown plot type: ' + plot_type)
aps = []
for label, score, weight in label_score_weight:
y, x, thresholds = analyze_func(label, score, sample_weight=weight)
aps.append(agg_func(label, score, sample_weight=weight))
# sort and dedupe points!
xys = [xy for xy in sorted(zip(x, y))]
xys_new = []
for i in range(len(xys) - 1):
if xys[i][0] != xys[i + 1][0]:
xys_new.append(xys[i])
xys_new.append(xys[-1])
xys = xys_new
x = [xy[0] for xy in xys]
y = [xy[1] for xy in xys]
plt.step(x, y, alpha=0.5, color='k', linestyle=cyc_line.next(), where='post')
plt.fill_between(x, y, step='post', alpha=0.1, color='b')
plt.title('%s curves for %s: %s=%.3f' % (title_prefix, tag, agg_name, np.mean(aps)))
plt.grid(True)
plt.ylim([0.0, 1.05])
plt.xlim([0.0, 1.0])
plt.savefig(os.path.join(dir_out, plot_type + '_' + tag + '.png'))
plt.close()
def score_classifier(classifier, X):
"""apply a classifier"""
if hasattr(classifier, 'predict_proba'):
score = classifier.predict_proba(X)[:, 1]
else:
# probability computation for svm is expensive and not needed
score = classifier.decision_function(X)
# important for evaluation metrics: add some random noise to break possible ties!
score += 1e-10 * (random.random() - 0.5)
return score
def enrichment(labels, score, at=0.1):
"""early enrichment metric"""
score, labels = zip(*sorted(zip(score, labels)))
score = [x for x in reversed(score)]
labels = [x for x in reversed(labels)]
avg = np.average(labels)
if avg == 0.0:
return float('NaN')
head = min(max(1, int(round(at * len(labels)))), len(labels) - 2)
return np.average(labels[:head]) / avg
def tpr_at_fpr(labels, score, at=0.2, **kwargs):
"""recall when tolerating a set level of false positives"""
fpr, tpr, thresholds = sklearn.metrics.roc_curve(labels, score, **kwargs)
return np.interp(at, fpr, tpr, left=0.0, right=1.0)
def fpr_tpr_at_thresh(labels, score, thresh, sample_weight=None):
"""false and true positive rates at given threshold"""
fpr, tpr, thresholds = sklearn.metrics.roc_curve(labels, score, sample_weight=sample_weight)
# note: thresholds are decreasing!
thresholds = list(reversed(thresholds))
fpr = list(reversed(fpr))
tpr = list(reversed(tpr))
assert(thresholds[0] <= thresholds[-1])
fpr_at_thresh = np.interp(thresh, thresholds, fpr, left=1.0, right=0.0)
tpr_at_thresh = np.interp(thresh, thresholds, tpr, left=1.0, right=0.0)
return fpr_at_thresh, tpr_at_thresh
def wrap_score(y_true, y_pred, sample_weight=None, func=None, **kwargs):
"""auxiliary closure to pass on sample weights to scoring metric"""
if sample_weight is not None:
sample_weight = sample_weight.iloc[y_true.index.values].values.reshape(-1)
check_consistent_length(sample_weight, y_true)
return func(y_true, y_pred, sample_weight=sample_weight, **kwargs)
def eval_score(y, score, sample_weight=None, thresh=None, rec=None):
"""calculate several evaluation metrics for predictions; store results in rec dictionary."""
if rec is None:
rec = {}
if 'auc' not in rec:
rec['auc'] = []
rec['pr'] = []
rec['pearson'] = []
rec['fpr'] = []
rec['tpr'] = []
rec['thresh'] = []
auc = sklearn.metrics.roc_auc_score(y, score, sample_weight=sample_weight)
rec['auc'].append(auc)
average_precision = sklearn.metrics.average_precision_score(y, score, sample_weight=sample_weight)
rec['pr'].append(average_precision)
# TODO: sample weight?
pearson = pearsonr(y, score)[0]
rec['pearson'].append(pearson)
if thresh is not None:
fpr_at_thresh, tpr_at_thresh = fpr_tpr_at_thresh(y, score, thresh, sample_weight=sample_weight)
else:
fpr_at_thresh = None
tpr_at_thresh = None
rec['fpr'].append(fpr_at_thresh)
rec['tpr'].append(tpr_at_thresh)
rec['thresh'].append(thresh)
fpr, tpr, thresholds = sklearn.metrics.roc_curve(y, score, sample_weight=sample_weight)
return fpr, tpr, thresholds
def plot_optim_results(df, random_grid, method, dir='.', tag='', include_train=False):
"""plot results data frame generated by RandomizedSearchCV"""
df = df.copy()
random_grid = random_grid.copy()
# note: values are actually objects, not numeric - see RandomizedSearchCV documentation
# for comparability, convert all types to string
# many value ranges are logarithmic, not much loss in uniform x-spacing
pref = 'param_'
for k, v in random_grid.items():
random_grid[k] = [str(x) for x in v]
#df[pref + k] = df[pref + k].astype(str)
df[pref + k] = [str(x) if str(x) != 'nan' else 'None' for x in df[pref + k]]
plot_names = [k for k in random_grid.keys() if pref + k in df.columns]
# cross plots - these parameters are highly correlated
cross_plot = None
cross_name = None
if method in ('gbm', 'xgb'):
cross_plot = ['clf__n_estimators', 'clf__learning_rate']
if method in ('svm_rbf', 'svm_poly', 'svm_sig'):
cross_plot = ['clf__C', 'clf__gamma']
if cross_plot is not None:
cross_name = cross_plot[0] + '_' + cross_plot[1]
df[pref + cross_name] = ['(%s,%s)' % (l, n) for l, n in zip(df[pref + cross_plot[0]], df[pref + cross_plot[1]])]
plot_names.append(cross_name)
for c in ['mean_train_score', 'mean_test_score']:
df[c] = df[c].astype(float)
if np.isnan(df[c]).any():
logging.warning('%s contains NaNs!' % c)
df[c].fillna(0.0, inplace=True)
for p in plot_names:
c = pref + p
# sort parameters in the same way as in the grid
if p != cross_name:
sort_cols = [p]
else:
sort_cols = cross_plot
for sort_col in sort_cols:
u = np.unique(list(df[pref + sort_col]))
u = sorted(u, key=cmp_to_key(cmp_mixed))
df['order'] = [u.index(x) for x in df[pref + sort_col]]
df.sort_values('order', inplace=True, kind='mergesort') # note: must be stable sort
u, i, x = np.unique(df[c], return_index=True, return_inverse=True)
if include_train:
x_jitter = [xx + 0.1 * (random.random() - 0.5) for xx in x]
y_jitter = [yy + 0.01 * (random.random() - 0.5) for yy in df['mean_train_score']]
plt.plot(x_jitter, y_jitter, "b.", label="train")
x_jitter = [xx + 0.25 * (random.random() - 0.5) for xx in x]
y_jitter = [yy + 0.01 * (random.random() - 0.5) for yy in df['mean_test_score']]
plt.plot(x_jitter, y_jitter, "r.", label="test")
if p == cross_name:
# accomodate long tick labels!
plt.xticks(range(len(u)), u[np.argsort(i)], rotation=90)
plt.gcf().subplots_adjust(bottom=0.2)
else:
plt.xticks(range(len(u)), u[np.argsort(i)])
# mean line
if include_train:
med = df.fillna(-1).groupby(c)[['mean_train_score']].mean()
plt.plot(range(len(med.index)), med, "b:")
med = df.fillna(-1).groupby(c)[['mean_test_score']].mean()
plt.plot(range(len(med.index)), med, "r:")
plt.margins(x=0.5)
plt.grid(True)
plt.title(p)
plt.legend(loc='best')
plt.savefig(os.path.join(dir, 'optim_%s_%s.png' % (tag, p)))
plt.close()
def _fit_and_score(pipe, X, y, y_enc, sample_weight, test_filter, train_idx, test_idx):
"""auxiliary inner loop function to pass to Parallel"""
X_train = X.iloc[train_idx]
y_train_enc = y_enc.iloc[train_idx]
f_train = test_filter[train_idx]
X_test = X.iloc[test_idx][test_filter[test_idx]]
y_test = y.iloc[test_idx][test_filter[test_idx]]
if sample_weight is not None:
w_train = sample_weight.iloc[train_idx]
w_test = sample_weight.iloc[test_idx][test_filter[test_idx]]
else:
w_train = None
w_test = None
pipe.fit(X_train, y_train_enc, clf__sample_weight=w_train, clf__test_filter=f_train)
score = pipe.predict_proba(X_test)
rec = {}
eval_score(y_test, score, w_test, pipe.named_steps['clf'].thresh, rec)
return y_test, score, w_test, rec
def optimize_subset_params(estimator, X, y, fit_params, scoring, param_grid, param_subset, cv, n_iter, random_state, verbose, n_jobs):
"""single pass of hyper-parameter optimization.
if n_iter is less than 70% of possible parameter space, RandomizedSearchCV is used, else GridSearchCV.
all params not listed in param_subset are kept fixed.
returns best parameters, score, dataframe with all results, and type of search.
"""
if param_subset is None:
subset_grid = param_grid