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