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