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,1501 @@
1
+ import copy
2
+ import json
3
+ import logging
4
+ import os
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ from sklearn.preprocessing import OneHotEncoder
9
+
10
+ from supervised.algorithms.catboost import catboost_eval_metric
11
+ from supervised.algorithms.lightgbm import lightgbm_eval_metric
12
+ from supervised.algorithms.registry import (
13
+ BINARY_CLASSIFICATION,
14
+ MULTICLASS_CLASSIFICATION,
15
+ REGRESSION,
16
+ AlgorithmsRegistry,
17
+ )
18
+ from supervised.algorithms.xgboost import xgboost_eval_metric
19
+ from supervised.preprocessing.label_encoder import LabelEncoder
20
+ from supervised.preprocessing.preprocessing_categorical import PreprocessingCategorical
21
+ from supervised.tuner.hill_climbing import HillClimbing
22
+ from supervised.tuner.preprocessing_tuner import PreprocessingTuner
23
+ from supervised.tuner.random_parameters import RandomParameters
24
+ from supervised.utils.config import LOG_LEVEL
25
+ from supervised.utils.utils import dump_data, load_data
26
+
27
+ logger = logging.getLogger(__name__)
28
+ logger.setLevel(LOG_LEVEL)
29
+
30
+
31
+ class MljarTuner:
32
+ def __init__(
33
+ self,
34
+ tuner_params,
35
+ algorithms,
36
+ ml_task,
37
+ eval_metric,
38
+ validation_strategy,
39
+ explain_level,
40
+ data_info,
41
+ golden_features,
42
+ features_selection,
43
+ train_ensemble,
44
+ stack_models,
45
+ adjust_validation,
46
+ boost_on_errors,
47
+ kmeans_features,
48
+ mix_encoding,
49
+ optuna_time_budget,
50
+ optuna_init_params,
51
+ optuna_verbose,
52
+ n_jobs,
53
+ seed,
54
+ fairness_metric=None,
55
+ fairness_threshold=None,
56
+ privileged_groups=[],
57
+ underprivileged_groups=[],
58
+ ):
59
+ logger.debug("MljarTuner.__init__")
60
+ self._start_random_models = tuner_params.get("start_random_models", 5)
61
+ self._hill_climbing_steps = tuner_params.get("hill_climbing_steps", 3)
62
+ self._top_models_to_improve = tuner_params.get("top_models_to_improve", 3)
63
+ self._algorithms = algorithms
64
+ self._ml_task = ml_task
65
+ self._validation_strategy = validation_strategy
66
+ self._explain_level = explain_level
67
+ self._data_info = data_info
68
+ self._golden_features = golden_features
69
+ self._features_selection = features_selection
70
+ self._train_ensemble = train_ensemble
71
+ self._stack_models = stack_models
72
+ self._adjust_validation = adjust_validation
73
+ self._boost_on_errors = boost_on_errors
74
+ self._kmeans_features = kmeans_features
75
+ self._mix_encoding = mix_encoding
76
+ self._optuna_time_budget = optuna_time_budget
77
+ self._optuna_init_params = optuna_init_params
78
+ self._optuna_verbose = optuna_verbose
79
+ self._eval_metric = eval_metric
80
+ self._n_jobs = n_jobs
81
+ self._fairness_metric = fairness_metric
82
+ self._fairness_threshold = fairness_threshold
83
+ self._privileged_groups = privileged_groups
84
+ self._underprivileged_groups = underprivileged_groups
85
+ self._seed = seed
86
+ self._unique_params_keys = []
87
+
88
+ def _apply_categorical_strategies(self):
89
+ if self._data_info is None:
90
+ return []
91
+ if self._data_info.get("columns_info") is None:
92
+ return []
93
+
94
+ strategies = []
95
+ for k, v in self._data_info["columns_info"].items():
96
+
97
+ if (
98
+ PreprocessingCategorical.FEW_CATEGORIES in v
99
+ and PreprocessingTuner.CATEGORICALS_MIX not in strategies
100
+ and self._mix_encoding
101
+ ):
102
+ strategies += [PreprocessingTuner.CATEGORICALS_MIX]
103
+
104
+ if len(strategies) == 1: # disable loo encoding
105
+ # cant add more
106
+ # stop
107
+ break
108
+
109
+ return strategies
110
+
111
+ def _can_apply_kmeans_features(self):
112
+ if self._data_info is None:
113
+ return False
114
+
115
+ # are there any continous
116
+ continous_cols = 0
117
+ for k, v in self._data_info["columns_info"].items():
118
+ if "categorical" not in v:
119
+ continous_cols += 1
120
+
121
+ # too little columns
122
+ if continous_cols == 0:
123
+ return False
124
+
125
+ # too many columns
126
+ if continous_cols > 300:
127
+ return False
128
+
129
+ # all good, can apply kmeans
130
+ return True
131
+
132
+ def _can_apply_golden_features(self):
133
+ if self._data_info is None:
134
+ return False
135
+
136
+ # are there any continous
137
+ continous_cols = 0
138
+ for k, v in self._data_info["columns_info"].items():
139
+ if "categorical" not in v:
140
+ continous_cols += 1
141
+
142
+ # too little columns
143
+ if continous_cols == 0:
144
+ return False
145
+
146
+ # all good, can apply golden features
147
+ return True
148
+
149
+ def steps(self):
150
+ all_steps = []
151
+ if self._adjust_validation:
152
+ all_steps += ["adjust_validation"]
153
+
154
+ all_steps += ["simple_algorithms", "default_algorithms"]
155
+
156
+ if self._fairness_metric is not None:
157
+ all_steps += ["unfairness_mitigation"]
158
+ # up to 10 steps
159
+ for i in range(10):
160
+ all_steps += [f"unfairness_mitigation_update_{i+1}"]
161
+
162
+ if self._start_random_models > 1:
163
+ all_steps += ["not_so_random"]
164
+
165
+ categorical_strategies = self._apply_categorical_strategies()
166
+ if PreprocessingTuner.CATEGORICALS_MIX in categorical_strategies:
167
+ all_steps += ["mix_encoding"]
168
+ if self._golden_features and self._can_apply_golden_features():
169
+ all_steps += ["golden_features"]
170
+ if self._kmeans_features and self._can_apply_kmeans_features():
171
+ all_steps += ["kmeans_features"]
172
+ if self._features_selection:
173
+ all_steps += ["insert_random_feature"]
174
+ all_steps += ["features_selection"]
175
+ for i in range(self._hill_climbing_steps):
176
+ all_steps += [f"hill_climbing_{i+1}"]
177
+ if (
178
+ self._boost_on_errors
179
+ and self._fairness_metric is None
180
+ and self._validation_strategy.get("validation_type", "") != "custom"
181
+ ):
182
+ # we can turn boost on errors only if there is not fairness optimization
183
+ # boost on errors will not work for custom validation strategy
184
+ # because we cant assure that we have all samples in out-of-folds predictions
185
+ all_steps += ["boost_on_errors"]
186
+ if self._train_ensemble:
187
+ all_steps += ["ensemble"]
188
+ if self._stack_models:
189
+ all_steps += ["stack"]
190
+ if self._train_ensemble:
191
+ all_steps += ["ensemble_stacked"]
192
+ return all_steps
193
+
194
+ def get_model_name(self, model_type, models_cnt, special=""):
195
+ return f"{models_cnt}_" + special + model_type.replace(" ", "")
196
+
197
+ def filter_random_feature_model(self, models):
198
+ return [m for m in models if "RandomFeature" not in m.get_name()]
199
+
200
+ def generate_params(
201
+ self, step, models, results_path, stacked_models, total_time_limit
202
+ ):
203
+ try:
204
+ models_cnt = len(models)
205
+ if step == "adjust_validation":
206
+ return self.adjust_validation_params(models_cnt)
207
+ elif step == "simple_algorithms":
208
+ return self.simple_algorithms_params(models_cnt)
209
+ elif step == "default_algorithms":
210
+ return self.default_params(models_cnt)
211
+ elif "fairness" in step:
212
+ return self.fairness_optimization(models, results_path)
213
+ elif step == "not_so_random":
214
+ return self.get_not_so_random_params(models_cnt, models)
215
+ elif step == "mix_encoding":
216
+ return self.get_mix_categorical_strategy(models, total_time_limit)
217
+ elif step == "golden_features":
218
+ return self.get_golden_features_params(
219
+ models, results_path, total_time_limit
220
+ )
221
+ elif step == "kmeans_features":
222
+ return self.get_kmeans_features_params(
223
+ models, results_path, total_time_limit
224
+ )
225
+ elif step == "insert_random_feature":
226
+ return self.get_params_to_insert_random_feature(
227
+ models, total_time_limit
228
+ )
229
+ elif step == "features_selection":
230
+ return self.get_features_selection_params(
231
+ self.filter_random_feature_model(models),
232
+ results_path,
233
+ total_time_limit,
234
+ )
235
+ elif "hill_climbing" in step:
236
+ return self.get_hill_climbing_params(
237
+ self.filter_random_feature_model(models)
238
+ )
239
+ elif step == "boost_on_errors":
240
+ return self.boost_params(models, results_path, total_time_limit)
241
+ elif step == "ensemble":
242
+ return [
243
+ {
244
+ "model_type": "ensemble",
245
+ "is_stacked": False,
246
+ "name": "Ensemble",
247
+ "status": "initialized",
248
+ "final_loss": None,
249
+ "train_time": None,
250
+ }
251
+ ]
252
+ elif step == "stack":
253
+ return self.get_params_stack_models(stacked_models)
254
+ elif step == "ensemble_stacked":
255
+ # do we have stacked models?
256
+ any_stacked = False
257
+ for m in models:
258
+ if m._is_stacked:
259
+ any_stacked = True
260
+ if not any_stacked:
261
+ return []
262
+
263
+ return [
264
+ {
265
+ "model_type": "ensemble",
266
+ "is_stacked": True,
267
+ "name": "Ensemble_Stacked",
268
+ "status": "initialized",
269
+ "final_loss": None,
270
+ "train_time": None,
271
+ }
272
+ ]
273
+
274
+ # didnt find anything matching the step, return empty array
275
+ return []
276
+ except Exception as e:
277
+ import traceback
278
+
279
+ print(str(e), traceback.format_exc())
280
+ return []
281
+
282
+ def fairness_optimization_binary_classification(self, current_models, results_path):
283
+ df_models, algorithms = self.df_models_algorithms(current_models)
284
+
285
+ generated_params = []
286
+ counts = {model_type: 0 for model_type in algorithms}
287
+
288
+ # get sensitive features for all samples
289
+ sensitive_features_path = os.path.join(results_path, "sensitive_features.data")
290
+ sensitive_features = load_data(sensitive_features_path)
291
+
292
+ # get target
293
+ y_path = os.path.join(results_path, "y.data")
294
+ target = np.array(load_data(y_path)["target"])
295
+
296
+ # we operate here on full target data (for all samples)
297
+ # we can't load preprocessed targets from other place
298
+ # we need to perform preprocessing here
299
+ if df_models.shape[0] > 0:
300
+ target_preprocessing = (
301
+ df_models["model"]
302
+ .iloc[0]
303
+ .params.get("preprocessing", {})
304
+ .get("target_preprocessing", {})
305
+ )
306
+ if PreprocessingCategorical.CONVERT_INTEGER in target_preprocessing:
307
+ cat_y = LabelEncoder(try_to_fit_numeric=True)
308
+ cat_y.fit(target)
309
+ target = cat_y.transform(target)
310
+
311
+ sensitive_columns = list(sensitive_features.columns)
312
+
313
+ for i in range(df_models.shape[0]):
314
+ model_type = df_models["model_type"].iloc[i]
315
+
316
+ if df_models["model_type"].iloc[i] in ["Baseline"]:
317
+ # we dont optimize Baseline
318
+ continue
319
+
320
+ counts[model_type] += 1
321
+ if counts[model_type] > 1:
322
+ continue
323
+
324
+ m = df_models["model"].iloc[i]
325
+
326
+ if "ratio" in self._fairness_metric.lower():
327
+ if m.get_worst_fairness() > self._fairness_threshold:
328
+ continue
329
+ else:
330
+ if m.get_worst_fairness() < self._fairness_threshold:
331
+ continue
332
+
333
+ fo = m.get_fairness_optimization()
334
+ fo_step = fo.get("step", 0)
335
+
336
+ samples_weight = np.ones(sensitive_features.shape[0])
337
+
338
+ fo = m.get_fairness_optimization()
339
+ weights = fo.get("weights")
340
+ for k, ws in weights.items():
341
+ sensitive_values = k.split("@")
342
+ ii = None
343
+ for i, sv in enumerate(sensitive_values):
344
+ if ii is None:
345
+ ii = sensitive_features[sensitive_columns[i]] == sv
346
+ else:
347
+ ii &= sensitive_features[sensitive_columns[i]] == sv
348
+
349
+ samples_weight[ii & (target == 0)] = max(ws[0], 0.01)
350
+ samples_weight[ii & (target == 1)] = max(
351
+ ws[1], 0.01
352
+ ) # weight cant be negative
353
+
354
+ samples_weight = samples_weight * target.shape[0] / np.sum(samples_weight)
355
+
356
+ sample_weight_path = os.path.join(
357
+ results_path, m.get_type() + f"_fairness_sample_weight_{fo_step}.data"
358
+ )
359
+ dump_data(
360
+ sample_weight_path, pd.DataFrame({"sample_weight": samples_weight})
361
+ )
362
+
363
+ fo = m.get_fairness_optimization()
364
+ fo["step"] = fo_step
365
+
366
+ params = copy.deepcopy(m.params)
367
+ params["fairness_optimization"] = fo
368
+
369
+ params["validation_strategy"]["sample_weight_path"] = sample_weight_path
370
+ params["injected_sample_weight"] = True
371
+ if "SampleWeigthing" not in params["name"]:
372
+ params["name"] += "_SampleWeigthing"
373
+ if fo_step > 0:
374
+ if "Update" in params["name"]:
375
+ n = params["name"].split("_")
376
+ params["name"] = "_".join(n[:-2])
377
+ params["name"] += f"_Update_{fo_step}"
378
+
379
+ params["status"] = "initialized"
380
+ params["final_loss"] = None
381
+ params["train_time"] = None
382
+ params["data_type"] = "fairness"
383
+ if "model_architecture_json" in params["learner"]:
384
+ del params["learner"]["model_architecture_json"]
385
+ if self._optuna_time_budget is not None:
386
+ params["optuna_time_budget"] = self._optuna_time_budget
387
+ params["optuna_init_params"] = self._optuna_init_params
388
+ params["optuna_verbose"] = self._optuna_verbose
389
+
390
+ unique_params_key = MljarTuner.get_params_key(params)
391
+
392
+ if unique_params_key not in self._unique_params_keys:
393
+ generated_params += [params]
394
+
395
+ return generated_params
396
+
397
+ def fairness_optimization_regression(self, current_models, results_path):
398
+ df_models, algorithms = self.df_models_algorithms(current_models)
399
+
400
+ generated_params = []
401
+ counts = {model_type: 0 for model_type in algorithms}
402
+
403
+ # get sensitive features for all samples
404
+ sensitive_features_path = os.path.join(results_path, "sensitive_features.data")
405
+ sensitive_features = load_data(sensitive_features_path)
406
+
407
+ # get target
408
+ y_path = os.path.join(results_path, "y.data")
409
+ target = np.array(load_data(y_path)["target"])
410
+
411
+ sensitive_columns = list(sensitive_features.columns)
412
+
413
+ for i in range(df_models.shape[0]):
414
+ model_type = df_models["model_type"].iloc[i]
415
+
416
+ if df_models["model_type"].iloc[i] in ["Baseline"]:
417
+ # we dont optimize Baseline
418
+ continue
419
+
420
+ counts[model_type] += 1
421
+
422
+ m = df_models["model"].iloc[i]
423
+
424
+ if "ratio" in self._fairness_metric.lower():
425
+ if m.get_worst_fairness() > self._fairness_threshold:
426
+ continue
427
+ else:
428
+ if m.get_worst_fairness() < self._fairness_threshold:
429
+ continue
430
+
431
+ fo = m.get_fairness_optimization()
432
+ fo_step = fo.get("step", 0)
433
+
434
+ samples_weight = np.ones(sensitive_features.shape[0])
435
+
436
+ fo = m.get_fairness_optimization()
437
+ weights = fo.get("weights")
438
+
439
+ for k, ws in weights.items():
440
+ sensitive_values = k.split("@")
441
+ ii = None
442
+ for i, sv in enumerate(sensitive_values):
443
+ if ii is None:
444
+ ii = sensitive_features[sensitive_columns[i]] == sv
445
+ else:
446
+ ii &= sensitive_features[sensitive_columns[i]] == sv
447
+
448
+ samples_weight[ii] = max(ws, 0.01)
449
+
450
+ samples_weight = samples_weight * target.shape[0] / np.sum(samples_weight)
451
+
452
+ sample_weight_path = os.path.join(
453
+ results_path, m.get_type() + f"_fairness_sample_weight_{fo_step}.data"
454
+ )
455
+ dump_data(
456
+ sample_weight_path, pd.DataFrame({"sample_weight": samples_weight})
457
+ )
458
+
459
+ fo = m.get_fairness_optimization()
460
+ fo["step"] = fo_step
461
+
462
+ params = copy.deepcopy(m.params)
463
+ params["fairness_optimization"] = fo
464
+
465
+ params["validation_strategy"]["sample_weight_path"] = sample_weight_path
466
+ params["injected_sample_weight"] = True
467
+ if "SampleWeigthing" not in params["name"]:
468
+ params["name"] += "_SampleWeigthing"
469
+
470
+ if fo_step > 0:
471
+ if "Update" in params["name"]:
472
+ n = params["name"].split("_")
473
+ params["name"] = "_".join(n[:-2])
474
+ params["name"] += f"_Update_{fo_step}"
475
+
476
+ params["status"] = "initialized"
477
+ params["final_loss"] = None
478
+ params["train_time"] = None
479
+ params["data_type"] = "fairness"
480
+ if "model_architecture_json" in params["learner"]:
481
+ del params["learner"]["model_architecture_json"]
482
+ if self._optuna_time_budget is not None:
483
+ params["optuna_time_budget"] = self._optuna_time_budget
484
+ params["optuna_init_params"] = self._optuna_init_params
485
+ params["optuna_verbose"] = self._optuna_verbose
486
+
487
+ unique_params_key = MljarTuner.get_params_key(params)
488
+
489
+ if unique_params_key not in self._unique_params_keys:
490
+ generated_params += [params]
491
+
492
+ return generated_params
493
+
494
+ def fairness_optimization_multiclass_classification(
495
+ self, current_models, results_path
496
+ ):
497
+ df_models, algorithms = self.df_models_algorithms(
498
+ current_models
499
+ ) # , sort_by_worst_fairness=True)
500
+
501
+ generated_params = []
502
+ counts = {model_type: 0 for model_type in algorithms}
503
+
504
+ # get sensitive features for all samples
505
+ sensitive_features_path = os.path.join(results_path, "sensitive_features.data")
506
+ sensitive_features = load_data(sensitive_features_path)
507
+
508
+ # get target
509
+ y_path = os.path.join(results_path, "y.data")
510
+ target = np.array(load_data(y_path)["target"])
511
+
512
+ sensitive_columns = list(sensitive_features.columns)
513
+
514
+ for i in range(df_models.shape[0]):
515
+ model_type = df_models["model_type"].iloc[i]
516
+
517
+ if df_models["model_type"].iloc[i] in ["Baseline"]:
518
+ # we dont optimize Baseline
519
+ continue
520
+
521
+ counts[model_type] += 1
522
+
523
+ m = df_models["model"].iloc[i]
524
+
525
+ if "ratio" in self._fairness_metric.lower():
526
+ if m.get_worst_fairness() > self._fairness_threshold:
527
+ continue
528
+ else:
529
+ if m.get_worst_fairness() < self._fairness_threshold:
530
+ continue
531
+
532
+ fo = m.get_fairness_optimization()
533
+ fo_step = fo.get("step", 0)
534
+
535
+ samples_weight = np.ones(sensitive_features.shape[0])
536
+
537
+ fo = m.get_fairness_optimization()
538
+ weights = fo.get("weights")
539
+ target_values = fo.get("target_values")
540
+
541
+ for k, ws in weights.items():
542
+ sensitive_values = k.split("@")
543
+ ii = None
544
+ for i, sv in enumerate(sensitive_values):
545
+ if ii is None:
546
+ ii = sensitive_features[sensitive_columns[i]] == sv
547
+ else:
548
+ ii &= sensitive_features[sensitive_columns[i]] == sv
549
+
550
+ for j, t in enumerate(target_values):
551
+ samples_weight[ii & (target == t)] = max(ws[j], 0.01)
552
+
553
+ samples_weight = samples_weight * target.shape[0] / np.sum(samples_weight)
554
+
555
+ sample_weight_path = os.path.join(
556
+ results_path, m.get_type() + f"_fairness_sample_weight_{fo_step}.data"
557
+ )
558
+ dump_data(
559
+ sample_weight_path, pd.DataFrame({"sample_weight": samples_weight})
560
+ )
561
+
562
+ fo = m.get_fairness_optimization()
563
+ fo["step"] = fo_step
564
+
565
+ params = copy.deepcopy(m.params)
566
+ params["fairness_optimization"] = fo
567
+
568
+ params["validation_strategy"]["sample_weight_path"] = sample_weight_path
569
+ params["injected_sample_weight"] = True
570
+ if "SampleWeigthing" not in params["name"]:
571
+ params["name"] += "_SampleWeigthing"
572
+ if fo_step > 0:
573
+ if "Update" in params["name"]:
574
+ n = params["name"].split("_")
575
+ params["name"] = "_".join(n[:-2])
576
+ params["name"] += f"_Update_{fo_step}"
577
+
578
+ params["status"] = "initialized"
579
+ params["final_loss"] = None
580
+ params["train_time"] = None
581
+ params["data_type"] = "fairness"
582
+ if "model_architecture_json" in params["learner"]:
583
+ del params["learner"]["model_architecture_json"]
584
+ if self._optuna_time_budget is not None:
585
+ params["optuna_time_budget"] = self._optuna_time_budget
586
+ params["optuna_init_params"] = self._optuna_init_params
587
+ params["optuna_verbose"] = self._optuna_verbose
588
+
589
+ unique_params_key = MljarTuner.get_params_key(params)
590
+
591
+ if unique_params_key not in self._unique_params_keys:
592
+ generated_params += [params]
593
+
594
+ return generated_params
595
+
596
+ def fairness_optimization(self, current_models, results_path):
597
+ if self._ml_task == BINARY_CLASSIFICATION:
598
+ return self.fairness_optimization_binary_classification(
599
+ current_models, results_path
600
+ )
601
+ if self._ml_task == REGRESSION:
602
+ return self.fairness_optimization_regression(current_models, results_path)
603
+ if self._ml_task == MULTICLASS_CLASSIFICATION:
604
+ return self.fairness_optimization_multiclass_classification(
605
+ current_models, results_path
606
+ )
607
+ return []
608
+
609
+ def get_params_stack_models(self, stacked_models):
610
+ if stacked_models is None or len(stacked_models) == 0:
611
+ return []
612
+
613
+ X_train_stacked_path = ""
614
+ added_columns = []
615
+
616
+ # model_types = ["Xgboost", "LightGBM", "CatBoost"]
617
+ model_types = [
618
+ "Xgboost",
619
+ "LightGBM",
620
+ "CatBoost",
621
+ "Random Forest",
622
+ "Extra Trees",
623
+ "Neural Network",
624
+ ]
625
+ generated_params = {m: [] for m in model_types}
626
+ types_score_order = []
627
+ # resue old params
628
+ for m in stacked_models:
629
+ # use only Xgboost, LightGBM and CatBoost as stacked models
630
+ if m.get_type() not in model_types:
631
+ continue
632
+
633
+ if m.get_type() not in types_score_order:
634
+ types_score_order += [m.get_type()]
635
+
636
+ # the below condition is only true for fair models
637
+ if self._fairness_metric is None and m.params.get(
638
+ "injected_sample_weight", False
639
+ ):
640
+ # dont use boost_on_errors model for stacking
641
+ # there will be additional boost_on_errors step
642
+ continue
643
+
644
+ params = copy.deepcopy(m.params)
645
+
646
+ params["validation_strategy"]["X_path"] = params["validation_strategy"][
647
+ "X_path"
648
+ ].replace("X.data", "X_stacked.data")
649
+
650
+ params["name"] = params["name"] + "_Stacked"
651
+ params["is_stacked"] = True
652
+ params["status"] = "initialized"
653
+ params["final_loss"] = None
654
+ params["train_time"] = None
655
+ params["data_type"] += "_stacked"
656
+ if self._optuna_time_budget is not None:
657
+ params["optuna_time_budget"] = self._optuna_time_budget
658
+ params["optuna_init_params"] = self._optuna_init_params
659
+ params["optuna_verbose"] = self._optuna_verbose
660
+
661
+ if "model_architecture_json" in params["learner"]:
662
+ # the new model will be created with wider input size
663
+ del params["learner"]["model_architecture_json"]
664
+
665
+ if self._ml_task == REGRESSION:
666
+ # scale added predictions in regression if the target was scaled (in the case of NN)
667
+ # this piece of code might not work, leave it as it is, because NN is not used for training with Stacked Data
668
+ target_preprocessing = params["preprocessing"]["target_preprocessing"]
669
+ scale = None
670
+ if "scale_log_and_normal" in target_preprocessing:
671
+ scale = "scale_log_and_normal"
672
+ elif "scale_normal" in target_preprocessing:
673
+ scale = "scale_normal"
674
+ if scale is not None:
675
+ for col in added_columns:
676
+ params["preprocessing"]["columns_preprocessing"][col] = [scale]
677
+
678
+ generated_params[m.get_type()] += [params]
679
+
680
+ return_params = []
681
+ for i in range(100):
682
+ total = 0
683
+ for m in types_score_order:
684
+ if generated_params[m]:
685
+ return_params += [generated_params[m].pop(0)]
686
+ total += len(generated_params[m])
687
+ if total == 0:
688
+ break
689
+
690
+ return return_params
691
+
692
+ def adjust_validation_params(self, models_cnt):
693
+ generated_params = []
694
+ for model_type in ["Decision Tree"]:
695
+ models_to_check = 1
696
+
697
+ logger.info(f"Generate parameters for {model_type} (#{models_cnt + 1})")
698
+ params = self._get_model_params(model_type, seed=1)
699
+ if params is None:
700
+ continue
701
+
702
+ params["name"] = self.get_model_name(model_type, models_cnt + 1)
703
+ params["status"] = "initialized"
704
+ params["final_loss"] = None
705
+ params["train_time"] = None
706
+ params["data_type"] = "original"
707
+
708
+ unique_params_key = MljarTuner.get_params_key(params)
709
+ if unique_params_key not in self._unique_params_keys:
710
+ generated_params += [params]
711
+ models_cnt += 1
712
+ return generated_params
713
+
714
+ def simple_algorithms_params(self, models_cnt):
715
+ generated_params = []
716
+ for model_type in ["Baseline", "Decision Tree", "Linear"]:
717
+ if model_type not in self._algorithms:
718
+ continue
719
+ models_to_check = 1
720
+ if model_type == "Decision Tree":
721
+ models_to_check = min(3, self._start_random_models)
722
+ for i in range(models_to_check):
723
+ logger.info(f"Generate parameters for {model_type} (#{models_cnt + 1})")
724
+ params = self._get_model_params(model_type, seed=i + 1)
725
+ if params is None:
726
+ continue
727
+
728
+ params["name"] = self.get_model_name(model_type, models_cnt + 1)
729
+ params["status"] = "initialized"
730
+ params["final_loss"] = None
731
+ params["train_time"] = None
732
+ params["data_type"] = "original"
733
+
734
+ unique_params_key = MljarTuner.get_params_key(params)
735
+ if unique_params_key not in self._unique_params_keys:
736
+ generated_params += [params]
737
+ models_cnt += 1
738
+ return generated_params
739
+
740
+ def skip_if_rows_cols_limit(self, model_type):
741
+ max_rows_limit = AlgorithmsRegistry.get_max_rows_limit(
742
+ self._ml_task, model_type
743
+ )
744
+ max_cols_limit = AlgorithmsRegistry.get_max_cols_limit(
745
+ self._ml_task, model_type
746
+ )
747
+
748
+ if max_rows_limit is not None:
749
+ if self._data_info["rows"] > max_rows_limit:
750
+ return True
751
+ if max_cols_limit is not None:
752
+ if self._data_info["cols"] > max_cols_limit:
753
+ return True
754
+
755
+ return False
756
+
757
+ def default_params(self, models_cnt):
758
+ generated_params = []
759
+ for model_type in [
760
+ "LightGBM",
761
+ "Xgboost",
762
+ "CatBoost",
763
+ "Neural Network",
764
+ "Random Forest",
765
+ "Extra Trees",
766
+ "Nearest Neighbors",
767
+ ]:
768
+ if model_type not in self._algorithms:
769
+ continue
770
+
771
+ if self.skip_if_rows_cols_limit(model_type):
772
+ continue
773
+
774
+ logger.info(f"Get default parameters for {model_type} (#{models_cnt + 1})")
775
+ params = self._get_model_params(
776
+ model_type, seed=models_cnt + 1, params_type="default"
777
+ )
778
+ if params is None:
779
+ continue
780
+ special = "Default_" if self._optuna_time_budget is None else "Optuna_"
781
+ params["name"] = self.get_model_name(
782
+ model_type, models_cnt + 1, special=special
783
+ )
784
+ params["status"] = "initialized"
785
+ params["final_loss"] = None
786
+ params["train_time"] = None
787
+ params["data_type"] = "original"
788
+ if self._optuna_time_budget is not None:
789
+ params["optuna_time_budget"] = self._optuna_time_budget
790
+ params["optuna_init_params"] = self._optuna_init_params
791
+ params["optuna_verbose"] = self._optuna_verbose
792
+
793
+ unique_params_key = MljarTuner.get_params_key(params)
794
+ if unique_params_key not in self._unique_params_keys:
795
+ generated_params += [params]
796
+ models_cnt += 1
797
+
798
+ return generated_params
799
+
800
+ def get_fairness_sample_weight(self, current_models, model_type):
801
+ try:
802
+ df_models, algorithms = self.df_models_algorithms(current_models)
803
+ # df_models are sorted based on fairness metric
804
+ df_models = df_models[df_models.model_type == model_type]
805
+
806
+ if df_models.shape[0]:
807
+ m = df_models["model"].iloc[0]
808
+ swp = m.params["validation_strategy"]["sample_weight_path"]
809
+
810
+ name_suffix = "_SampleWeigthing"
811
+ name = m.params["name"]
812
+ if "Update" in name:
813
+ words = name.split("_")
814
+ i = words.index("Update")
815
+ name_suffix += f"_Update_{words[i+1]}"
816
+
817
+ return swp, name_suffix
818
+ except Exception:
819
+ pass
820
+ return None, None
821
+
822
+ def get_not_so_random_params(self, models_cnt, current_models):
823
+ model_types = [
824
+ "Xgboost",
825
+ "LightGBM",
826
+ "CatBoost",
827
+ "Random Forest",
828
+ "Extra Trees",
829
+ "Neural Network",
830
+ "Nearest Neighbors",
831
+ ]
832
+
833
+ generated_params = {m: [] for m in model_types}
834
+
835
+ for model_type in model_types:
836
+ if model_type not in self._algorithms:
837
+ continue
838
+
839
+ if self.skip_if_rows_cols_limit(model_type):
840
+ continue
841
+ # minus 1 because already have 1 default
842
+ for i in range(self._start_random_models - 1):
843
+ logger.info(
844
+ f"Generate not-so-random parameters for {model_type} (#{models_cnt+1})"
845
+ )
846
+ params = self._get_model_params(model_type, seed=i + 1)
847
+ if params is None:
848
+ continue
849
+
850
+ params["name"] = self.get_model_name(model_type, models_cnt + 1)
851
+ params["status"] = "initialized"
852
+ params["final_loss"] = None
853
+ params["train_time"] = None
854
+ params["data_type"] = "original"
855
+ if self._optuna_time_budget is not None:
856
+ params["optuna_time_budget"] = self._optuna_time_budget
857
+ params["optuna_init_params"] = self._optuna_init_params
858
+ params["optuna_verbose"] = self._optuna_verbose
859
+
860
+ if self._fairness_metric is not None:
861
+ swp, name_suffix = self.get_fairness_sample_weight(
862
+ current_models, model_type
863
+ )
864
+ if swp is not None:
865
+ params["validation_strategy"]["sample_weight_path"] = swp
866
+ params["injected_sample_weight"] = True
867
+ if name_suffix is not None:
868
+ params["name"] += name_suffix
869
+
870
+ unique_params_key = MljarTuner.get_params_key(params)
871
+ if unique_params_key not in self._unique_params_keys:
872
+ generated_params[model_type] += [params]
873
+ models_cnt += 1
874
+
875
+ """
876
+ return_params = []
877
+ for i in range(100):
878
+ total = 0
879
+ for m in ["Xgboost", "LightGBM", "CatBoost"]:
880
+ if generated_params[m]:
881
+ return_params += [generated_params[m].pop(0)]
882
+ total += len(generated_params[m])
883
+ if total == 0:
884
+ break
885
+
886
+ rest_params = []
887
+ for m in [
888
+ "Random Forest",
889
+ "Extra Trees",
890
+ "Neural Network",
891
+ "Nearest Neighbors",
892
+ ]:
893
+ rest_params += generated_params[m]
894
+ if rest_params:
895
+ np.random.shuffle(rest_params)
896
+ return_params += rest_params
897
+ """
898
+ return_params = []
899
+ for i in range(100):
900
+ total = 0
901
+ for m in [
902
+ "LightGBM",
903
+ "Xgboost",
904
+ "CatBoost",
905
+ "Random Forest",
906
+ "Extra Trees",
907
+ "Neural Network",
908
+ "Nearest Neighbors",
909
+ ]:
910
+ if generated_params[m]:
911
+ return_params += [generated_params[m].pop(0)]
912
+ total += len(generated_params[m])
913
+ if total == 0:
914
+ break
915
+
916
+ return return_params
917
+
918
+ def get_hill_climbing_params(self, current_models):
919
+ df_models, algorithms = self.df_models_algorithms(current_models)
920
+ generated_params = []
921
+ counts = {model_type: 0 for model_type in algorithms}
922
+
923
+ for i in range(df_models.shape[0]):
924
+ model_type = df_models["model_type"].iloc[i]
925
+ counts[model_type] += 1
926
+ if counts[model_type] > self._top_models_to_improve:
927
+ continue
928
+
929
+ m = df_models["model"].iloc[i]
930
+
931
+ for p in HillClimbing.get(
932
+ m.params.get("learner"), self._ml_task, len(current_models) + self._seed
933
+ ):
934
+ model_indices = [
935
+ int(m.get_name().split("_")[0]) for m in current_models
936
+ ]
937
+ model_max_index = np.max(model_indices)
938
+
939
+ logger.info(
940
+ "Hill climbing step, for model #{0}".format(model_max_index + 1)
941
+ )
942
+ if p is not None:
943
+ all_params = copy.deepcopy(m.params)
944
+ all_params["learner"] = p
945
+
946
+ all_params["name"] = self.get_model_name(
947
+ all_params["learner"]["model_type"],
948
+ model_max_index + 1 + len(generated_params),
949
+ )
950
+ if "SampleWeigthing" in m.get_name():
951
+ all_params["name"] += "_SampleWeigthing"
952
+ n = m.get_name().split("_")
953
+ if "Update" in n:
954
+ i = n.index("Update")
955
+ all_params["name"] += f"_Update_{n[i+1]}"
956
+
957
+ if "golden_features" in all_params["preprocessing"]:
958
+ all_params["name"] += "_GoldenFeatures"
959
+ if "drop_features" in all_params["preprocessing"] and len(
960
+ all_params["preprocessing"]["drop_features"]
961
+ ):
962
+ all_params["name"] += "_SelectedFeatures"
963
+ all_params["status"] = "initialized"
964
+ all_params["final_loss"] = None
965
+ all_params["train_time"] = None
966
+ unique_params_key = MljarTuner.get_params_key(all_params)
967
+
968
+ if unique_params_key not in self._unique_params_keys:
969
+ generated_params += [all_params]
970
+
971
+ return generated_params
972
+
973
+ def get_all_int_categorical_strategy(self, current_models, total_time_limit):
974
+ return self.get_categorical_strategy(
975
+ current_models, PreprocessingTuner.CATEGORICALS_ALL_INT, total_time_limit
976
+ )
977
+
978
+ def get_mix_categorical_strategy(self, current_models, total_time_limit):
979
+ return self.get_categorical_strategy(
980
+ current_models, PreprocessingTuner.CATEGORICALS_MIX, total_time_limit
981
+ )
982
+
983
+ def get_categorical_strategy(self, current_models, strategy, total_time_limit):
984
+ model_selection_time_limit = (
985
+ None if total_time_limit is None else 0.1 * total_time_limit
986
+ )
987
+ df_models, algorithms = self.df_models_algorithms(
988
+ current_models, time_limit=model_selection_time_limit
989
+ )
990
+ generated_params = []
991
+ for m_type in algorithms:
992
+ # try to add categorical strategy only for below algorithms
993
+ if m_type not in [
994
+ "Xgboost",
995
+ # "LightGBM", # use built-in categoricals (but need to int encode)
996
+ # "Neural Network",
997
+ # "Random Forest",
998
+ # "Extra Trees",
999
+ ]:
1000
+ continue
1001
+ models = df_models[df_models.model_type == m_type]["model"]
1002
+
1003
+ for i in range(min(1, len(models))):
1004
+ m = models.iloc[i]
1005
+
1006
+ params = copy.deepcopy(m.params)
1007
+ cols_preprocessing = params["preprocessing"]["columns_preprocessing"]
1008
+
1009
+ for col, preproc in params["preprocessing"][
1010
+ "columns_preprocessing"
1011
+ ].items():
1012
+ new_preproc = []
1013
+ convert_categorical = False
1014
+
1015
+ for p in preproc:
1016
+ if "categorical" not in p:
1017
+ new_preproc += [p]
1018
+ else:
1019
+ convert_categorical = True
1020
+
1021
+ col_data_info = self._data_info["columns_info"].get(col)
1022
+ few_categories = False
1023
+ if col_data_info is not None and "few_categories" in col_data_info:
1024
+ few_categories = True
1025
+
1026
+ if convert_categorical:
1027
+ if strategy == PreprocessingTuner.CATEGORICALS_ALL_INT:
1028
+ new_preproc += [PreprocessingCategorical.CONVERT_INTEGER]
1029
+ elif strategy == PreprocessingTuner.CATEGORICALS_MIX:
1030
+ if few_categories:
1031
+ new_preproc += [
1032
+ PreprocessingCategorical.CONVERT_ONE_HOT
1033
+ ]
1034
+ else:
1035
+ new_preproc += [
1036
+ PreprocessingCategorical.CONVERT_INTEGER
1037
+ ]
1038
+
1039
+ cols_preprocessing[col] = new_preproc
1040
+
1041
+ params["preprocessing"]["columns_preprocessing"] = cols_preprocessing
1042
+ # if there is already a name of categorical strategy in the name
1043
+ # please remove it to avoid confusion (I hope!)
1044
+ for st in [
1045
+ PreprocessingTuner.CATEGORICALS_ALL_INT,
1046
+ PreprocessingTuner.CATEGORICALS_MIX,
1047
+ ]:
1048
+ params["name"] = params["name"].replace("_" + st, "")
1049
+ params["name"] += f"_{strategy}"
1050
+ params["status"] = "initialized"
1051
+ params["final_loss"] = None
1052
+ params["train_time"] = None
1053
+ params["data_type"] = params.get("data_type", "") + "_" + strategy
1054
+ if self._optuna_time_budget is not None:
1055
+ params["optuna_time_budget"] = self._optuna_time_budget
1056
+ params["optuna_init_params"] = self._optuna_init_params
1057
+ params["optuna_verbose"] = self._optuna_verbose
1058
+
1059
+ if "model_architecture_json" in params["learner"]:
1060
+ del params["learner"]["model_architecture_json"]
1061
+ unique_params_key = MljarTuner.get_params_key(params)
1062
+ if unique_params_key not in self._unique_params_keys:
1063
+ generated_params += [params]
1064
+ return generated_params
1065
+
1066
+ def df_models_algorithms(
1067
+ self,
1068
+ current_models,
1069
+ time_limit=None,
1070
+ exclude_golden=False,
1071
+ sort_by_worst_fairness=False,
1072
+ ):
1073
+ scores = [m.get_final_loss() for m in current_models]
1074
+ model_types = [m.get_type() for m in current_models]
1075
+ names = [m.get_name() for m in current_models]
1076
+ train_times = [m.get_train_time() for m in current_models]
1077
+
1078
+ df_models = pd.DataFrame(
1079
+ {
1080
+ "model": current_models,
1081
+ "score": scores,
1082
+ "model_type": model_types,
1083
+ "name": names,
1084
+ "train_time": train_times,
1085
+ }
1086
+ )
1087
+ if self._fairness_metric is not None:
1088
+ worst_fairness = [m.get_worst_fairness() for m in current_models]
1089
+ df_models["worst_fairness"] = worst_fairness
1090
+ best_fairness = [m.get_best_fairness() for m in current_models]
1091
+ df_models["best_fairness"] = best_fairness
1092
+
1093
+ if time_limit is not None:
1094
+ df_models = df_models[df_models.train_time < time_limit]
1095
+ df_models.reset_index(drop=True, inplace=True)
1096
+
1097
+ if exclude_golden:
1098
+ ii = df_models["name"].apply(lambda x: "GoldenFeatures" in x)
1099
+ df_models = df_models[~ii]
1100
+ df_models.reset_index(drop=True, inplace=True)
1101
+
1102
+ df_models.sort_values(by="score", ascending=True, inplace=True)
1103
+
1104
+ if self._fairness_metric is not None:
1105
+ sort_by_worst_fairness = True
1106
+
1107
+ ascending = True
1108
+ if "ratio" in self._fairness_metric.lower():
1109
+ ascending = False
1110
+ if sort_by_worst_fairness:
1111
+ df_models.sort_values(
1112
+ by="worst_fairness", ascending=ascending, inplace=True
1113
+ )
1114
+ else:
1115
+ df_models.sort_values(
1116
+ by="best_fairness", ascending=ascending, inplace=True
1117
+ )
1118
+
1119
+ model_types = list(df_models.model_type)
1120
+ u, idx = np.unique(model_types, return_index=True)
1121
+ algorithms = u[np.argsort(idx)]
1122
+
1123
+ return df_models, algorithms
1124
+
1125
+ def get_golden_features_params(
1126
+ self, current_models, results_path, total_time_limit
1127
+ ):
1128
+ model_selection_time_limit = (
1129
+ None if total_time_limit is None else 0.1 * total_time_limit
1130
+ )
1131
+ df_models, algorithms = self.df_models_algorithms(
1132
+ current_models, time_limit=model_selection_time_limit
1133
+ )
1134
+
1135
+ generated_params = []
1136
+ for i in range(min(3, df_models.shape[0])):
1137
+ m = df_models["model"].iloc[i]
1138
+
1139
+ params = copy.deepcopy(m.params)
1140
+ params["preprocessing"]["golden_features"] = {
1141
+ "results_path": results_path,
1142
+ "ml_task": self._ml_task,
1143
+ "n_jobs": self._n_jobs,
1144
+ }
1145
+ if (
1146
+ self._golden_features is not None
1147
+ and not isinstance(self._golden_features, bool)
1148
+ and isinstance(self._golden_features, int)
1149
+ ):
1150
+ params["preprocessing"]["golden_features"][
1151
+ "features_count"
1152
+ ] = self._golden_features
1153
+
1154
+ params["name"] += "_GoldenFeatures"
1155
+ params["status"] = "initialized"
1156
+ params["final_loss"] = None
1157
+ params["train_time"] = None
1158
+ params["data_type"] = params.get("data_type", "") + "_golden_features"
1159
+ if self._optuna_time_budget is not None:
1160
+ params["optuna_time_budget"] = self._optuna_time_budget
1161
+ params["optuna_init_params"] = self._optuna_init_params
1162
+ params["optuna_verbose"] = self._optuna_verbose
1163
+
1164
+ if "model_architecture_json" in params["learner"]:
1165
+ del params["learner"]["model_architecture_json"]
1166
+ unique_params_key = MljarTuner.get_params_key(params)
1167
+ if unique_params_key not in self._unique_params_keys:
1168
+ generated_params += [params]
1169
+ return generated_params
1170
+
1171
+ def get_kmeans_features_params(
1172
+ self, current_models, results_path, total_time_limit
1173
+ ):
1174
+ model_selection_time_limit = (
1175
+ None if total_time_limit is None else 0.1 * total_time_limit
1176
+ )
1177
+ df_models, algorithms = self.df_models_algorithms(
1178
+ current_models, time_limit=model_selection_time_limit, exclude_golden=True
1179
+ )
1180
+
1181
+ generated_params = []
1182
+ for i in range(min(3, df_models.shape[0])):
1183
+ m = df_models["model"].iloc[i]
1184
+
1185
+ params = copy.deepcopy(m.params)
1186
+ params["preprocessing"]["kmeans_features"] = {"results_path": results_path}
1187
+ params["name"] += "_KMeansFeatures"
1188
+ params["status"] = "initialized"
1189
+ params["final_loss"] = None
1190
+ params["train_time"] = None
1191
+ params["data_type"] = params.get("data_type", "") + "_kmeans_features"
1192
+ if self._optuna_time_budget is not None:
1193
+ params["optuna_time_budget"] = self._optuna_time_budget
1194
+ params["optuna_init_params"] = self._optuna_init_params
1195
+ params["optuna_verbose"] = self._optuna_verbose
1196
+
1197
+ if "model_architecture_json" in params["learner"]:
1198
+ del params["learner"]["model_architecture_json"]
1199
+ unique_params_key = MljarTuner.get_params_key(params)
1200
+ if unique_params_key not in self._unique_params_keys:
1201
+ generated_params += [params]
1202
+ return generated_params
1203
+
1204
+ def time_features_selection(self, current_models, total_time_limit):
1205
+ model_selection_time_limit = (
1206
+ None if total_time_limit is None else 0.1 * total_time_limit
1207
+ )
1208
+ df_models, algorithms = self.df_models_algorithms(
1209
+ current_models, time_limit=model_selection_time_limit
1210
+ )
1211
+
1212
+ time_needed = 0
1213
+ for m_type in algorithms:
1214
+ if m_type not in [
1215
+ "Xgboost",
1216
+ "LightGBM",
1217
+ "CatBoost",
1218
+ "Neural Network",
1219
+ "Random Forest",
1220
+ "Extra Trees",
1221
+ ]:
1222
+ continue
1223
+ models = df_models[df_models.model_type == m_type]["model"]
1224
+
1225
+ for i in range(min(1, len(models))):
1226
+ m = models.iloc[i]
1227
+ if time_needed == 0:
1228
+ # best model will be used two times
1229
+ # one for insert random feature
1230
+ # one for selected features
1231
+ time_needed += 2.0 * m.get_train_time()
1232
+ else:
1233
+ time_needed += m.get_train_time()
1234
+
1235
+ return time_needed
1236
+
1237
+ def get_params_to_insert_random_feature(self, current_models, total_time_limit):
1238
+ time_needed = self.time_features_selection(current_models, total_time_limit)
1239
+
1240
+ if total_time_limit is not None and time_needed > 0.1 * total_time_limit:
1241
+ print("Not enough time to perform features selection. Skip")
1242
+ print(
1243
+ "Time needed for features selection ~", np.round(time_needed), "seconds"
1244
+ )
1245
+ print(
1246
+ f"Please increase total_time_limit to at least ({int(np.round(10.0*time_needed))+60} seconds) to have features selection"
1247
+ )
1248
+ return None
1249
+
1250
+ model_selection_time_limit = (
1251
+ None if total_time_limit is None else 0.1 * total_time_limit
1252
+ )
1253
+ df_models, algorithms = self.df_models_algorithms(
1254
+ current_models, time_limit=model_selection_time_limit
1255
+ )
1256
+ if df_models.shape[0] == 0:
1257
+ return None
1258
+
1259
+ m = df_models.iloc[0]["model"]
1260
+
1261
+ params = copy.deepcopy(m.params)
1262
+ params["preprocessing"]["add_random_feature"] = True
1263
+ params["name"] += "_RandomFeature"
1264
+ params["status"] = "initialized"
1265
+ params["final_loss"] = None
1266
+ params["train_time"] = None
1267
+ params["explain_level"] = 1
1268
+ if "model_architecture_json" in params["learner"]:
1269
+ del params["learner"]["model_architecture_json"]
1270
+ if self._optuna_time_budget is not None:
1271
+ # dont tune algorithm with random feature inserted
1272
+ # algorithm will be tuned after feature selection
1273
+ params["optuna_time_budget"] = None
1274
+ params["optuna_init_params"] = {}
1275
+
1276
+ unique_params_key = MljarTuner.get_params_key(params)
1277
+ if unique_params_key not in self._unique_params_keys:
1278
+ return [params]
1279
+ return None
1280
+
1281
+ def get_features_selection_params(
1282
+ self, current_models, results_path, total_time_limit
1283
+ ):
1284
+ fname = os.path.join(results_path, "drop_features.json")
1285
+ if not os.path.exists(fname):
1286
+ return None
1287
+
1288
+ drop_features = json.load(open(fname, "r"))
1289
+ print("Drop features", drop_features)
1290
+
1291
+ # in case of droping only one feature (random_feature)
1292
+ # skip this step
1293
+ if len(drop_features) <= 1:
1294
+ return None
1295
+
1296
+ model_selection_time_limit = (
1297
+ None if total_time_limit is None else 0.1 * total_time_limit
1298
+ )
1299
+ df_models, algorithms = self.df_models_algorithms(
1300
+ current_models, time_limit=model_selection_time_limit
1301
+ )
1302
+
1303
+ generated_params = []
1304
+ for m_type in algorithms:
1305
+ # try to do features selection only for below algorithms
1306
+ if m_type not in [
1307
+ "Xgboost",
1308
+ "LightGBM",
1309
+ "CatBoost",
1310
+ "Neural Network",
1311
+ "Random Forest",
1312
+ "Extra Trees",
1313
+ ]:
1314
+ continue
1315
+ models = df_models[df_models.model_type == m_type]["model"]
1316
+
1317
+ for i in range(min(1, len(models))):
1318
+ m = models.iloc[i]
1319
+
1320
+ params = copy.deepcopy(m.params)
1321
+ params["preprocessing"]["drop_features"] = drop_features
1322
+ params["name"] += "_SelectedFeatures"
1323
+ params["status"] = "initialized"
1324
+ params["final_loss"] = None
1325
+ params["train_time"] = None
1326
+ params["data_type"] = (
1327
+ params.get("data_type", "") + "_features_selection"
1328
+ )
1329
+ if self._optuna_time_budget is not None:
1330
+ params["optuna_time_budget"] = self._optuna_time_budget
1331
+ params["optuna_init_params"] = self._optuna_init_params
1332
+ params["optuna_verbose"] = self._optuna_verbose
1333
+
1334
+ if "model_architecture_json" in params["learner"]:
1335
+ del params["learner"]["model_architecture_json"]
1336
+ unique_params_key = MljarTuner.get_params_key(params)
1337
+ if unique_params_key not in self._unique_params_keys:
1338
+ generated_params += [params]
1339
+ return generated_params
1340
+
1341
+ def _get_model_params(self, model_type, seed, params_type="random"):
1342
+ model_info = AlgorithmsRegistry.registry[self._ml_task][model_type]
1343
+
1344
+ model_params = None
1345
+ if params_type == "default":
1346
+ model_params = model_info["default_params"]
1347
+ model_params["seed"] = seed
1348
+
1349
+ else:
1350
+ model_params = RandomParameters.get(model_info["params"], seed + self._seed)
1351
+ if model_params is None:
1352
+ return None
1353
+
1354
+ # set eval metric
1355
+ if model_info["class"].algorithm_short_name == "Xgboost":
1356
+ model_params["eval_metric"] = xgboost_eval_metric(
1357
+ self._ml_task, self._eval_metric
1358
+ )
1359
+ if model_info["class"].algorithm_short_name == "LightGBM":
1360
+ metric, custom_metric = lightgbm_eval_metric(
1361
+ self._ml_task, self._eval_metric
1362
+ )
1363
+ model_params["metric"] = metric
1364
+ model_params["custom_eval_metric_name"] = custom_metric
1365
+ if model_info["class"].algorithm_short_name == "CatBoost":
1366
+ model_params["eval_metric"] = catboost_eval_metric(
1367
+ self._ml_task, self._eval_metric
1368
+ )
1369
+ elif model_info["class"].algorithm_short_name in [
1370
+ "Random Forest",
1371
+ "Extra Trees",
1372
+ ]:
1373
+ model_params["eval_metric_name"] = self._eval_metric
1374
+ model_params["ml_task"] = self._ml_task
1375
+
1376
+ required_preprocessing = model_info["required_preprocessing"]
1377
+ model_additional = model_info["additional"]
1378
+ preprocessing_params = PreprocessingTuner.get(
1379
+ required_preprocessing, self._data_info, self._ml_task
1380
+ )
1381
+
1382
+ model_params = {
1383
+ "additional": model_additional,
1384
+ "preprocessing": preprocessing_params,
1385
+ "validation_strategy": self._validation_strategy,
1386
+ "learner": {
1387
+ "model_type": model_info["class"].algorithm_short_name,
1388
+ "ml_task": self._ml_task,
1389
+ "n_jobs": self._n_jobs,
1390
+ **model_params,
1391
+ },
1392
+ "automl_random_state": self._seed,
1393
+ }
1394
+
1395
+ if self._data_info.get("num_class") is not None:
1396
+ model_params["learner"]["num_class"] = self._data_info.get("num_class")
1397
+
1398
+ model_params["ml_task"] = self._ml_task
1399
+ model_params["explain_level"] = self._explain_level
1400
+
1401
+ if self._fairness_metric is not None:
1402
+ model_params["fairness_metric"] = self._fairness_metric
1403
+ model_params["fairness_threshold"] = self._fairness_threshold
1404
+ model_params["privileged_groups"] = self._privileged_groups
1405
+ model_params["underprivileged_groups"] = self._underprivileged_groups
1406
+
1407
+ return model_params
1408
+
1409
+ @staticmethod
1410
+ def get_params_key(params):
1411
+ key = "key_"
1412
+ for main_key in ["preprocessing", "learner", "validation_strategy"]:
1413
+ key += "_" + main_key
1414
+ for k in sorted(params[main_key]):
1415
+ if k in ["seed", "explain_level"]:
1416
+ continue
1417
+ key += "_{}_{}".format(k, params[main_key][k])
1418
+ return key
1419
+
1420
+ def add_key(self, model):
1421
+ if model.get_type() != "Ensemble":
1422
+ key = MljarTuner.get_params_key(model.params)
1423
+ self._unique_params_keys += [key]
1424
+
1425
+ def boost_params(self, current_models, results_path, total_time_limit):
1426
+ model_selection_time_limit = (
1427
+ None if total_time_limit is None else 0.1 * total_time_limit
1428
+ )
1429
+ df_models, algorithms = self.df_models_algorithms(
1430
+ current_models, time_limit=model_selection_time_limit
1431
+ )
1432
+ best_model = None
1433
+ for i in range(df_models.shape[0]):
1434
+ if df_models["model_type"].iloc[i] in [
1435
+ "Ensemble",
1436
+ "Neural Network",
1437
+ "Nearest Neighbors",
1438
+ ]:
1439
+ continue
1440
+ if "RandomFeature" in df_models["model"].iloc[i].get_name():
1441
+ continue
1442
+ best_model = df_models["model"].iloc[i]
1443
+ break
1444
+ if best_model is None:
1445
+ return []
1446
+
1447
+ # load predictions
1448
+ oof = best_model.get_out_of_folds()
1449
+
1450
+ predictions = oof[[c for c in oof.columns if c.startswith("prediction")]]
1451
+ y = oof["target"]
1452
+
1453
+ if self._ml_task == MULTICLASS_CLASSIFICATION:
1454
+ oh = OneHotEncoder(sparse_output=False)
1455
+ y_encoded = oh.fit_transform(np.array(y).reshape(-1, 1))
1456
+ residua = np.sum(
1457
+ np.abs(np.array(y_encoded) - np.array(predictions)), axis=1
1458
+ )
1459
+ else:
1460
+ residua = np.abs(np.array(y) - np.array(predictions).ravel())
1461
+
1462
+ df_preds = pd.DataFrame(
1463
+ {"res": residua, "lp": range(residua.shape[0]), "target": np.array(y)}
1464
+ )
1465
+
1466
+ df_preds = df_preds.sort_values(by="res", ascending=True)
1467
+ df_preds["order"] = range(residua.shape[0])
1468
+ df_preds["order"] = (df_preds["order"]) / residua.shape[0] / 5.0 + 0.9
1469
+ df_preds = df_preds.sort_values(by="lp", ascending=True)
1470
+
1471
+ sample_weight_path = os.path.join(
1472
+ results_path, best_model.get_name() + "_sample_weight.data"
1473
+ )
1474
+ dump_data(
1475
+ sample_weight_path, pd.DataFrame({"sample_weight": df_preds["order"]})
1476
+ )
1477
+
1478
+ generated_params = []
1479
+
1480
+ params = copy.deepcopy(best_model.params)
1481
+
1482
+ params["validation_strategy"]["sample_weight_path"] = sample_weight_path
1483
+ params["injected_sample_weight"] = True
1484
+ params["name"] += "_BoostOnErrors"
1485
+ params["status"] = "initialized"
1486
+ params["final_loss"] = None
1487
+ params["train_time"] = None
1488
+ params["data_type"] = "boost_on_error"
1489
+ if "model_architecture_json" in params["learner"]:
1490
+ del params["learner"]["model_architecture_json"]
1491
+ if self._optuna_time_budget is not None:
1492
+ params["optuna_time_budget"] = self._optuna_time_budget
1493
+ params["optuna_init_params"] = self._optuna_init_params
1494
+ params["optuna_verbose"] = self._optuna_verbose
1495
+
1496
+ unique_params_key = MljarTuner.get_params_key(params)
1497
+
1498
+ if unique_params_key not in self._unique_params_keys:
1499
+ generated_params += [params]
1500
+
1501
+ return generated_params