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
|
@@ -0,0 +1,652 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
|
|
6
|
+
from supervised.algorithms.registry import (
|
|
7
|
+
BINARY_CLASSIFICATION,
|
|
8
|
+
MULTICLASS_CLASSIFICATION,
|
|
9
|
+
)
|
|
10
|
+
from supervised.exceptions import AutoMLException
|
|
11
|
+
from supervised.preprocessing.datetime_transformer import DateTimeTransformer
|
|
12
|
+
from supervised.preprocessing.exclude_missing_target import ExcludeRowsMissingTarget
|
|
13
|
+
from supervised.preprocessing.goldenfeatures_transformer import (
|
|
14
|
+
GoldenFeaturesTransformer,
|
|
15
|
+
)
|
|
16
|
+
from supervised.preprocessing.kmeans_transformer import KMeansTransformer
|
|
17
|
+
from supervised.preprocessing.label_binarizer import LabelBinarizer
|
|
18
|
+
from supervised.preprocessing.label_encoder import LabelEncoder
|
|
19
|
+
from supervised.preprocessing.preprocessing_categorical import PreprocessingCategorical
|
|
20
|
+
from supervised.preprocessing.preprocessing_missing import PreprocessingMissingValues
|
|
21
|
+
from supervised.preprocessing.scale import Scale
|
|
22
|
+
from supervised.preprocessing.text_transformer import TextTransformer
|
|
23
|
+
from supervised.utils.config import LOG_LEVEL
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
logger.setLevel(LOG_LEVEL)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Preprocessing(object):
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
preprocessing_params={"target_preprocessing": [], "columns_preprocessing": {}},
|
|
33
|
+
model_name=None,
|
|
34
|
+
k_fold=None,
|
|
35
|
+
repeat=None,
|
|
36
|
+
):
|
|
37
|
+
self._params = preprocessing_params
|
|
38
|
+
|
|
39
|
+
if "target_preprocessing" not in preprocessing_params:
|
|
40
|
+
self._params["target_preprocessing"] = []
|
|
41
|
+
if "columns_preprocessing" not in preprocessing_params:
|
|
42
|
+
self._params["columns_preprocessing"] = {}
|
|
43
|
+
|
|
44
|
+
# preprocssing step attributes
|
|
45
|
+
self._categorical_y = None
|
|
46
|
+
self._scale_y = None
|
|
47
|
+
self._missing_values = []
|
|
48
|
+
self._categorical = []
|
|
49
|
+
self._scale = []
|
|
50
|
+
self._remove_columns = []
|
|
51
|
+
self._datetime_transforms = []
|
|
52
|
+
self._text_transforms = []
|
|
53
|
+
self._golden_features = None
|
|
54
|
+
self._kmeans = None
|
|
55
|
+
self._add_random_feature = self._params.get("add_random_feature", False)
|
|
56
|
+
self._drop_features = self._params.get("drop_features", [])
|
|
57
|
+
self._model_name = model_name
|
|
58
|
+
self._k_fold = k_fold
|
|
59
|
+
self._repeat = repeat
|
|
60
|
+
|
|
61
|
+
def _exclude_missing_targets(self, X=None, y=None):
|
|
62
|
+
# check if there are missing values in target column
|
|
63
|
+
if y is None:
|
|
64
|
+
return X, y
|
|
65
|
+
y_missing = pd.isnull(y)
|
|
66
|
+
if np.sum(np.array(y_missing)) == 0:
|
|
67
|
+
return X, y
|
|
68
|
+
y = y.drop(y.index[y_missing])
|
|
69
|
+
y.index = range(y.shape[0])
|
|
70
|
+
if X is not None:
|
|
71
|
+
X = X.drop(X.index[y_missing])
|
|
72
|
+
X.index = range(X.shape[0])
|
|
73
|
+
return X, y
|
|
74
|
+
|
|
75
|
+
# fit and transform
|
|
76
|
+
def fit_and_transform(self, X_train, y_train, sample_weight=None):
|
|
77
|
+
logger.debug("Preprocessing.fit_and_transform")
|
|
78
|
+
|
|
79
|
+
if y_train is not None:
|
|
80
|
+
# target preprocessing
|
|
81
|
+
# this must be used first, maybe we will drop some rows because of missing target values
|
|
82
|
+
target_preprocessing = self._params.get("target_preprocessing")
|
|
83
|
+
logger.debug("target_preprocessing params: {}".format(target_preprocessing))
|
|
84
|
+
|
|
85
|
+
X_train, y_train, sample_weight, _ = ExcludeRowsMissingTarget.transform(
|
|
86
|
+
X_train, y_train, sample_weight
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
if PreprocessingCategorical.CONVERT_INTEGER in target_preprocessing:
|
|
90
|
+
logger.debug("Convert target to integer")
|
|
91
|
+
self._categorical_y = LabelEncoder(try_to_fit_numeric=True)
|
|
92
|
+
self._categorical_y.fit(y_train)
|
|
93
|
+
y_train = pd.Series(self._categorical_y.transform(y_train))
|
|
94
|
+
|
|
95
|
+
if PreprocessingCategorical.CONVERT_ONE_HOT in target_preprocessing:
|
|
96
|
+
logger.debug("Convert target to one-hot coding")
|
|
97
|
+
self._categorical_y = LabelBinarizer()
|
|
98
|
+
self._categorical_y.fit(pd.DataFrame({"target": y_train}), "target")
|
|
99
|
+
y_train = self._categorical_y.transform(
|
|
100
|
+
pd.DataFrame({"target": y_train}), "target"
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
if Scale.SCALE_LOG_AND_NORMAL in target_preprocessing:
|
|
104
|
+
logger.debug("Scale log and normal")
|
|
105
|
+
|
|
106
|
+
self._scale_y = Scale(
|
|
107
|
+
["target"], scale_method=Scale.SCALE_LOG_AND_NORMAL
|
|
108
|
+
)
|
|
109
|
+
y_train = pd.DataFrame({"target": y_train})
|
|
110
|
+
self._scale_y.fit(y_train)
|
|
111
|
+
y_train = self._scale_y.transform(y_train)
|
|
112
|
+
y_train = y_train["target"]
|
|
113
|
+
|
|
114
|
+
if Scale.SCALE_NORMAL in target_preprocessing:
|
|
115
|
+
logger.debug("Scale normal")
|
|
116
|
+
|
|
117
|
+
self._scale_y = Scale(["target"], scale_method=Scale.SCALE_NORMAL)
|
|
118
|
+
y_train = pd.DataFrame({"target": y_train})
|
|
119
|
+
self._scale_y.fit(y_train)
|
|
120
|
+
y_train = self._scale_y.transform(y_train)
|
|
121
|
+
y_train = y_train["target"]
|
|
122
|
+
|
|
123
|
+
# columns preprocessing
|
|
124
|
+
columns_preprocessing = self._params.get("columns_preprocessing")
|
|
125
|
+
for column in columns_preprocessing:
|
|
126
|
+
transforms = columns_preprocessing[column]
|
|
127
|
+
# logger.debug("Preprocess column {} with: {}".format(column, transforms))
|
|
128
|
+
|
|
129
|
+
# remove empty or constant columns
|
|
130
|
+
cols_to_remove = list(
|
|
131
|
+
filter(
|
|
132
|
+
lambda k: "remove_column" in columns_preprocessing[k],
|
|
133
|
+
columns_preprocessing,
|
|
134
|
+
)
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
if X_train is not None:
|
|
138
|
+
X_train.drop(cols_to_remove, axis=1, inplace=True)
|
|
139
|
+
self._remove_columns = cols_to_remove
|
|
140
|
+
|
|
141
|
+
numeric_cols = [] # get numeric cols before text transformations
|
|
142
|
+
# needed for golden features
|
|
143
|
+
if X_train is not None and (
|
|
144
|
+
"golden_features" in self._params or "kmeans_features" in self._params
|
|
145
|
+
):
|
|
146
|
+
numeric_cols = X_train.select_dtypes(include="number").columns.tolist()
|
|
147
|
+
|
|
148
|
+
# there can be missing values in the text data,
|
|
149
|
+
# but we don't want to handle it by fill missing methods
|
|
150
|
+
# zeros will be imputed by text_transform method
|
|
151
|
+
cols_to_process = list(
|
|
152
|
+
filter(
|
|
153
|
+
lambda k: "text_transform" in columns_preprocessing[k],
|
|
154
|
+
columns_preprocessing,
|
|
155
|
+
)
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
new_text_columns = []
|
|
159
|
+
for col in cols_to_process:
|
|
160
|
+
t = TextTransformer()
|
|
161
|
+
t.fit(X_train, col)
|
|
162
|
+
X_train = t.transform(X_train)
|
|
163
|
+
self._text_transforms += [t]
|
|
164
|
+
new_text_columns += t._new_columns
|
|
165
|
+
# end of text transform
|
|
166
|
+
|
|
167
|
+
for missing_method in [PreprocessingMissingValues.FILL_NA_MEDIAN]:
|
|
168
|
+
cols_to_process = list(
|
|
169
|
+
filter(
|
|
170
|
+
lambda k: missing_method in columns_preprocessing[k],
|
|
171
|
+
columns_preprocessing,
|
|
172
|
+
)
|
|
173
|
+
)
|
|
174
|
+
missing = PreprocessingMissingValues(cols_to_process, missing_method)
|
|
175
|
+
missing.fit(X_train)
|
|
176
|
+
X_train = missing.transform(X_train)
|
|
177
|
+
self._missing_values += [missing]
|
|
178
|
+
|
|
179
|
+
# golden features
|
|
180
|
+
golden_columns = []
|
|
181
|
+
if "golden_features" in self._params:
|
|
182
|
+
results_path = self._params["golden_features"]["results_path"]
|
|
183
|
+
ml_task = self._params["golden_features"]["ml_task"]
|
|
184
|
+
features_count = self._params["golden_features"].get("features_count")
|
|
185
|
+
n_jobs = self._params["golden_features"].get("n_jobs", -1)
|
|
186
|
+
self._golden_features = GoldenFeaturesTransformer(
|
|
187
|
+
results_path, ml_task, features_count, n_jobs
|
|
188
|
+
)
|
|
189
|
+
self._golden_features.fit(X_train[numeric_cols], y_train)
|
|
190
|
+
X_train = self._golden_features.transform(X_train)
|
|
191
|
+
golden_columns = self._golden_features._new_columns
|
|
192
|
+
|
|
193
|
+
kmeans_columns = []
|
|
194
|
+
if "kmeans_features" in self._params:
|
|
195
|
+
results_path = self._params["kmeans_features"]["results_path"]
|
|
196
|
+
self._kmeans = KMeansTransformer(
|
|
197
|
+
results_path, self._model_name, self._k_fold
|
|
198
|
+
)
|
|
199
|
+
self._kmeans.fit(X_train[numeric_cols], y_train)
|
|
200
|
+
X_train = self._kmeans.transform(X_train)
|
|
201
|
+
kmeans_columns = self._kmeans._new_features
|
|
202
|
+
|
|
203
|
+
for convert_method in [
|
|
204
|
+
PreprocessingCategorical.CONVERT_INTEGER,
|
|
205
|
+
PreprocessingCategorical.CONVERT_ONE_HOT
|
|
206
|
+
]:
|
|
207
|
+
cols_to_process = list(
|
|
208
|
+
filter(
|
|
209
|
+
lambda k: convert_method in columns_preprocessing[k],
|
|
210
|
+
columns_preprocessing,
|
|
211
|
+
)
|
|
212
|
+
)
|
|
213
|
+
convert = PreprocessingCategorical(cols_to_process, convert_method)
|
|
214
|
+
convert.fit(X_train, y_train)
|
|
215
|
+
X_train = convert.transform(X_train)
|
|
216
|
+
self._categorical += [convert]
|
|
217
|
+
|
|
218
|
+
# datetime transform
|
|
219
|
+
cols_to_process = list(
|
|
220
|
+
filter(
|
|
221
|
+
lambda k: "datetime_transform" in columns_preprocessing[k],
|
|
222
|
+
columns_preprocessing,
|
|
223
|
+
)
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
new_datetime_columns = []
|
|
227
|
+
for col in cols_to_process:
|
|
228
|
+
t = DateTimeTransformer()
|
|
229
|
+
t.fit(X_train, col)
|
|
230
|
+
X_train = t.transform(X_train)
|
|
231
|
+
self._datetime_transforms += [t]
|
|
232
|
+
new_datetime_columns += t._new_columns
|
|
233
|
+
|
|
234
|
+
# SCALE
|
|
235
|
+
for scale_method in [Scale.SCALE_NORMAL, Scale.SCALE_LOG_AND_NORMAL]:
|
|
236
|
+
cols_to_process = list(
|
|
237
|
+
filter(
|
|
238
|
+
lambda k: scale_method in columns_preprocessing[k],
|
|
239
|
+
columns_preprocessing,
|
|
240
|
+
)
|
|
241
|
+
)
|
|
242
|
+
if (
|
|
243
|
+
len(cols_to_process)
|
|
244
|
+
and len(new_datetime_columns)
|
|
245
|
+
and scale_method == Scale.SCALE_NORMAL
|
|
246
|
+
):
|
|
247
|
+
cols_to_process += new_datetime_columns
|
|
248
|
+
if (
|
|
249
|
+
len(cols_to_process)
|
|
250
|
+
and len(new_text_columns)
|
|
251
|
+
and scale_method == Scale.SCALE_NORMAL
|
|
252
|
+
):
|
|
253
|
+
cols_to_process += new_text_columns
|
|
254
|
+
|
|
255
|
+
if (
|
|
256
|
+
len(cols_to_process)
|
|
257
|
+
and len(golden_columns)
|
|
258
|
+
and scale_method == Scale.SCALE_NORMAL
|
|
259
|
+
):
|
|
260
|
+
cols_to_process += golden_columns
|
|
261
|
+
|
|
262
|
+
if (
|
|
263
|
+
len(cols_to_process)
|
|
264
|
+
and len(kmeans_columns)
|
|
265
|
+
and scale_method == Scale.SCALE_NORMAL
|
|
266
|
+
):
|
|
267
|
+
cols_to_process += kmeans_columns
|
|
268
|
+
|
|
269
|
+
if len(cols_to_process):
|
|
270
|
+
scale = Scale(cols_to_process)
|
|
271
|
+
scale.fit(X_train)
|
|
272
|
+
X_train = scale.transform(X_train)
|
|
273
|
+
self._scale += [scale]
|
|
274
|
+
|
|
275
|
+
if self._add_random_feature:
|
|
276
|
+
# -1, 1, with 0 mean
|
|
277
|
+
X_train["random_feature"] = np.random.rand(X_train.shape[0]) * 2.0 - 1.0
|
|
278
|
+
|
|
279
|
+
if self._drop_features:
|
|
280
|
+
available_cols = X_train.columns.tolist()
|
|
281
|
+
drop_cols = [c for c in self._drop_features if c in available_cols]
|
|
282
|
+
if len(drop_cols) == X_train.shape[1]:
|
|
283
|
+
raise AutoMLException(
|
|
284
|
+
"All features are droppped! Your data looks like random data."
|
|
285
|
+
)
|
|
286
|
+
if drop_cols:
|
|
287
|
+
X_train.drop(drop_cols, axis=1, inplace=True)
|
|
288
|
+
self._drop_features = drop_cols
|
|
289
|
+
|
|
290
|
+
if X_train is not None:
|
|
291
|
+
# there can be catagorical columns (in CatBoost) which cant be clipped
|
|
292
|
+
numeric_cols = X_train.select_dtypes(include="number").columns.tolist()
|
|
293
|
+
X_train[numeric_cols] = X_train[numeric_cols].clip(
|
|
294
|
+
lower=np.finfo(np.float32).min + 1000,
|
|
295
|
+
upper=np.finfo(np.float32).max - 1000,
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
return X_train, y_train, sample_weight
|
|
299
|
+
|
|
300
|
+
def transform(self, X_validation, y_validation, sample_weight_validation=None):
|
|
301
|
+
logger.debug("Preprocessing.transform")
|
|
302
|
+
|
|
303
|
+
# doing copy to avoid SettingWithCopyWarning
|
|
304
|
+
if X_validation is not None:
|
|
305
|
+
X_validation = X_validation.copy(deep=False)
|
|
306
|
+
if y_validation is not None:
|
|
307
|
+
y_validation = y_validation.copy(deep=False)
|
|
308
|
+
|
|
309
|
+
# target preprocessing
|
|
310
|
+
# this must be used first, maybe we will drop some rows because of missing target values
|
|
311
|
+
if y_validation is not None:
|
|
312
|
+
target_preprocessing = self._params.get("target_preprocessing")
|
|
313
|
+
logger.debug("target_preprocessing -> {}".format(target_preprocessing))
|
|
314
|
+
|
|
315
|
+
(
|
|
316
|
+
X_validation,
|
|
317
|
+
y_validation,
|
|
318
|
+
sample_weight_validation,
|
|
319
|
+
_,
|
|
320
|
+
) = ExcludeRowsMissingTarget.transform(
|
|
321
|
+
X_validation, y_validation, sample_weight_validation
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
if PreprocessingCategorical.CONVERT_INTEGER in target_preprocessing:
|
|
325
|
+
if y_validation is not None and self._categorical_y is not None:
|
|
326
|
+
y_validation = pd.Series(
|
|
327
|
+
self._categorical_y.transform(y_validation)
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
if PreprocessingCategorical.CONVERT_ONE_HOT in target_preprocessing:
|
|
331
|
+
if y_validation is not None and self._categorical_y is not None:
|
|
332
|
+
y_validation = self._categorical_y.transform(
|
|
333
|
+
pd.DataFrame({"target": y_validation}), "target"
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
if Scale.SCALE_LOG_AND_NORMAL in target_preprocessing:
|
|
337
|
+
if self._scale_y is not None and y_validation is not None:
|
|
338
|
+
logger.debug("Transform log and normalize")
|
|
339
|
+
y_validation = pd.DataFrame({"target": y_validation})
|
|
340
|
+
y_validation = self._scale_y.transform(y_validation)
|
|
341
|
+
y_validation = y_validation["target"]
|
|
342
|
+
|
|
343
|
+
if Scale.SCALE_NORMAL in target_preprocessing:
|
|
344
|
+
if self._scale_y is not None and y_validation is not None:
|
|
345
|
+
logger.debug("Transform normalize")
|
|
346
|
+
y_validation = pd.DataFrame({"target": y_validation})
|
|
347
|
+
y_validation = self._scale_y.transform(y_validation)
|
|
348
|
+
y_validation = y_validation["target"]
|
|
349
|
+
|
|
350
|
+
# columns preprocessing
|
|
351
|
+
if len(self._remove_columns) and X_validation is not None:
|
|
352
|
+
cols_to_remove = [
|
|
353
|
+
col for col in X_validation.columns if col in self._remove_columns
|
|
354
|
+
]
|
|
355
|
+
X_validation.drop(cols_to_remove, axis=1, inplace=True)
|
|
356
|
+
|
|
357
|
+
# text transform
|
|
358
|
+
for tt in self._text_transforms:
|
|
359
|
+
if X_validation is not None and tt is not None:
|
|
360
|
+
X_validation = tt.transform(X_validation)
|
|
361
|
+
|
|
362
|
+
for missing in self._missing_values:
|
|
363
|
+
if X_validation is not None and missing is not None:
|
|
364
|
+
X_validation = missing.transform(X_validation)
|
|
365
|
+
|
|
366
|
+
# to be sure that all missing are filled
|
|
367
|
+
# in case new data there can be gaps!
|
|
368
|
+
if (
|
|
369
|
+
X_validation is not None
|
|
370
|
+
and pd.isnull(X_validation).sum().sum() > 0
|
|
371
|
+
and len(self._params["columns_preprocessing"]) > 0
|
|
372
|
+
):
|
|
373
|
+
# there is something missing, fill it
|
|
374
|
+
# we should notice user about it!
|
|
375
|
+
# warnings should go to the separate file ...
|
|
376
|
+
# warnings.warn(
|
|
377
|
+
# "There are columns {} with missing values which didnt have missing values in train dataset.".format(
|
|
378
|
+
# list(
|
|
379
|
+
# X_validation.columns[np.where(np.sum(pd.isnull(X_validation)))]
|
|
380
|
+
# )
|
|
381
|
+
# )
|
|
382
|
+
# )
|
|
383
|
+
missing = PreprocessingMissingValues(
|
|
384
|
+
X_validation.columns, PreprocessingMissingValues.FILL_NA_MEDIAN
|
|
385
|
+
)
|
|
386
|
+
missing.fit(X_validation)
|
|
387
|
+
X_validation = missing.transform(X_validation)
|
|
388
|
+
|
|
389
|
+
# golden features
|
|
390
|
+
if self._golden_features is not None:
|
|
391
|
+
X_validation = self._golden_features.transform(X_validation)
|
|
392
|
+
|
|
393
|
+
if self._kmeans is not None:
|
|
394
|
+
X_validation = self._kmeans.transform(X_validation)
|
|
395
|
+
|
|
396
|
+
for convert in self._categorical:
|
|
397
|
+
if X_validation is not None and convert is not None:
|
|
398
|
+
X_validation = convert.transform(X_validation)
|
|
399
|
+
|
|
400
|
+
for dtt in self._datetime_transforms:
|
|
401
|
+
if X_validation is not None and dtt is not None:
|
|
402
|
+
X_validation = dtt.transform(X_validation)
|
|
403
|
+
|
|
404
|
+
for scale in self._scale:
|
|
405
|
+
if X_validation is not None and scale is not None:
|
|
406
|
+
X_validation = scale.transform(X_validation)
|
|
407
|
+
|
|
408
|
+
if self._add_random_feature:
|
|
409
|
+
# -1, 1, with 0 mean
|
|
410
|
+
X_validation["random_feature"] = (
|
|
411
|
+
np.random.rand(X_validation.shape[0]) * 2.0 - 1.0
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
if self._drop_features and X_validation is not None:
|
|
415
|
+
X_validation.drop(self._drop_features, axis=1, inplace=True)
|
|
416
|
+
|
|
417
|
+
if X_validation is not None:
|
|
418
|
+
# there can be catagorical columns (in CatBoost) which cant be clipped
|
|
419
|
+
numeric_cols = X_validation.select_dtypes(include="number").columns.tolist()
|
|
420
|
+
X_validation[numeric_cols] = X_validation[numeric_cols].clip(
|
|
421
|
+
lower=np.finfo(np.float32).min + 1000,
|
|
422
|
+
upper=np.finfo(np.float32).max - 1000,
|
|
423
|
+
)
|
|
424
|
+
|
|
425
|
+
return X_validation, y_validation, sample_weight_validation
|
|
426
|
+
|
|
427
|
+
def inverse_scale_target(self, y):
|
|
428
|
+
if self._scale_y is not None:
|
|
429
|
+
y = pd.DataFrame({"target": y})
|
|
430
|
+
y = self._scale_y.inverse_transform(y)
|
|
431
|
+
y = y["target"]
|
|
432
|
+
return y
|
|
433
|
+
|
|
434
|
+
def inverse_categorical_target(self, y):
|
|
435
|
+
if self._categorical_y is not None:
|
|
436
|
+
y = self._categorical_y.inverse_transform(y)
|
|
437
|
+
y = y.astype(str)
|
|
438
|
+
return y
|
|
439
|
+
|
|
440
|
+
def get_target_class_names(self):
|
|
441
|
+
pos_label, neg_label = "1", "0"
|
|
442
|
+
if self._categorical_y is not None:
|
|
443
|
+
if self._params["ml_task"] == BINARY_CLASSIFICATION:
|
|
444
|
+
# binary classification
|
|
445
|
+
for label, value in self._categorical_y.to_json().items():
|
|
446
|
+
if value == 1:
|
|
447
|
+
pos_label = label
|
|
448
|
+
else:
|
|
449
|
+
neg_label = label
|
|
450
|
+
return [neg_label, pos_label]
|
|
451
|
+
else:
|
|
452
|
+
# multiclass classification
|
|
453
|
+
# logger.debug(self._categorical_y.to_json())
|
|
454
|
+
if "unique_values" not in self._categorical_y.to_json():
|
|
455
|
+
labels = dict(
|
|
456
|
+
(v, k) for k, v in self._categorical_y.to_json().items()
|
|
457
|
+
)
|
|
458
|
+
else:
|
|
459
|
+
labels = {
|
|
460
|
+
i: v
|
|
461
|
+
for i, v in enumerate(
|
|
462
|
+
self._categorical_y.to_json()["unique_values"]
|
|
463
|
+
)
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
return list(labels.values())
|
|
467
|
+
|
|
468
|
+
else: # self._categorical_y is None
|
|
469
|
+
if "ml_task" in self._params:
|
|
470
|
+
if self._params["ml_task"] == BINARY_CLASSIFICATION:
|
|
471
|
+
return ["0", "1"]
|
|
472
|
+
return []
|
|
473
|
+
|
|
474
|
+
def prepare_target_labels(self, y):
|
|
475
|
+
pos_label, neg_label = "1", "0"
|
|
476
|
+
|
|
477
|
+
if self._categorical_y is not None:
|
|
478
|
+
if len(y.shape) == 1:
|
|
479
|
+
# binary classification
|
|
480
|
+
for label, value in self._categorical_y.to_json().items():
|
|
481
|
+
if value == 1:
|
|
482
|
+
pos_label = label
|
|
483
|
+
else:
|
|
484
|
+
neg_label = label
|
|
485
|
+
# threshold is applied in AutoML class
|
|
486
|
+
return pd.DataFrame(
|
|
487
|
+
{
|
|
488
|
+
"prediction_{}".format(neg_label): 1 - y,
|
|
489
|
+
"prediction_{}".format(pos_label): y,
|
|
490
|
+
}
|
|
491
|
+
)
|
|
492
|
+
else:
|
|
493
|
+
# multiclass classification
|
|
494
|
+
if "unique_values" not in self._categorical_y.to_json():
|
|
495
|
+
labels = dict(
|
|
496
|
+
(v, k) for k, v in self._categorical_y.to_json().items()
|
|
497
|
+
)
|
|
498
|
+
else:
|
|
499
|
+
labels = {
|
|
500
|
+
i: v
|
|
501
|
+
for i, v in enumerate(
|
|
502
|
+
self._categorical_y.to_json()["unique_values"]
|
|
503
|
+
)
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
d = {}
|
|
507
|
+
cols = []
|
|
508
|
+
for i in range(y.shape[1]):
|
|
509
|
+
d["prediction_{}".format(labels[i])] = y[:, i]
|
|
510
|
+
cols += ["prediction_{}".format(labels[i])]
|
|
511
|
+
df = pd.DataFrame(d)
|
|
512
|
+
df["label"] = np.argmax(np.array(df[cols]), axis=1)
|
|
513
|
+
|
|
514
|
+
df["label"] = df["label"].map(labels)
|
|
515
|
+
|
|
516
|
+
return df
|
|
517
|
+
else: # self._categorical_y is None
|
|
518
|
+
if "ml_task" in self._params:
|
|
519
|
+
if self._params["ml_task"] == BINARY_CLASSIFICATION:
|
|
520
|
+
return pd.DataFrame({"prediction_0": 1 - y, "prediction_1": y})
|
|
521
|
+
elif self._params["ml_task"] == MULTICLASS_CLASSIFICATION:
|
|
522
|
+
return pd.DataFrame(
|
|
523
|
+
data=y,
|
|
524
|
+
columns=["prediction_{}".format(i) for i in range(y.shape[1])],
|
|
525
|
+
)
|
|
526
|
+
|
|
527
|
+
return pd.DataFrame({"prediction": y})
|
|
528
|
+
|
|
529
|
+
def to_json(self):
|
|
530
|
+
preprocessing_params = {}
|
|
531
|
+
if self._remove_columns:
|
|
532
|
+
preprocessing_params["remove_columns"] = self._remove_columns
|
|
533
|
+
if self._missing_values is not None and len(self._missing_values):
|
|
534
|
+
mvs = [] # refactor
|
|
535
|
+
for mv in self._missing_values:
|
|
536
|
+
if mv.to_json():
|
|
537
|
+
mvs += [mv.to_json()]
|
|
538
|
+
if mvs:
|
|
539
|
+
preprocessing_params["missing_values"] = mvs
|
|
540
|
+
if self._categorical is not None and len(self._categorical):
|
|
541
|
+
cats = [] # refactor
|
|
542
|
+
for cat in self._categorical:
|
|
543
|
+
if cat.to_json():
|
|
544
|
+
cats += [cat.to_json()]
|
|
545
|
+
if cats:
|
|
546
|
+
preprocessing_params["categorical"] = cats
|
|
547
|
+
|
|
548
|
+
if self._datetime_transforms is not None and len(self._datetime_transforms):
|
|
549
|
+
dtts = []
|
|
550
|
+
for dtt in self._datetime_transforms:
|
|
551
|
+
dtts += [dtt.to_json()]
|
|
552
|
+
if dtts:
|
|
553
|
+
preprocessing_params["datetime_transforms"] = dtts
|
|
554
|
+
|
|
555
|
+
if self._text_transforms is not None and len(self._text_transforms):
|
|
556
|
+
tts = []
|
|
557
|
+
for tt in self._text_transforms:
|
|
558
|
+
tts += [tt.to_json()]
|
|
559
|
+
if tts:
|
|
560
|
+
preprocessing_params["text_transforms"] = tts
|
|
561
|
+
|
|
562
|
+
if self._golden_features is not None:
|
|
563
|
+
preprocessing_params["golden_features"] = self._golden_features.to_json()
|
|
564
|
+
|
|
565
|
+
if self._kmeans is not None:
|
|
566
|
+
preprocessing_params["kmeans"] = self._kmeans.to_json()
|
|
567
|
+
|
|
568
|
+
if self._scale is not None and len(self._scale):
|
|
569
|
+
scs = [sc.to_json() for sc in self._scale if sc.to_json()]
|
|
570
|
+
if scs:
|
|
571
|
+
preprocessing_params["scale"] = scs
|
|
572
|
+
if self._categorical_y is not None:
|
|
573
|
+
cat_y = self._categorical_y.to_json()
|
|
574
|
+
if cat_y:
|
|
575
|
+
preprocessing_params["categorical_y"] = cat_y
|
|
576
|
+
if self._scale_y is not None:
|
|
577
|
+
preprocessing_params["scale_y"] = self._scale_y.to_json()
|
|
578
|
+
|
|
579
|
+
if "ml_task" in self._params:
|
|
580
|
+
preprocessing_params["ml_task"] = self._params["ml_task"]
|
|
581
|
+
|
|
582
|
+
if self._add_random_feature:
|
|
583
|
+
preprocessing_params["add_random_feature"] = True
|
|
584
|
+
|
|
585
|
+
if self._drop_features:
|
|
586
|
+
preprocessing_params["drop_features"] = self._drop_features
|
|
587
|
+
|
|
588
|
+
preprocessing_params["params"] = self._params
|
|
589
|
+
|
|
590
|
+
return preprocessing_params
|
|
591
|
+
|
|
592
|
+
def from_json(self, data_json, results_path):
|
|
593
|
+
self._params = data_json.get("params", self._params)
|
|
594
|
+
|
|
595
|
+
if "remove_columns" in data_json:
|
|
596
|
+
self._remove_columns = data_json.get("remove_columns", [])
|
|
597
|
+
if "missing_values" in data_json:
|
|
598
|
+
self._missing_values = []
|
|
599
|
+
for mv_data in data_json["missing_values"]:
|
|
600
|
+
mv = PreprocessingMissingValues()
|
|
601
|
+
mv.from_json(mv_data)
|
|
602
|
+
self._missing_values += [mv]
|
|
603
|
+
if "categorical" in data_json:
|
|
604
|
+
self._categorical = []
|
|
605
|
+
for cat_data in data_json["categorical"]:
|
|
606
|
+
cat = PreprocessingCategorical()
|
|
607
|
+
cat.from_json(cat_data)
|
|
608
|
+
self._categorical += [cat]
|
|
609
|
+
|
|
610
|
+
if "datetime_transforms" in data_json:
|
|
611
|
+
self._datetime_transforms = []
|
|
612
|
+
for dtt_params in data_json["datetime_transforms"]:
|
|
613
|
+
dtt = DateTimeTransformer()
|
|
614
|
+
dtt.from_json(dtt_params)
|
|
615
|
+
self._datetime_transforms += [dtt]
|
|
616
|
+
|
|
617
|
+
if "text_transforms" in data_json:
|
|
618
|
+
self._text_transforms = []
|
|
619
|
+
for tt_params in data_json["text_transforms"]:
|
|
620
|
+
tt = TextTransformer()
|
|
621
|
+
tt.from_json(tt_params)
|
|
622
|
+
self._text_transforms += [tt]
|
|
623
|
+
|
|
624
|
+
if "golden_features" in data_json:
|
|
625
|
+
self._golden_features = GoldenFeaturesTransformer()
|
|
626
|
+
self._golden_features.from_json(data_json["golden_features"], results_path)
|
|
627
|
+
|
|
628
|
+
if "kmeans" in data_json:
|
|
629
|
+
self._kmeans = KMeansTransformer()
|
|
630
|
+
self._kmeans.from_json(data_json["kmeans"], results_path)
|
|
631
|
+
|
|
632
|
+
if "scale" in data_json:
|
|
633
|
+
self._scale = []
|
|
634
|
+
for scale_data in data_json["scale"]:
|
|
635
|
+
sc = Scale()
|
|
636
|
+
sc.from_json(scale_data)
|
|
637
|
+
self._scale += [sc]
|
|
638
|
+
if "categorical_y" in data_json:
|
|
639
|
+
if "new_columns" in data_json["categorical_y"]:
|
|
640
|
+
self._categorical_y = LabelBinarizer()
|
|
641
|
+
else:
|
|
642
|
+
self._categorical_y = LabelEncoder()
|
|
643
|
+
|
|
644
|
+
self._categorical_y.from_json(data_json["categorical_y"])
|
|
645
|
+
if "scale_y" in data_json:
|
|
646
|
+
self._scale_y = Scale()
|
|
647
|
+
self._scale_y.from_json(data_json["scale_y"])
|
|
648
|
+
if "ml_task" in data_json:
|
|
649
|
+
self._params["ml_task"] = data_json["ml_task"]
|
|
650
|
+
|
|
651
|
+
self._add_random_feature = data_json.get("add_random_feature", False)
|
|
652
|
+
self._drop_features = data_json.get("drop_features", [])
|