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,436 @@
1
+ import copy
2
+ import logging
3
+ import time
4
+
5
+ import numpy as np
6
+ import pandas as pd
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.preprocessing.preprocessing_utils import PreprocessingUtils
17
+ from supervised.utils.config import LOG_LEVEL
18
+ from supervised.utils.metric import (
19
+ CatBoostEvalMetricAveragePrecision,
20
+ CatBoostEvalMetricMSE,
21
+ CatBoostEvalMetricPearson,
22
+ CatBoostEvalMetricSpearman,
23
+ CatBoostEvalMetricUserDefined,
24
+ )
25
+
26
+ logger = logging.getLogger(__name__)
27
+ logger.setLevel(LOG_LEVEL)
28
+
29
+ import catboost
30
+ from catboost import CatBoostClassifier, CatBoostRegressor, Pool
31
+
32
+
33
+ def catboost_eval_metric(ml_task, eval_metric):
34
+ if eval_metric == "user_defined_metric":
35
+ return eval_metric
36
+ metric_name_mapping = {
37
+ BINARY_CLASSIFICATION: {
38
+ "auc": "AUC",
39
+ "logloss": "Logloss",
40
+ "f1": "F1",
41
+ "average_precision": "average_precision",
42
+ "accuracy": "Accuracy",
43
+ },
44
+ MULTICLASS_CLASSIFICATION: {
45
+ "logloss": "MultiClass",
46
+ "f1": "TotalF1:average=Micro",
47
+ "accuracy": "Accuracy",
48
+ },
49
+ REGRESSION: {
50
+ "rmse": "RMSE",
51
+ "mse": "mse",
52
+ "mae": "MAE",
53
+ "mape": "MAPE",
54
+ "r2": "R2",
55
+ "spearman": "spearman",
56
+ "pearson": "pearson",
57
+ },
58
+ }
59
+ return metric_name_mapping[ml_task][eval_metric]
60
+
61
+
62
+ def catboost_objective(ml_task, eval_metric):
63
+ objective = "RMSE"
64
+ if ml_task == BINARY_CLASSIFICATION:
65
+ objective = "Logloss"
66
+ elif ml_task == MULTICLASS_CLASSIFICATION:
67
+ objective = "MultiClass"
68
+ else: # ml_task == REGRESSION
69
+ objective = catboost_eval_metric(REGRESSION, eval_metric)
70
+ if objective in [
71
+ "mse",
72
+ "R2",
73
+ "spearman",
74
+ "pearson",
75
+ "user_defined_metric",
76
+ ]: # cant optimize them directly
77
+ objective = "RMSE"
78
+ return objective
79
+
80
+
81
+ class CatBoostAlgorithm(BaseAlgorithm):
82
+ algorithm_name = "CatBoost"
83
+ algorithm_short_name = "CatBoost"
84
+ warmup_iterations = 20
85
+
86
+ def __init__(self, params):
87
+ super(CatBoostAlgorithm, self).__init__(params)
88
+ self.library_version = catboost.__version__
89
+ self.snapshot_file_path = "training_snapshot"
90
+
91
+ self.explain_level = params.get("explain_level", 0)
92
+ self.rounds = additional.get("max_rounds", 10000)
93
+ self.max_iters = 1
94
+ self.early_stopping_rounds = additional.get("early_stopping_rounds", 50)
95
+
96
+ Algo = CatBoostClassifier
97
+ loss_function = "Logloss"
98
+ if self.params["ml_task"] == BINARY_CLASSIFICATION:
99
+ loss_function = self.params.get("loss_function", "Logloss")
100
+ elif self.params["ml_task"] == MULTICLASS_CLASSIFICATION:
101
+ loss_function = self.params.get("loss_function", "MultiClass")
102
+ elif self.params["ml_task"] == REGRESSION:
103
+ loss_function = self.params.get("loss_function", "RMSE")
104
+ Algo = CatBoostRegressor
105
+
106
+ cat_params = {
107
+ "iterations": self.params.get("num_boost_round", self.rounds),
108
+ "learning_rate": self.params.get("learning_rate", 0.1),
109
+ "depth": self.params.get("depth", 3),
110
+ "rsm": self.params.get("rsm", 1.0),
111
+ "l2_leaf_reg": self.params.get("l2_leaf_reg", 3.0),
112
+ "random_strength": self.params.get("random_strength", 1.0),
113
+ "loss_function": loss_function,
114
+ "eval_metric": self.params.get("eval_metric", loss_function),
115
+ # "custom_metric": self.params.get("eval_metric", loss_function),
116
+ "thread_count": self.params.get("n_jobs", -1),
117
+ "verbose": False,
118
+ "allow_writing_files": False,
119
+ "random_seed": self.params.get("seed", 1),
120
+ }
121
+
122
+ for extra_param in [
123
+ "min_data_in_leaf",
124
+ "bootstrap_type",
125
+ "bagging_temperature",
126
+ "subsample",
127
+ "border_count",
128
+ ]:
129
+ if extra_param in self.params:
130
+ cat_params[extra_param] = self.params[extra_param]
131
+
132
+ self.log_metric_name = cat_params["eval_metric"]
133
+ if cat_params["eval_metric"] == "spearman":
134
+ cat_params["eval_metric"] = CatBoostEvalMetricSpearman()
135
+ self.log_metric_name = "CatBoostEvalMetricSpearman"
136
+ elif cat_params["eval_metric"] == "pearson":
137
+ cat_params["eval_metric"] = CatBoostEvalMetricPearson()
138
+ self.log_metric_name = "CatBoostEvalMetricPearson"
139
+ elif cat_params["eval_metric"] == "average_precision":
140
+ cat_params["eval_metric"] = CatBoostEvalMetricAveragePrecision()
141
+ self.log_metric_name = "CatBoostEvalMetricAveragePrecision"
142
+ elif cat_params["eval_metric"] == "mse":
143
+ cat_params["eval_metric"] = CatBoostEvalMetricMSE()
144
+ self.log_metric_name = "CatBoostEvalMetricMSE"
145
+ elif cat_params["eval_metric"] == "user_defined_metric":
146
+ cat_params["eval_metric"] = CatBoostEvalMetricUserDefined()
147
+ self.log_metric_name = "CatBoostEvalMetricUserDefined"
148
+
149
+ self.model = Algo(**cat_params)
150
+ self.cat_features = None
151
+ self.best_ntree_limit = 0
152
+
153
+ logger.debug("CatBoostAlgorithm.__init__")
154
+
155
+ def _assess_iterations(self, X, y, sample_weight, eval_set, max_time=None):
156
+ if max_time is None:
157
+ max_time = 3600
158
+ try:
159
+ model = copy.deepcopy(self.model)
160
+ model.set_params(iterations=self.warmup_iterations)
161
+ start_time = time.time()
162
+ model.fit(
163
+ X,
164
+ y,
165
+ sample_weight=sample_weight,
166
+ cat_features=self.cat_features,
167
+ init_model=None if self.model.tree_count_ is None else self.model,
168
+ eval_set=eval_set,
169
+ early_stopping_rounds=self.early_stopping_rounds,
170
+ verbose_eval=False,
171
+ )
172
+ elapsed_time = (time.time() - start_time) / float(self.warmup_iterations)
173
+ # print(max_time, elapsed_time, max_time / elapsed_time, np.round(time.time() - start_time, 2))
174
+ new_rounds = int(min(10000, max_time / elapsed_time))
175
+ new_rounds = max(new_rounds, 10)
176
+ return model, new_rounds
177
+ except Exception as e:
178
+ # print(str(e))
179
+ return None, 1000
180
+
181
+ def fit(
182
+ self,
183
+ X,
184
+ y,
185
+ sample_weight=None,
186
+ X_validation=None,
187
+ y_validation=None,
188
+ sample_weight_validation=None,
189
+ log_to_file=None,
190
+ max_time=None,
191
+ ):
192
+ if self.is_fitted():
193
+ print("CatBoost model already fitted. Skip fit().")
194
+ return
195
+
196
+ if self.cat_features is None:
197
+ self.cat_features = []
198
+ for i in range(X.shape[1]):
199
+ if PreprocessingUtils.is_categorical(X.iloc[:, i]):
200
+ self.cat_features += [i]
201
+ col_name = X.columns[i]
202
+ X[col_name] = X[col_name].astype(str)
203
+ if X_validation is not None:
204
+ X_validation[col_name] = X_validation[col_name].astype(str)
205
+
206
+ eval_set = None
207
+ if X_validation is not None and y_validation is not None:
208
+ eval_set = Pool(
209
+ data=X_validation,
210
+ label=y_validation,
211
+ cat_features=self.cat_features,
212
+ weight=sample_weight_validation,
213
+ )
214
+
215
+ if self.params.get("num_boost_round") is None:
216
+ model_init, new_iterations = self._assess_iterations(
217
+ X, y, sample_weight, eval_set, max_time
218
+ )
219
+ self.model.set_params(iterations=new_iterations)
220
+ else:
221
+ model_init = None
222
+ self.model.set_params(iterations=self.params.get("num_boost_round"))
223
+ self.early_stopping_rounds = self.params.get("early_stopping_rounds", 50)
224
+
225
+ self.model.fit(
226
+ X,
227
+ y,
228
+ sample_weight=sample_weight,
229
+ cat_features=self.cat_features,
230
+ init_model=model_init,
231
+ eval_set=eval_set,
232
+ early_stopping_rounds=self.early_stopping_rounds,
233
+ verbose_eval=False,
234
+ )
235
+
236
+ if self.model.best_iteration_ is not None:
237
+ if model_init is not None:
238
+ self.best_ntree_limit = (
239
+ self.model.best_iteration_ + model_init.tree_count_ + 1
240
+ )
241
+ else:
242
+ self.best_ntree_limit = self.model.best_iteration_ + 1
243
+
244
+ else:
245
+ # just take all the trees
246
+ # the warm-up trees are already included
247
+ # dont need to add +1
248
+ self.best_ntree_limit = self.model.tree_count_
249
+
250
+ if log_to_file is not None:
251
+ train_scores = self.model.evals_result_["learn"].get(self.log_metric_name)
252
+ validation_scores = self.model.evals_result_["validation"].get(
253
+ self.log_metric_name
254
+ )
255
+ if model_init is not None:
256
+ if train_scores is not None:
257
+ train_scores = (
258
+ model_init.evals_result_["learn"].get(self.log_metric_name)
259
+ + train_scores
260
+ )
261
+ if validation_scores is not None:
262
+ validation_scores = (
263
+ model_init.evals_result_["validation"].get(self.log_metric_name)
264
+ + validation_scores
265
+ )
266
+ iteration = None
267
+ if train_scores is not None:
268
+ iteration = range(len(validation_scores))
269
+ elif validation_scores is not None:
270
+ iteration = range(len(validation_scores))
271
+
272
+ result = pd.DataFrame(
273
+ {
274
+ "iteration": iteration,
275
+ "train": train_scores,
276
+ "validation": validation_scores,
277
+ }
278
+ )
279
+ result.to_csv(log_to_file, index=False, header=False)
280
+
281
+ if self.params["ml_task"] != REGRESSION:
282
+ self.classes_ = np.unique(y)
283
+
284
+ def is_fitted(self):
285
+ return self.model is not None and self.model.tree_count_ is not None
286
+
287
+ def predict(self, X):
288
+ self.reload()
289
+ if self.params["ml_task"] == BINARY_CLASSIFICATION:
290
+ return self.model.predict_proba(X, ntree_end=self.best_ntree_limit)[:, 1]
291
+ elif self.params["ml_task"] == MULTICLASS_CLASSIFICATION:
292
+ return self.model.predict_proba(X, ntree_end=self.best_ntree_limit)
293
+
294
+ return self.model.predict(X, ntree_end=self.best_ntree_limit)
295
+
296
+ def copy(self):
297
+ return copy.deepcopy(self)
298
+
299
+ def save(self, model_file_path):
300
+ self.model.save_model(model_file_path)
301
+ self.model_file_path = model_file_path
302
+ logger.debug("CatBoostAlgorithm save model to %s" % model_file_path)
303
+
304
+ def load(self, model_file_path):
305
+ logger.debug("CatBoostLearner load model from %s" % model_file_path)
306
+
307
+ # waiting for fix https://github.com/catboost/catboost/issues/696
308
+ Algo = CatBoostClassifier
309
+ if self.params["ml_task"] == REGRESSION:
310
+ Algo = CatBoostRegressor
311
+
312
+ # loading might throw warnings in the case of custom eval_metric
313
+ # check https://github.com/catboost/catboost/issues/1169
314
+ self.model = Algo().load_model(model_file_path)
315
+ self.model_file_path = model_file_path
316
+
317
+ def file_extension(self):
318
+ return "catboost"
319
+
320
+ def get_metric_name(self):
321
+ metric = self.params.get("eval_metric")
322
+ if metric is None:
323
+ return None
324
+ if metric == "Logloss":
325
+ return "logloss"
326
+ elif metric == "AUC":
327
+ return "auc"
328
+ elif metric == "MultiClass":
329
+ return "logloss"
330
+ elif metric == "RMSE":
331
+ return "rmse"
332
+ elif metric == "MSE":
333
+ return "mse"
334
+ elif metric == "MAE":
335
+ return "mae"
336
+ elif metric == "MAPE":
337
+ return "mape"
338
+ elif metric in ["F1", "TotalF1:average=Micro"]:
339
+ return "f1"
340
+ elif metric == "Accuracy":
341
+ return "accuracy"
342
+ return metric
343
+
344
+
345
+ classification_params = {
346
+ "learning_rate": [0.025, 0.05, 0.1, 0.2],
347
+ "depth": [4, 5, 6, 7, 8, 9],
348
+ "rsm": [0.7, 0.8, 0.9, 1], # random subspace method
349
+ "loss_function": ["Logloss"],
350
+ }
351
+
352
+ classification_default_params = {
353
+ "learning_rate": 0.1,
354
+ "depth": 6,
355
+ "rsm": 1,
356
+ "loss_function": "Logloss",
357
+ }
358
+
359
+ additional = {
360
+ "max_rounds": 10000,
361
+ "early_stopping_rounds": 50,
362
+ "max_rows_limit": None,
363
+ "max_cols_limit": None,
364
+ }
365
+ required_preprocessing = [
366
+ "missing_values_inputation",
367
+ "datetime_transform",
368
+ "text_transform",
369
+ "target_as_integer",
370
+ ]
371
+
372
+
373
+ class CBClassifier(ClassifierMixin, CatBoostAlgorithm):
374
+ pass
375
+
376
+
377
+ AlgorithmsRegistry.add(
378
+ BINARY_CLASSIFICATION,
379
+ CBClassifier,
380
+ classification_params,
381
+ required_preprocessing,
382
+ additional,
383
+ classification_default_params,
384
+ )
385
+
386
+ multiclass_classification_params = copy.deepcopy(classification_params)
387
+ multiclass_classification_params["loss_function"] = ["MultiClass"]
388
+ multiclass_classification_params["depth"] = [3, 4, 5, 6]
389
+ multiclass_classification_params["learning_rate"] = [0.1, 0.15, 0.2]
390
+
391
+ multiclass_classification_default_params = copy.deepcopy(classification_default_params)
392
+ multiclass_classification_default_params["loss_function"] = "MultiClass"
393
+ multiclass_classification_default_params["depth"] = 5
394
+ multiclass_classification_default_params["learning_rate"] = 0.15
395
+
396
+
397
+ AlgorithmsRegistry.add(
398
+ MULTICLASS_CLASSIFICATION,
399
+ CBClassifier,
400
+ multiclass_classification_params,
401
+ required_preprocessing,
402
+ additional,
403
+ multiclass_classification_default_params,
404
+ )
405
+
406
+ regression_params = copy.deepcopy(classification_params)
407
+ regression_params["loss_function"] = ["RMSE", "MAE", "MAPE"]
408
+
409
+ regression_required_preprocessing = [
410
+ "missing_values_inputation",
411
+ "datetime_transform",
412
+ "text_transform",
413
+ "target_scale",
414
+ ]
415
+
416
+
417
+ regression_default_params = {
418
+ "learning_rate": 0.1,
419
+ "depth": 6,
420
+ "rsm": 1,
421
+ "loss_function": "RMSE",
422
+ }
423
+
424
+
425
+ class CBRegressor(RegressorMixin, CatBoostAlgorithm):
426
+ pass
427
+
428
+
429
+ AlgorithmsRegistry.add(
430
+ REGRESSION,
431
+ CBRegressor,
432
+ regression_params,
433
+ regression_required_preprocessing,
434
+ additional,
435
+ regression_default_params,
436
+ )