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.
Files changed (94) hide show
  1. mljar_supervised-1.2.1.dist-info/METADATA +657 -0
  2. mljar_supervised-1.2.1.dist-info/RECORD +94 -0
  3. mljar_supervised-1.2.1.dist-info/WHEEL +5 -0
  4. mljar_supervised-1.2.1.dist-info/licenses/LICENSE +21 -0
  5. mljar_supervised-1.2.1.dist-info/top_level.txt +1 -0
  6. supervised/__init__.py +14 -0
  7. supervised/algorithms/__init__.py +0 -0
  8. supervised/algorithms/algorithm.py +151 -0
  9. supervised/algorithms/baseline.py +90 -0
  10. supervised/algorithms/catboost.py +436 -0
  11. supervised/algorithms/decision_tree.py +305 -0
  12. supervised/algorithms/extra_trees.py +176 -0
  13. supervised/algorithms/factory.py +28 -0
  14. supervised/algorithms/knn.py +137 -0
  15. supervised/algorithms/lightgbm.py +406 -0
  16. supervised/algorithms/linear.py +211 -0
  17. supervised/algorithms/nn.py +180 -0
  18. supervised/algorithms/random_forest.py +181 -0
  19. supervised/algorithms/registry.py +76 -0
  20. supervised/algorithms/sklearn.py +197 -0
  21. supervised/algorithms/xgboost.py +413 -0
  22. supervised/automl.py +568 -0
  23. supervised/base_automl.py +2542 -0
  24. supervised/callbacks/__init__.py +0 -0
  25. supervised/callbacks/callback.py +25 -0
  26. supervised/callbacks/callback_list.py +33 -0
  27. supervised/callbacks/early_stopping.py +213 -0
  28. supervised/callbacks/learner_time_constraint.py +47 -0
  29. supervised/callbacks/max_iters_constraint.py +16 -0
  30. supervised/callbacks/metric_logger.py +48 -0
  31. supervised/callbacks/terminate_on_nan.py +28 -0
  32. supervised/callbacks/total_time_constraint.py +79 -0
  33. supervised/ensemble.py +583 -0
  34. supervised/exceptions.py +21 -0
  35. supervised/fairness/__init__.py +0 -0
  36. supervised/fairness/metrics.py +654 -0
  37. supervised/fairness/optimization.py +414 -0
  38. supervised/fairness/plots.py +131 -0
  39. supervised/fairness/report.py +116 -0
  40. supervised/fairness/utils.py +40 -0
  41. supervised/model_framework.py +734 -0
  42. supervised/preprocessing/__init__.py +0 -0
  43. supervised/preprocessing/datetime_transformer.py +106 -0
  44. supervised/preprocessing/encoding_selector.py +30 -0
  45. supervised/preprocessing/exclude_missing_target.py +46 -0
  46. supervised/preprocessing/goldenfeatures_transformer.py +310 -0
  47. supervised/preprocessing/kmeans_transformer.py +115 -0
  48. supervised/preprocessing/label_binarizer.py +81 -0
  49. supervised/preprocessing/label_encoder.py +54 -0
  50. supervised/preprocessing/preprocessing.py +652 -0
  51. supervised/preprocessing/preprocessing_categorical.py +117 -0
  52. supervised/preprocessing/preprocessing_missing.py +97 -0
  53. supervised/preprocessing/preprocessing_utils.py +136 -0
  54. supervised/preprocessing/scale.py +92 -0
  55. supervised/preprocessing/text_transformer.py +73 -0
  56. supervised/tuner/__init__.py +0 -0
  57. supervised/tuner/data_info.py +64 -0
  58. supervised/tuner/hill_climbing.py +80 -0
  59. supervised/tuner/mljar_tuner.py +1501 -0
  60. supervised/tuner/optuna/__init__.py +0 -0
  61. supervised/tuner/optuna/catboost.py +148 -0
  62. supervised/tuner/optuna/extra_trees.py +80 -0
  63. supervised/tuner/optuna/knn.py +64 -0
  64. supervised/tuner/optuna/lightgbm.py +165 -0
  65. supervised/tuner/optuna/nn.py +66 -0
  66. supervised/tuner/optuna/random_forest.py +77 -0
  67. supervised/tuner/optuna/tuner.py +335 -0
  68. supervised/tuner/optuna/xgboost.py +130 -0
  69. supervised/tuner/preprocessing_tuner.py +137 -0
  70. supervised/tuner/random_parameters.py +22 -0
  71. supervised/tuner/time_controller.py +273 -0
  72. supervised/utils/__init__.py +11 -0
  73. supervised/utils/additional_metrics.py +955 -0
  74. supervised/utils/additional_plots.py +228 -0
  75. supervised/utils/automl_plots.py +368 -0
  76. supervised/utils/common.py +39 -0
  77. supervised/utils/config.py +25 -0
  78. supervised/utils/constants.py +4 -0
  79. supervised/utils/data_validation.py +48 -0
  80. supervised/utils/importance.py +93 -0
  81. supervised/utils/jsonencoder.py +33 -0
  82. supervised/utils/leaderboard_plots.py +137 -0
  83. supervised/utils/learning_curves.py +145 -0
  84. supervised/utils/metric.py +450 -0
  85. supervised/utils/report_structured.py +525 -0
  86. supervised/utils/shap.py +373 -0
  87. supervised/utils/subsample.py +17 -0
  88. supervised/utils/utils.py +29 -0
  89. supervised/validation/__init__.py +0 -0
  90. supervised/validation/validation_step.py +37 -0
  91. supervised/validation/validator_base.py +17 -0
  92. supervised/validation/validator_custom.py +112 -0
  93. supervised/validation/validator_kfold.py +153 -0
  94. supervised/validation/validator_split.py +143 -0
@@ -0,0 +1,413 @@
1
+ import copy
2
+ import logging
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+ import xgboost as xgb
7
+ from sklearn.base import ClassifierMixin, RegressorMixin
8
+
9
+ from supervised.algorithms.algorithm import BaseAlgorithm
10
+ from supervised.algorithms.registry import (
11
+ BINARY_CLASSIFICATION,
12
+ MULTICLASS_CLASSIFICATION,
13
+ REGRESSION,
14
+ AlgorithmsRegistry,
15
+ )
16
+ from supervised.utils.config import LOG_LEVEL
17
+ from supervised.utils.metric import (
18
+ xgboost_eval_metric_accuracy,
19
+ xgboost_eval_metric_average_precision,
20
+ xgboost_eval_metric_f1,
21
+ xgboost_eval_metric_mse,
22
+ xgboost_eval_metric_pearson,
23
+ xgboost_eval_metric_r2,
24
+ xgboost_eval_metric_spearman,
25
+ xgboost_eval_metric_user_defined,
26
+ )
27
+
28
+ logger = logging.getLogger(__name__)
29
+ logger.setLevel(LOG_LEVEL)
30
+
31
+
32
+ class XgbAlgorithmException(Exception):
33
+ def __init__(self, message):
34
+ super(XgbAlgorithmException, self).__init__(message)
35
+ logger.error(message)
36
+
37
+
38
+ def time_constraint(env):
39
+ # print("time constraint")
40
+ pass
41
+
42
+
43
+ def xgboost_eval_metric(ml_task, automl_eval_metric):
44
+ # the mapping is almost the same
45
+ eval_metric_name = automl_eval_metric
46
+ if ml_task == MULTICLASS_CLASSIFICATION:
47
+ if automl_eval_metric == "logloss":
48
+ eval_metric_name = "mlogloss"
49
+ return eval_metric_name
50
+
51
+
52
+ def xgboost_objective(ml_task, automl_eval_metric):
53
+ objective = "reg:squarederror"
54
+ if ml_task == BINARY_CLASSIFICATION:
55
+ objective = "binary:logistic"
56
+ elif ml_task == MULTICLASS_CLASSIFICATION:
57
+ objective = "multi:softprob"
58
+ else: # ml_task == REGRESSION
59
+ objective = "reg:squarederror"
60
+ return objective
61
+
62
+
63
+ class XgbAlgorithm(BaseAlgorithm):
64
+ """
65
+ This is a wrapper over xgboost algorithm.
66
+ """
67
+
68
+ algorithm_name = "Extreme Gradient Boosting"
69
+ algorithm_short_name = "Xgboost"
70
+
71
+ def __init__(self, params):
72
+ super(XgbAlgorithm, self).__init__(params)
73
+ self.library_version = xgb.__version__
74
+
75
+ self.explain_level = params.get("explain_level", 0)
76
+ self.boosting_rounds = additional.get("max_rounds", 10000)
77
+ self.max_iters = 1
78
+ self.early_stopping_rounds = additional.get("early_stopping_rounds", 50)
79
+ self.learner_params = {
80
+ "tree_method": "hist",
81
+ "device": "cpu",
82
+ "booster": "gbtree",
83
+ "objective": self.params.get("objective"),
84
+ "eval_metric": self.params.get("eval_metric"),
85
+ "eta": self.params.get("eta", 0.01),
86
+ "max_depth": self.params.get("max_depth", 1),
87
+ "min_child_weight": self.params.get("min_child_weight", 1),
88
+ "subsample": self.params.get("subsample", 0.8),
89
+ "colsample_bytree": self.params.get("colsample_bytree", 0.8),
90
+ "n_jobs": self.params.get("n_jobs", -1),
91
+ # "silent": self.params.get("silent", 1),
92
+ "seed": self.params.get("seed", 1),
93
+ "verbosity": 0,
94
+ }
95
+
96
+ if "lambda" in self.params:
97
+ self.learner_params["lambda"] = self.params["lambda"]
98
+ if "alpha" in self.params:
99
+ self.learner_params["alpha"] = self.params["alpha"]
100
+
101
+ # check https://github.com/dmlc/xgboost/issues/5637
102
+ if self.learner_params["seed"] > 2147483647:
103
+ self.learner_params["seed"] = self.learner_params["seed"] % 2147483647
104
+ if "num_class" in self.params: # multiclass classification
105
+ self.learner_params["num_class"] = self.params.get("num_class")
106
+
107
+ if "max_rounds" in self.params:
108
+ self.boosting_rounds = self.params["max_rounds"]
109
+
110
+ self.custom_eval_metric = None
111
+ if self.params.get("eval_metric", "") == "r2":
112
+ self.custom_eval_metric = xgboost_eval_metric_r2
113
+ elif self.params.get("eval_metric", "") == "spearman":
114
+ self.custom_eval_metric = xgboost_eval_metric_spearman
115
+ elif self.params.get("eval_metric", "") == "pearson":
116
+ self.custom_eval_metric = xgboost_eval_metric_pearson
117
+ elif self.params.get("eval_metric", "") == "f1":
118
+ self.custom_eval_metric = xgboost_eval_metric_f1
119
+ elif self.params.get("eval_metric", "") == "average_precision":
120
+ self.custom_eval_metric = xgboost_eval_metric_average_precision
121
+ elif self.params.get("eval_metric", "") == "accuracy":
122
+ self.custom_eval_metric = xgboost_eval_metric_accuracy
123
+ elif self.params.get("eval_metric", "") == "mse":
124
+ self.custom_eval_metric = xgboost_eval_metric_mse
125
+ elif self.params.get("eval_metric", "") == "user_defined_metric":
126
+ self.custom_eval_metric = xgboost_eval_metric_user_defined
127
+
128
+ logger.debug("XgbLearner __init__")
129
+
130
+ """
131
+ def get_boosting_rounds(self, dtrain, evals, esr, max_time):
132
+ if max_time is None:
133
+ return self.boosting_rounds
134
+
135
+ start_time = time.time()
136
+ evals_result = {}
137
+ model = xgb.train(
138
+ self.learner_params,
139
+ dtrain,
140
+ 2,
141
+ evals=evals,
142
+ early_stopping_rounds=esr,
143
+ evals_result=evals_result,
144
+ verbose_eval=False,
145
+ )
146
+ time_1_iter = (time.time() - start_time) / 2.0
147
+
148
+ # 2.0 is just a scaling factor
149
+ # purely heuristic
150
+ iters = int(max_time / time_1_iter * 2.0)
151
+ iters = max(iters, 100)
152
+ iters = min(iters, 10000)
153
+ return iters
154
+ """
155
+
156
+ def fit(
157
+ self,
158
+ X,
159
+ y,
160
+ sample_weight=None,
161
+ X_validation=None,
162
+ y_validation=None,
163
+ sample_weight_validation=None,
164
+ log_to_file=None,
165
+ max_time=None,
166
+ ):
167
+ dtrain = xgb.DMatrix(
168
+ X.values if isinstance(X, pd.DataFrame) else X,
169
+ label=y,
170
+ missing=np.nan,
171
+ weight=sample_weight,
172
+ )
173
+
174
+ if X_validation is not None and y_validation is not None:
175
+ dvalidation = xgb.DMatrix(
176
+ X_validation.values
177
+ if isinstance(X_validation, pd.DataFrame)
178
+ else X_validation,
179
+ label=y_validation,
180
+ missing=np.nan,
181
+ weight=sample_weight_validation,
182
+ )
183
+ else:
184
+ dvalidation = None
185
+
186
+ evals_result = {}
187
+
188
+ evals = []
189
+ esr = None
190
+ if X_validation is not None and y_validation is not None:
191
+ evals = [(dtrain, "train"), (dvalidation, "validation")]
192
+ esr = self.early_stopping_rounds
193
+
194
+ # disable for now, dont have better idea how to handle time limit ...
195
+ # looks like there is better not to limit the algorithm
196
+ # just wait till they converge ...
197
+ # boosting_rounds = self.get_boosting_rounds(dtrain, evals, esr, max_time)
198
+
199
+ if self.custom_eval_metric is not None:
200
+ del self.learner_params["eval_metric"]
201
+
202
+ self.model = xgb.train(
203
+ self.learner_params,
204
+ dtrain,
205
+ self.boosting_rounds,
206
+ evals=evals,
207
+ early_stopping_rounds=esr,
208
+ evals_result=evals_result,
209
+ verbose_eval=False,
210
+ custom_metric=self.custom_eval_metric
211
+ # callbacks=[time_constraint] # callback slows down by factor ~8
212
+ )
213
+
214
+ del dtrain
215
+ del dvalidation
216
+
217
+ if log_to_file is not None:
218
+ metric_name = list(evals_result["train"].keys())[-1]
219
+
220
+ result = pd.DataFrame(
221
+ {
222
+ "iteration": range(len(evals_result["train"][metric_name])),
223
+ "train": evals_result["train"][metric_name],
224
+ "validation": evals_result["validation"][metric_name],
225
+ }
226
+ )
227
+ # it a is custom metric
228
+ # that is always minimized
229
+ # we need to revert it
230
+ if metric_name in [
231
+ "r2",
232
+ "spearman",
233
+ "pearson",
234
+ "f1",
235
+ "average_precision",
236
+ "accuracy",
237
+ ]:
238
+ result["train"] *= -1.0
239
+ result["validation"] *= -1.0
240
+
241
+ result.to_csv(log_to_file, index=False, header=False)
242
+
243
+ if self.params["ml_task"] != REGRESSION:
244
+ self.classes_ = np.unique(y)
245
+
246
+ # fix high memory consumption in xgboost,
247
+ # waiting for release with fix
248
+ # https://github.com/dmlc/xgboost/issues/5474
249
+ """
250
+ # disable, for now all learners are saved to hard disk and then deleted from RAM
251
+ with tempfile.NamedTemporaryFile() as tmp:
252
+ self.model.save_model(tmp.name)
253
+ del self.model
254
+ self.model = xgb.Booster()
255
+ self.model.load_model(tmp.name)
256
+ """
257
+
258
+ def is_fitted(self):
259
+ return self.model is not None
260
+
261
+ def predict(self, X):
262
+ self.reload()
263
+
264
+ if self.model is None:
265
+ raise XgbAlgorithmException("Xgboost model is None")
266
+
267
+ dtrain = xgb.DMatrix(
268
+ X.values if isinstance(X, pd.DataFrame) else X, missing=np.nan
269
+ )
270
+ # xgboost > 2.0.0 version
271
+ if hasattr(self.model, "best_iteration"):
272
+ a = self.model.predict(
273
+ dtrain, iteration_range=(0, self.model.best_iteration + 1)
274
+ )
275
+ else:
276
+ a = self.model.predict(dtrain)
277
+
278
+ return a
279
+
280
+ def copy(self):
281
+ return copy.deepcopy(self)
282
+
283
+ def save(self, model_file_path):
284
+ self.model.save_model(model_file_path)
285
+ self.model_file_path = model_file_path
286
+ logger.debug("XgbAlgorithm save model to %s" % model_file_path)
287
+
288
+ def load(self, model_file_path):
289
+ logger.debug("XgbLearner load model from %s" % model_file_path)
290
+ self.model = xgb.Booster() # init model
291
+ self.model.load_model(model_file_path)
292
+ self.model_file_path = model_file_path
293
+
294
+ def file_extension(self):
295
+ # we need to keep models as json files
296
+ # to keep information about best_iteration
297
+ return "xgboost.json"
298
+
299
+ def get_metric_name(self):
300
+ metric = self.params.get("eval_metric")
301
+ if metric is None:
302
+ return None
303
+ if metric == "mlogloss":
304
+ return "logloss"
305
+ return metric
306
+
307
+
308
+ # For binary classification target should be 0, 1. There should be no NaNs in target.
309
+ xgb_bin_class_params = {
310
+ "objective": ["binary:logistic"],
311
+ "eta": [0.05, 0.075, 0.1, 0.15],
312
+ "max_depth": [4, 5, 6, 7, 8, 9],
313
+ "min_child_weight": [1, 5, 10, 25, 50],
314
+ "subsample": [0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
315
+ "colsample_bytree": [0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
316
+ }
317
+
318
+ classification_bin_default_params = {
319
+ "objective": "binary:logistic",
320
+ "eta": 0.075,
321
+ "max_depth": 6,
322
+ "min_child_weight": 1,
323
+ "subsample": 1.0,
324
+ "colsample_bytree": 1.0,
325
+ }
326
+
327
+ xgb_regression_params = dict(xgb_bin_class_params)
328
+ xgb_regression_params["objective"] = ["reg:squarederror"]
329
+ # xgb_regression_params["eval_metric"] = ["rmse", "mae", "mape"]
330
+ xgb_regression_params["max_depth"] = [4, 5, 6, 7, 8, 9]
331
+
332
+
333
+ xgb_multi_class_params = dict(xgb_bin_class_params)
334
+ xgb_multi_class_params["objective"] = ["multi:softprob"]
335
+ # xgb_multi_class_params["eval_metric"] = ["mlogloss"]
336
+
337
+ classification_multi_default_params = {
338
+ "objective": "multi:softprob",
339
+ "eta": 0.075,
340
+ "max_depth": 6,
341
+ "min_child_weight": 1,
342
+ "subsample": 1.0,
343
+ "colsample_bytree": 1.0,
344
+ }
345
+
346
+
347
+ regression_default_params = {
348
+ "objective": "reg:squarederror",
349
+ "eta": 0.075,
350
+ "max_depth": 6,
351
+ "min_child_weight": 1,
352
+ "subsample": 1.0,
353
+ "colsample_bytree": 1.0,
354
+ }
355
+
356
+ additional = {
357
+ "max_rounds": 10000,
358
+ "early_stopping_rounds": 50,
359
+ "max_rows_limit": None,
360
+ "max_cols_limit": None,
361
+ }
362
+ required_preprocessing = [
363
+ "missing_values_inputation",
364
+ "convert_categorical",
365
+ "datetime_transform",
366
+ "text_transform",
367
+ "target_as_integer",
368
+ ]
369
+
370
+
371
+ class XgbClassifier(ClassifierMixin, XgbAlgorithm):
372
+ pass
373
+
374
+
375
+ AlgorithmsRegistry.add(
376
+ BINARY_CLASSIFICATION,
377
+ XgbClassifier,
378
+ xgb_bin_class_params,
379
+ required_preprocessing,
380
+ additional,
381
+ classification_bin_default_params,
382
+ )
383
+
384
+ AlgorithmsRegistry.add(
385
+ MULTICLASS_CLASSIFICATION,
386
+ XgbClassifier,
387
+ xgb_multi_class_params,
388
+ required_preprocessing,
389
+ additional,
390
+ classification_multi_default_params,
391
+ )
392
+
393
+ regression_required_preprocessing = [
394
+ "missing_values_inputation",
395
+ "convert_categorical",
396
+ "datetime_transform",
397
+ "text_transform",
398
+ "target_scale",
399
+ ]
400
+
401
+
402
+ class XgbRegressor(RegressorMixin, XgbAlgorithm):
403
+ pass
404
+
405
+
406
+ AlgorithmsRegistry.add(
407
+ REGRESSION,
408
+ XgbRegressor,
409
+ xgb_regression_params,
410
+ regression_required_preprocessing,
411
+ additional,
412
+ regression_default_params,
413
+ )