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,338 @@
1
+ import json
2
+ import os
3
+ import warnings
4
+
5
+ import joblib
6
+ import matplotlib
7
+ import optuna
8
+ from matplotlib import pyplot as plt
9
+
10
+ from supervised.exceptions import AutoMLException
11
+ from supervised.preprocessing.preprocessing_utils import PreprocessingUtils
12
+ from supervised.tuner.optuna.catboost import CatBoostObjective
13
+ from supervised.tuner.optuna.extra_trees import ExtraTreesObjective
14
+ from supervised.tuner.optuna.knn import KNNObjective
15
+ from supervised.tuner.optuna.lightgbm import LightgbmObjective
16
+ from supervised.tuner.optuna.nn import NeuralNetworkObjective
17
+ from supervised.tuner.optuna.random_forest import RandomForestObjective
18
+ from supervised.tuner.optuna.xgboost import XgboostObjective
19
+ from supervised.utils.jsonencoder import MLJSONEncoder
20
+ from supervised.utils.metric import Metric
21
+
22
+
23
+ class OptunaTuner:
24
+ def __init__(
25
+ self,
26
+ results_path,
27
+ ml_task,
28
+ eval_metric,
29
+ time_budget=3600,
30
+ init_params={},
31
+ verbose=True,
32
+ n_jobs=-1,
33
+ random_state=42,
34
+ ):
35
+ if eval_metric.name not in [
36
+ "auc",
37
+ "logloss",
38
+ "rmse",
39
+ "mse",
40
+ "mae",
41
+ "mape",
42
+ "r2",
43
+ "spearman",
44
+ "pearson",
45
+ "f1",
46
+ "f1_micro",
47
+ "f1_macro",
48
+ "f1_weighted",
49
+ "average_precision",
50
+ "accuracy",
51
+ "user_defined_metric",
52
+ ]:
53
+ raise AutoMLException(f"Metric {eval_metric.name} is not supported")
54
+
55
+ self.study_dir = os.path.join(results_path, "optuna")
56
+ if not os.path.exists(self.study_dir):
57
+ try:
58
+ os.mkdir(self.study_dir)
59
+ except Exception as e:
60
+ print("Problem while creating directory for optuna studies.", str(e))
61
+ self.tuning_fname = os.path.join(self.study_dir, "optuna.json")
62
+ self.tuning = init_params
63
+ self.eval_metric = eval_metric
64
+
65
+ self.direction = (
66
+ "maximize" if Metric.optimize_negative(eval_metric.name) else "minimize"
67
+ )
68
+ self.n_warmup_steps = (
69
+ 500 # set large enough to give small learning rates a chance
70
+ )
71
+ self.time_budget = time_budget
72
+ self.verbose = verbose
73
+ self.ml_task = ml_task
74
+ self.n_jobs = n_jobs
75
+ self.random_state = random_state
76
+ self.cat_features_indices = []
77
+ self.load()
78
+ if not self.verbose:
79
+ optuna.logging.set_verbosity(optuna.logging.CRITICAL)
80
+
81
+ @staticmethod
82
+ def is_optimizable(algorithm_name):
83
+ return algorithm_name in [
84
+ "Extra Trees",
85
+ "Random Forest",
86
+ "CatBoost",
87
+ "Xgboost",
88
+ "LightGBM",
89
+ "Nearest Neighbors",
90
+ "Neural Network",
91
+ ]
92
+
93
+ def optimize(
94
+ self,
95
+ algorithm,
96
+ data_type,
97
+ X_train,
98
+ y_train,
99
+ sample_weight,
100
+ X_validation,
101
+ y_validation,
102
+ sample_weight_validation,
103
+ learner_params,
104
+ ):
105
+ # only tune models with original data type
106
+ if data_type != "original":
107
+ return learner_params
108
+
109
+ key = f"{data_type}_{algorithm}"
110
+ if key in self.tuning:
111
+ return self.update_learner_params(learner_params, self.tuning[key])
112
+
113
+ if self.verbose:
114
+ print(
115
+ f"Optuna optimizes {algorithm} with time budget {self.time_budget} seconds "
116
+ f"eval_metric {self.eval_metric.name} ({self.direction})"
117
+ )
118
+
119
+ self.cat_features_indices = []
120
+ for i in range(X_train.shape[1]):
121
+ if PreprocessingUtils.is_categorical(X_train.iloc[:, i]):
122
+ self.cat_features_indices += [i]
123
+
124
+ study = optuna.create_study(
125
+ direction=self.direction,
126
+ sampler=optuna.samplers.TPESampler(seed=self.random_state),
127
+ pruner=optuna.pruners.MedianPruner(n_warmup_steps=self.n_warmup_steps),
128
+ )
129
+ obejctive = None
130
+ if algorithm == "LightGBM":
131
+ objective = LightgbmObjective(
132
+ self.ml_task,
133
+ X_train,
134
+ y_train,
135
+ sample_weight,
136
+ X_validation,
137
+ y_validation,
138
+ sample_weight_validation,
139
+ self.eval_metric,
140
+ self.cat_features_indices,
141
+ self.n_jobs,
142
+ self.random_state,
143
+ )
144
+ elif algorithm == "Xgboost":
145
+ objective = XgboostObjective(
146
+ self.ml_task,
147
+ X_train,
148
+ y_train,
149
+ sample_weight,
150
+ X_validation,
151
+ y_validation,
152
+ sample_weight_validation,
153
+ self.eval_metric,
154
+ self.n_jobs,
155
+ self.random_state,
156
+ )
157
+ elif algorithm == "CatBoost":
158
+ objective = CatBoostObjective(
159
+ self.ml_task,
160
+ X_train,
161
+ y_train,
162
+ sample_weight,
163
+ X_validation,
164
+ y_validation,
165
+ sample_weight_validation,
166
+ self.eval_metric,
167
+ self.cat_features_indices,
168
+ self.n_jobs,
169
+ self.random_state,
170
+ )
171
+ elif algorithm == "Random Forest":
172
+ objective = RandomForestObjective(
173
+ self.ml_task,
174
+ X_train,
175
+ y_train,
176
+ sample_weight,
177
+ X_validation,
178
+ y_validation,
179
+ sample_weight_validation,
180
+ self.eval_metric,
181
+ self.n_jobs,
182
+ self.random_state,
183
+ )
184
+ elif algorithm == "Extra Trees":
185
+ objective = ExtraTreesObjective(
186
+ self.ml_task,
187
+ X_train,
188
+ y_train,
189
+ sample_weight,
190
+ X_validation,
191
+ y_validation,
192
+ sample_weight_validation,
193
+ self.eval_metric,
194
+ self.n_jobs,
195
+ self.random_state,
196
+ )
197
+ elif algorithm == "Nearest Neighbors":
198
+ objective = KNNObjective(
199
+ self.ml_task,
200
+ X_train,
201
+ y_train,
202
+ sample_weight,
203
+ X_validation,
204
+ y_validation,
205
+ sample_weight_validation,
206
+ self.eval_metric,
207
+ self.n_jobs,
208
+ self.random_state,
209
+ )
210
+ elif algorithm == "Neural Network":
211
+ objective = NeuralNetworkObjective(
212
+ self.ml_task,
213
+ X_train,
214
+ y_train,
215
+ sample_weight,
216
+ X_validation,
217
+ y_validation,
218
+ sample_weight_validation,
219
+ self.eval_metric,
220
+ self.n_jobs,
221
+ self.random_state,
222
+ )
223
+
224
+ study.optimize(
225
+ objective, n_trials=5000, timeout=self.time_budget, gc_after_trial=True
226
+ )
227
+
228
+ self.plot_study(algorithm, data_type, study)
229
+
230
+ joblib.dump(study, os.path.join(self.study_dir, key + ".joblib"))
231
+
232
+ best = study.best_params
233
+
234
+ if algorithm == "LightGBM":
235
+ best["metric"] = objective.eval_metric_name
236
+ best["custom_eval_metric_name"] = objective.custom_eval_metric_name
237
+ best["num_boost_round"] = objective.rounds
238
+ best["early_stopping_rounds"] = objective.early_stopping_rounds
239
+ # best["learning_rate"] = objective.learning_rate
240
+ best["cat_feature"] = self.cat_features_indices
241
+ best["feature_pre_filter"] = False
242
+ best["seed"] = objective.seed
243
+ elif algorithm == "CatBoost":
244
+ best["eval_metric"] = objective.eval_metric_name
245
+ best["num_boost_round"] = objective.rounds
246
+ best["early_stopping_rounds"] = objective.early_stopping_rounds
247
+ # best["bootstrap_type"] = "Bernoulli"
248
+ # best["learning_rate"] = objective.learning_rate
249
+ best["seed"] = objective.seed
250
+ elif algorithm == "Xgboost":
251
+ best["objective"] = objective.objective
252
+ best["eval_metric"] = objective.eval_metric_name
253
+ # best["eta"] = objective.learning_rate
254
+ best["max_rounds"] = objective.rounds
255
+ best["early_stopping_rounds"] = objective.early_stopping_rounds
256
+ best["seed"] = objective.seed
257
+ elif algorithm == "Extra Trees":
258
+ # Extra Trees are not using early stopping
259
+ best["max_steps"] = objective.max_steps # each step has 100 trees
260
+ best["seed"] = objective.seed
261
+ best["eval_metric_name"] = self.eval_metric.name
262
+ elif algorithm == "Random Forest":
263
+ # Random Forest is not using early stopping
264
+ best["max_steps"] = objective.max_steps # each step has 100 trees
265
+ best["seed"] = objective.seed
266
+ best["eval_metric_name"] = self.eval_metric.name
267
+ elif algorithm == "Nearest Neighbors":
268
+ best["rows_limit"] = 100000
269
+ elif algorithm == "Neural Network":
270
+ pass
271
+
272
+ self.tuning[key] = best
273
+ self.save()
274
+
275
+ return self.update_learner_params(learner_params, best)
276
+
277
+ def update_learner_params(self, learner_params, best):
278
+ for k, v in best.items():
279
+ learner_params[k] = v
280
+ return learner_params
281
+
282
+ def save(self):
283
+ with open(self.tuning_fname, "w") as fout:
284
+ fout.write(json.dumps(self.tuning, indent=4, cls=MLJSONEncoder))
285
+
286
+ def load(self):
287
+ if os.path.exists(self.tuning_fname):
288
+ params = json.loads(open(self.tuning_fname).read())
289
+ for k, v in params.items():
290
+ self.tuning[k] = v
291
+
292
+ def plot_study(self, algorithm, data_type, study):
293
+ key = f"{data_type}_{algorithm}"
294
+
295
+ plots = [
296
+ (
297
+ optuna.visualization.matplotlib.plot_optimization_history,
298
+ "optimization_history",
299
+ ),
300
+ (
301
+ optuna.visualization.matplotlib.plot_parallel_coordinate,
302
+ "parallel_coordinate",
303
+ ),
304
+ (
305
+ optuna.visualization.matplotlib.plot_param_importances,
306
+ "param_importances",
307
+ ),
308
+ # (optuna.visualization.matplotlib.plot_slice, "slice"),
309
+ ]
310
+
311
+ matplotlib_default_figsize = matplotlib.rcParams["figure.figsize"]
312
+ matplotlib.rcParams["figure.figsize"] = (11, 7)
313
+
314
+ md = f"# Optuna tuning for {algorithm} on {data_type} data\n\n"
315
+ for plot, title in plots:
316
+ try:
317
+ with warnings.catch_warnings():
318
+ warnings.simplefilter("ignore")
319
+ plt.figure()
320
+ plt.rcParams["axes.grid"] = title != "parallel_coordinate"
321
+ plot(study)
322
+ plt.tight_layout(pad=2.0)
323
+ fname = f"{key}_{title}.png"
324
+ plt.savefig(os.path.join(self.study_dir, fname))
325
+ plt.close("all")
326
+
327
+ md += f'## {algorithm} {title.replace("_", " ").title()}\n\n'
328
+ md += f"![{algorithm} {data_type} {title}]({fname})\n\n"
329
+
330
+ except Exception as e:
331
+ print(str(e))
332
+
333
+ matplotlib.rcParams["figure.figsize"] = matplotlib_default_figsize
334
+ plt.style.use("default")
335
+
336
+ with open(os.path.join(self.study_dir, "README.md"), "a") as fout:
337
+ fout.write(md)
338
+ fout.write("\n\n[<< Go back](../README.md)\n")
@@ -0,0 +1,136 @@
1
+ from functools import partial
2
+
3
+ import numpy as np
4
+ import optuna
5
+ import optuna_integration
6
+ import xgboost as xgb
7
+
8
+ from supervised.algorithms.registry import (
9
+ MULTICLASS_CLASSIFICATION,
10
+ )
11
+ from supervised.algorithms.xgboost import xgboost_eval_metric, xgboost_objective
12
+ from supervised.utils.metric import (
13
+ F1_METRICS,
14
+ Metric,
15
+ xgboost_eval_metric_accuracy,
16
+ xgboost_eval_metric_average_precision,
17
+ xgboost_eval_metric_f1,
18
+ xgboost_eval_metric_mse,
19
+ xgboost_eval_metric_pearson,
20
+ xgboost_eval_metric_r2,
21
+ xgboost_eval_metric_spearman,
22
+ xgboost_eval_metric_user_defined,
23
+ )
24
+
25
+ EPS = 1e-8
26
+
27
+
28
+ class XgboostObjective:
29
+ def __init__(
30
+ self,
31
+ ml_task,
32
+ X_train,
33
+ y_train,
34
+ sample_weight,
35
+ X_validation,
36
+ y_validation,
37
+ sample_weight_validation,
38
+ eval_metric,
39
+ n_jobs,
40
+ random_state,
41
+ ):
42
+ self.dtrain = xgb.DMatrix(X_train, label=y_train, weight=sample_weight)
43
+ self.dvalidation = xgb.DMatrix(
44
+ X_validation, label=y_validation, weight=sample_weight_validation
45
+ )
46
+ self.X_validation = X_validation
47
+ self.y_validation = y_validation
48
+ self.eval_metric = eval_metric
49
+ self.n_jobs = n_jobs
50
+
51
+ self.learning_rate = 0.0125
52
+ self.rounds = 1000
53
+ self.early_stopping_rounds = 50
54
+ self.seed = random_state
55
+
56
+ self.objective = ""
57
+ self.eval_metric_name = ""
58
+ self.num_class = (
59
+ len(np.unique(y_train)) if ml_task == MULTICLASS_CLASSIFICATION else None
60
+ )
61
+
62
+ self.objective = xgboost_objective(ml_task, eval_metric.name)
63
+ self.eval_metric_name = xgboost_eval_metric(ml_task, eval_metric.name)
64
+
65
+ self.custom_eval_metric = None
66
+ if self.eval_metric_name == "r2":
67
+ self.custom_eval_metric = xgboost_eval_metric_r2
68
+ elif self.eval_metric_name == "spearman":
69
+ self.custom_eval_metric = xgboost_eval_metric_spearman
70
+ elif self.eval_metric_name == "pearson":
71
+ self.custom_eval_metric = xgboost_eval_metric_pearson
72
+ elif self.eval_metric_name in F1_METRICS:
73
+ self.custom_eval_metric = partial(
74
+ xgboost_eval_metric_f1, metric_name=self.eval_metric_name, maximize=True
75
+ )
76
+ elif self.eval_metric_name == "average_precision":
77
+ self.custom_eval_metric = xgboost_eval_metric_average_precision
78
+ elif self.eval_metric_name == "accuracy":
79
+ self.custom_eval_metric = xgboost_eval_metric_accuracy
80
+ elif self.eval_metric_name == "mse":
81
+ self.custom_eval_metric = xgboost_eval_metric_mse
82
+ elif self.eval_metric_name == "user_defined_metric":
83
+ self.custom_eval_metric = xgboost_eval_metric_user_defined
84
+
85
+ def __call__(self, trial):
86
+ param = {
87
+ "objective": self.objective,
88
+ "eval_metric": self.eval_metric_name,
89
+ "tree_method": "hist",
90
+ "booster": "gbtree",
91
+ "eta": trial.suggest_categorical("eta", [0.0125, 0.025, 0.05, 0.1]),
92
+ "max_depth": trial.suggest_int("max_depth", 2, 12),
93
+ "lambda": trial.suggest_float("lambda", EPS, 10.0, log=True),
94
+ "alpha": trial.suggest_float("alpha", EPS, 10.0, log=True),
95
+ "colsample_bytree": min(
96
+ trial.suggest_float("colsample_bytree", 0.3, 1.0 + EPS), 1.0
97
+ ),
98
+ "subsample": min(trial.suggest_float("subsample", 0.3, 1.0 + EPS), 1.0),
99
+ "min_child_weight": trial.suggest_int("min_child_weight", 1, 100),
100
+ "n_jobs": self.n_jobs,
101
+ "seed": self.seed,
102
+ "verbosity": 0,
103
+ }
104
+ if self.custom_eval_metric is not None:
105
+ del param["eval_metric"]
106
+
107
+ if self.num_class is not None:
108
+ param["num_class"] = self.num_class
109
+ try:
110
+ pruning_callback = optuna_integration.XGBoostPruningCallback(
111
+ trial, f"validation-{self.eval_metric_name}"
112
+ )
113
+ bst = xgb.train(
114
+ param,
115
+ self.dtrain,
116
+ self.rounds,
117
+ evals=[(self.dvalidation, "validation")],
118
+ early_stopping_rounds=self.early_stopping_rounds,
119
+ callbacks=[pruning_callback],
120
+ verbose_eval=False,
121
+ custom_metric=self.custom_eval_metric,
122
+ maximize=True if self.eval_metric_name in F1_METRICS else None,
123
+ )
124
+ preds = bst.predict(
125
+ self.dvalidation, iteration_range=(0, bst.best_iteration)
126
+ )
127
+ score = self.eval_metric(self.y_validation, preds)
128
+ if Metric.optimize_negative(self.eval_metric.name):
129
+ score *= -1.0
130
+ except optuna.exceptions.TrialPruned as e:
131
+ raise e
132
+ except Exception as e:
133
+ print("Exception in XgboostObjective", str(e))
134
+ return None
135
+
136
+ return score
@@ -0,0 +1,147 @@
1
+ from supervised.algorithms.registry import (
2
+ BINARY_CLASSIFICATION,
3
+ MULTICLASS_CLASSIFICATION,
4
+ REGRESSION,
5
+ )
6
+ from supervised.preprocessing.preprocessing_categorical import PreprocessingCategorical
7
+ from supervised.preprocessing.preprocessing_missing import PreprocessingMissingValues
8
+ from supervised.preprocessing.scale import Scale
9
+
10
+
11
+ class PreprocessingTuner:
12
+
13
+ """
14
+ This class prepare configuration for data preprocessing
15
+ """
16
+
17
+ CATEGORICALS_MIX = "categorical_mix" # mix int and one-hot
18
+ CATEGORICALS_ALL_INT = "categoricals_all_integers"
19
+
20
+ @staticmethod
21
+ def get(
22
+ required_preprocessing,
23
+ data_info,
24
+ machinelearning_task,
25
+ categorical_strategy=CATEGORICALS_ALL_INT,
26
+ ):
27
+ columns_preprocessing = {}
28
+ columns_info = data_info["columns_info"]
29
+
30
+ for col, preprocessing_needed in columns_info.items():
31
+ preprocessing_to_apply = []
32
+
33
+ # remove empty columns and columns with only one variable
34
+ if (
35
+ "empty_column" in preprocessing_needed
36
+ or "constant_column" in preprocessing_needed
37
+ ):
38
+ preprocessing_to_apply += ["remove_column"]
39
+ columns_preprocessing[col] = preprocessing_to_apply
40
+ continue
41
+
42
+ # always check for missing values
43
+ if (
44
+ "missing_values_inputation" in required_preprocessing
45
+ and "missing_values" in preprocessing_needed
46
+ ):
47
+ preprocessing_to_apply += [PreprocessingMissingValues.FILL_NA_MEDIAN]
48
+ # convert to categorical only for categorical types
49
+ convert_to_integer_will_be_applied = False
50
+ if (
51
+ "convert_categorical"
52
+ in required_preprocessing # the algorithm needs converted categoricals
53
+ and "categorical" in preprocessing_needed # the feature is categorical
54
+ ):
55
+ if categorical_strategy == PreprocessingTuner.CATEGORICALS_MIX:
56
+ if PreprocessingCategorical.MANY_CATEGORIES in preprocessing_needed:
57
+ preprocessing_to_apply += [
58
+ PreprocessingCategorical.CONVERT_INTEGER
59
+ ]
60
+ convert_to_integer_will_be_applied = True # maybe scale needed
61
+ else:
62
+ preprocessing_to_apply += [
63
+ PreprocessingCategorical.CONVERT_ONE_HOT
64
+ ]
65
+ else: # all integers
66
+ preprocessing_to_apply += [PreprocessingCategorical.CONVERT_INTEGER]
67
+ convert_to_integer_will_be_applied = True # maybe scale needed
68
+
69
+ """
70
+ if PreprocessingCategorical.CONVERT_ONE_HOT in preprocessing_needed:
71
+ preprocessing_to_apply += [PreprocessingCategorical.CONVERT_ONE_HOT]
72
+ elif PreprocessingCategorical.CONVERT_LOO in preprocessing_needed:
73
+ preprocessing_to_apply += [PreprocessingCategorical.CONVERT_LOO]
74
+ convert_to_integer_will_be_applied = True # maybe scale needed
75
+ else:
76
+ preprocessing_to_apply += [PreprocessingCategorical.CONVERT_INTEGER]
77
+ convert_to_integer_will_be_applied = True # maybe scale needed
78
+ """
79
+
80
+ if (
81
+ "datetime_transform" in required_preprocessing
82
+ and "datetime_transform" in preprocessing_needed
83
+ ):
84
+ preprocessing_to_apply += ["datetime_transform"]
85
+ if (
86
+ "text_transform" in required_preprocessing
87
+ and "text_transform" in preprocessing_needed
88
+ ):
89
+ preprocessing_to_apply += ["text_transform"]
90
+
91
+ if "scale" in required_preprocessing:
92
+ if (
93
+ convert_to_integer_will_be_applied
94
+ or "scale" in preprocessing_needed
95
+ ):
96
+ preprocessing_to_apply += [Scale.SCALE_NORMAL]
97
+
98
+ if (
99
+ "ip_transform" in required_preprocessing
100
+ and "ip_transform" in preprocessing_needed
101
+ ):
102
+ # IPTransformer handles missing addresses itself, and scaling
103
+ # must refer to its generated columns rather than the raw input.
104
+ preprocessing_to_apply = ["ip_transform"]
105
+ if "scale" in required_preprocessing:
106
+ preprocessing_to_apply.append(Scale.SCALE_NORMAL)
107
+
108
+ # remeber which preprocessing we need to apply
109
+ if preprocessing_to_apply:
110
+ columns_preprocessing[col] = preprocessing_to_apply
111
+
112
+ target_info = data_info["target_info"]
113
+ target_preprocessing = []
114
+ # always remove missing values from target,
115
+ # target with missing values might be in the train and in the validation datasets
116
+ target_preprocessing += [PreprocessingMissingValues.NA_EXCLUDE]
117
+
118
+ if "target_as_integer" in required_preprocessing:
119
+ if machinelearning_task == BINARY_CLASSIFICATION:
120
+ if "convert_0_1" in target_info:
121
+ target_preprocessing += [PreprocessingCategorical.CONVERT_INTEGER]
122
+
123
+ if machinelearning_task == MULTICLASS_CLASSIFICATION:
124
+ # if PreprocessingUtils.is_categorical(y):
125
+ # always convert to integer, there can be many situations that can break
126
+ # for example, classes starting from 1, ...
127
+ # or classes not for every number, for example 0,2,3,4
128
+ # just always convert
129
+ target_preprocessing += [PreprocessingCategorical.CONVERT_INTEGER]
130
+
131
+ elif "target_as_one_hot" in required_preprocessing:
132
+ target_preprocessing += [PreprocessingCategorical.CONVERT_ONE_HOT]
133
+
134
+ if (
135
+ machinelearning_task == REGRESSION
136
+ and "target_scale" in required_preprocessing
137
+ ):
138
+ if "scale_log" in target_info:
139
+ target_preprocessing += [Scale.SCALE_LOG_AND_NORMAL]
140
+ elif "scale" in target_info:
141
+ target_preprocessing += [Scale.SCALE_NORMAL]
142
+
143
+ return {
144
+ "columns_preprocessing": columns_preprocessing,
145
+ "target_preprocessing": target_preprocessing,
146
+ "ml_task": machinelearning_task,
147
+ }
@@ -0,0 +1,22 @@
1
+ import numpy as np
2
+
3
+
4
+ class RandomParameters:
5
+
6
+ """
7
+ Example params are in JSON format:
8
+ {
9
+ "booster": ["gbtree", "gblinear"],
10
+ "objective": ["binary:logistic"],
11
+ "eval_metric": ["auc", "logloss"],
12
+ "eta": [0.0025, 0.005, 0.0075, 0.01, 0.025, 0.05, 0.075, 0.1]
13
+ }
14
+ """
15
+
16
+ @staticmethod
17
+ def get(params, seed=1):
18
+ np.random.seed(seed)
19
+ generated_params = {"seed": seed}
20
+ for k in params:
21
+ generated_params[k] = np.random.permutation(params[k])[0].item()
22
+ return generated_params