-
Notifications
You must be signed in to change notification settings - Fork 9
/
interpretable_drift.py
486 lines (405 loc) · 16.4 KB
/
interpretable_drift.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
import shap
import warnings
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
try:
import plotly.express as px
import plotly.graph_objects as go
except ModuleNotFoundError:
_has_plotly = False
_plotly_exception_message = (
'Plotly is required to run this pydrift functionality.'
)
else:
_has_plotly = True
_plotly_exception_message = None
from typing import List, Union, Dict, Tuple
from sklearn.pipeline import Pipeline
from pathlib import Path
from ..models import ScikitModel
from ..decorators import check_optional_module
class InterpretableDrift:
def __init__(self,
model: ScikitModel,
X_train: pd.DataFrame,
X_test: pd.DataFrame,
y_train: pd.DataFrame,
y_test: pd.DataFrame,
column_names: List[str]):
"""Inits `InterpretableDrift` for a given `model`,
`X_train` and `X_test` datasets and `column_names
"""
if isinstance(model, Pipeline):
X_train_to_shap = model[:-1].transform(X_train)
X_test_to_shap = model[:-1].transform(X_test)
model_to_shap = model.steps[-1][1]
else:
X_train_to_shap = X_train.copy()
X_test_to_shap = X_test.copy()
model_to_shap = model
self.model = model_to_shap
self.X_train_to_shap = pd.DataFrame(X_train_to_shap,
columns=column_names)
self.X_test_to_shap = pd.DataFrame(X_test_to_shap,
columns=column_names)
self.X_train = X_train
self.X_test = X_test
self.y_train = y_train
self.y_test = y_test
self.column_names = column_names
self.shap_values = np.empty(0)
def compute_shap_values(self) -> None:
"""Shap values depending on what model we are using
`shap.TreeExplainer` by default and if not it uses
`KernelExplainer`
Also provides compatibility with sklearn pipelines
`shap_values` are stored in `self.shap_values`
"""
with warnings.catch_warnings():
# Some `shap` warnings are not useful for this implementation
warnings.simplefilter("ignore")
try:
explainer = shap.TreeExplainer(
model=self.model,
feature_perturbation='tree_path_dependent'
)
shap_values_arguments = dict(X=self.X_test_to_shap)
except Exception:
def model_predict(data_array):
data_frame = pd.DataFrame(data_array,
columns=self.column_names)
return self.model.predict_proba(data_frame)[:, 1]
explainer = shap.KernelExplainer(model=model_predict,
data=shap.sample(
self.X_train_to_shap,
100
),
link='logit')
shap_values_arguments = dict(X=self.X_test_to_shap,
l1_reg='aic')
self.shap_values = explainer.shap_values(**shap_values_arguments)
def most_discriminative_features_plot(self,
save_plot_path: Path = None) -> None:
"""Plots most discriminative features with its
shap values
You can save the plot in `save_plot_path` path
"""
if self.shap_values.size == 0:
self.compute_shap_values()
shap.summary_plot(self.shap_values,
self.X_test_to_shap,
plot_type='bar',
title='Most Discriminative Features',
show=True if not save_plot_path else False)
if save_plot_path:
plt.savefig(save_plot_path, bbox_inches='tight')
@check_optional_module(has_module=_has_plotly,
exception_message=_plotly_exception_message)
def both_histogram_plot(self,
column: str,
fillna_value: Union[str, float, int] = None,
nbins: int = None,
save_plot_path: Path = None) -> None:
"""Plots histogram for the column passed
in `column`
You can set `nbins` to any number that makes
your plot better
You can save the plot as html file in `save_plot_path` path
Requires `plotly`
"""
X_train_column = self.X_train.loc[:, [column]]
X_test_column = self.X_test.loc[:, [column]]
if fillna_value:
X_train_column.fillna(fillna_value, inplace=True)
X_test_column.fillna(fillna_value, inplace=True)
X_train_total_nans = X_train_column[column].isna().sum()
X_test_total_nans = X_test_column[column].isna().sum()
if X_train_total_nans or X_test_total_nans:
warnings.warn(
f'Column {column} has '
f'{X_train_total_nans + X_test_total_nans} nan values, '
f'you can use `fillna_value` if you need it'
)
X_train_column['is_left'] = self.y_train.to_numpy()
X_test_column['is_left'] = self.y_test.to_numpy()
X_train_and_test = pd.concat([X_train_column, X_test_column])
fig = px.histogram(X_train_and_test,
title=f'Both Histogram Normalized For {column}',
x=column,
color='is_left',
barmode='group',
nbins=nbins,
histnorm='probability density')
fig.update_layout(bargroupgap=.1)
if save_plot_path:
fig.write_html(save_plot_path)
else:
fig.show()
@check_optional_module(has_module=_has_plotly,
exception_message=_plotly_exception_message)
def feature_importance_vs_drift_map_plot(
self,
dict_each_column_drift_coefficient: Dict[str, float],
top: int = 10,
save_plot_path: Path = None) -> None:
"""Feature importance versus drift coefficient map,
with this plot you can visualize the most critical
features involved in your model drift process
By default shows you the top 10 most important features
but you can customize it with `top` parameter
You can save the plot as html file in `save_plot_path` path
"""
df_feature_importance = pd.DataFrame(
zip(self.column_names,
np.abs(self.shap_values).mean(axis=0)),
columns=['Feature Name', 'Feature Importance']
)
df_feature_importance['Drift Coefficient'] = (
(df_feature_importance['Feature Name']
.map(dict_each_column_drift_coefficient))
)
value_min = df_feature_importance['Feature Importance'].min()
value_max = df_feature_importance['Feature Importance'].max()
df_feature_importance['Feature Importance Scaled'] = (
(df_feature_importance['Feature Importance'] - value_min)
/ (value_max - value_min)
)
df_feature_importance_to_plot = (
df_feature_importance
.sort_values('Feature Importance Scaled', ascending=False)
.nlargest(top, columns='Feature Importance Scaled')
)
fig = px.scatter(df_feature_importance_to_plot,
x='Feature Importance Scaled',
y='Drift Coefficient',
text='Feature Name',
hover_name='Feature Name',
hover_data={'Feature Importance Scaled': ':.2f',
'Drift Coefficient': ':.2f',
'Feature Importance': False,
'Feature Name': False},
title='Feature Importance vs Drift Map')
fig.update_traces(marker=dict(size=10, opacity=.75))
axis_value_min, axis_value_medium, axis_value_max = 0, .5, 1
fig.add_trace(
go.Scatter(
x=[axis_value_min + .15, axis_value_max - .15,
axis_value_max - .15, axis_value_min + .15],
y=[axis_value_max + .05, axis_value_max + .05,
axis_value_min - .05, axis_value_min - .05],
text=['NON-IMPORTANT FEATURES DRIFTED',
'IMPORTANT FEATURES AND DRIFTED',
'IMPORTANT FEATURES NON-DRIFTED',
'NON-IMPORTANT FEATURES NON-DRIFTED'],
mode="text",
showlegend=False
)
)
fig.add_shape(
type="rect",
x0=axis_value_min,
y0=axis_value_min,
x1=axis_value_medium,
y1=axis_value_medium,
fillcolor="khaki",
opacity=.25
)
fig.add_shape(
type="rect",
x0=axis_value_min,
y0=axis_value_medium,
x1=axis_value_medium,
y1=axis_value_max,
fillcolor="coral",
opacity=.25
)
fig.add_shape(
type="rect",
x0=axis_value_medium,
y0=axis_value_min,
x1=axis_value_max,
y1=axis_value_medium,
fillcolor="limegreen",
opacity=.25
)
fig.add_shape(
type="rect",
x0=axis_value_medium,
y0=axis_value_medium,
x1=axis_value_max,
y1=axis_value_max,
fillcolor="crimson",
opacity=.25
)
fig.update_layout(
xaxis=dict(range=[axis_value_min - .05, axis_value_max + .05]),
yaxis=dict(range=[axis_value_min - .1, axis_value_max + .1])
)
if save_plot_path:
fig.write_html(save_plot_path)
else:
fig.show()
@staticmethod
@check_optional_module(has_module=_has_plotly,
exception_message=_plotly_exception_message)
def weights_plot(weights: np.array, save_plot_path: Path = None) -> None:
"""Weights plot, the higher the weight, the more
similar the train data is to the test data
This will be used to retrain the model
You can save the plot as html file in `save_plot_path` path
"""
fig = px.histogram(weights,
title='Weights From The Discriminative Model')
fig.update_layout(showlegend=False)
if save_plot_path:
fig.write_html(save_plot_path)
else:
fig.show()
@staticmethod
def _drop_outliers_between(
df: pd.DataFrame,
feature: str,
percentiles: Tuple[float,
float] = (.05, .95)) -> pd.DataFrame:
"""Drop outliers for column `feature` of
`df` between `percentiles`
"""
lower, upper = percentiles
return df[df[feature].between(df[feature].quantile(lower),
df[feature].quantile(upper))]
@staticmethod
def _convert_to_mid_interval_with_max_bins(
serie: pd.Series,
bins: int = 25) -> pd.DataFrame:
"""Convert `series` values to a binned version
of it in `bins` as number of
intervals
"""
return (pd
.cut(serie, bins=bins)
.apply(lambda x: x.mid)
.astype(float))
@check_optional_module(has_module=_has_plotly,
exception_message=_plotly_exception_message)
def partial_dependence_comparison_plot(
self,
feature: str,
percentiles: Tuple[float, float] = (.05, .95),
max_bins: int = 25,
save_plot_path: Path = None) -> None:
"""Partial dependence plot for `feature` in
both datasets predictions
You can save the plot as html file in `save_plot_path` path
"""
X_train_copy = self.X_train.copy()
X_test_copy = self.X_test.copy()
X_train_copy['is_left'] = '1'
X_test_copy['is_left'] = '0'
X_train_copy['Prediction'] = (
self.model.predict_proba(X_train_copy)[:, 1]
)
X_test_copy['Prediction'] = (
self.model.predict_proba(X_test_copy)[:, 1]
)
is_numeric = pd.api.types.is_numeric_dtype(
X_train_copy[feature]
)
if is_numeric:
X_train_copy = (
self._drop_outliers_between(X_train_copy,
feature=feature,
percentiles=percentiles)
)
X_test_copy = (
self._drop_outliers_between(X_test_copy,
feature=feature,
percentiles=percentiles)
)
bins = min(X_train_copy[feature].nunique(),
max_bins)
X_train_copy[feature] = (
self._convert_to_mid_interval_with_max_bins(
X_train_copy[feature],
bins
)
)
X_test_copy[feature] = (
self._convert_to_mid_interval_with_max_bins(
X_test_copy[feature],
bins
)
)
X_both = pd.concat([X_train_copy, X_test_copy])
data_to_plot = (
X_both
.groupby(['is_left', feature])
.Prediction
.mean()
.reset_index()
)
if is_numeric:
fig = px.scatter(data_to_plot,
x=feature,
y='Prediction',
color='is_left',
trendline="ols")
else:
fig = px.bar(data_to_plot,
x=feature,
y='Prediction',
color='is_left',
barmode='group')
fig.update_layout(title=f'Partial Dependence For {feature}',
bargroupgap=.1)
if save_plot_path:
fig.write_html(save_plot_path)
else:
fig.show()
@check_optional_module(has_module=_has_plotly,
exception_message=_plotly_exception_message)
def drift_by_sorted_bins_plot(self,
feature: str,
bins: int = 10,
save_plot_path: Path = None) -> None:
"""Concat all the data in both dataframes and
sort it by `feature`, then it cuts in `bins`
number of bins and computes quantity of registers
in each bin
You can save the plot as html file in `save_plot_path` path
"""
X_train_copy = self.X_train.copy()
X_test_copy = self.X_test.copy()
X_train_copy['is_left'] = '1'
X_test_copy['is_left'] = '0'
X_both = (
pd
.concat([X_train_copy[[feature, 'is_left']],
X_test_copy[[feature, 'is_left']]])
.sample(frac=1)
.reset_index()
)
is_categorical = not pd.api.types.is_numeric_dtype(
X_both[feature]
)
if is_categorical:
X_both[feature] = X_both[feature].astype('category')
X_both['rank'] = (
X_both[feature].cat.codes .rank(method='first') if is_categorical
else X_both[feature].rank(method='first')
)
X_both['Bin Number'] = pd.qcut(X_both['rank'],
q=bins,
labels=range(1, bins + 1))
fig = px.histogram(X_both,
x='Bin Number',
color='is_left',
nbins=bins,
barmode='group')
fig.update_layout(title=f'Drift By Bin For {feature}',
bargroupgap=.1,
xaxis=dict(tickmode='linear'))
if save_plot_path:
fig.write_html(save_plot_path)
else:
fig.show()