/
eval.py
2255 lines (1711 loc) · 76.1 KB
/
eval.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
import pandas as pd
import numpy as np
from sklearn.base import clone
import time
import warnings
from ..dataset.helpers import verbose_print
from ..pipeline.helpers import get_mean_fis
from sklearn.utils import Bunch
from scipy.stats import t
from pandas.util._decorators import doc
from .stats_helpers import corrected_std, compute_corrected_ttest
from sklearn.metrics._scorer import (_PredictScorer, _ProbaScorer,
_ThresholdScorer)
from .helpers import clean_str
from copy import deepcopy
import pickle as pkl
from numpy.random import default_rng
import seaborn as sns
import matplotlib.pyplot as plt
from ..util import _refresh_bar, get_progress_bar
from sklearn.metrics._scorer import _MultimetricScorer
_base_docs = {}
_base_docs['dataset'] = """dataset : :class:`Dataset`
The instance of :class:`Dataset` originally passed to
:func:`evaluate`.
.. note::
If a different dataset is passed, then unexpected
behavior may occur.
"""
def score_rep(score):
# If big int
if len(repr(int(score))) > 5:
return f'{score:.1f}'
# Smaller
if score > 1 or score < -1:
return f'{score:.2f}'
# Last case is between 1 and -1
return f'{score:.4f}'
# @TODO
# 1. Store permutation FI's in object after call
# 2. Add methods for plot feature importance's ?
# TODO - function to easily export saved results in different formats.
def get_non_nan_Xy(X, y):
# Check for if any missing targets in the test set to skip
if pd.isnull(y).any():
non_nan_subjs = y[~pd.isnull(y)].index
X, y = X.loc[non_nan_subjs], y.loc[non_nan_subjs]
return X, y
def fi_to_series(fi, feat_names):
try:
fi = fi.squeeze()
except AttributeError:
pass
# Base flat case
if len(fi.shape) == 1:
return pd.Series(fi, index=feat_names)
# Categorical case
# @TODO is there a better way to have this?
# e.g., maybe explicitly by class value, see self.estimators[0].classes_
# could put it as another index level.
series = []
for class_fi in fi:
series.append(pd.Series(class_fi, index=feat_names))
return series
def fis_to_df(fis):
# Base case - assume that first element is representative
if isinstance(fis[0], pd.Series):
return pd.DataFrame(fis)
# Categorical case
dfs = []
for c in range(len(fis[0])):
dfs.append(pd.DataFrame([fi[c] for fi in fis]))
return dfs
def mean_no_zeros(df):
mean = df.mean()
return mean[mean != 0]
class EvalResults():
'''This class is returned from calls to :func:`evaluate`,
and can be used to store information from evaluate, or
compute additional feature importances. It should typically not be
initialized by the user.'''
# Add verbose print
_print = verbose_print
def __init__(self, estimator, ps,
encoders=None,
progress_bar=True,
store_preds=False,
store_estimators=False,
store_timing=False,
store_cv=True,
store_data_ref=True,
eval_verbose=0,
progress_loc=None,
mute_warnings=False,
compare_bars=None):
# Save base
self.estimator = estimator
self.ps = ps
self.encoders_ = encoders
# Set if using progress bar
self._set_progress_bar(progress_bar)
# If store preds
self.preds = None
if store_preds:
self.preds = {}
# If store estimator
self.estimators = None
if store_estimators:
self.estimators = []
# If store timing
self.timing = None
if store_timing:
self.timing = {'fit': [], 'score': []}
# Keep track of if to store cv
self._store_cv = store_cv
if not self._store_cv:
self.cv = None
# If store reference to data
self._store_data_ref = store_data_ref
if not self._store_data_ref:
self._dataset = None
self.progress_loc = progress_loc
self.verbose = eval_verbose
self.mute_warnings = mute_warnings
self.compare_bars = compare_bars
@property
def estimator(self):
'''This parameter stores the passed saved, unfitted estimator
used in this evaluation. This is a sklearn style estimator obtained
from :func:`get_estimator`.'''
return self._estimator
@estimator.setter
def estimator(self, estimator):
self._estimator = estimator
@property
def mean_scores(self):
'''This parameter stores the mean scores as
a dictionary of values, where each dictionary
is indexed by the name of the scorer, and the dictionary value
is the mean score for that scorer.'''
return self._mean_scores
@mean_scores.setter
def mean_scores(self, mean_scores):
self._mean_scores = mean_scores
@property
def std_scores(self):
'''This parameter stores the standard deviation scores as
a dictionary of values, where each dictionary
is indexed by the name of the scorer, and value
contains the standard deviation across evaluation folds
for that scorer.
The default scorer key stores the micro standard
deviation, but in the case that macro standard deviation differs,
i.e., in the case of multiple repeats in an evaluation, then
a separate macro standard deviation will be stored under
the name of the scorer with _macro appended to the key.
For example if a 3-fold twice repeated evaluation was
run, with just r2 as the scorer, this parameter might
look something like:
::
self.std_scores = {'r2': .5, 'r2_macro': .01}
'''
return self._std_scores
@std_scores.setter
def std_scores(self, std_scores):
self._std_scores = std_scores
@property
def weighted_mean_scores(self):
'''This property stores the mean scores
across evaluation folds (simmilar to
:data:`mean_scores<EvalResults.mean_scores>`),
but weighted by the
number of subjects / datapoints in each fold.
It is scores as a dictionary indexed by the name
of the scorer as the key, where values are
the weighted mean score.
'''
return self._weighted_mean_scores
@weighted_mean_scores.setter
def weighted_mean_scores(self, weighted_mean_scores):
self._weighted_mean_scores = weighted_mean_scores
@property
def scores(self):
'''This property stores the scores for
each scorer as a dictionary of lists, where
the keys are the names of the scorer and the list
represents the score obtained for each fold, where each
index corresponds to to a fold of cross validation.'''
return self._scores
@scores.setter
def scores(self, scores):
self._scores = scores
@property
def score(self):
'''This property represents
a quick helper for accessing the mean scores
of whatever the first scorer is (in the case of
multiple scorers).
'''
first_scorer = list(self.scores)[0]
if len(self.scores[first_scorer]) == 0:
return None
return np.mean(self.scores[first_scorer])
@property
def ps(self):
'''A saved and pre-processed version of the problem_spec
used (with any extra_params applied) when running this
instance of Evaluator.'''
return self._ps
@ps.setter
def ps(self, ps):
self._ps = ps
@property
def feat_names(self):
'''The features names corresponding to any measures of
feature importance, stored as a list of lists, where the top
level list represents each fold of cross validation.
This parameter may be especially useful when pipeline
objects such as transformers or feature selectors are used
as these can drastically change the features passed to an
eventual model.
The values stored here may change
based on the passed
value of the `decode_feat_names` parameter from
:func:`evaluate`.
For example the feat_names from a 3-fold cross-validation
with input features ['feat1', 'feat2', 'feat3'] with
feature selection as a piece of the pipeline may look like:
::
self.feat_names = [['feat1', 'feat2'],
['feat2', 'feat3'],
['feat1', 'feat2']]
'''
return self._feat_names
@feat_names.setter
def feat_names(self, feat_names):
self._feat_names = feat_names
@property
def val_subjects(self):
'''| This parameter stores the validation subjects / index
used in every fold of the cross-validation. It can be
useful in some cases
to check to see exactly what cross-validation was applied.
| This parameter
differs from
:data:`all_val_subjects<EvalResults.all_val_subjects>`
in that even subjects with missing target values are not included.
'''
return self._val_subjects
@val_subjects.setter
def val_subjects(self, val_subjects):
self._val_subjects = val_subjects
@property
def train_subjects(self):
'''| This parameter stores the training subjects / index
used in every fold of the cross-validation. It can be
useful in some cases to check to see exactly what
cross-validation was applied.
| This parameter
differs from
:data:`all_train_subjects<EvalResults.all_train_subjects>`
in that even subjects with missing target values are not included.
'''
return self._train_subjects
@train_subjects.setter
def train_subjects(self, train_subjects):
self._train_subjects = train_subjects
@property
def all_val_subjects(self):
'''| This parameter stores the validation subjects / index
used in every fold of the cross-validation.
| This parameter
differs from :data:`val_subjects<EvalResults.val_subjects>`
in that even subjects with missing target values are included.
'''
return self._all_val_subjects
@all_val_subjects.setter
def all_val_subjects(self, all_val_subjects):
self._all_val_subjects = all_val_subjects
@property
def all_train_subjects(self):
'''| This parameter stores the training subjects / index
used in every fold of the cross-validation.
| This parameter
differs from :data:`train_subjects<EvalResults.train_subjects>`
in that even subjects with missing target values are included.
'''
return self._all_train_subjects
@all_train_subjects.setter
def all_train_subjects(self, all_train_subjects):
self._all_train_subjects = all_train_subjects
@property
def n_subjects(self):
'''A quicker helper property to get
the sum of the length of :data:`train_subjects<EvalResults.train_subjects>`
and :data:`val_subjects<EvalResults.val_subjects>`. If this number varies by fold,
it will be set to None.
This number is supposed to represent the number of subjects with non NaN targets
used in the training and testing.
'''
lens = [len(self.train_subjects[i]) + len(self.val_subjects[i]) for i in range(len(self.train_subjects))]
if len(set(lens)) == 1:
return lens[0]
return None
@property
def n_folds(self):
'''A quicker helper property to get the number of CV folds
this object was evaluated with.
'''
# Just use len of train subjects as proxy for n_folds
return len(self.train_subjects)
@property
def timing(self):
'''This property stores information on
the fit and scoring times, if requested by the
original call to :func:`evaluate`.
This parameter is a dictionary with two keys,
'fit' and 'score'.
Each key stores the time in seconds as a list of
values for each of the evaluation folds.
'''
return self._timing
@timing.setter
def timing(self, timing):
self._timing = timing
@property
def mean_timing(self):
'''This property stores information on
the fit and scoring times, if requested by the
original call to :func:`evaluate`.
This parameter is a dictionary with two keys,
'fit' and 'score'.
Each key stores the mean time in seconds across folds.
'''
return self._mean_timing
@mean_timing.setter
def mean_timing(self, mean_timing):
self._mean_timing = mean_timing
@property
def preds(self):
'''If the parameter `store_preds` is set to True when
calling :func:`evaluate`, then this parameter will store the
predictions from every evaluate fold.
The parameter preds is a dictionary, where raw predictions made
can be accessed by the key 'predict'. Values are stored as list
corresponding to each evaluation fold.
In the case where other predict-like functions are available, e.g.,
in the case of a binary problem, where it may be desirable to
see the predicted probability, then the those predictions
will be made available under the name of the underlying predict
function. In this case, that is self.preds['predict_proba'].
It will also store results from 'predict' as well.
self.preds also will store under 'y_true' a list, where
each element of the list corresponds to the corresponding
true target values for the predictions made.
'''
return self._preds
@preds.setter
def preds(self, preds):
self._preds = preds
@property
def estimators(self):
'''If the parameter `store_estimators` is set to True when
calling :func:`evaluate`, then this parameter will store the fitted
estimator in a list. Where each element of the list corresponds to one
of the validation folds.
For example to access the fitted estimator from this first
fold ::
first_est = self.estimators[0]
'''
return self._estimators
@estimators.setter
def estimators(self, estimators):
self._estimators = estimators
@property
def cv(self):
'''If set to store CV is true, a deepcopy of the
passed cv splitter will be stored'''
try:
return self._cv
except AttributeError:
return None
@cv.setter
def cv(self, cv):
self._cv = cv
def _set_progress_bar(self, progress_bar):
'''Sets correct bar type based on if in notebook or not.'''
self.progress_bar = get_progress_bar(progress_bar)
def _eval(self, X, y, cv, dataset=None):
# Optionally store reference to dataset
if self._store_data_ref:
self._dataset = dataset.copy(deep=False)
# If verbose is lower than -1,
# then don't show any warnings no matter the source.
# or mute warnings flag set.
if self.verbose < -1 or self.mute_warnings:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
self._evaluate(X, y, cv)
# Otherwise, base behavior
else:
self._evaluate(X, y, cv)
def _evaluate(self, X, y, cv):
'''cv is passed as raw index, X and y as dataframes.'''
# Store a deep copy of cv if requested
if self._store_cv:
self.cv = deepcopy(cv)
# Compute and warn about num nan targets
n_nan_targets = pd.isnull(y).sum()
if n_nan_targets > 0:
self._print('Warning: There are', str(n_nan_targets) + ' missing',
'targets passed to evaluate. Subjects with missing',
'target values will be skipped during training and '
'scoring.')
if self.preds is not None:
self._print('Predictions will still be made for any',
'subjects with missing values in',
'any validation folds.')
# Verbose info
self._print('Predicting target =', str(self.ps.target), level=1)
self._print('Using problem_type =', str(self.ps.problem_type), level=1)
self._print('Using scope =', str(self.ps.scope),
'(defining a total of', str(X.shape[1]),
'features).', level=1)
self._print(f'Evaluating {len(X)} total data points.', level=1)
# Init scores as dictionary of lists
self.scores = {scorer_str: [] for scorer_str in self.ps.scorer}
# Save train and test subjs
self.all_train_subjects, self.all_val_subjects = [], []
self.train_subjects, self.val_subjects = [], []
# Save final feat names
self.feat_names = []
# Init progress bar / save and compute fold info from cv
progress_bars = self._init_progress_bars(cv)
self._print('Using CV: ', cv,
'to generate evaluation splits.', level=2)
self._print(level=1)
# Run each split
for train_inds, val_inds in cv.split(X, y):
# Eval
self._eval_fold(X.iloc[train_inds], y.iloc[train_inds],
X.iloc[val_inds], y.iloc[val_inds])
# Increment progress bars
progress_bars = self._incr_progress_bars(progress_bars)
self._incr_compare_bar()
# Clean up progress bars
self._finish_progress_bars(progress_bars)
# Compute and score mean and stds
self._compute_summary_scores()
def _init_progress_bars(self, cv):
# Passed cv should have n_repeats param - save in class
self.n_repeats_ = 1
if hasattr(cv, 'n_repeats'):
self.n_repeats_ = cv.n_repeats
# Passed cv should already be sklearn style
n_all_splits = cv.get_n_splits()
# Compute number of splits per repeat
self.n_splits_ = n_all_splits
if self.n_repeats_ > 1:
self.n_splits_ = int(n_all_splits / self.n_repeats_)
# Skip if no progress bar
if self.progress_bar is None:
return []
# If passed compare bars is int, init top level bar
if isinstance(self.compare_bars, int):
# Init and set as new
compare_bar = self.progress_bar(total=self.compare_bars,
desc='Compare', dynamic_ncols=True)
self.compare_bars = [compare_bar]
# If already init'ed
elif isinstance(self.compare_bars, list):
# Return all but last compare bar
return self.compare_bars[:-1]
bars = []
# If 1 repeat, then just folds progress bar
if self.n_repeats_ == 1:
folds_bar = self.progress_bar(total=self.n_splits_, desc='Folds',
dynamic_ncols=True)
bars = [folds_bar]
# Otherwise folds and repeats bars - init repeats bar first, so on top
else:
repeats_bar = self.progress_bar(total=self.n_repeats_,
desc='Repeats', dynamic_ncols=True)
folds_bar = self.progress_bar(total=self.n_splits_, desc='Folds',
dynamic_ncols=True)
bars = [folds_bar, repeats_bar]
# If compare bars was init'ed this run
if self.compare_bars is not None:
self.compare_bars = bars + self.compare_bars
return bars
def _incr_progress_bars(self, progress_bars):
# Skip if not requested
if self.progress_bar is None:
return []
# Increment folds bar
folds_bar = progress_bars[0]
folds_bar.n += 1
# Calculate estimate for this fold so far, and set
first_scorer = list(self.scores)[0]
fold_mean = np.mean(self.scores[first_scorer][-folds_bar.n:])
folds_bar.desc = f'Folds ({score_rep(fold_mean)})'
# If just folds bar update and return
if len(progress_bars) == 1:
_refresh_bar(folds_bar)
return [folds_bar]
# Increment partially repeats bar
repeats_bar = progress_bars[1]
repeats_bar.n += (1 / self.n_splits_)
repeats_bar.n = round(repeats_bar.n, 2)
# Set estimate score from all avaliable
repeats_bar.desc = f'Repeats ({score_rep(self.score)})'
# If both, check to see if n_repeats should be
# rounded, and folds bar reset to 0, and reset descr
if folds_bar.n == self.n_splits_:
folds_bar.n = 0
folds_bar.desc = 'Folds'
repeats_bar.n = round(repeats_bar.n)
# If end, set to full
if repeats_bar.n == self.n_repeats_:
folds_bar.n = self.n_splits_
# Update and then return
_refresh_bar([folds_bar, repeats_bar])
return [folds_bar, repeats_bar]
def _incr_compare_bar(self):
if self.compare_bars is None:
return
amt = 1 / (self.n_repeats_ * self.n_splits_)
self.compare_bars[-1].n += amt
self.compare_bars[-1].n = round(self.compare_bars[-1].n, 2)
_refresh_bar(self.compare_bars[-1])
def _finish_progress_bars(self, progress_bars):
# Refresh label on repeats (if any)
if len(progress_bars) == 2:
progress_bars[1].desc = 'Repeats'
_refresh_bar(progress_bars[1])
# Refresh label on folds
if len(progress_bars) > 0:
progress_bars[0].desc = 'Folds'
_refresh_bar(progress_bars[0])
# Close progress bars
if self.compare_bars is None:
for p_bar in progress_bars:
p_bar.close()
return
# Otherwise compare bars case, reset
_refresh_bar(progress_bars, n=0)
# Increment w/ round and refresh compare
self.compare_bars[-1].n = round(self.compare_bars[-1].n)
_refresh_bar(self.compare_bars[-1])
return
def _eval_fold(self, X_tr, y_tr, X_val, y_val):
# Get clone of estimator to fit
estimator_ = clone(self.estimator)
# Save all train and val inds before missing targets removed
self.all_train_subjects.append(X_tr.index)
self.all_val_subjects.append(X_val.index)
# Check for if any missing targets, if so - skip
# those subjects.
X_tr, y_tr = get_non_nan_Xy(X_tr, y_tr)
X_val_c, y_val_c = get_non_nan_Xy(X_val, y_val)
# Keep track of subjects in folds - where a subject is not included
# in the train or val fold if has NaN target
self.train_subjects.append(X_tr.index)
self.val_subjects.append(X_val_c.index)
# Add extra to verbose print if any skipped for NaN
tr_extra, val_extra = '', ''
dif_tr = len(self.all_train_subjects[-1]) -\
len(self.train_subjects[-1])
dif_val = len(self.all_val_subjects[-1]) -\
len(self.val_subjects[-1])
if dif_tr != 0:
tr_extra = f' (skipped {dif_tr} NaN targets)'
if dif_val != 0:
val_extra = f' (skipped {dif_val} NaN targets)'
# Print info on sizes
self._print(f'Training Set: {X_tr.shape}{tr_extra}', level=1)
self._print(f'Validation Set: {X_val_c.shape}{val_extra}', level=1)
# Fit estimator_, passing as arrays, and with train data index
start_time = time.time()
estimator_.fit(X=X_tr, y=np.array(y_tr))
fit_time = time.time() - start_time
self._print(f'Fit fold in {fit_time:.1f} seconds.', level=1)
# Score estimator
start_time = time.time()
self._score_estimator(estimator_, X_val_c, y_val_c)
score_time = time.time() - start_time
# Store timing if requested
if self.timing is not None:
self.timing['fit'].append(fit_time)
self.timing['score'].append(score_time)
# Save preds - pass full val with NaN targets
self._save_preds(estimator_, X_val, y_val)
# Get and save final transformed feat names
# Feat names w/ nested model applied ~
self.feat_names.append(
estimator_.transform_feat_names(X_tr,
encoders=self.encoders_,
nested_model=True))
# If store estimators, save in self.estimators
if self.estimators is not None:
self.estimators.append(estimator_)
def _score_estimator(self, estimator_, X_val, y_val):
# Use multi-metric scorer here - handles not repeating calls to
# predict / predict proba, ect... - can safely wrap even single metrics
scorers = _MultimetricScorer(**self.ps.scorer)
scores = scorers(estimator_, X_val, np.array(y_val))
# Append each to scores, keeps track per fold
for scorer_str in self.scores:
score = scores[scorer_str]
self.scores[scorer_str].append(score)
# Optional verbose
self._print(f'{scorer_str}: {score_rep(score)}', level=1)
# Spacing for nice looking output
self._print(level=1)
def _save_preds(self, estimator, X_val, y_val):
if self.preds is None:
return
self._print('Saving predictions on validation set.', level=2)
for predict_func in ['predict', 'predict_proba', 'decision_function']:
# Get preds, skip if estimator doesn't have predict func
try:
preds = getattr(estimator, predict_func)(X_val)
except AttributeError:
continue
# Add to preds dict if estimator has predict func
try:
self.preds[predict_func].append(preds)
except KeyError:
self.preds[predict_func] = [preds]
# Add y_true
try:
self.preds['y_true'].append(np.array(y_val))
except KeyError:
self.preds['y_true'] = [np.array(y_val)]
def _compute_summary_scores(self):
self._print('Computing summary scores.', level=2)
self.mean_scores, self.std_scores = {}, {}
self.weighted_mean_scores = {}
for scorer_key in self.scores:
# Save mean under same name
scores = self.scores[scorer_key]
self.mean_scores[scorer_key] = np.mean(scores)
# Compute scores weighted by number of subjs
# Use val_subjects without NaN targets
weights = [len(self.val_subjects[i])
for i in range(len(self.val_subjects))]
self.weighted_mean_scores[scorer_key] =\
np.average(scores, weights=weights)
# Compute and add base micro std
self.std_scores[scorer_key] = np.std(scores)
# If more than 1 repeat, add the macro std
if self.n_repeats_ > 1:
scores = np.reshape(scores,
(self.n_repeats_, self.n_splits_))
self.std_scores[scorer_key + '_macro'] =\
np.std(np.mean(scores, axis=1))
# Add mean timing
if self.timing is not None:
self.mean_timing = {}
for time_key in self.timing:
self.mean_timing[time_key] = np.mean(self.timing[time_key])
def get_preds_dfs(self, drop_nan_targets=False):
'''This function can be used to return the raw predictions
made during evaluation as a list of pandas Dataframes.
Parameters
------------
drop_nan_targets : bool, optional
If False (default), then this method will return the
DataFrame of predictions including targets
with NaN. To skip these, e.g., in this case
of plotting against ground truth or computing
new metrics, set to True.
::
default = False
Returns
---------
dfs : list of pandas.DataFrame
list of dataframe's per fold, where each DataFrame
contains predictions made.
'''
dfs = []
# For each fold
for fold_indx in range(len(self.all_val_subjects)):
# Init df
df = pd.DataFrame(index=self.all_val_subjects[fold_indx])
# Add each predict type as a column
for predict_type in self.preds:
ps = self.preds[predict_type][fold_indx]
# Either float or multi-class case
if isinstance(ps[0], (float, np.floating)):
df[predict_type] = ps
else:
for cls in range(len(ps[0])):
df[predict_type + '_' + str(cls)] = ps[:, cls]
# Drop nan-cols if not requested
if drop_nan_targets:
nan_targets = df[df['y_true'].isna()].index
df = df.drop(nan_targets)
# Add to by fold list
dfs.append(df)
return dfs
def _get_display_name(self):
return str(self.__class__.__name__)
def __repr__(self):
rep = self._get_display_name() + '\n'
rep += '------------\n'
# Add scores + means pretty rep
for key in self.mean_scores:
rep += f'{key}: {score_rep(self.mean_scores[key])} '
rep += f'± {score_rep(self.std_scores[key])}\n'
rep += '\n'
# Show available saved attrs
saved_attrs = []
avaliable_methods = ['to_pickle', 'compare']
if self.estimators is not None:
saved_attrs.append('estimators')
avaliable_methods.append('get_X_transform_df')
avaliable_methods.append('get_inverse_fis')
avaliable_methods.append('run_permutation_test')
if self.preds is not None:
saved_attrs.append('preds')
avaliable_methods.append('get_preds_dfs')
avaliable_methods.append('subset_by')
if self.timing is not None:
saved_attrs.append('timing')
saved_attrs += ['estimator', 'train_subjects', 'val_subjects',
'feat_names', 'ps',
'mean_scores', 'std_scores',
'weighted_mean_scores', 'scores']
# Only show if different
ati_len = len(sum([list(e) for e in self.all_train_subjects], []))
ti_len = len(sum([list(e) for e in self.train_subjects], []))
if ati_len != ti_len:
saved_attrs.append('all_train_subjects')
avi_len = len(sum([list(e) for e in self.all_val_subjects], []))
vi_len = len(sum([list(e) for e in self.val_subjects], []))
if avi_len != vi_len:
saved_attrs.append('all_val_subjects')
if self.estimators is not None:
# Either or
if self.feature_importances_ is not None:
saved_attrs += ['fis_', 'feature_importances_']
avaliable_methods += ['get_fis', 'get_feature_importances']
elif self.coef_ is not None:
saved_attrs += ['fis_', 'coef_']
avaliable_methods += ['get_fis', 'get_coef_']
avaliable_methods.append('permutation_importance')
if self._store_cv:
saved_attrs += ['cv']
rep += 'Saved Attributes: ' + repr(saved_attrs) + '\n\n'
rep += 'Available Methods: ' + repr(avaliable_methods) + '\n\n'
# Use custom display str, no need to show scorer.
rep += 'Evaluated With:\n'
rep += self.ps._get_display_str(show_scorer=False) + '\n'
return rep
def _estimators_check(self):
if self.estimators is None: