-
Notifications
You must be signed in to change notification settings - Fork 54
/
explain.py
371 lines (293 loc) · 13.3 KB
/
explain.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
import os
import sys
import re
from pathlib import Path
from sys import platform
import subprocess
import time
path = Path(__file__).parent.absolute()
path_dataset = os.path.join(path, "datasets")
path = os.path.join(path, "lib")
sys.path.append(path)
from imports import *
from dashboard import *
from calculate_shap import *
from analytics import Analytics
class explain():
def __init__(self):
super(explain, self).__init__()
self.param = {}
# is classification function?
# def is_classification_given_y_array(self, y_test):
# is_classification = False
# total = len(y_test)
# total_unique = len(set(y_test))
# if total < 30:
# if total_unique < 10:
# is_classification = True
# else:
# if total_unique < 20:
# is_classification = True
# return is_classification
def random_string_generator(self):
random_str = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
return random_str
def ai_h2o_automl(self, df, y_column_name, model, model_name="h2o", mode=None):
y_variable = "y_actual"
y_variable_predict = "y_prediction"
y_variable = "y_actual"
y_variable_predict = "y_prediction"
instance_id = self.random_string_generator()
analytics = Analytics()
analytics['ip'] = analytics.finding_ip()
analytics['mac'] = analytics.finding_address()
analytics['instance_id'] = instance_id
analytics['time'] = str(datetime.datetime.now())
analytics['total_columns'] = len(df.columns)
analytics['total_rows'] = len(df)
analytics['os'] = analytics.finding_system()
analytics['model_name'] = model_name
analytics["function"] = 'before_dashboard'
analytics["query"] = "before_dashboard"
analytics['finish_time'] = ''
analytics.insert_data()
# If yes, then different shap functuions are required.
# get the shap value based on predcton and make a new dataframe.
# find predictions first as shap values need that.
prediction_col = []
if model_name == 'h2o':
if isinstance(df, pd.DataFrame):
df = h2o.H2OFrame(df)
prediction_col = model.predict(df[y_column_name])
# is classification?
is_classification = True if model.type == 'classifier' else False
# shap
c = calculate_shap()
self.df_final, self.explainer = c.find(model, df, prediction_col, is_classification,
model_name=model_name)
# prediction col
self.df_final[y_variable_predict] = prediction_col.as_data_frame()[y_column_name].tolist()
self.df_final[y_variable] = df.as_data_frame()[y_column_name].tolist()
# additional inputs.
if is_classification is True:
# find and add probabilities in the dataset.
try:
prediction_col_prob = model.predict_proba(df)
except:
prediction_col_prob = model.predict(df)
prediction_col_prob = prediction_col_prob.as_data_frame()
pd_prediction_col_prob = pd.DataFrame(prediction_col_prob)
for c in pd_prediction_col_prob.columns:
self.df_final["probability_of_predicting_class_" + str(c)] = list(pd_prediction_col_prob[c])
classes = []
for c in pd_prediction_col_prob.columns:
classes.append(str(c))
self.param["classes"] = classes
try:
expected_values_by_class = self.explainer.expected_value
except:
expected_values_by_class = []
for c in range(len(classes)):
expected_values_by_class.append(1 / len(classes))
self.param["expected_values"] = expected_values_by_class
else:
try:
expected_values = self.explainer.expected_value
self.param["expected_values"] = [expected_values]
except:
expected_value = [round(np.array(y).mean(), 2)]
self.param["expected_values"] = expected_value
self.param["is_classification"] = is_classification
self.param["model_name"] = model_name
self.param["model"] = model
self.param["columns"] = df.columns
self.param["y_variable"] = y_variable
self.param["y_variable_predict"] = y_variable_predict
self.param['instance_id'] = instance_id
d = dashboard()
d.find(self.df_final, mode, self.param)
return True
def ai(self, df, y, model, model_name="xgboost", mode=None):
y_variable = "y_actual"
y_variable_predict = "y_prediction"
# Code for Analytics
instance_id = self.random_string_generator()
analytics = Analytics()
analytics['ip'] = analytics.finding_ip()
analytics['mac'] = analytics.finding_address()
analytics['instance_id'] = instance_id
analytics['time'] = str(datetime.datetime.now())
analytics['total_columns'] = len(df.columns)
analytics['total_rows'] = len(df)
analytics['os'] = analytics.finding_system()
analytics['model_name'] = model_name
analytics["function"] = 'before_dashboard'
analytics["query"] = "before_dashboard"
analytics['finish_time'] = ''
analytics.insert_data()
prediction_col = []
if model_name == "xgboost":
import xgboost
if xgboost.__version__ in ['1.1.0', '1.1.1', '1.1.0rc2', '1.1.0rc1']:
print(
"Current Xgboost version is not supported. Please install Xgboost using 'pip install xgboost==1.0.2'")
return False
prediction_col = model.predict(xgboost.DMatrix(df))
elif model_name == "catboost":
prediction_col = model.predict(df.to_numpy())
else:
prediction_col = model.predict(df)
# is classification?
# is_classification = self.is_classification_given_y_array(prediction_col)
ModelType = lambda model: True if is_classifier(model) else False
is_classification = ModelType(model)
# shap
c = calculate_shap()
self.df_final, self.explainer = c.find(model, df, prediction_col, is_classification, model_name=model_name)
# Append Model Decision & True Labels Columns into the dataset.
self.df_final[y_variable_predict] = prediction_col
self.df_final[y_variable] = y
# additional inputs.
if is_classification == True:
# find and add probabilities in the dataset.
# prediction_col_prob = model.predict_proba(df)
# pd_prediction_col_prob = pd.DataFrame(prediction_col_prob)
probabilities = model.predict_proba(df)
for i in range(len(np.unique(prediction_col))):
self.df_final['Probability: {}'.format(np.unique(prediction_col)[i])] = probabilities[:, i]
self.param['classes'] = np.unique(prediction_col)
# for c in pd_prediction_col_prob.columns:
# self.df_final["probability_of_predicting_class_" + str(c)] = list(pd_prediction_col_prob[c])
# classes = []
# for c in pd_prediction_col_prob.columns:
# classes.append(str(c))
# self.param["classes"] = classes
try:
expected_values_by_class = self.explainer.expected_value
except:
expected_values_by_class = []
for c in range(len(np.unique(prediction_col))):
expected_values_by_class.append(1 / len(np.unique(prediction_col)))
self.param["expected_values"] = expected_values_by_class
else:
try:
expected_values = self.explainer.expected_value
self.param["expected_values"] = [expected_values]
except:
expected_value = [round(np.array(y).mean(), 2)]
self.param["expected_values"] = expected_value
self.param["is_classification"] = is_classification
self.param["model_name"] = model_name
self.param["model"] = model
self.param["columns"] = df.columns
self.param["y_variable"] = y_variable
self.param["y_variable_predict"] = y_variable_predict
self.param['instance_id'] = instance_id
d = dashboard()
d.find(self.df_final, mode, self.param)
return True
def ai_test(self, df, y, model, model_name="xgboost", mode=None):
y_variable = "y_actual"
y_variable_predict = "y_prediction"
prediction_col = []
if model_name == "xgboost":
import xgboost
if xgboost.__version__ in ['1.1.0', '1.1.1', '1.1.0rc2', '1.1.0rc1']:
print(
"Current Xgboost version is not supported. Please install Xgboost using 'pip install xgboost==1.0.2'")
return False
prediction_col = model.predict(xgboost.DMatrix(df))
elif model_name == "catboost":
prediction_col = model.predict(df.to_numpy())
else:
prediction_col = model.predict(df.to_numpy())
# is classification?
is_classification = self.is_classification_given_y_array(prediction_col)
# shap
c = calculate_shap()
self.df_final, self.explainer = c.find(model, df, prediction_col, is_classification, model_name=model_name)
# prediction col
self.df_final[y_variable_predict] = prediction_col
self.df_final[y_variable] = y
# additional inputs.
if is_classification == True:
# find and add probabilities in the dataset.
prediction_col_prob = model.predict_proba(df.to_numpy())
pd_prediction_col_prob = pd.DataFrame(prediction_col_prob)
for c in pd_prediction_col_prob.columns:
self.df_final["Probability_" + str(c)] = list(pd_prediction_col_prob[c])
classes = []
for c in pd_prediction_col_prob.columns:
classes.append(str(c))
self.param["classes"] = classes
try:
expected_values_by_class = self.explainer.expected_value
except:
expected_values_by_class = []
for c in range(len(classes)):
expected_values_by_class.append(1 / len(classes))
self.param["expected_values"] = expected_values_by_class
else:
try:
expected_values = self.explainer.expected_value
self.param["expected_values"] = [expected_values]
except:
expected_value = [round(np.array(y).mean(), 2)]
self.param["expected_values"] = expected_value
self.param["is_classification"] = is_classification
self.param["model_name"] = model_name
self.param["model"] = model
self.param["columns"] = df.columns
self.param["y_variable"] = y_variable
self.param["y_variable_predict"] = y_variable_predict
# manually test all the graphs to see if all work
g = plotly_graphs()
__, df2 = g.feature_importance(self.df_final)
fim, df2 = g.feature_impact(self.df_final)
sp = g.summary_plot(self.df_final)
return True
def dataset_boston(self):
# load JS visualization code to notebook
shap.initjs()
X, y = shap.datasets.boston()
return X, y
def dataset_iris(self):
# load JS visualization code to notebook
shap.initjs()
X, y = shap.datasets.iris()
return X, y
def dataset_heloc(self):
dataset = pd.read_csv(path_dataset + "/heloc_dataset.csv")
map_riskperformance = {"RiskPerformance": {"Good": 1, "Bad": 0}}
dataset.replace(map_riskperformance, inplace=True)
y = list(dataset["RiskPerformance"])
X = dataset.drop("RiskPerformance", axis=1)
return X, y
def run_only_first_time(self):
if platform == "linux" or platform == "linux2":
try:
run_command("curl -sL https://rpm.nodesource.com/setup_10.x | sudo bash -")
run_command("sudo apt install nodejs")
run_command("sudo apt install npm")
except:
run_command("sudo yum install nodejs")
run_command("sudo yum install npm")
run_command("npm install -g localtunnel")
elif platform == "darwin":
run_command("xcode-select --install")
run_command("brew install nodejs")
run_command("npm install -g localtunnel")
elif platform == "win32":
print("Please install nodejs, npm, and localtunnel manually")
run_command("npm install -g localtunnel")
elif platform == "win64":
print("Please install nodejs, npm, and localtunnel manually")
run_command("npm install -g localtunnel")
explainx = explain()
def run_command(command):
# subdomain= 'explainx-'+ get_random_string(10)
command_arr = command.split(" ")
task = subprocess.Popen(command_arr,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid)
for line in iter(task.stdout.readline, b''):
print('{0}'.format(line.decode('utf-8')), end='')