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,406 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import copy
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
import lightgbm as lgb
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
from sklearn.base import ClassifierMixin, RegressorMixin
|
|
10
|
+
|
|
11
|
+
from supervised.algorithms.algorithm import BaseAlgorithm
|
|
12
|
+
from supervised.algorithms.registry import (
|
|
13
|
+
BINARY_CLASSIFICATION,
|
|
14
|
+
MULTICLASS_CLASSIFICATION,
|
|
15
|
+
REGRESSION,
|
|
16
|
+
AlgorithmsRegistry,
|
|
17
|
+
)
|
|
18
|
+
from supervised.utils.config import LOG_LEVEL
|
|
19
|
+
from supervised.utils.metric import (
|
|
20
|
+
lightgbm_eval_metric_accuracy,
|
|
21
|
+
lightgbm_eval_metric_average_precision,
|
|
22
|
+
lightgbm_eval_metric_f1,
|
|
23
|
+
lightgbm_eval_metric_pearson,
|
|
24
|
+
lightgbm_eval_metric_r2,
|
|
25
|
+
lightgbm_eval_metric_spearman,
|
|
26
|
+
lightgbm_eval_metric_user_defined,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger(__name__)
|
|
30
|
+
logger.setLevel(LOG_LEVEL)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def lightgbm_objective(ml_task, automl_eval_metric):
|
|
34
|
+
objective = "regression"
|
|
35
|
+
if ml_task == BINARY_CLASSIFICATION:
|
|
36
|
+
objective = "binary"
|
|
37
|
+
elif ml_task == MULTICLASS_CLASSIFICATION:
|
|
38
|
+
objective = "multiclass"
|
|
39
|
+
else: # ml_task == REGRESSION
|
|
40
|
+
objective = "regression"
|
|
41
|
+
return objective
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def lightgbm_eval_metric(ml_task, automl_eval_metric):
|
|
45
|
+
if automl_eval_metric == "user_defined_metric":
|
|
46
|
+
return "custom", automl_eval_metric
|
|
47
|
+
metric_name_mapping = {
|
|
48
|
+
BINARY_CLASSIFICATION: {
|
|
49
|
+
"auc": "auc",
|
|
50
|
+
"logloss": "binary_logloss",
|
|
51
|
+
"f1": "custom",
|
|
52
|
+
"average_precision": "custom",
|
|
53
|
+
"accuracy": "custom",
|
|
54
|
+
},
|
|
55
|
+
MULTICLASS_CLASSIFICATION: {
|
|
56
|
+
"logloss": "multi_logloss",
|
|
57
|
+
"f1": "custom",
|
|
58
|
+
"accuracy": "custom",
|
|
59
|
+
},
|
|
60
|
+
REGRESSION: {
|
|
61
|
+
"rmse": "rmse",
|
|
62
|
+
"mse": "l2",
|
|
63
|
+
"mae": "l1",
|
|
64
|
+
"mape": "mape",
|
|
65
|
+
"r2": "custom",
|
|
66
|
+
"spearman": "custom",
|
|
67
|
+
"pearson": "custom",
|
|
68
|
+
},
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
metric = metric_name_mapping[ml_task][automl_eval_metric]
|
|
72
|
+
custom_eval_metric = None
|
|
73
|
+
|
|
74
|
+
if automl_eval_metric in [
|
|
75
|
+
"r2",
|
|
76
|
+
"spearman",
|
|
77
|
+
"pearson",
|
|
78
|
+
"f1",
|
|
79
|
+
"average_precision",
|
|
80
|
+
"accuracy",
|
|
81
|
+
]:
|
|
82
|
+
custom_eval_metric = automl_eval_metric
|
|
83
|
+
|
|
84
|
+
return metric, custom_eval_metric
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class LightgbmAlgorithm(BaseAlgorithm):
|
|
88
|
+
algorithm_name = "LightGBM"
|
|
89
|
+
algorithm_short_name = "LightGBM"
|
|
90
|
+
|
|
91
|
+
def __init__(self, params):
|
|
92
|
+
super(LightgbmAlgorithm, self).__init__(params)
|
|
93
|
+
self.library_version = lgb.__version__
|
|
94
|
+
|
|
95
|
+
self.explain_level = params.get("explain_level", 0)
|
|
96
|
+
self.rounds = additional.get("max_rounds", 10000)
|
|
97
|
+
self.max_iters = 1
|
|
98
|
+
self.early_stopping_rounds = additional.get("early_stopping_rounds", 50)
|
|
99
|
+
|
|
100
|
+
n_jobs = self.params.get("n_jobs", 0)
|
|
101
|
+
# 0 is the default for LightGBM to use all cores
|
|
102
|
+
if n_jobs == -1:
|
|
103
|
+
n_jobs = 0
|
|
104
|
+
|
|
105
|
+
self.learner_params = {
|
|
106
|
+
"boosting_type": "gbdt",
|
|
107
|
+
"objective": self.params.get("objective", "binary"),
|
|
108
|
+
"metric": self.params.get("metric", "binary_logloss"),
|
|
109
|
+
"num_leaves": self.params.get("num_leaves", 31),
|
|
110
|
+
"learning_rate": self.params.get("learning_rate", 0.1),
|
|
111
|
+
"feature_fraction": self.params.get("feature_fraction", 1.0),
|
|
112
|
+
"bagging_fraction": self.params.get("bagging_fraction", 1.0),
|
|
113
|
+
"min_data_in_leaf": self.params.get("min_data_in_leaf", 20),
|
|
114
|
+
"num_threads": n_jobs,
|
|
115
|
+
"verbose": -1,
|
|
116
|
+
"seed": self.params.get("seed", 1),
|
|
117
|
+
"extra_trees": self.params.get("extra_trees", False),
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
for extra_param in [
|
|
121
|
+
"lambda_l1",
|
|
122
|
+
"lambda_l2",
|
|
123
|
+
"bagging_freq",
|
|
124
|
+
"feature_pre_filter",
|
|
125
|
+
"cat_feature",
|
|
126
|
+
"cat_l2",
|
|
127
|
+
"cat_smooth",
|
|
128
|
+
"max_bin",
|
|
129
|
+
]:
|
|
130
|
+
if extra_param in self.params:
|
|
131
|
+
self.learner_params[extra_param] = self.params[extra_param]
|
|
132
|
+
|
|
133
|
+
if "num_boost_round" in self.params:
|
|
134
|
+
self.rounds = self.params["num_boost_round"]
|
|
135
|
+
if "early_stopping_rounds" in self.params:
|
|
136
|
+
self.early_stopping_rounds = self.params["early_stopping_rounds"]
|
|
137
|
+
|
|
138
|
+
if "num_class" in self.params: # multiclass classification
|
|
139
|
+
self.learner_params["num_class"] = self.params.get("num_class")
|
|
140
|
+
|
|
141
|
+
self.custom_eval_metric = None
|
|
142
|
+
if self.params.get("custom_eval_metric_name") is not None:
|
|
143
|
+
if self.params["custom_eval_metric_name"] == "r2":
|
|
144
|
+
self.custom_eval_metric = lightgbm_eval_metric_r2
|
|
145
|
+
elif self.params["custom_eval_metric_name"] == "spearman":
|
|
146
|
+
self.custom_eval_metric = lightgbm_eval_metric_spearman
|
|
147
|
+
elif self.params["custom_eval_metric_name"] == "pearson":
|
|
148
|
+
self.custom_eval_metric = lightgbm_eval_metric_pearson
|
|
149
|
+
elif self.params["custom_eval_metric_name"] == "f1":
|
|
150
|
+
self.custom_eval_metric = lightgbm_eval_metric_f1
|
|
151
|
+
elif self.params["custom_eval_metric_name"] == "average_precision":
|
|
152
|
+
self.custom_eval_metric = lightgbm_eval_metric_average_precision
|
|
153
|
+
elif self.params["custom_eval_metric_name"] == "accuracy":
|
|
154
|
+
self.custom_eval_metric = lightgbm_eval_metric_accuracy
|
|
155
|
+
elif self.params["custom_eval_metric_name"] == "user_defined_metric":
|
|
156
|
+
self.custom_eval_metric = lightgbm_eval_metric_user_defined
|
|
157
|
+
|
|
158
|
+
logger.debug("LightgbmLearner __init__")
|
|
159
|
+
|
|
160
|
+
def file_extension(self):
|
|
161
|
+
return "lightgbm"
|
|
162
|
+
|
|
163
|
+
def update(self, update_params):
|
|
164
|
+
pass
|
|
165
|
+
|
|
166
|
+
"""
|
|
167
|
+
def get_boosting_rounds(self, lgb_train, valid_sets, esr, max_time):
|
|
168
|
+
if max_time is None:
|
|
169
|
+
max_time = 3600.0
|
|
170
|
+
start_time = time.time()
|
|
171
|
+
evals_result = {}
|
|
172
|
+
model = lgb.train(
|
|
173
|
+
self.learner_params,
|
|
174
|
+
lgb_train,
|
|
175
|
+
num_boost_round=2,
|
|
176
|
+
valid_sets=valid_sets,
|
|
177
|
+
early_stopping_rounds=esr,
|
|
178
|
+
evals_result=evals_result,
|
|
179
|
+
verbose_eval=False,
|
|
180
|
+
)
|
|
181
|
+
time_1_iter = (time.time() - start_time) / 2.0
|
|
182
|
+
|
|
183
|
+
# 2.0 is just a scaling factor
|
|
184
|
+
# purely heuristic
|
|
185
|
+
iters = int(max_time / time_1_iter * 2.0)
|
|
186
|
+
iters = max(iters, 100)
|
|
187
|
+
iters = min(iters, 10000)
|
|
188
|
+
return iters
|
|
189
|
+
"""
|
|
190
|
+
|
|
191
|
+
def fit(
|
|
192
|
+
self,
|
|
193
|
+
X,
|
|
194
|
+
y,
|
|
195
|
+
sample_weight=None,
|
|
196
|
+
X_validation=None,
|
|
197
|
+
y_validation=None,
|
|
198
|
+
sample_weight_validation=None,
|
|
199
|
+
log_to_file=None,
|
|
200
|
+
max_time=None,
|
|
201
|
+
):
|
|
202
|
+
lgb_train = lgb.Dataset(
|
|
203
|
+
X.values if isinstance(X, pd.DataFrame) else X,
|
|
204
|
+
y,
|
|
205
|
+
weight=sample_weight,
|
|
206
|
+
)
|
|
207
|
+
valid_sets = None
|
|
208
|
+
if self.early_stopping_rounds == 0:
|
|
209
|
+
self.model = lgb.train(
|
|
210
|
+
self.learner_params,
|
|
211
|
+
lgb_train,
|
|
212
|
+
num_boost_round=self.rounds,
|
|
213
|
+
init_model=self.model,
|
|
214
|
+
)
|
|
215
|
+
else:
|
|
216
|
+
valid_names = None
|
|
217
|
+
esr = None
|
|
218
|
+
if X_validation is not None and y_validation is not None:
|
|
219
|
+
valid_sets = [
|
|
220
|
+
lgb_train,
|
|
221
|
+
lgb.Dataset(
|
|
222
|
+
X_validation.values
|
|
223
|
+
if isinstance(X_validation, pd.DataFrame)
|
|
224
|
+
else X_validation,
|
|
225
|
+
y_validation,
|
|
226
|
+
weight=sample_weight_validation,
|
|
227
|
+
),
|
|
228
|
+
]
|
|
229
|
+
valid_names = ["train", "validation"]
|
|
230
|
+
esr = self.early_stopping_rounds
|
|
231
|
+
evals_result = {}
|
|
232
|
+
|
|
233
|
+
# disable for now ...
|
|
234
|
+
# boosting_rounds = self.get_boosting_rounds(lgb_train, valid_sets, esr, max_time)
|
|
235
|
+
|
|
236
|
+
self.model = lgb.train(
|
|
237
|
+
self.learner_params,
|
|
238
|
+
lgb_train,
|
|
239
|
+
num_boost_round=self.rounds,
|
|
240
|
+
valid_sets=valid_sets,
|
|
241
|
+
valid_names=valid_names,
|
|
242
|
+
feval=self.custom_eval_metric,
|
|
243
|
+
callbacks=[
|
|
244
|
+
lgb.early_stopping(esr, verbose=False),
|
|
245
|
+
lgb.record_evaluation(evals_result),
|
|
246
|
+
],
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
del lgb_train
|
|
250
|
+
if valid_sets is not None:
|
|
251
|
+
del valid_sets[0]
|
|
252
|
+
del valid_sets
|
|
253
|
+
|
|
254
|
+
if log_to_file is not None:
|
|
255
|
+
metric_name = list(evals_result["train"].keys())[0]
|
|
256
|
+
result = pd.DataFrame(
|
|
257
|
+
{
|
|
258
|
+
"iteration": range(len(evals_result["train"][metric_name])),
|
|
259
|
+
"train": evals_result["train"][metric_name],
|
|
260
|
+
"validation": evals_result["validation"][metric_name],
|
|
261
|
+
}
|
|
262
|
+
)
|
|
263
|
+
result.to_csv(log_to_file, index=False, header=False)
|
|
264
|
+
|
|
265
|
+
if self.params["ml_task"] != REGRESSION:
|
|
266
|
+
self.classes_ = np.unique(y)
|
|
267
|
+
|
|
268
|
+
def is_fitted(self):
|
|
269
|
+
return self.model is not None
|
|
270
|
+
|
|
271
|
+
def predict(self, X):
|
|
272
|
+
self.reload()
|
|
273
|
+
return self.model.predict(X.values if isinstance(X, pd.DataFrame) else X)
|
|
274
|
+
|
|
275
|
+
def copy(self):
|
|
276
|
+
with open(os.devnull, "w") as f, contextlib.redirect_stdout(f):
|
|
277
|
+
return copy.deepcopy(self)
|
|
278
|
+
|
|
279
|
+
def save(self, model_file_path):
|
|
280
|
+
self.model.save_model(model_file_path)
|
|
281
|
+
self.model_file_path = model_file_path
|
|
282
|
+
logger.debug("LightgbmAlgorithm save model to %s" % model_file_path)
|
|
283
|
+
|
|
284
|
+
def load(self, model_file_path):
|
|
285
|
+
logger.debug("LightgbmAlgorithm load model from %s" % model_file_path)
|
|
286
|
+
self.model_file_path = model_file_path
|
|
287
|
+
self.model = lgb.Booster(model_file=model_file_path)
|
|
288
|
+
|
|
289
|
+
def get_metric_name(self):
|
|
290
|
+
metric = self.params.get("metric")
|
|
291
|
+
custom_metric = self.params.get("custom_eval_metric_name")
|
|
292
|
+
|
|
293
|
+
if metric is None:
|
|
294
|
+
return None
|
|
295
|
+
if metric == "custom":
|
|
296
|
+
return custom_metric
|
|
297
|
+
if metric == "binary_logloss":
|
|
298
|
+
return "logloss"
|
|
299
|
+
elif metric == "multi_logloss":
|
|
300
|
+
return "logloss"
|
|
301
|
+
return metric
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
lgbm_bin_params = {
|
|
305
|
+
"objective": ["binary"],
|
|
306
|
+
"num_leaves": [15, 31, 63, 95, 127],
|
|
307
|
+
"learning_rate": [0.05, 0.1, 0.2],
|
|
308
|
+
"feature_fraction": [0.5, 0.8, 0.9, 1.0],
|
|
309
|
+
"bagging_fraction": [0.5, 0.8, 0.9, 1.0],
|
|
310
|
+
"min_data_in_leaf": [5, 10, 15, 20, 30, 50],
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
classification_bin_default_params = {
|
|
314
|
+
"objective": "binary",
|
|
315
|
+
"num_leaves": 63,
|
|
316
|
+
"learning_rate": 0.05,
|
|
317
|
+
"feature_fraction": 0.9,
|
|
318
|
+
"bagging_fraction": 0.9,
|
|
319
|
+
"min_data_in_leaf": 10,
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
additional = {
|
|
324
|
+
"max_rounds": 10000,
|
|
325
|
+
"early_stopping_rounds": 50,
|
|
326
|
+
"max_rows_limit": None,
|
|
327
|
+
"max_cols_limit": None,
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
required_preprocessing = [
|
|
331
|
+
"missing_values_inputation",
|
|
332
|
+
"convert_categorical",
|
|
333
|
+
"datetime_transform",
|
|
334
|
+
"text_transform",
|
|
335
|
+
"target_as_integer",
|
|
336
|
+
]
|
|
337
|
+
|
|
338
|
+
lgbm_multi_params = copy.deepcopy(lgbm_bin_params)
|
|
339
|
+
lgbm_multi_params["objective"] = ["multiclass"]
|
|
340
|
+
|
|
341
|
+
classification_multi_default_params = {
|
|
342
|
+
"objective": "multiclass",
|
|
343
|
+
"num_leaves": 63,
|
|
344
|
+
"learning_rate": 0.05,
|
|
345
|
+
"feature_fraction": 0.9,
|
|
346
|
+
"bagging_fraction": 0.9,
|
|
347
|
+
"min_data_in_leaf": 10,
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
lgbr_params = copy.deepcopy(lgbm_bin_params)
|
|
351
|
+
lgbr_params["objective"] = ["regression"]
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
class LgbmClassifier(ClassifierMixin, LightgbmAlgorithm):
|
|
355
|
+
pass
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
AlgorithmsRegistry.add(
|
|
359
|
+
BINARY_CLASSIFICATION,
|
|
360
|
+
LgbmClassifier,
|
|
361
|
+
lgbm_bin_params,
|
|
362
|
+
required_preprocessing,
|
|
363
|
+
additional,
|
|
364
|
+
classification_bin_default_params,
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
AlgorithmsRegistry.add(
|
|
368
|
+
MULTICLASS_CLASSIFICATION,
|
|
369
|
+
LgbmClassifier,
|
|
370
|
+
lgbm_multi_params,
|
|
371
|
+
required_preprocessing,
|
|
372
|
+
additional,
|
|
373
|
+
classification_multi_default_params,
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
regression_required_preprocessing = [
|
|
377
|
+
"missing_values_inputation",
|
|
378
|
+
"convert_categorical",
|
|
379
|
+
"datetime_transform",
|
|
380
|
+
"text_transform",
|
|
381
|
+
"target_scale",
|
|
382
|
+
]
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
regression_default_params = {
|
|
386
|
+
"objective": "regression",
|
|
387
|
+
"num_leaves": 63,
|
|
388
|
+
"learning_rate": 0.05,
|
|
389
|
+
"feature_fraction": 0.9,
|
|
390
|
+
"bagging_fraction": 0.9,
|
|
391
|
+
"min_data_in_leaf": 10,
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
class LgbmRegressor(RegressorMixin, LightgbmAlgorithm):
|
|
396
|
+
pass
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
AlgorithmsRegistry.add(
|
|
400
|
+
REGRESSION,
|
|
401
|
+
LgbmRegressor,
|
|
402
|
+
lgbr_params,
|
|
403
|
+
regression_required_preprocessing,
|
|
404
|
+
additional,
|
|
405
|
+
regression_default_params,
|
|
406
|
+
)
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pandas as pd
|
|
6
|
+
import sklearn
|
|
7
|
+
from sklearn.base import ClassifierMixin, RegressorMixin
|
|
8
|
+
from sklearn.linear_model import LinearRegression, LogisticRegression
|
|
9
|
+
|
|
10
|
+
from supervised.algorithms.registry import (
|
|
11
|
+
BINARY_CLASSIFICATION,
|
|
12
|
+
MULTICLASS_CLASSIFICATION,
|
|
13
|
+
REGRESSION,
|
|
14
|
+
AlgorithmsRegistry,
|
|
15
|
+
)
|
|
16
|
+
from supervised.algorithms.sklearn import SklearnAlgorithm
|
|
17
|
+
from supervised.utils.config import LOG_LEVEL
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
logger.setLevel(LOG_LEVEL)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class LinearAlgorithm(ClassifierMixin, SklearnAlgorithm):
|
|
24
|
+
algorithm_name = "Logistic Regression"
|
|
25
|
+
algorithm_short_name = "Linear"
|
|
26
|
+
|
|
27
|
+
def __init__(self, params):
|
|
28
|
+
super(LinearAlgorithm, self).__init__(params)
|
|
29
|
+
logger.debug("LinearAlgorithm.__init__")
|
|
30
|
+
self.max_iters = 1
|
|
31
|
+
self.library_version = sklearn.__version__
|
|
32
|
+
self.model = LogisticRegression(
|
|
33
|
+
max_iter=500, tol=5e-4, n_jobs=self.params.get("n_jobs", -1)
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def is_fitted(self):
|
|
37
|
+
return (
|
|
38
|
+
hasattr(self.model, "coef_")
|
|
39
|
+
and self.model.coef_ is not None
|
|
40
|
+
and self.model.coef_.shape[0] > 0
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
def file_extension(self):
|
|
44
|
+
return "linear"
|
|
45
|
+
|
|
46
|
+
def interpret(
|
|
47
|
+
self,
|
|
48
|
+
X_train,
|
|
49
|
+
y_train,
|
|
50
|
+
X_validation,
|
|
51
|
+
y_validation,
|
|
52
|
+
model_file_path,
|
|
53
|
+
learner_name,
|
|
54
|
+
target_name=None,
|
|
55
|
+
class_names=None,
|
|
56
|
+
metric_name=None,
|
|
57
|
+
ml_task=None,
|
|
58
|
+
explain_level=2,
|
|
59
|
+
):
|
|
60
|
+
super(LinearAlgorithm, self).interpret(
|
|
61
|
+
X_train,
|
|
62
|
+
y_train,
|
|
63
|
+
X_validation,
|
|
64
|
+
y_validation,
|
|
65
|
+
model_file_path,
|
|
66
|
+
learner_name,
|
|
67
|
+
target_name,
|
|
68
|
+
class_names,
|
|
69
|
+
metric_name,
|
|
70
|
+
ml_task,
|
|
71
|
+
explain_level,
|
|
72
|
+
)
|
|
73
|
+
if explain_level == 0:
|
|
74
|
+
return
|
|
75
|
+
if X_train.shape[1] > 100:
|
|
76
|
+
# if too many columns, skip this step
|
|
77
|
+
return
|
|
78
|
+
coefs = self.model.coef_
|
|
79
|
+
intercept = self.model.intercept_
|
|
80
|
+
if self.params["ml_task"] == BINARY_CLASSIFICATION:
|
|
81
|
+
df = pd.DataFrame(
|
|
82
|
+
{
|
|
83
|
+
"feature": ["intercept"] + X_train.columns.tolist(),
|
|
84
|
+
"weight": [intercept[0]] + list(coefs[0, :]),
|
|
85
|
+
}
|
|
86
|
+
)
|
|
87
|
+
df.to_csv(
|
|
88
|
+
os.path.join(model_file_path, f"{learner_name}_coefs.csv"), index=False
|
|
89
|
+
)
|
|
90
|
+
elif self.params["ml_task"] == MULTICLASS_CLASSIFICATION:
|
|
91
|
+
classes = list(class_names)
|
|
92
|
+
if isinstance(class_names, dict):
|
|
93
|
+
classes = class_names.values()
|
|
94
|
+
if len(classes) > 20:
|
|
95
|
+
# if there are too many classes, skip this step
|
|
96
|
+
return
|
|
97
|
+
df = pd.DataFrame(
|
|
98
|
+
np.transpose(np.column_stack((intercept, coefs))),
|
|
99
|
+
index=["intercept"] + X_train.columns.tolist(),
|
|
100
|
+
columns=classes,
|
|
101
|
+
)
|
|
102
|
+
df.to_csv(
|
|
103
|
+
os.path.join(model_file_path, f"{learner_name}_coefs.csv"), index=True
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class LinearRegressorAlgorithm(RegressorMixin, SklearnAlgorithm):
|
|
108
|
+
algorithm_name = "Linear Regression"
|
|
109
|
+
algorithm_short_name = "Linear"
|
|
110
|
+
|
|
111
|
+
def __init__(self, params):
|
|
112
|
+
super(LinearRegressorAlgorithm, self).__init__(params)
|
|
113
|
+
logger.debug("LinearRegressorAlgorithm.__init__")
|
|
114
|
+
self.max_iters = 1
|
|
115
|
+
self.library_version = sklearn.__version__
|
|
116
|
+
self.model = LinearRegression(n_jobs=self.params.get("n_jobs", -1))
|
|
117
|
+
|
|
118
|
+
def is_fitted(self):
|
|
119
|
+
return (
|
|
120
|
+
hasattr(self.model, "coef_")
|
|
121
|
+
and self.model.coef_ is not None
|
|
122
|
+
and self.model.coef_.shape[0] > 0
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
def file_extension(self):
|
|
126
|
+
return "linear"
|
|
127
|
+
|
|
128
|
+
def interpret(
|
|
129
|
+
self,
|
|
130
|
+
X_train,
|
|
131
|
+
y_train,
|
|
132
|
+
X_validation,
|
|
133
|
+
y_validation,
|
|
134
|
+
model_file_path,
|
|
135
|
+
learner_name,
|
|
136
|
+
target_name=None,
|
|
137
|
+
class_names=None,
|
|
138
|
+
metric_name=None,
|
|
139
|
+
ml_task=None,
|
|
140
|
+
explain_level=2,
|
|
141
|
+
):
|
|
142
|
+
super(LinearRegressorAlgorithm, self).interpret(
|
|
143
|
+
X_train,
|
|
144
|
+
y_train,
|
|
145
|
+
X_validation,
|
|
146
|
+
y_validation,
|
|
147
|
+
model_file_path,
|
|
148
|
+
learner_name,
|
|
149
|
+
target_name,
|
|
150
|
+
class_names,
|
|
151
|
+
metric_name,
|
|
152
|
+
ml_task,
|
|
153
|
+
explain_level,
|
|
154
|
+
)
|
|
155
|
+
if explain_level == 0:
|
|
156
|
+
return
|
|
157
|
+
if X_train.shape[1] > 100:
|
|
158
|
+
# if too many columns, skip this step
|
|
159
|
+
return
|
|
160
|
+
coefs = self.model.coef_
|
|
161
|
+
intercept = self.model.intercept_
|
|
162
|
+
df = pd.DataFrame(
|
|
163
|
+
{
|
|
164
|
+
"feature": ["intercept"] + X_train.columns.tolist(),
|
|
165
|
+
"weight": [intercept] + list(coefs),
|
|
166
|
+
}
|
|
167
|
+
)
|
|
168
|
+
df.to_csv(
|
|
169
|
+
os.path.join(model_file_path, f"{learner_name}_coefs.csv"), index=False
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
additional = {"max_steps": 1, "max_rows_limit": None, "max_cols_limit": None}
|
|
174
|
+
required_preprocessing = [
|
|
175
|
+
"missing_values_inputation",
|
|
176
|
+
"convert_categorical",
|
|
177
|
+
"datetime_transform",
|
|
178
|
+
"text_transform",
|
|
179
|
+
"scale",
|
|
180
|
+
"target_as_integer",
|
|
181
|
+
]
|
|
182
|
+
|
|
183
|
+
AlgorithmsRegistry.add(
|
|
184
|
+
BINARY_CLASSIFICATION, LinearAlgorithm, {}, required_preprocessing, additional, {}
|
|
185
|
+
)
|
|
186
|
+
AlgorithmsRegistry.add(
|
|
187
|
+
MULTICLASS_CLASSIFICATION,
|
|
188
|
+
LinearAlgorithm,
|
|
189
|
+
{},
|
|
190
|
+
required_preprocessing,
|
|
191
|
+
additional,
|
|
192
|
+
{},
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
regression_required_preprocessing = [
|
|
196
|
+
"missing_values_inputation",
|
|
197
|
+
"convert_categorical",
|
|
198
|
+
"datetime_transform",
|
|
199
|
+
"text_transform",
|
|
200
|
+
"scale",
|
|
201
|
+
"target_scale",
|
|
202
|
+
]
|
|
203
|
+
|
|
204
|
+
AlgorithmsRegistry.add(
|
|
205
|
+
REGRESSION,
|
|
206
|
+
LinearRegressorAlgorithm,
|
|
207
|
+
{},
|
|
208
|
+
regression_required_preprocessing,
|
|
209
|
+
additional,
|
|
210
|
+
{},
|
|
211
|
+
)
|