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
File without changes
@@ -0,0 +1,148 @@
1
+ import optuna
2
+ from catboost import CatBoostClassifier, CatBoostRegressor, Pool
3
+
4
+ from supervised.algorithms.catboost import catboost_eval_metric, catboost_objective
5
+ from supervised.algorithms.registry import (
6
+ BINARY_CLASSIFICATION,
7
+ MULTICLASS_CLASSIFICATION,
8
+ REGRESSION,
9
+ )
10
+ from supervised.utils.metric import (
11
+ CatBoostEvalMetricAveragePrecision,
12
+ CatBoostEvalMetricMSE,
13
+ CatBoostEvalMetricPearson,
14
+ CatBoostEvalMetricSpearman,
15
+ CatBoostEvalMetricUserDefined,
16
+ Metric,
17
+ )
18
+
19
+ EPS = 1e-8
20
+
21
+
22
+ class CatBoostObjective:
23
+ def __init__(
24
+ self,
25
+ ml_task,
26
+ X_train,
27
+ y_train,
28
+ sample_weight,
29
+ X_validation,
30
+ y_validation,
31
+ sample_weight_validation,
32
+ eval_metric,
33
+ cat_features_indices,
34
+ n_jobs,
35
+ random_state,
36
+ ):
37
+ self.ml_task = ml_task
38
+ self.X_train = X_train
39
+ self.y_train = y_train
40
+ self.sample_weight = sample_weight
41
+ self.X_validation = X_validation
42
+ self.y_validation = y_validation
43
+ self.eval_metric = eval_metric
44
+ self.cat_features = cat_features_indices
45
+ self.eval_set = Pool(
46
+ data=X_validation,
47
+ label=y_validation,
48
+ cat_features=self.cat_features,
49
+ weight=sample_weight_validation,
50
+ )
51
+ self.n_jobs = n_jobs
52
+ self.rounds = 1000
53
+ self.learning_rate = 0.0125
54
+ self.early_stopping_rounds = 50
55
+ self.seed = random_state
56
+
57
+ self.objective = catboost_objective(ml_task, self.eval_metric.name)
58
+ self.eval_metric_name = catboost_eval_metric(ml_task, self.eval_metric.name)
59
+ self.custom_eval_metric = None
60
+ if self.eval_metric_name == "spearman":
61
+ self.custom_eval_metric = CatBoostEvalMetricSpearman()
62
+ elif self.eval_metric_name == "pearson":
63
+ self.custom_eval_metric = CatBoostEvalMetricPearson()
64
+ elif self.eval_metric_name == "average_precision":
65
+ self.custom_eval_metric = CatBoostEvalMetricAveragePrecision()
66
+ elif self.eval_metric_name == "mse":
67
+ self.custom_eval_metric = CatBoostEvalMetricMSE()
68
+ elif self.eval_metric_name == "user_defined_metric":
69
+ self.custom_eval_metric = CatBoostEvalMetricUserDefined()
70
+
71
+ def __call__(self, trial):
72
+ try:
73
+ params = {
74
+ "iterations": self.rounds,
75
+ "learning_rate": trial.suggest_categorical(
76
+ "learning_rate", [0.05, 0.1, 0.2]
77
+ ),
78
+ "depth": trial.suggest_int("depth", 2, 9),
79
+ "l2_leaf_reg": trial.suggest_float(
80
+ "l2_leaf_reg", 0.0001, 10.0, log=False
81
+ ),
82
+ "random_strength": trial.suggest_float(
83
+ "random_strength", EPS, 10.0, log=False
84
+ ),
85
+ "rsm": trial.suggest_float("rsm", 0.1, 1), # colsample_bylevel=rsm
86
+ "loss_function": self.objective,
87
+ "eval_metric": self.eval_metric_name,
88
+ "verbose": False,
89
+ "allow_writing_files": False,
90
+ "thread_count": self.n_jobs,
91
+ "random_seed": self.seed,
92
+ # "border_count": trial.suggest_int("border_count", 16, 2048),
93
+ "min_data_in_leaf": trial.suggest_int("min_data_in_leaf", 1, 100),
94
+ # "bootstrap_type": "Bernoulli"
95
+ # trial.suggest_categorical(
96
+ # "bootstrap_type", ["Bayesian", "Bernoulli", "MVS"]
97
+ # ),
98
+ }
99
+ # if params["bootstrap_type"] == "Bayesian":
100
+ # params["bagging_temperature"] = trial.suggest_float(
101
+ # "bagging_temperature", 0, 10
102
+ # )
103
+ # elif params["bootstrap_type"] in ["Bernoulli", "MVS"]:
104
+ # params["subsample"] = trial.suggest_float("subsample", 0.1, 1)
105
+
106
+ Algorithm = (
107
+ CatBoostRegressor if self.ml_task == REGRESSION else CatBoostClassifier
108
+ )
109
+ if self.custom_eval_metric is not None:
110
+ params["eval_metric"] = self.custom_eval_metric
111
+ model = Algorithm(**params)
112
+
113
+ model.fit(
114
+ self.X_train,
115
+ self.y_train,
116
+ sample_weight=self.sample_weight,
117
+ early_stopping_rounds=self.early_stopping_rounds,
118
+ eval_set=self.eval_set,
119
+ verbose_eval=False,
120
+ cat_features=self.cat_features,
121
+ )
122
+
123
+ if self.ml_task == BINARY_CLASSIFICATION:
124
+ preds = model.predict_proba(
125
+ self.X_validation, ntree_end=model.best_iteration_ + 1
126
+ )[:, 1]
127
+ elif self.ml_task == MULTICLASS_CLASSIFICATION:
128
+ preds = model.predict_proba(
129
+ self.X_validation, ntree_end=model.best_iteration_ + 1
130
+ )
131
+ else: # REGRESSION
132
+ preds = model.predict(
133
+ self.X_validation, ntree_end=model.best_iteration_ + 1
134
+ )
135
+
136
+ score = self.eval_metric(self.y_validation, preds)
137
+ if Metric.optimize_negative(self.eval_metric.name):
138
+ score *= -1.0
139
+
140
+ except optuna.exceptions.TrialPruned as e:
141
+ raise e
142
+ except Exception as e:
143
+ print("Exception in CatBoostObjective", str(e))
144
+ # import traceback
145
+ # print(traceback.format_exc())
146
+ return None
147
+
148
+ return score
@@ -0,0 +1,80 @@
1
+ import optuna
2
+
3
+ from supervised.algorithms.extra_trees import (
4
+ ExtraTreesAlgorithm,
5
+ ExtraTreesRegressorAlgorithm,
6
+ )
7
+ from supervised.algorithms.registry import (
8
+ REGRESSION,
9
+ )
10
+ from supervised.utils.metric import Metric
11
+
12
+ EPS = 1e-8
13
+
14
+
15
+ class ExtraTreesObjective:
16
+ def __init__(
17
+ self,
18
+ ml_task,
19
+ X_train,
20
+ y_train,
21
+ sample_weight,
22
+ X_validation,
23
+ y_validation,
24
+ sample_weight_validation,
25
+ eval_metric,
26
+ n_jobs,
27
+ random_state,
28
+ ):
29
+ self.ml_task = ml_task
30
+ self.X_train = X_train
31
+ self.y_train = y_train
32
+ self.sample_weight = sample_weight
33
+ self.X_validation = X_validation
34
+ self.y_validation = y_validation
35
+ self.eval_metric = eval_metric
36
+ self.n_jobs = n_jobs
37
+ self.objective = "squared_error" if ml_task == REGRESSION else "gini"
38
+ self.max_steps = 10 # ET is trained in steps 100 trees each
39
+ self.seed = random_state
40
+
41
+ def __call__(self, trial):
42
+ try:
43
+ Algorithm = (
44
+ ExtraTreesRegressorAlgorithm
45
+ if self.ml_task == REGRESSION
46
+ else ExtraTreesAlgorithm
47
+ )
48
+ self.objective = (
49
+ "squared_error"
50
+ if self.ml_task == REGRESSION
51
+ else trial.suggest_categorical("criterion", ["gini", "entropy"])
52
+ )
53
+ params = {
54
+ "max_steps": self.max_steps,
55
+ "criterion": self.objective,
56
+ "max_depth": trial.suggest_int("max_depth", 2, 32),
57
+ "min_samples_split": trial.suggest_int("min_samples_split", 2, 100),
58
+ "min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 100),
59
+ "max_features": trial.suggest_float("max_features", 0.01, 1),
60
+ "n_jobs": self.n_jobs,
61
+ "seed": self.seed,
62
+ "ml_task": self.ml_task,
63
+ }
64
+ model = Algorithm(params)
65
+
66
+ model.fit(self.X_train, self.y_train, sample_weight=self.sample_weight)
67
+
68
+ preds = model.predict(self.X_validation)
69
+
70
+ score = self.eval_metric(self.y_validation, preds)
71
+ if Metric.optimize_negative(self.eval_metric.name):
72
+ score *= -1.0
73
+
74
+ except optuna.exceptions.TrialPruned as e:
75
+ raise e
76
+ except Exception as e:
77
+ print("Exception in ExtraTreesObjective", str(e))
78
+ return None
79
+
80
+ return score
@@ -0,0 +1,64 @@
1
+ import optuna
2
+
3
+ from supervised.algorithms.knn import KNeighborsAlgorithm, KNeighborsRegressorAlgorithm
4
+ from supervised.algorithms.registry import (
5
+ REGRESSION,
6
+ )
7
+ from supervised.utils.metric import Metric
8
+
9
+
10
+ class KNNObjective:
11
+ def __init__(
12
+ self,
13
+ ml_task,
14
+ X_train,
15
+ y_train,
16
+ sample_weight,
17
+ X_validation,
18
+ y_validation,
19
+ sample_weight_validation,
20
+ eval_metric,
21
+ n_jobs,
22
+ random_state,
23
+ ):
24
+ self.ml_task = ml_task
25
+ self.X_train = X_train
26
+ self.y_train = y_train
27
+ self.sample_weight = sample_weight
28
+ self.X_validation = X_validation
29
+ self.y_validation = y_validation
30
+ self.eval_metric = eval_metric
31
+ self.n_jobs = n_jobs
32
+ self.seed = random_state
33
+
34
+ def __call__(self, trial):
35
+ try:
36
+ params = {
37
+ "n_neighbors": trial.suggest_int("n_neighbors", 1, 128),
38
+ "weights": trial.suggest_categorical(
39
+ "weights", ["uniform", "distance"]
40
+ ),
41
+ "n_jobs": self.n_jobs,
42
+ "rows_limit": 100000,
43
+ "ml_task": self.ml_task,
44
+ }
45
+ Algorithm = (
46
+ KNeighborsRegressorAlgorithm
47
+ if self.ml_task == REGRESSION
48
+ else KNeighborsAlgorithm
49
+ )
50
+ model = Algorithm(params)
51
+ model.fit(self.X_train, self.y_train, sample_weight=self.sample_weight)
52
+ preds = model.predict(self.X_validation)
53
+
54
+ score = self.eval_metric(self.y_validation, preds)
55
+ if Metric.optimize_negative(self.eval_metric.name):
56
+ score *= -1.0
57
+
58
+ except optuna.exceptions.TrialPruned as e:
59
+ raise e
60
+ except Exception as e:
61
+ print("Exception in KNNObjective", str(e))
62
+ return None
63
+
64
+ return score
@@ -0,0 +1,165 @@
1
+ import lightgbm as lgb
2
+ import numpy as np
3
+ import optuna
4
+ import optuna_integration
5
+ import pandas as pd
6
+
7
+ from supervised.algorithms.lightgbm import lightgbm_eval_metric, lightgbm_objective
8
+ from supervised.algorithms.registry import (
9
+ MULTICLASS_CLASSIFICATION,
10
+ )
11
+ from supervised.utils.metric import (
12
+ Metric,
13
+ lightgbm_eval_metric_accuracy,
14
+ lightgbm_eval_metric_average_precision,
15
+ lightgbm_eval_metric_f1,
16
+ lightgbm_eval_metric_pearson,
17
+ lightgbm_eval_metric_r2,
18
+ lightgbm_eval_metric_spearman,
19
+ lightgbm_eval_metric_user_defined,
20
+ )
21
+
22
+ EPS = 1e-8
23
+
24
+
25
+ class LightgbmObjective:
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
+ cat_features_indices,
37
+ n_jobs,
38
+ random_state,
39
+ ):
40
+ self.X_train = X_train
41
+ self.y_train = y_train
42
+ self.sample_weight = sample_weight
43
+ self.X_validation = X_validation
44
+ self.y_validation = y_validation
45
+ self.sample_weight_validation = sample_weight_validation
46
+ self.dtrain = lgb.Dataset(
47
+ self.X_train.to_numpy()
48
+ if isinstance(self.X_train, pd.DataFrame)
49
+ else self.X_train,
50
+ label=self.y_train,
51
+ weight=self.sample_weight,
52
+ )
53
+ self.dvalid = lgb.Dataset(
54
+ self.X_validation.to_numpy()
55
+ if isinstance(self.X_validation, pd.DataFrame)
56
+ else self.X_validation,
57
+ label=self.y_validation,
58
+ weight=self.sample_weight_validation,
59
+ )
60
+
61
+ self.cat_features_indices = cat_features_indices
62
+ self.eval_metric = eval_metric
63
+ self.learning_rate = 0.025
64
+ self.rounds = 1000
65
+ self.early_stopping_rounds = 50
66
+ self.seed = random_state
67
+
68
+ self.n_jobs = n_jobs
69
+ if n_jobs == -1:
70
+ self.n_jobs = 0
71
+
72
+ self.objective = ""
73
+ self.eval_metric_name = ""
74
+
75
+ self.eval_metric_name, self.custom_eval_metric_name = lightgbm_eval_metric(
76
+ ml_task, eval_metric.name
77
+ )
78
+
79
+ self.custom_eval_metric = None
80
+ if self.eval_metric.name == "r2":
81
+ self.custom_eval_metric = lightgbm_eval_metric_r2
82
+ elif self.eval_metric.name == "spearman":
83
+ self.custom_eval_metric = lightgbm_eval_metric_spearman
84
+ elif self.eval_metric.name == "pearson":
85
+ self.custom_eval_metric = lightgbm_eval_metric_pearson
86
+ elif self.eval_metric.name == "f1":
87
+ self.custom_eval_metric = lightgbm_eval_metric_f1
88
+ elif self.eval_metric.name == "average_precision":
89
+ self.custom_eval_metric = lightgbm_eval_metric_average_precision
90
+ elif self.eval_metric.name == "accuracy":
91
+ self.custom_eval_metric = lightgbm_eval_metric_accuracy
92
+ elif self.eval_metric.name == "user_defined_metric":
93
+ self.custom_eval_metric = lightgbm_eval_metric_user_defined
94
+
95
+ self.num_class = (
96
+ len(np.unique(y_train)) if ml_task == MULTICLASS_CLASSIFICATION else None
97
+ )
98
+ self.objective = lightgbm_objective(ml_task, eval_metric.name)
99
+
100
+ def __call__(self, trial):
101
+ param = {
102
+ "objective": self.objective,
103
+ "metric": self.eval_metric_name,
104
+ "verbosity": -1,
105
+ "boosting_type": "gbdt",
106
+ "learning_rate": trial.suggest_categorical(
107
+ "learning_rate", [0.0125, 0.025, 0.05, 0.1]
108
+ ),
109
+ "num_leaves": trial.suggest_int("num_leaves", 2, 2048),
110
+ "lambda_l1": trial.suggest_float("lambda_l1", 1e-8, 10.0, log=True),
111
+ "lambda_l2": trial.suggest_float("lambda_l2", 1e-8, 10.0, log=True),
112
+ "feature_fraction": min(
113
+ trial.suggest_float("feature_fraction", 0.3, 1.0 + EPS), 1.0
114
+ ),
115
+ "bagging_fraction": min(
116
+ trial.suggest_float("bagging_fraction", 0.3, 1.0 + EPS), 1.0
117
+ ),
118
+ "bagging_freq": trial.suggest_int("bagging_freq", 1, 7),
119
+ "min_data_in_leaf": trial.suggest_int("min_data_in_leaf", 1, 100),
120
+ "feature_pre_filter": False,
121
+ "seed": self.seed,
122
+ "num_threads": self.n_jobs,
123
+ "extra_trees": trial.suggest_categorical("extra_trees", [True, False]),
124
+ }
125
+
126
+ if self.cat_features_indices:
127
+ param["cat_feature"] = self.cat_features_indices
128
+ param["cat_l2"] = trial.suggest_float("cat_l2", EPS, 100.0)
129
+ param["cat_smooth"] = trial.suggest_float("cat_smooth", EPS, 100.0)
130
+
131
+ if self.num_class is not None:
132
+ param["num_class"] = self.num_class
133
+
134
+ try:
135
+ metric_name = self.eval_metric_name
136
+ if metric_name == "custom":
137
+ metric_name = self.custom_eval_metric_name
138
+ pruning_callback = optuna_integration.LightGBMPruningCallback(
139
+ trial, metric_name, "validation"
140
+ )
141
+ early_stopping_callback = lgb.early_stopping(
142
+ self.early_stopping_rounds, verbose=False
143
+ )
144
+
145
+ gbm = lgb.train(
146
+ param,
147
+ self.dtrain,
148
+ valid_sets=[self.dvalid],
149
+ valid_names=["validation"],
150
+ callbacks=[pruning_callback, early_stopping_callback],
151
+ num_boost_round=self.rounds,
152
+ feval=self.custom_eval_metric,
153
+ )
154
+
155
+ preds = gbm.predict(self.X_validation)
156
+ score = self.eval_metric(self.y_validation, preds)
157
+ if Metric.optimize_negative(self.eval_metric.name):
158
+ score *= -1.0
159
+ except optuna.exceptions.TrialPruned as e:
160
+ raise e
161
+ except Exception as e:
162
+ print("Exception in LightgbmObjective", str(e))
163
+ return None
164
+
165
+ return score
@@ -0,0 +1,66 @@
1
+ import optuna
2
+
3
+ from supervised.algorithms.nn import MLPAlgorithm, MLPRegressorAlgorithm
4
+ from supervised.algorithms.registry import (
5
+ REGRESSION,
6
+ )
7
+ from supervised.utils.metric import Metric
8
+
9
+
10
+ class NeuralNetworkObjective:
11
+ def __init__(
12
+ self,
13
+ ml_task,
14
+ X_train,
15
+ y_train,
16
+ sample_weight,
17
+ X_validation,
18
+ y_validation,
19
+ sample_weight_validation,
20
+ eval_metric,
21
+ n_jobs,
22
+ random_state,
23
+ ):
24
+ self.ml_task = ml_task
25
+ self.X_train = X_train
26
+ self.y_train = y_train
27
+ self.sample_weight = sample_weight
28
+ self.X_validation = X_validation
29
+ self.y_validation = y_validation
30
+ self.eval_metric = eval_metric
31
+ self.seed = random_state
32
+
33
+ def __call__(self, trial):
34
+ try:
35
+ Algorithm = (
36
+ MLPRegressorAlgorithm if self.ml_task == REGRESSION else MLPAlgorithm
37
+ )
38
+ params = {
39
+ "dense_1_size": trial.suggest_int("dense_1_size", 4, 100),
40
+ "dense_2_size": trial.suggest_int("dense_2_size", 2, 100),
41
+ "learning_rate": trial.suggest_categorical(
42
+ "learning_rate", [0.005, 0.01, 0.05, 0.1, 0.2]
43
+ ),
44
+ "learning_rate_type": trial.suggest_categorical(
45
+ "learning_rate_type", ["constant", "adaptive"]
46
+ ),
47
+ "alpha": trial.suggest_float("alpha", 1e-8, 10.0, log=True),
48
+ "seed": self.seed,
49
+ "ml_task": self.ml_task,
50
+ }
51
+ model = Algorithm(params)
52
+ model.fit(self.X_train, self.y_train, sample_weight=self.sample_weight)
53
+
54
+ preds = model.predict(self.X_validation)
55
+
56
+ score = self.eval_metric(self.y_validation, preds)
57
+ if Metric.optimize_negative(self.eval_metric.name):
58
+ score *= -1.0
59
+
60
+ except optuna.exceptions.TrialPruned as e:
61
+ raise e
62
+ except Exception as e:
63
+ print("Exception in NeuralNetworkObjective", str(e))
64
+ return None
65
+
66
+ return score
@@ -0,0 +1,77 @@
1
+ import optuna
2
+
3
+ from supervised.algorithms.random_forest import (
4
+ RandomForestAlgorithm,
5
+ RandomForestRegressorAlgorithm,
6
+ )
7
+ from supervised.algorithms.registry import (
8
+ REGRESSION,
9
+ )
10
+ from supervised.utils.metric import Metric
11
+
12
+
13
+ class RandomForestObjective:
14
+ def __init__(
15
+ self,
16
+ ml_task,
17
+ X_train,
18
+ y_train,
19
+ sample_weight,
20
+ X_validation,
21
+ y_validation,
22
+ sample_weight_validation,
23
+ eval_metric,
24
+ n_jobs,
25
+ random_state,
26
+ ):
27
+ self.ml_task = ml_task
28
+ self.X_train = X_train
29
+ self.y_train = y_train
30
+ self.sample_weight = sample_weight
31
+ self.X_validation = X_validation
32
+ self.y_validation = y_validation
33
+ self.eval_metric = eval_metric
34
+ self.n_jobs = n_jobs
35
+ self.objective = "squared_error" if ml_task == REGRESSION else "gini"
36
+ self.max_steps = 10 # RF is trained in steps 100 trees each
37
+ self.seed = random_state
38
+
39
+ def __call__(self, trial):
40
+ try:
41
+ Algorithm = (
42
+ RandomForestRegressorAlgorithm
43
+ if self.ml_task == REGRESSION
44
+ else RandomForestAlgorithm
45
+ )
46
+ self.objective = (
47
+ "squared_error"
48
+ if self.ml_task == REGRESSION
49
+ else trial.suggest_categorical("criterion", ["gini", "entropy"])
50
+ )
51
+ params = {
52
+ "max_steps": self.max_steps,
53
+ "criterion": self.objective,
54
+ "max_depth": trial.suggest_int("max_depth", 2, 32),
55
+ "min_samples_split": trial.suggest_int("min_samples_split", 2, 100),
56
+ "min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 100),
57
+ "max_features": trial.suggest_float("max_features", 0.01, 1),
58
+ "n_jobs": self.n_jobs,
59
+ "seed": self.seed,
60
+ "ml_task": self.ml_task,
61
+ }
62
+ model = Algorithm(params)
63
+ model.fit(self.X_train, self.y_train, sample_weight=self.sample_weight)
64
+
65
+ preds = model.predict(self.X_validation)
66
+
67
+ score = self.eval_metric(self.y_validation, preds)
68
+ if Metric.optimize_negative(self.eval_metric.name):
69
+ score *= -1.0
70
+
71
+ except optuna.exceptions.TrialPruned as e:
72
+ raise e
73
+ except Exception as e:
74
+ print("Exception in RandomForestObjective", str(e))
75
+ return None
76
+
77
+ return score