-
Notifications
You must be signed in to change notification settings - Fork 18
/
powershap.py
534 lines (465 loc) · 22.5 KB
/
powershap.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
__author__ = "Jarne Verhaeghe, Jeroen Van Der Donckt"
import warnings
import numpy as np
import pandas as pd
import sklearn
from sklearn.base import BaseEstimator
from sklearn.feature_selection import SelectorMixin
from sklearn.model_selection import BaseCrossValidator
from sklearn.utils.validation import check_is_fitted
from .shap_wrappers import ShapExplainerFactory
from .utils import powerSHAP_statistical_analysis
class PowerShap(SelectorMixin, BaseEstimator):
"""
Feature selection based on significance of shap values.
"""
def __init__(
self,
model=None,
power_iterations: int = 10,
power_alpha: float = 0.01,
val_size: float = 0.2,
power_req_iterations: float = 0.99,
include_all: bool = False,
automatic: bool = True,
force_convergence: bool = False,
limit_convergence_its: int = 0,
limit_automatic: int = 10,
limit_incremental_iterations: int = 10,
limit_recursive_automatic: int = 3,
stratify: bool = False,
cv: BaseCrossValidator = None,
show_progress: bool = True,
verbose: bool = False,
**fit_kwargs,
):
"""
Create a powershap object.
Parameters
----------
model: Any, optional
The model used for for the powershap calculation. The currently supported
models are; catboost, sklearn tree-based, sklearn linear, and tensorflow
deep learning models.
If no model is passed, by default, a catboost model will be used. If the
data type is of type float, a CatBoostRegressor will be selected, for all
the other cases a CatBoostClassifier is selected.
..note::
The deep learning model should take |features| + 1 as input size.
It is thus the user his/her responsibility to account for the added
random feature, when using deep learning models.
power_iterations: int, optional
The number of shuffles and iterations of the power feature selection method,
ignored when using automatic mode. By default 10.
power_alpha: float, optional
The alpha value used for the power-calculation of the used statistical test
and significance threshold. Should be a float between ]0,1[. By default
0.01.
val_size: float, optional
The fractional size of the validation set. Should be a float between ]0,1[.
By default 0.2.
power_req_iterations: float, optional
The fractional power percentage for the required iterations calculation. By
default 0.95.
include_all: bool
Flag indicating whether all features should be analyzed or only those with a
threshold of `power_alpha`.
automatic: bool, optional
If True, the powershap will first calculate the required iterations by using
10 iterations and then restart using the required iterations for
`power_iterations`. By default False.
force_convergence: bool, optional
Only used for automatic mode. If True, powershap will continue delete
the found relevant features and rerun until no more relevant features are found.
This is especially useful in high-dimensional datasets
limit_convergence_its: int, optional
The number of maximum allowed recursions when `force_convergence` is True. By
default 0, meaning that no limit is applied. A limit_convergence_its of 1 suggests
only executing one convergence recursion
after a single full automatic PowerShap execution.
limit_automatic: int, optional
The number of maximum allowed iterations when `automatic` is True. By
default None, meaning that no limit is applied.
limit_incremental_iterations: int, optional
If the required iterations exceed `limit_automatic` in automatic mode, add
`limit_incremental_iterations` iterations and re-evaluate. By default 10.
limit_recursive_automatic: int, optional
The number of maximum allowed times that `limit_incremental_iterations`
iterations are added. This restricts the amount of powershap recursion. By
default 3.
stratify: bool, optional
Whether to create a stratified train_test_split (based on the `y` that is
given to the `.fit` method). By default False.
..note::
If you want to pass a specific array as stratify (that is not `y`), you
can pass it as `stratify` argument to the `.fit` method.
cv: BaseCrossValidator, optional
The cross-validator to use. By default None.
This cross-validator should have a `.split` method which yields
(train_idx, test_idx) tuples. The arguments of the `.split` method should be
X, y, groups. This splitter will be wrapped to yield infinite splits.
..note::
If the given coss validator has no `random_state` argument, the same
splits will be used multiple times in the powershap iterations. This
may lead to overfitting on the cross-validation splits (and thus
selection of non-informative variables).
show_progress: bool, optional
Flag indicating whether progress of the powershap iterations should be
shown. By default True.
verbose: bool, optional
Flag indicating whether verbose console output should be shown. By default
False.
**fit_kwargs: dict
Keyword arguments for fitting the model.
..note::
For a deep learning model, the following keyword arguments are required:
"epochs", "optimizer", "batch_size", "nn_metric", "loss"
"""
self.model = model
self.power_iterations = power_iterations
self.power_alpha = power_alpha
self.val_size = val_size
self.power_req_iterations = power_req_iterations
self.include_all = include_all
self.automatic = automatic
self.force_convergence = force_convergence
self.limit_convergence_its = limit_convergence_its
self.limit_automatic = limit_automatic
self.limit_incremental_iterations = limit_incremental_iterations
self.limit_recursive_automatic = limit_recursive_automatic
self.stratify = stratify
self.show_progress = show_progress
self.verbose = verbose
self.fit_kwargs = fit_kwargs
def _infinite_splitter(cv):
"""Infinite yields for the given splitter.
If the splitter is exhausted, it will be reset and restarted.
"""
from copy import deepcopy
cv = deepcopy(cv)
splitter = None
random_state = 0
def split(X, y=None, groups=None):
nonlocal splitter, random_state
if splitter is None:
if hasattr(cv, "random_state"): # Update random state
cv.__setattr__("random_state", random_state)
random_state += 1
splitter = cv.split(X, y=y, groups=groups)
while True:
try:
yield next(splitter)
except StopIteration:
if hasattr(cv, "random_state"): # Update random state
cv.__setattr__("random_state", random_state)
random_state += 1
splitter = cv.split(X, y=y, groups=groups)
yield next(splitter)
return split
if cv is not None:
self.cv = _infinite_splitter(cv)
else:
self.cv = None
if model is not None:
self._explainer = ShapExplainerFactory.get_explainer(model=model)
@staticmethod
def _get_default_model(y: np.ndarray):
from catboost import CatBoostClassifier, CatBoostRegressor
assert isinstance(y, np.ndarray)
dtype = y.dtype
if np.issubdtype(dtype, np.number) and not np.issubdtype(dtype, np.integer):
return CatBoostRegressor(
n_estimators=250, od_type="Iter", od_wait=25, use_best_model=True, verbose=0
)
if np.issubdtype(dtype, np.integer) and len(np.unique(y.ravel())) >= 5:
warnings.warn(
"Classifying although there are >= 5 integers in the labels.", UserWarning
)
return CatBoostClassifier(
n_estimators=250, od_type="Iter", od_wait=25, use_best_model=True, verbose=0
)
def _log_feature_names_sklean_v0(self, X):
"""Log the feature names if we have sklearn 0.x"""
assert sklearn.__version__.startswith("0.")
feature_names = np.asarray(X.columns) if hasattr(X, "columns") else None
if feature_names is not None and len(feature_names) > 0:
# Check if all feature names of type string
types = sorted(t.__qualname__ for t in set(type(v) for v in feature_names))
if len(types) > 1 or types[0] != "str":
feature_names = None
warnings.warn("Feature names only support names that are all strings.", UserWarning)
if feature_names is not None and len(feature_names) > 0:
self.feature_names_in_ = feature_names
elif hasattr(self, "feature_names_in_"):
# Delete the attribute when the estimator is fitted on a new dataset that
# has no feature names.
delattr(self, "feature_names_in_")
def _print(self, *values):
"""Helper method for printing if `verbose` is set to True."""
if self.verbose:
print(*values)
def _automatic_fit(
self, X, y, processed_shaps_df, loop_its, stratify, groups, shaps_df, **kwargs
):
if not any(processed_shaps_df.p_value < self.power_alpha):
# There is no feature found yet...
self._print("No features selected after 10 automatic iterations!")
# Return already as more iterations will only result in including less
# features
return processed_shaps_df
max_iterations = int(
np.ceil(
processed_shaps_df[processed_shaps_df.p_value < self.power_alpha][
str(self.power_req_iterations) + "_power_its_req"
].max()
)
)
max_iterations_old = loop_its
recurs_counter = 0
if max_iterations <= max_iterations_old:
self._print(
f"{loop_its} iterations were already sufficient as only",
f"{max_iterations} iterations were required for the current ",
f"power_alpha = {self.power_alpha}.",
)
while (
max_iterations > max_iterations_old
# and max_iterations < limit_automatic
and recurs_counter < self.limit_recursive_automatic
):
shaps_df_recursive: pd.DataFrame = None
if max_iterations - max_iterations_old > self.limit_automatic:
self._print(
f"Automatic mode: powershap requires {max_iterations} ",
"iterations; The extra required iterations exceed the limit_automatic ",
"threshold. Powershap will add ",
f"{self.limit_incremental_iterations} powershap iterations and ",
"re-evaluate.",
)
shaps_df_recursive = self._explainer.explain(
X=X,
y=y,
loop_its=self.limit_incremental_iterations,
val_size=self.val_size,
stratify=stratify,
groups=groups,
cv_split=self.cv, # pass the wrapped cv split function
random_seed_start=max_iterations_old,
show_progress=self.show_progress,
**kwargs,
)
max_iterations_old = max_iterations_old + self.limit_incremental_iterations
else:
self._print(
f"Automatic mode: Powershap requires {max_iterations} "
f"iterations; Adding {max_iterations-max_iterations_old} ",
"powershap iterations.",
)
shaps_df_recursive = self._explainer.explain(
X=X,
y=y,
loop_its=max_iterations - max_iterations_old,
val_size=self.val_size,
stratify=stratify,
groups=groups,
cv_split=self.cv, # pass the wrapped cv split function
random_seed_start=max_iterations_old,
show_progress=self.show_progress,
**kwargs,
)
max_iterations_old = max_iterations
shaps_df = pd.concat([shaps_df, shaps_df_recursive])
processed_shaps_df = powerSHAP_statistical_analysis(
shaps_df, self.power_alpha, self.power_req_iterations, include_all=self.include_all
)
if not any(processed_shaps_df.p_value < self.power_alpha):
# There is no feature found yet...
self._print("No features selected after 10 automatic iterations!")
# Return already as more iterations will only result in including less
# features
return processed_shaps_df
max_iterations = int(
np.ceil(
processed_shaps_df[processed_shaps_df.p_value < self.power_alpha][
str(self.power_req_iterations) + "_power_its_req"
].max()
)
)
recurs_counter += 1
return processed_shaps_df
def fit(self, X, y, stratify=None, groups=None, **kwargs):
"""Fit the powershap feature selector.
Parameters
----------
X: array-like of shape (n_samples, n_features)
Training data, where ``n_samples`` is the number of samples and
``n_features`` is the number of features.
y: array-like of shape (n_samples,)
The target variable for supervised learning problems.
stratify: array-like of shape (n_samples,), optional
Array that will be used to perform stratified train-test splits. By default
None.
Note: if None, than `y` will be used as `stratify` if the stratify flag of
the object is True.
groups: array-like of shape (n_samples,), optional
Group labels for the samples used while splitting the dataset into
train/test set. By default None.
"""
if stratify is None and self.stratify:
# Set stratify to y, if no stratify is given and self.stratify is True
stratify = y
# kwargs take precedence over fit_kwargs
kwargs = {**self.fit_kwargs, **kwargs}
if self.model is None:
# If no model is passed to the constructor -> select the default catboost
# model
self.model = PowerShap._get_default_model(np.asarray(y))
self._explainer = ShapExplainerFactory.get_explainer(self.model)
if sklearn.__version__.startswith("0."):
# Log the feature names if we have sklearn 0.x
self._log_feature_names_sklean_v0(X)
# Perform the necessary sklearn checks -> X and y are both ndarray.
# Logs the feature names as well (in self.feature_names_in_ in sklearn 1.x).
#
# These two operations (_validate_data and pd.DataFrame) will also copy
# the data into a new place in memory, avoiding data mutation. How this
# happens may not be obvious at first glance:
#
# 1. _validate_data ensures that the data is a numpy array, copying it
# upon conversion if necessary.
#
# 2. pd.DataFrame then copies X, which is now an numpy array, into a
# new pandas dataframe.
#
# If this is changed in some way which would allow explain() to mutate
# the original data, it should cause the data mutation tests to fail.
X, y = self._explainer._validate_data(self._validate_data, X, y, multi_output=True)
X = pd.DataFrame(data=X, columns=list(range(X.shape[1])))
self._print("Starting powershap")
loop_its = self.power_iterations
if self.automatic:
loop_its = 10
self._print(
"Automatic mode enabled: Finding the minimal required powershap",
f"iterations for significance of {self.power_alpha}.",
)
shaps_df = self._explainer.explain(
X=X,
y=y,
loop_its=loop_its,
val_size=self.val_size,
stratify=stratify,
groups=groups,
cv_split=self.cv, # pass the wrapped cv split function
show_progress=self.show_progress,
**kwargs,
)
processed_shaps_df = powerSHAP_statistical_analysis(
shaps_df, self.power_alpha, self.power_req_iterations, include_all=self.include_all
)
if self.automatic:
processed_shaps_df = self._automatic_fit(
X=X,
y=y,
processed_shaps_df=processed_shaps_df,
loop_its=loop_its,
stratify=stratify,
groups=groups,
shaps_df=shaps_df,
**kwargs,
)
# Continue powershap until no more informative features are found
if self.force_convergence:
self._print("Forcing convergence.")
converge_df = processed_shaps_df.copy()
significant_cols = np.array(
converge_df[converge_df.p_value < self.power_alpha].index.values
)
# If limit_convergence_its is zero, the convergence mode does not have a limit.
# If not, the while loop condition is recalculated every while loop iteration.
if self.limit_convergence_its > 0:
current_converge_recursions = 0
while_convergence_bool = (
current_converge_recursions < self.limit_convergence_its
)
else:
while_convergence_bool = True
while (len(converge_df[converge_df.p_value < self.power_alpha]) > 0) & (
while_convergence_bool
):
self._print("Rerunning powershap for convergence. ")
converge_shaps_df = self._explainer.explain(
X=X.drop(columns=X.columns.values[significant_cols.astype(np.int32)]),
y=y,
loop_its=loop_its,
val_size=self.val_size,
stratify=stratify,
groups=groups,
cv_split=self.cv, # pass the wrapped cv split function
show_progress=self.show_progress,
**kwargs,
)
converge_df = powerSHAP_statistical_analysis(
converge_shaps_df,
self.power_alpha,
self.power_req_iterations,
include_all=self.include_all,
)
converge_df = self._automatic_fit(
X=X.drop(columns=X.columns.values[significant_cols.astype(np.int32)]),
y=y,
processed_shaps_df=converge_df,
loop_its=loop_its,
stratify=stratify,
groups=groups,
converge_shaps_df=converge_shaps_df,
shaps_df=converge_shaps_df,
**kwargs,
)
significant_cols = np.append(
significant_cols,
converge_df[converge_df.p_value < self.power_alpha].index.values,
)
processed_shaps_df.loc[
converge_df[converge_df.p_value < self.power_alpha].index.values
] = converge_df[converge_df.p_value < self.power_alpha]
if self.limit_convergence_its > 0:
current_converge_recursions += 1
print(current_converge_recursions)
while_convergence_bool = (
current_converge_recursions < self.limit_convergence_its
)
if not while_convergence_bool:
self._print("Convergence limit reached: Stopping convergence mode.")
processed_shaps_df.loc[converge_df.index.values] = converge_df
self._print("Done!")
## Set the p-values property (used in the transform function)
# Remove the random feature (legit features have int index)
sub_df = processed_shaps_df[processed_shaps_df.index.map(lambda x: isinstance(x, int))]
# Sort to have original order again
sub_df = sub_df.sort_index()
self._p_values = sub_df.p_value.values
## Store the processed_shaps_df in the object
self._processed_shaps_df = processed_shaps_df
if hasattr(self, "feature_names_in_"):
self._processed_shaps_df.index = [
self.feature_names_in_[i] if isinstance(i, int) else i
for i in processed_shaps_df.index.values
]
# It is convention to return self
return self
# This is the only method that needs to be implemented to serve the transform
# functionality
def _get_support_mask(self):
# Select the significant features
return self._p_values < self.power_alpha
def transform(self, X):
check_is_fitted(self, ["_processed_shaps_df", "_p_values", "_explainer"])
if hasattr(self, "feature_names_in_") and isinstance(X, pd.DataFrame):
assert np.all(X.columns.values == self.feature_names_in_)
return pd.DataFrame(
super().transform(X), columns=self.feature_names_in_[self._get_support_mask()]
)
return super().transform(X)
def _more_tags(self):
return self._explainer._get_more_tags()