mljar-supervised 1.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mljar_supervised-1.2.1.dist-info/METADATA +657 -0
- mljar_supervised-1.2.1.dist-info/RECORD +94 -0
- mljar_supervised-1.2.1.dist-info/WHEEL +5 -0
- mljar_supervised-1.2.1.dist-info/licenses/LICENSE +21 -0
- mljar_supervised-1.2.1.dist-info/top_level.txt +1 -0
- supervised/__init__.py +14 -0
- supervised/algorithms/__init__.py +0 -0
- supervised/algorithms/algorithm.py +151 -0
- supervised/algorithms/baseline.py +90 -0
- supervised/algorithms/catboost.py +436 -0
- supervised/algorithms/decision_tree.py +305 -0
- supervised/algorithms/extra_trees.py +176 -0
- supervised/algorithms/factory.py +28 -0
- supervised/algorithms/knn.py +137 -0
- supervised/algorithms/lightgbm.py +406 -0
- supervised/algorithms/linear.py +211 -0
- supervised/algorithms/nn.py +180 -0
- supervised/algorithms/random_forest.py +181 -0
- supervised/algorithms/registry.py +76 -0
- supervised/algorithms/sklearn.py +197 -0
- supervised/algorithms/xgboost.py +413 -0
- supervised/automl.py +568 -0
- supervised/base_automl.py +2542 -0
- supervised/callbacks/__init__.py +0 -0
- supervised/callbacks/callback.py +25 -0
- supervised/callbacks/callback_list.py +33 -0
- supervised/callbacks/early_stopping.py +213 -0
- supervised/callbacks/learner_time_constraint.py +47 -0
- supervised/callbacks/max_iters_constraint.py +16 -0
- supervised/callbacks/metric_logger.py +48 -0
- supervised/callbacks/terminate_on_nan.py +28 -0
- supervised/callbacks/total_time_constraint.py +79 -0
- supervised/ensemble.py +583 -0
- supervised/exceptions.py +21 -0
- supervised/fairness/__init__.py +0 -0
- supervised/fairness/metrics.py +654 -0
- supervised/fairness/optimization.py +414 -0
- supervised/fairness/plots.py +131 -0
- supervised/fairness/report.py +116 -0
- supervised/fairness/utils.py +40 -0
- supervised/model_framework.py +734 -0
- supervised/preprocessing/__init__.py +0 -0
- supervised/preprocessing/datetime_transformer.py +106 -0
- supervised/preprocessing/encoding_selector.py +30 -0
- supervised/preprocessing/exclude_missing_target.py +46 -0
- supervised/preprocessing/goldenfeatures_transformer.py +310 -0
- supervised/preprocessing/kmeans_transformer.py +115 -0
- supervised/preprocessing/label_binarizer.py +81 -0
- supervised/preprocessing/label_encoder.py +54 -0
- supervised/preprocessing/preprocessing.py +652 -0
- supervised/preprocessing/preprocessing_categorical.py +117 -0
- supervised/preprocessing/preprocessing_missing.py +97 -0
- supervised/preprocessing/preprocessing_utils.py +136 -0
- supervised/preprocessing/scale.py +92 -0
- supervised/preprocessing/text_transformer.py +73 -0
- supervised/tuner/__init__.py +0 -0
- supervised/tuner/data_info.py +64 -0
- supervised/tuner/hill_climbing.py +80 -0
- supervised/tuner/mljar_tuner.py +1501 -0
- supervised/tuner/optuna/__init__.py +0 -0
- supervised/tuner/optuna/catboost.py +148 -0
- supervised/tuner/optuna/extra_trees.py +80 -0
- supervised/tuner/optuna/knn.py +64 -0
- supervised/tuner/optuna/lightgbm.py +165 -0
- supervised/tuner/optuna/nn.py +66 -0
- supervised/tuner/optuna/random_forest.py +77 -0
- supervised/tuner/optuna/tuner.py +335 -0
- supervised/tuner/optuna/xgboost.py +130 -0
- supervised/tuner/preprocessing_tuner.py +137 -0
- supervised/tuner/random_parameters.py +22 -0
- supervised/tuner/time_controller.py +273 -0
- supervised/utils/__init__.py +11 -0
- supervised/utils/additional_metrics.py +955 -0
- supervised/utils/additional_plots.py +228 -0
- supervised/utils/automl_plots.py +368 -0
- supervised/utils/common.py +39 -0
- supervised/utils/config.py +25 -0
- supervised/utils/constants.py +4 -0
- supervised/utils/data_validation.py +48 -0
- supervised/utils/importance.py +93 -0
- supervised/utils/jsonencoder.py +33 -0
- supervised/utils/leaderboard_plots.py +137 -0
- supervised/utils/learning_curves.py +145 -0
- supervised/utils/metric.py +450 -0
- supervised/utils/report_structured.py +525 -0
- supervised/utils/shap.py +373 -0
- supervised/utils/subsample.py +17 -0
- supervised/utils/utils.py +29 -0
- supervised/validation/__init__.py +0 -0
- supervised/validation/validation_step.py +37 -0
- supervised/validation/validator_base.py +17 -0
- supervised/validation/validator_custom.py +112 -0
- supervised/validation/validator_kfold.py +153 -0
- supervised/validation/validator_split.py +143 -0
supervised/utils/shap.py
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
import matplotlib.pyplot as plt
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
shap_pacakge_available = False
|
|
8
|
+
try:
|
|
9
|
+
# I'm tired of all shap dependency hell
|
|
10
|
+
# ugh
|
|
11
|
+
import shap
|
|
12
|
+
shap_pacakge_available = True
|
|
13
|
+
except Exception:
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
from sklearn.preprocessing import OneHotEncoder
|
|
17
|
+
|
|
18
|
+
from supervised.algorithms.registry import (
|
|
19
|
+
BINARY_CLASSIFICATION,
|
|
20
|
+
MULTICLASS_CLASSIFICATION,
|
|
21
|
+
REGRESSION,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
from supervised.utils.config import LOG_LEVEL
|
|
26
|
+
|
|
27
|
+
logger.setLevel(LOG_LEVEL)
|
|
28
|
+
import warnings
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class PlotSHAP:
|
|
32
|
+
@staticmethod
|
|
33
|
+
def is_available(algorithm, X_train, y_train, ml_task):
|
|
34
|
+
if not shap_pacakge_available:
|
|
35
|
+
return False
|
|
36
|
+
# https://github.com/mljar/mljar-supervised/issues/112 disable for NN
|
|
37
|
+
# https://github.com/mljar/mljar-supervised/issues/114 disable for CatBoost
|
|
38
|
+
if algorithm.algorithm_short_name in ["Baseline", "Neural Network", "CatBoost"]:
|
|
39
|
+
return False
|
|
40
|
+
if (
|
|
41
|
+
algorithm.algorithm_short_name == "Xgboost"
|
|
42
|
+
and algorithm.learner_params["booster"] == "gblinear"
|
|
43
|
+
):
|
|
44
|
+
# Xgboost gblinear is not supported by SHAP
|
|
45
|
+
return False
|
|
46
|
+
# disable for large number of columns
|
|
47
|
+
if X_train.shape[1] > 500:
|
|
48
|
+
warnings.warn(
|
|
49
|
+
"Disable SHAP explanations because of number of columns > 500."
|
|
50
|
+
)
|
|
51
|
+
return False
|
|
52
|
+
if ml_task == MULTICLASS_CLASSIFICATION and len(np.unique(y_train)) > 100:
|
|
53
|
+
warnings.warn(
|
|
54
|
+
"Disable SHAP explanations because of large number of classes (> 100)."
|
|
55
|
+
)
|
|
56
|
+
return False
|
|
57
|
+
if X_train.shape[0] < 20:
|
|
58
|
+
warnings.warn(
|
|
59
|
+
"Disable SHAP explanations because of small number of samples (< 20)."
|
|
60
|
+
)
|
|
61
|
+
return False
|
|
62
|
+
return True
|
|
63
|
+
|
|
64
|
+
@staticmethod
|
|
65
|
+
def get_explainer(algorithm, X_train):
|
|
66
|
+
explainer = None
|
|
67
|
+
if algorithm.algorithm_short_name in [
|
|
68
|
+
"Xgboost",
|
|
69
|
+
"Decision Tree",
|
|
70
|
+
"Random Forest",
|
|
71
|
+
"LightGBM",
|
|
72
|
+
"Extra Trees",
|
|
73
|
+
"CatBoost",
|
|
74
|
+
]:
|
|
75
|
+
explainer = shap.TreeExplainer(algorithm.model)
|
|
76
|
+
elif algorithm.algorithm_short_name in ["Linear"]:
|
|
77
|
+
explainer = shap.LinearExplainer(algorithm.model, X_train)
|
|
78
|
+
# elif algorithm.algorithm_short_name in ["Neural Network"]:
|
|
79
|
+
# explainer = shap.KernelExplainer(algorithm.model.predict, X_train) # slow
|
|
80
|
+
|
|
81
|
+
return explainer
|
|
82
|
+
|
|
83
|
+
@staticmethod
|
|
84
|
+
def get_sample(X_validation, y_validation):
|
|
85
|
+
# too many samples in the data, down-sample it
|
|
86
|
+
SAMPLES_LIMIT = 1000
|
|
87
|
+
if X_validation.shape[0] > SAMPLES_LIMIT:
|
|
88
|
+
X_validation.reset_index(inplace=True, drop=True)
|
|
89
|
+
y_validation.reset_index(inplace=True, drop=True)
|
|
90
|
+
X_vald = X_validation.sample(SAMPLES_LIMIT)
|
|
91
|
+
y_vald = y_validation[X_vald.index]
|
|
92
|
+
else:
|
|
93
|
+
X_vald = X_validation
|
|
94
|
+
y_vald = y_validation
|
|
95
|
+
return X_vald, y_vald
|
|
96
|
+
|
|
97
|
+
def get_predictions(algorithm, X_vald, y_vald, ml_task):
|
|
98
|
+
# compute predictions on down-sampled data
|
|
99
|
+
predictions = algorithm.predict(X_vald)
|
|
100
|
+
|
|
101
|
+
if ml_task == MULTICLASS_CLASSIFICATION:
|
|
102
|
+
oh = OneHotEncoder(sparse_output=False)
|
|
103
|
+
y_encoded = oh.fit_transform(np.array(y_vald).reshape(-1, 1))
|
|
104
|
+
residua = np.sum(np.abs(np.array(y_encoded) - predictions), axis=1)
|
|
105
|
+
else:
|
|
106
|
+
residua = np.abs(np.array(y_vald) - predictions)
|
|
107
|
+
|
|
108
|
+
df_preds = pd.DataFrame(
|
|
109
|
+
{"res": residua, "lp": range(residua.shape[0]), "target": np.array(y_vald)},
|
|
110
|
+
index=X_vald.index,
|
|
111
|
+
)
|
|
112
|
+
df_preds = df_preds.sort_values(by="res", ascending=False)
|
|
113
|
+
|
|
114
|
+
return df_preds
|
|
115
|
+
|
|
116
|
+
@staticmethod
|
|
117
|
+
def summary(shap_values, X_vald, model_file_path, learner_name, class_names):
|
|
118
|
+
fig = plt.gcf()
|
|
119
|
+
classes = None
|
|
120
|
+
if class_names is not None and len(class_names):
|
|
121
|
+
classes = class_names
|
|
122
|
+
with warnings.catch_warnings():
|
|
123
|
+
warnings.simplefilter("ignore")
|
|
124
|
+
shap.summary_plot(
|
|
125
|
+
shap_values, X_vald, plot_type="bar", show=False, class_names=classes
|
|
126
|
+
)
|
|
127
|
+
fig.tight_layout(pad=2.0)
|
|
128
|
+
fig.savefig(os.path.join(model_file_path, f"{learner_name}_shap_summary.png"))
|
|
129
|
+
plt.close("all")
|
|
130
|
+
|
|
131
|
+
vals = None
|
|
132
|
+
if isinstance(shap_values, list):
|
|
133
|
+
for sh in shap_values:
|
|
134
|
+
v = np.abs(sh).mean(0)
|
|
135
|
+
vals = v if vals is None else vals + v
|
|
136
|
+
else:
|
|
137
|
+
vals = np.abs(shap_values).mean(0)
|
|
138
|
+
feature_importance = pd.DataFrame(
|
|
139
|
+
list(zip(X_vald.columns, vals)), columns=["feature", "shap_importance"]
|
|
140
|
+
)
|
|
141
|
+
feature_importance.sort_values(
|
|
142
|
+
by=["shap_importance"], ascending=False, inplace=True
|
|
143
|
+
)
|
|
144
|
+
feature_importance.to_csv(
|
|
145
|
+
os.path.join(model_file_path, f"{learner_name}_shap_importance.csv"),
|
|
146
|
+
index=False,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
@staticmethod
|
|
150
|
+
def dependence(shap_values, X_vald, model_file_path, learner_name, file_postfix=""):
|
|
151
|
+
with warnings.catch_warnings():
|
|
152
|
+
warnings.simplefilter("ignore")
|
|
153
|
+
fig = plt.figure(figsize=(14, 7))
|
|
154
|
+
plots_cnt = np.min([9, X_vald.shape[1]])
|
|
155
|
+
cols_cnt = 3
|
|
156
|
+
rows_cnt = 3
|
|
157
|
+
if plots_cnt < 4:
|
|
158
|
+
rows_cnt = 1
|
|
159
|
+
elif plots_cnt < 7:
|
|
160
|
+
rows_cnt = 2
|
|
161
|
+
for i in range(plots_cnt):
|
|
162
|
+
ax = fig.add_subplot(rows_cnt, cols_cnt, i + 1)
|
|
163
|
+
shap.dependence_plot(
|
|
164
|
+
f"rank({i})",
|
|
165
|
+
shap_values,
|
|
166
|
+
X_vald,
|
|
167
|
+
show=False,
|
|
168
|
+
title=f"Importance #{i+1}",
|
|
169
|
+
ax=ax,
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
fig.tight_layout(pad=2.0)
|
|
173
|
+
fig.savefig(
|
|
174
|
+
os.path.join(
|
|
175
|
+
model_file_path, f"{learner_name}_shap_dependence{file_postfix}.png"
|
|
176
|
+
)
|
|
177
|
+
)
|
|
178
|
+
plt.close("all")
|
|
179
|
+
|
|
180
|
+
@staticmethod
|
|
181
|
+
def compute(
|
|
182
|
+
algorithm,
|
|
183
|
+
X_train,
|
|
184
|
+
y_train,
|
|
185
|
+
X_validation,
|
|
186
|
+
y_validation,
|
|
187
|
+
model_file_path,
|
|
188
|
+
learner_name,
|
|
189
|
+
class_names,
|
|
190
|
+
ml_task,
|
|
191
|
+
):
|
|
192
|
+
if not PlotSHAP.is_available(algorithm, X_train, y_train, ml_task):
|
|
193
|
+
return
|
|
194
|
+
try:
|
|
195
|
+
with warnings.catch_warnings():
|
|
196
|
+
warnings.simplefilter("ignore")
|
|
197
|
+
explainer = PlotSHAP.get_explainer(algorithm, X_train)
|
|
198
|
+
X_vald, y_vald = PlotSHAP.get_sample(X_validation, y_validation)
|
|
199
|
+
shap_values = explainer.shap_values(X_vald)
|
|
200
|
+
|
|
201
|
+
# fix problem with 1 or 2 dimensions for binary classification
|
|
202
|
+
expected_value = explainer.expected_value
|
|
203
|
+
if ml_task == BINARY_CLASSIFICATION and isinstance(shap_values, list):
|
|
204
|
+
shap_values = shap_values[1]
|
|
205
|
+
expected_value = explainer.expected_value[1]
|
|
206
|
+
|
|
207
|
+
# Summary SHAP plot
|
|
208
|
+
PlotSHAP.summary(
|
|
209
|
+
shap_values, X_vald, model_file_path, learner_name, class_names
|
|
210
|
+
)
|
|
211
|
+
# Dependence SHAP plots
|
|
212
|
+
if ml_task == MULTICLASS_CLASSIFICATION:
|
|
213
|
+
for t in np.unique(y_vald):
|
|
214
|
+
PlotSHAP.dependence(
|
|
215
|
+
shap_values[t],
|
|
216
|
+
X_vald,
|
|
217
|
+
model_file_path,
|
|
218
|
+
learner_name,
|
|
219
|
+
f"_class_{class_names[t]}",
|
|
220
|
+
)
|
|
221
|
+
else:
|
|
222
|
+
PlotSHAP.dependence(shap_values, X_vald, model_file_path, learner_name)
|
|
223
|
+
|
|
224
|
+
# Decision SHAP plots
|
|
225
|
+
df_preds = PlotSHAP.get_predictions(algorithm, X_vald, y_vald, ml_task)
|
|
226
|
+
|
|
227
|
+
if ml_task == REGRESSION:
|
|
228
|
+
PlotSHAP.decisions_regression(
|
|
229
|
+
df_preds,
|
|
230
|
+
shap_values,
|
|
231
|
+
expected_value,
|
|
232
|
+
X_vald,
|
|
233
|
+
y_vald,
|
|
234
|
+
model_file_path,
|
|
235
|
+
learner_name,
|
|
236
|
+
)
|
|
237
|
+
elif ml_task == BINARY_CLASSIFICATION:
|
|
238
|
+
PlotSHAP.decisions_binary(
|
|
239
|
+
df_preds,
|
|
240
|
+
shap_values,
|
|
241
|
+
expected_value,
|
|
242
|
+
X_vald,
|
|
243
|
+
y_vald,
|
|
244
|
+
model_file_path,
|
|
245
|
+
learner_name,
|
|
246
|
+
)
|
|
247
|
+
else:
|
|
248
|
+
PlotSHAP.decisions_multiclass(
|
|
249
|
+
df_preds,
|
|
250
|
+
shap_values,
|
|
251
|
+
expected_value,
|
|
252
|
+
X_vald,
|
|
253
|
+
y_vald,
|
|
254
|
+
model_file_path,
|
|
255
|
+
learner_name,
|
|
256
|
+
class_names,
|
|
257
|
+
)
|
|
258
|
+
except Exception as e:
|
|
259
|
+
pass
|
|
260
|
+
# print(
|
|
261
|
+
# f"Exception while producing SHAP explanations. {str(e)}\nContinuing ..."
|
|
262
|
+
# )
|
|
263
|
+
|
|
264
|
+
@staticmethod
|
|
265
|
+
def decisions_regression(
|
|
266
|
+
df_preds,
|
|
267
|
+
shap_values,
|
|
268
|
+
expected_value,
|
|
269
|
+
X_vald,
|
|
270
|
+
y_vald,
|
|
271
|
+
model_file_path,
|
|
272
|
+
learner_name,
|
|
273
|
+
):
|
|
274
|
+
fig = plt.gcf()
|
|
275
|
+
shap.decision_plot(
|
|
276
|
+
expected_value,
|
|
277
|
+
shap_values[df_preds.lp[:10], :],
|
|
278
|
+
X_vald.loc[df_preds.index[:10]],
|
|
279
|
+
show=False,
|
|
280
|
+
)
|
|
281
|
+
fig.tight_layout(pad=2.0)
|
|
282
|
+
fig.savefig(
|
|
283
|
+
os.path.join(model_file_path, f"{learner_name}_shap_worst_decisions.png")
|
|
284
|
+
)
|
|
285
|
+
plt.close("all")
|
|
286
|
+
|
|
287
|
+
fig = plt.gcf()
|
|
288
|
+
shap.decision_plot(
|
|
289
|
+
expected_value,
|
|
290
|
+
shap_values[df_preds.lp[-10:], :],
|
|
291
|
+
X_vald.loc[df_preds.index[-10:]],
|
|
292
|
+
show=False,
|
|
293
|
+
)
|
|
294
|
+
fig.tight_layout(pad=2.0)
|
|
295
|
+
fig.savefig(
|
|
296
|
+
os.path.join(model_file_path, f"{learner_name}_shap_best_decisions.png")
|
|
297
|
+
)
|
|
298
|
+
plt.close("all")
|
|
299
|
+
|
|
300
|
+
@staticmethod
|
|
301
|
+
def decisions_binary(
|
|
302
|
+
df_preds,
|
|
303
|
+
shap_values,
|
|
304
|
+
expected_value,
|
|
305
|
+
X_vald,
|
|
306
|
+
y_vald,
|
|
307
|
+
model_file_path,
|
|
308
|
+
learner_name,
|
|
309
|
+
):
|
|
310
|
+
# classes are from 0 ...
|
|
311
|
+
for t in np.unique(y_vald):
|
|
312
|
+
fig = plt.gcf()
|
|
313
|
+
shap.decision_plot(
|
|
314
|
+
expected_value,
|
|
315
|
+
shap_values[df_preds[df_preds.target == t].lp[:10], :],
|
|
316
|
+
X_vald.loc[df_preds[df_preds.target == t].index[:10]],
|
|
317
|
+
show=False,
|
|
318
|
+
)
|
|
319
|
+
fig.tight_layout(pad=2.0)
|
|
320
|
+
fig.savefig(
|
|
321
|
+
os.path.join(
|
|
322
|
+
model_file_path,
|
|
323
|
+
f"{learner_name}_shap_class_{t}_worst_decisions.png",
|
|
324
|
+
)
|
|
325
|
+
)
|
|
326
|
+
plt.close("all")
|
|
327
|
+
|
|
328
|
+
fig = plt.gcf()
|
|
329
|
+
shap.decision_plot(
|
|
330
|
+
expected_value,
|
|
331
|
+
shap_values[df_preds[df_preds.target == t].lp[-10:], :],
|
|
332
|
+
X_vald.loc[df_preds[df_preds.target == t].index[-10:]],
|
|
333
|
+
show=False,
|
|
334
|
+
)
|
|
335
|
+
fig.tight_layout(pad=2.0)
|
|
336
|
+
fig.savefig(
|
|
337
|
+
os.path.join(
|
|
338
|
+
model_file_path, f"{learner_name}_shap_class_{t}_best_decisions.png"
|
|
339
|
+
)
|
|
340
|
+
)
|
|
341
|
+
plt.close("all")
|
|
342
|
+
|
|
343
|
+
@staticmethod
|
|
344
|
+
def decisions_multiclass(
|
|
345
|
+
df_preds,
|
|
346
|
+
shap_values,
|
|
347
|
+
expected_value,
|
|
348
|
+
X_vald,
|
|
349
|
+
y_vald,
|
|
350
|
+
model_file_path,
|
|
351
|
+
learner_name,
|
|
352
|
+
class_names,
|
|
353
|
+
):
|
|
354
|
+
for decision_type in ["worst", "best"]:
|
|
355
|
+
m = 1 if decision_type == "worst" else -1
|
|
356
|
+
for i in range(4):
|
|
357
|
+
fig = plt.gcf()
|
|
358
|
+
shap.multioutput_decision_plot(
|
|
359
|
+
list(expected_value),
|
|
360
|
+
shap_values,
|
|
361
|
+
row_index=df_preds.lp.iloc[m * i],
|
|
362
|
+
show=False,
|
|
363
|
+
legend_labels=class_names,
|
|
364
|
+
title=f"It should be {class_names[df_preds.target.iloc[m*i]]}",
|
|
365
|
+
)
|
|
366
|
+
fig.tight_layout(pad=2.0)
|
|
367
|
+
fig.savefig(
|
|
368
|
+
os.path.join(
|
|
369
|
+
model_file_path,
|
|
370
|
+
f"{learner_name}_sample_{i}_{decision_type}_decisions.png",
|
|
371
|
+
)
|
|
372
|
+
)
|
|
373
|
+
plt.close("all")
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from sklearn.model_selection import train_test_split
|
|
2
|
+
|
|
3
|
+
from supervised.algorithms.registry import REGRESSION
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def subsample(X, y, ml_task, train_size):
|
|
7
|
+
shuffle = True
|
|
8
|
+
stratify = None
|
|
9
|
+
|
|
10
|
+
if ml_task != REGRESSION:
|
|
11
|
+
stratify = y
|
|
12
|
+
|
|
13
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
14
|
+
X, y, train_size=train_size, shuffle=shuffle, stratify=stratify
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
return X_train, X_test, y_train, y_test
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Store:
|
|
5
|
+
data = {}
|
|
6
|
+
|
|
7
|
+
def set(self, key, value):
|
|
8
|
+
Store.data[key] = value
|
|
9
|
+
|
|
10
|
+
def get(self, key):
|
|
11
|
+
return copy.deepcopy(Store.data[key])
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def dump_data(file_path, df):
|
|
15
|
+
store = Store()
|
|
16
|
+
store.set(file_path, df)
|
|
17
|
+
# try:
|
|
18
|
+
# df.to_parquet(file_path, index=False)
|
|
19
|
+
# except Exception as e:
|
|
20
|
+
# df.to_csv(file_path, index=False)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def load_data(file_path):
|
|
24
|
+
store = Store()
|
|
25
|
+
return store.get(file_path)
|
|
26
|
+
# try:
|
|
27
|
+
# return pd.read_parquet(file_path)
|
|
28
|
+
# except Exception as e:
|
|
29
|
+
# return pd.read_csv(file_path)
|
|
File without changes
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
log = logging.getLogger(__name__)
|
|
4
|
+
|
|
5
|
+
from supervised.exceptions import AutoMLException
|
|
6
|
+
from supervised.validation.validator_custom import CustomValidator
|
|
7
|
+
from supervised.validation.validator_kfold import KFoldValidator
|
|
8
|
+
from supervised.validation.validator_split import SplitValidator
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ValidationStep:
|
|
12
|
+
def __init__(self, params):
|
|
13
|
+
# kfold is default validation technique
|
|
14
|
+
self.validation_type = params.get("validation_type", "kfold")
|
|
15
|
+
|
|
16
|
+
if self.validation_type == "kfold":
|
|
17
|
+
self.validator = KFoldValidator(params)
|
|
18
|
+
elif self.validation_type == "split":
|
|
19
|
+
self.validator = SplitValidator(params)
|
|
20
|
+
elif self.validation_type == "custom":
|
|
21
|
+
self.validator = CustomValidator(params)
|
|
22
|
+
else:
|
|
23
|
+
raise AutoMLException(
|
|
24
|
+
f"The validation type ({self.validation_type}) is not implemented."
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
def get_split(self, k, repeat=0):
|
|
28
|
+
return self.validator.get_split(k, repeat)
|
|
29
|
+
|
|
30
|
+
def split(self):
|
|
31
|
+
return self.validator.split()
|
|
32
|
+
|
|
33
|
+
def get_n_splits(self):
|
|
34
|
+
return self.validator.get_n_splits()
|
|
35
|
+
|
|
36
|
+
def get_repeats(self):
|
|
37
|
+
return self.validator.get_repeats()
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
log = logging.getLogger(__name__)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class BaseValidator(object):
|
|
7
|
+
def __init__(self, params):
|
|
8
|
+
self.params = params
|
|
9
|
+
|
|
10
|
+
def split(self):
|
|
11
|
+
pass
|
|
12
|
+
|
|
13
|
+
def get_n_splits(self):
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
def get_repeats(self):
|
|
17
|
+
return 1
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
import joblib
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
log = logging.getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
from supervised.exceptions import AutoMLException
|
|
10
|
+
from supervised.utils.utils import load_data
|
|
11
|
+
from supervised.validation.validator_base import BaseValidator
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CustomValidator(BaseValidator):
|
|
15
|
+
def __init__(self, params):
|
|
16
|
+
BaseValidator.__init__(self, params)
|
|
17
|
+
|
|
18
|
+
cv_path = self.params.get("cv_path")
|
|
19
|
+
|
|
20
|
+
if cv_path is None:
|
|
21
|
+
raise AutoMLException("You need to specify `cv` as list or iterable")
|
|
22
|
+
|
|
23
|
+
self.cv = joblib.load(cv_path)
|
|
24
|
+
self.cv = list(self.cv)
|
|
25
|
+
|
|
26
|
+
self._results_path = self.params.get("results_path")
|
|
27
|
+
self._X_path = self.params.get("X_path")
|
|
28
|
+
self._y_path = self.params.get("y_path")
|
|
29
|
+
self._sample_weight_path = self.params.get("sample_weight_path")
|
|
30
|
+
self._sensitive_features_path = self.params.get("sensitive_features_path")
|
|
31
|
+
|
|
32
|
+
if self._X_path is None or self._y_path is None:
|
|
33
|
+
raise AutoMLException("No data path set in CustomValidator params")
|
|
34
|
+
|
|
35
|
+
folds_path = os.path.join(self._results_path, "folds")
|
|
36
|
+
|
|
37
|
+
if not os.path.exists(folds_path):
|
|
38
|
+
os.mkdir(folds_path)
|
|
39
|
+
|
|
40
|
+
print("Custom validation strategy")
|
|
41
|
+
for fold_cnt, (train_index, validation_index) in enumerate(self.cv):
|
|
42
|
+
print(f"Split {fold_cnt}.")
|
|
43
|
+
print(f"Train {train_index.shape[0]} samples.")
|
|
44
|
+
print(f"Validation {validation_index.shape[0]} samples.")
|
|
45
|
+
train_index_file = os.path.join(
|
|
46
|
+
self._results_path,
|
|
47
|
+
"folds",
|
|
48
|
+
f"fold_{fold_cnt}_train_indices.npy",
|
|
49
|
+
)
|
|
50
|
+
validation_index_file = os.path.join(
|
|
51
|
+
self._results_path,
|
|
52
|
+
"folds",
|
|
53
|
+
f"fold_{fold_cnt}_validation_indices.npy",
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
np.save(train_index_file, train_index)
|
|
57
|
+
np.save(validation_index_file, validation_index)
|
|
58
|
+
|
|
59
|
+
else:
|
|
60
|
+
log.debug("Folds split already done, reuse it")
|
|
61
|
+
|
|
62
|
+
def get_split(self, k, repeat=0):
|
|
63
|
+
try:
|
|
64
|
+
train_index_file = os.path.join(
|
|
65
|
+
self._results_path, "folds", f"fold_{k}_train_indices.npy"
|
|
66
|
+
)
|
|
67
|
+
validation_index_file = os.path.join(
|
|
68
|
+
self._results_path, "folds", f"fold_{k}_validation_indices.npy"
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
train_index = np.load(train_index_file)
|
|
72
|
+
validation_index = np.load(validation_index_file)
|
|
73
|
+
|
|
74
|
+
X = load_data(self._X_path)
|
|
75
|
+
y = load_data(self._y_path)
|
|
76
|
+
y = y["target"]
|
|
77
|
+
|
|
78
|
+
sample_weight = None
|
|
79
|
+
if self._sample_weight_path is not None:
|
|
80
|
+
sample_weight = load_data(self._sample_weight_path)
|
|
81
|
+
sample_weight = sample_weight["sample_weight"]
|
|
82
|
+
|
|
83
|
+
sensitive_features = None
|
|
84
|
+
if self._sensitive_features_path is not None:
|
|
85
|
+
sensitive_features = load_data(self._sensitive_features_path)
|
|
86
|
+
|
|
87
|
+
train_data = {"X": X.iloc[train_index], "y": y.iloc[train_index]}
|
|
88
|
+
validation_data = {
|
|
89
|
+
"X": X.iloc[validation_index],
|
|
90
|
+
"y": y.iloc[validation_index],
|
|
91
|
+
}
|
|
92
|
+
if sample_weight is not None:
|
|
93
|
+
train_data["sample_weight"] = sample_weight.iloc[train_index]
|
|
94
|
+
validation_data["sample_weight"] = sample_weight.iloc[validation_index]
|
|
95
|
+
if sensitive_features is not None:
|
|
96
|
+
train_data["sensitive_features"] = sensitive_features.iloc[train_index]
|
|
97
|
+
validation_data["sensitive_features"] = sensitive_features.iloc[
|
|
98
|
+
validation_index
|
|
99
|
+
]
|
|
100
|
+
|
|
101
|
+
except Exception as e:
|
|
102
|
+
import traceback
|
|
103
|
+
|
|
104
|
+
print(traceback.format_exc())
|
|
105
|
+
raise AutoMLException("Problem with custom validation. " + str(e))
|
|
106
|
+
return (train_data, validation_data)
|
|
107
|
+
|
|
108
|
+
def get_n_splits(self):
|
|
109
|
+
return len(self.cv)
|
|
110
|
+
|
|
111
|
+
def get_repeats(self):
|
|
112
|
+
return 1
|