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.
- mljar_supervised-1.2.1.dist-info/METADATA +657 -0
- mljar_supervised-1.2.1.dist-info/RECORD +94 -0
- mljar_supervised-1.2.1.dist-info/WHEEL +5 -0
- mljar_supervised-1.2.1.dist-info/licenses/LICENSE +21 -0
- mljar_supervised-1.2.1.dist-info/top_level.txt +1 -0
- supervised/__init__.py +14 -0
- supervised/algorithms/__init__.py +0 -0
- supervised/algorithms/algorithm.py +151 -0
- supervised/algorithms/baseline.py +90 -0
- supervised/algorithms/catboost.py +436 -0
- supervised/algorithms/decision_tree.py +305 -0
- supervised/algorithms/extra_trees.py +176 -0
- supervised/algorithms/factory.py +28 -0
- supervised/algorithms/knn.py +137 -0
- supervised/algorithms/lightgbm.py +406 -0
- supervised/algorithms/linear.py +211 -0
- supervised/algorithms/nn.py +180 -0
- supervised/algorithms/random_forest.py +181 -0
- supervised/algorithms/registry.py +76 -0
- supervised/algorithms/sklearn.py +197 -0
- supervised/algorithms/xgboost.py +413 -0
- supervised/automl.py +568 -0
- supervised/base_automl.py +2542 -0
- supervised/callbacks/__init__.py +0 -0
- supervised/callbacks/callback.py +25 -0
- supervised/callbacks/callback_list.py +33 -0
- supervised/callbacks/early_stopping.py +213 -0
- supervised/callbacks/learner_time_constraint.py +47 -0
- supervised/callbacks/max_iters_constraint.py +16 -0
- supervised/callbacks/metric_logger.py +48 -0
- supervised/callbacks/terminate_on_nan.py +28 -0
- supervised/callbacks/total_time_constraint.py +79 -0
- supervised/ensemble.py +583 -0
- supervised/exceptions.py +21 -0
- supervised/fairness/__init__.py +0 -0
- supervised/fairness/metrics.py +654 -0
- supervised/fairness/optimization.py +414 -0
- supervised/fairness/plots.py +131 -0
- supervised/fairness/report.py +116 -0
- supervised/fairness/utils.py +40 -0
- supervised/model_framework.py +734 -0
- supervised/preprocessing/__init__.py +0 -0
- supervised/preprocessing/datetime_transformer.py +106 -0
- supervised/preprocessing/encoding_selector.py +30 -0
- supervised/preprocessing/exclude_missing_target.py +46 -0
- supervised/preprocessing/goldenfeatures_transformer.py +310 -0
- supervised/preprocessing/kmeans_transformer.py +115 -0
- supervised/preprocessing/label_binarizer.py +81 -0
- supervised/preprocessing/label_encoder.py +54 -0
- supervised/preprocessing/preprocessing.py +652 -0
- supervised/preprocessing/preprocessing_categorical.py +117 -0
- supervised/preprocessing/preprocessing_missing.py +97 -0
- supervised/preprocessing/preprocessing_utils.py +136 -0
- supervised/preprocessing/scale.py +92 -0
- supervised/preprocessing/text_transformer.py +73 -0
- supervised/tuner/__init__.py +0 -0
- supervised/tuner/data_info.py +64 -0
- supervised/tuner/hill_climbing.py +80 -0
- supervised/tuner/mljar_tuner.py +1501 -0
- supervised/tuner/optuna/__init__.py +0 -0
- supervised/tuner/optuna/catboost.py +148 -0
- supervised/tuner/optuna/extra_trees.py +80 -0
- supervised/tuner/optuna/knn.py +64 -0
- supervised/tuner/optuna/lightgbm.py +165 -0
- supervised/tuner/optuna/nn.py +66 -0
- supervised/tuner/optuna/random_forest.py +77 -0
- supervised/tuner/optuna/tuner.py +335 -0
- supervised/tuner/optuna/xgboost.py +130 -0
- supervised/tuner/preprocessing_tuner.py +137 -0
- supervised/tuner/random_parameters.py +22 -0
- supervised/tuner/time_controller.py +273 -0
- supervised/utils/__init__.py +11 -0
- supervised/utils/additional_metrics.py +955 -0
- supervised/utils/additional_plots.py +228 -0
- supervised/utils/automl_plots.py +368 -0
- supervised/utils/common.py +39 -0
- supervised/utils/config.py +25 -0
- supervised/utils/constants.py +4 -0
- supervised/utils/data_validation.py +48 -0
- supervised/utils/importance.py +93 -0
- supervised/utils/jsonencoder.py +33 -0
- supervised/utils/leaderboard_plots.py +137 -0
- supervised/utils/learning_curves.py +145 -0
- supervised/utils/metric.py +450 -0
- supervised/utils/report_structured.py +525 -0
- supervised/utils/shap.py +373 -0
- supervised/utils/subsample.py +17 -0
- supervised/utils/utils.py +29 -0
- supervised/validation/__init__.py +0 -0
- supervised/validation/validation_step.py +37 -0
- supervised/validation/validator_base.py +17 -0
- supervised/validation/validator_custom.py +112 -0
- supervised/validation/validator_kfold.py +153 -0
- supervised/validation/validator_split.py +143 -0
|
File without changes
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
class Callback(object):
|
|
2
|
+
def __init__(self, params):
|
|
3
|
+
self.params = params
|
|
4
|
+
self.learners = []
|
|
5
|
+
self.learner = None # current learner
|
|
6
|
+
self.name = "callback"
|
|
7
|
+
|
|
8
|
+
def add_and_set_learner(self, learner):
|
|
9
|
+
self.learners += [learner]
|
|
10
|
+
self.learner = learner
|
|
11
|
+
|
|
12
|
+
def on_learner_train_start(self, logs):
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
def on_learner_train_end(self, logs):
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
def on_iteration_start(self, logs):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
def on_iteration_end(self, logs, predictions):
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
def on_framework_train_end(self, logs):
|
|
25
|
+
pass
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
class CallbackList(object):
|
|
2
|
+
def __init__(self, callbacks=[]):
|
|
3
|
+
self.callbacks = callbacks
|
|
4
|
+
|
|
5
|
+
def add_and_set_learner(self, learner):
|
|
6
|
+
for cb in self.callbacks:
|
|
7
|
+
cb.add_and_set_learner(learner)
|
|
8
|
+
|
|
9
|
+
def on_learner_train_start(self, logs=None):
|
|
10
|
+
for cb in self.callbacks:
|
|
11
|
+
cb.on_learner_train_start(logs)
|
|
12
|
+
|
|
13
|
+
def on_learner_train_end(self, logs=None):
|
|
14
|
+
for cb in self.callbacks:
|
|
15
|
+
cb.on_learner_train_end(logs)
|
|
16
|
+
|
|
17
|
+
def on_iteration_start(self, logs=None):
|
|
18
|
+
for cb in self.callbacks:
|
|
19
|
+
cb.on_iteration_start(logs)
|
|
20
|
+
|
|
21
|
+
def on_iteration_end(self, logs=None, predictions=None):
|
|
22
|
+
for cb in self.callbacks:
|
|
23
|
+
cb.on_iteration_end(logs, predictions)
|
|
24
|
+
|
|
25
|
+
def on_framework_train_end(self, logs=None):
|
|
26
|
+
for cb in self.callbacks:
|
|
27
|
+
cb.on_framework_train_end(logs)
|
|
28
|
+
|
|
29
|
+
def get(self, callback_name):
|
|
30
|
+
for cb in self.callbacks:
|
|
31
|
+
if cb.name == callback_name:
|
|
32
|
+
return cb
|
|
33
|
+
return None
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
from supervised.callbacks.callback import Callback
|
|
8
|
+
from supervised.utils.config import LOG_LEVEL
|
|
9
|
+
from supervised.utils.metric import Metric
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
logger.setLevel(LOG_LEVEL)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class EarlyStopping(Callback):
|
|
16
|
+
def __init__(self, params):
|
|
17
|
+
super(EarlyStopping, self).__init__(params)
|
|
18
|
+
self.name = params.get("name", "early_stopping")
|
|
19
|
+
self.metric = Metric(params.get("metric"))
|
|
20
|
+
self.max_no_improvement_cnt = params.get("max_no_improvement_cnt", 5)
|
|
21
|
+
self.log_to_dir = params.get("log_to_dir")
|
|
22
|
+
|
|
23
|
+
self.keep_best_model = params.get("keep_best_model", True)
|
|
24
|
+
self.best_iter = {}
|
|
25
|
+
self.best_loss = {}
|
|
26
|
+
self.loss_values = {}
|
|
27
|
+
self.best_models = {}
|
|
28
|
+
self.best_y_predicted = {}
|
|
29
|
+
self.best_y_oof = (
|
|
30
|
+
None # predictions computed on out of folds or on validation set
|
|
31
|
+
)
|
|
32
|
+
self.final_loss = (
|
|
33
|
+
None # final score computed on combined predictions from all learners
|
|
34
|
+
)
|
|
35
|
+
# path to best model local copy, only used if cannot deep copy
|
|
36
|
+
self.best_model_paths = {}
|
|
37
|
+
self.multiple_target = False
|
|
38
|
+
self.target_columns = None
|
|
39
|
+
|
|
40
|
+
def add_and_set_learner(self, learner):
|
|
41
|
+
self.learners += [learner]
|
|
42
|
+
self.learner = learner
|
|
43
|
+
self.best_iter[learner.uid] = None
|
|
44
|
+
self.best_loss[learner.uid] = self.metric.worst_value()
|
|
45
|
+
self.loss_values[learner.uid] = {"train": [], "validation": [], "iters": []}
|
|
46
|
+
self.best_models[learner.uid] = None
|
|
47
|
+
self.best_model_paths[learner.uid] = None
|
|
48
|
+
self.best_y_predicted[learner.uid] = None
|
|
49
|
+
|
|
50
|
+
def on_learner_train_start(self, logs):
|
|
51
|
+
self.no_improvement_cnt = 0
|
|
52
|
+
|
|
53
|
+
def on_framework_train_end(self, logs):
|
|
54
|
+
# aggregate predictions from all learners
|
|
55
|
+
# it has two columns: 'prediction', 'target'
|
|
56
|
+
logger.debug("early stopping on framework train end")
|
|
57
|
+
self.best_y_oof = pd.concat(list(self.best_y_predicted.values()))
|
|
58
|
+
self.best_y_oof.sort_index(inplace=True)
|
|
59
|
+
# check for duplicates in index -> repeats of validation
|
|
60
|
+
if np.sum(self.best_y_oof.index.duplicated()):
|
|
61
|
+
# we need to aggregate predictions from multiple repeats
|
|
62
|
+
target_cols = [c for c in self.best_y_oof.columns if "prediction" not in c]
|
|
63
|
+
prediction_cols = [c for c in self.best_y_oof.columns if "prediction" in c]
|
|
64
|
+
|
|
65
|
+
aggs = {}
|
|
66
|
+
for t in target_cols:
|
|
67
|
+
aggs[t] = "first"
|
|
68
|
+
for p in prediction_cols:
|
|
69
|
+
aggs[p] = "mean"
|
|
70
|
+
# aggregate predictions from repeats
|
|
71
|
+
self.best_y_oof = self.best_y_oof.groupby(
|
|
72
|
+
target_cols + prediction_cols, level=0
|
|
73
|
+
).agg(aggs)
|
|
74
|
+
|
|
75
|
+
sample_weight = None
|
|
76
|
+
if "sample_weight" in self.best_y_oof.columns:
|
|
77
|
+
sample_weight = self.best_y_oof["sample_weight"]
|
|
78
|
+
|
|
79
|
+
if "prediction" in self.best_y_oof:
|
|
80
|
+
self.final_loss = self.metric(
|
|
81
|
+
self.best_y_oof[self.target_columns],
|
|
82
|
+
self.best_y_oof["prediction"],
|
|
83
|
+
sample_weight=sample_weight,
|
|
84
|
+
)
|
|
85
|
+
else:
|
|
86
|
+
prediction_cols = [c for c in self.best_y_oof.columns if "prediction" in c]
|
|
87
|
+
self.final_loss = self.metric(
|
|
88
|
+
self.best_y_oof[self.target_columns],
|
|
89
|
+
self.best_y_oof[prediction_cols],
|
|
90
|
+
sample_weight=sample_weight,
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
def on_iteration_end(self, logs, predictions):
|
|
94
|
+
train_loss = 0
|
|
95
|
+
if predictions.get("y_train_predicted") is not None:
|
|
96
|
+
train_loss = self.metric(
|
|
97
|
+
predictions.get("y_train_true"),
|
|
98
|
+
predictions.get("y_train_predicted"),
|
|
99
|
+
predictions.get("sample_weight"),
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
validation_loss = self.metric(
|
|
103
|
+
predictions.get("y_validation_true"),
|
|
104
|
+
predictions.get("y_validation_predicted"),
|
|
105
|
+
predictions.get("sample_weight_validation"),
|
|
106
|
+
)
|
|
107
|
+
self.loss_values[self.learner.uid]["train"] += [train_loss]
|
|
108
|
+
self.loss_values[self.learner.uid]["validation"] += [validation_loss]
|
|
109
|
+
self.loss_values[self.learner.uid]["iters"] += [logs.get("iter_cnt")]
|
|
110
|
+
|
|
111
|
+
if self.metric.improvement(
|
|
112
|
+
previous=self.best_loss[self.learner.uid], current=validation_loss
|
|
113
|
+
):
|
|
114
|
+
y_validation_true = predictions.get("y_validation_true")
|
|
115
|
+
self.no_improvement_cnt = 0
|
|
116
|
+
self.best_iter[self.learner.uid] = logs.get("iter_cnt")
|
|
117
|
+
self.best_loss[self.learner.uid] = validation_loss
|
|
118
|
+
|
|
119
|
+
if len(y_validation_true.shape) == 1 or y_validation_true.shape[1] == 1:
|
|
120
|
+
self.best_y_predicted[self.learner.uid] = pd.DataFrame(
|
|
121
|
+
{
|
|
122
|
+
"target": np.array(y_validation_true)
|
|
123
|
+
# y_validation_true.values.reshape(
|
|
124
|
+
# y_validation_true.shape[0]
|
|
125
|
+
# )
|
|
126
|
+
},
|
|
127
|
+
index=predictions.get("validation_index"),
|
|
128
|
+
)
|
|
129
|
+
self.multiple_target = False
|
|
130
|
+
self.target_columns = "target"
|
|
131
|
+
else:
|
|
132
|
+
# in case of Neural Networks and multi-class classification with one-hot encoding
|
|
133
|
+
self.best_y_predicted[self.learner.uid] = pd.DataFrame(
|
|
134
|
+
y_validation_true, index=predictions.get("validation_index")
|
|
135
|
+
)
|
|
136
|
+
self.multiple_target = True
|
|
137
|
+
self.target_columns = y_validation_true.columns
|
|
138
|
+
|
|
139
|
+
y_validation_predicted = predictions.get("y_validation_predicted")
|
|
140
|
+
|
|
141
|
+
if len(y_validation_predicted.shape) == 1:
|
|
142
|
+
# only one prediction column (binary classification or regression)
|
|
143
|
+
col = predictions.get("validation_columns", "prediction")
|
|
144
|
+
self.best_y_predicted[self.learner.uid][col] = np.array(
|
|
145
|
+
y_validation_predicted
|
|
146
|
+
)
|
|
147
|
+
else:
|
|
148
|
+
# several columns in multiclass classification
|
|
149
|
+
cols = predictions.get("validation_columns")
|
|
150
|
+
for i_col in range(y_validation_predicted.shape[1]):
|
|
151
|
+
self.best_y_predicted[self.learner.uid][
|
|
152
|
+
# "prediction_{}".format(i_col)
|
|
153
|
+
cols[i_col]
|
|
154
|
+
] = y_validation_predicted[:, i_col]
|
|
155
|
+
|
|
156
|
+
# store sample_weight
|
|
157
|
+
sample_weight_validation = predictions.get("sample_weight_validation")
|
|
158
|
+
if sample_weight_validation is not None:
|
|
159
|
+
self.best_y_predicted[self.learner.uid]["sample_weight"] = np.array(
|
|
160
|
+
sample_weight_validation
|
|
161
|
+
)
|
|
162
|
+
# store sensitive features
|
|
163
|
+
sensitive_features_validation = predictions.get(
|
|
164
|
+
"sensitive_features_validation"
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
if sensitive_features_validation is not None:
|
|
168
|
+
for col in list(sensitive_features_validation.columns):
|
|
169
|
+
self.best_y_predicted[self.learner.uid][
|
|
170
|
+
f"sensitive_{col}"
|
|
171
|
+
] = np.array(sensitive_features_validation[col])
|
|
172
|
+
|
|
173
|
+
self.best_models[self.learner.uid] = self.learner.copy()
|
|
174
|
+
# if local copy is not available, save model and keep path
|
|
175
|
+
if self.best_models[self.learner.uid] is None:
|
|
176
|
+
self.best_model_paths[self.learner.uid] = self.learner.save()
|
|
177
|
+
else:
|
|
178
|
+
self.no_improvement_cnt += 1
|
|
179
|
+
|
|
180
|
+
if self.no_improvement_cnt > self.max_no_improvement_cnt:
|
|
181
|
+
self.learner.stop_training = True
|
|
182
|
+
|
|
183
|
+
logger.info(
|
|
184
|
+
"EarlyStopping.on_iteration_end, train loss: {}, validation loss: {}, "
|
|
185
|
+
"no improvement cnt {}, iters {}".format(
|
|
186
|
+
train_loss,
|
|
187
|
+
validation_loss,
|
|
188
|
+
self.no_improvement_cnt,
|
|
189
|
+
len(self.loss_values[self.learner.uid]["iters"]),
|
|
190
|
+
)
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
if self.log_to_dir is not None and self.learner.algorithm_short_name not in [
|
|
194
|
+
"Xgboost",
|
|
195
|
+
"Random Forest",
|
|
196
|
+
"Extra Trees",
|
|
197
|
+
"LightGBM",
|
|
198
|
+
"CatBoost",
|
|
199
|
+
"Neural Network",
|
|
200
|
+
]:
|
|
201
|
+
sign = -1.0 if Metric.optimize_negative(self.metric.name) else 1.0
|
|
202
|
+
with open(
|
|
203
|
+
os.path.join(self.log_to_dir, f"{self.learner.name}_training.log"), "a"
|
|
204
|
+
) as fout:
|
|
205
|
+
iteration = len(self.loss_values[self.learner.uid]["iters"])
|
|
206
|
+
fout.write(f"{iteration},{sign*train_loss},{sign*validation_loss}\n")
|
|
207
|
+
|
|
208
|
+
def get_status(self):
|
|
209
|
+
return "Train loss: {}, Validation loss: {} @ iteration {}".format(
|
|
210
|
+
self.loss_values[self.learner.uid]["train"][-1],
|
|
211
|
+
self.loss_values[self.learner.uid]["validation"][-1],
|
|
212
|
+
len(self.loss_values[self.learner.uid]["iters"]),
|
|
213
|
+
)
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import time
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from supervised.callbacks.callback import Callback
|
|
7
|
+
from supervised.utils.config import LOG_LEVEL
|
|
8
|
+
|
|
9
|
+
log = logging.getLogger(__name__)
|
|
10
|
+
log.setLevel(LOG_LEVEL)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class LearnerTimeConstraint(Callback):
|
|
14
|
+
def __init__(self, params={}):
|
|
15
|
+
super(LearnerTimeConstraint, self).__init__(params)
|
|
16
|
+
self.name = params.get("name", "learner_time_constraint")
|
|
17
|
+
self.min_steps = params.get("min_steps")
|
|
18
|
+
self.learner_time_limit = params.get("learner_time_limit") # in seconds
|
|
19
|
+
self.iterations_count = 0
|
|
20
|
+
|
|
21
|
+
def on_learner_train_start(self, logs):
|
|
22
|
+
self.train_start_time = time.time()
|
|
23
|
+
self.iterations_count = 0
|
|
24
|
+
|
|
25
|
+
def on_iteration_start(self, logs):
|
|
26
|
+
self.iter_start_time = time.time()
|
|
27
|
+
|
|
28
|
+
def on_iteration_end(self, logs, predictions):
|
|
29
|
+
self.iterations_count += 1
|
|
30
|
+
iteration_elapsed_time = np.round(time.time() - self.iter_start_time, 2)
|
|
31
|
+
learner_elapsed_time = np.round(time.time() - self.train_start_time, 2)
|
|
32
|
+
log.debug(
|
|
33
|
+
"Iteration {0} took {1} seconds, learner training time {2} seconds".format(
|
|
34
|
+
self.iterations_count, iteration_elapsed_time, learner_elapsed_time
|
|
35
|
+
)
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
if self.min_steps is not None:
|
|
39
|
+
if self.iterations_count < self.min_steps:
|
|
40
|
+
# self.learner.stop_training = False
|
|
41
|
+
# return before checking other conditions
|
|
42
|
+
return
|
|
43
|
+
|
|
44
|
+
if self.learner_time_limit is not None:
|
|
45
|
+
if learner_elapsed_time >= self.learner_time_limit:
|
|
46
|
+
self.learner.stop_training = True
|
|
47
|
+
log.info("Terminating learning, time limit reached")
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from supervised.callbacks.callback import Callback
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class MaxItersConstraint(Callback):
|
|
5
|
+
def __init__(self, params):
|
|
6
|
+
super(MaxItersConstraint, self).__init__(params)
|
|
7
|
+
self.name = params.get("name", "max_iters_constraint")
|
|
8
|
+
self.max_iters = params.get("max_iters", 10)
|
|
9
|
+
|
|
10
|
+
def add_and_set_learner(self, learner):
|
|
11
|
+
self.learner = learner
|
|
12
|
+
|
|
13
|
+
def on_iteration_end(self, logs, predictions):
|
|
14
|
+
# iters are computed starting from 0
|
|
15
|
+
if logs.get("iter_cnt") + 1 >= self.max_iters:
|
|
16
|
+
self.learner.stop_training = True
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
log = logging.getLogger(__name__)
|
|
4
|
+
|
|
5
|
+
from supervised.callbacks.callback import Callback
|
|
6
|
+
from supervised.utils.metric import Metric
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class MetricLogger(Callback):
|
|
10
|
+
def __init__(self, params):
|
|
11
|
+
super(MetricLogger, self).__init__(params)
|
|
12
|
+
self.name = params.get("name", "metric_logger")
|
|
13
|
+
self.loss_values = {}
|
|
14
|
+
self.metrics = []
|
|
15
|
+
for metric_name in params.get("metric_names"):
|
|
16
|
+
self.metrics += [Metric({"name": metric_name})]
|
|
17
|
+
|
|
18
|
+
def add_and_set_learner(self, learner):
|
|
19
|
+
self.loss_values[learner.uid] = {"train": {}, "validation": {}, "iters": []}
|
|
20
|
+
for metric in self.metrics:
|
|
21
|
+
self.loss_values[learner.uid]["train"][metric.name] = []
|
|
22
|
+
self.loss_values[learner.uid]["validation"][metric.name] = []
|
|
23
|
+
|
|
24
|
+
self.current_learner_uid = learner.uid
|
|
25
|
+
|
|
26
|
+
def on_iteration_end(self, logs, predictions):
|
|
27
|
+
for metric in self.metrics:
|
|
28
|
+
train_loss = 0
|
|
29
|
+
if predictions.get("y_train_predicted") is not None:
|
|
30
|
+
train_loss = metric(
|
|
31
|
+
predictions.get("y_train_true"),
|
|
32
|
+
predictions.get("y_train_predicted"),
|
|
33
|
+
)
|
|
34
|
+
validation_loss = metric(
|
|
35
|
+
predictions.get("y_validation_true"),
|
|
36
|
+
predictions.get("y_validation_predicted"),
|
|
37
|
+
)
|
|
38
|
+
self.loss_values[self.current_learner_uid]["train"][metric.name] += [
|
|
39
|
+
train_loss
|
|
40
|
+
]
|
|
41
|
+
self.loss_values[self.current_learner_uid]["validation"][metric.name] += [
|
|
42
|
+
validation_loss
|
|
43
|
+
]
|
|
44
|
+
# keep information about iter number only once :)
|
|
45
|
+
if metric == self.metrics[0]:
|
|
46
|
+
self.loss_values[self.current_learner_uid]["iters"] += [
|
|
47
|
+
logs.get("iter_cnt")
|
|
48
|
+
]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
log = logging.getLogger(__name__)
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from supervised.callbacks.callback import Callback
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TerminateOnNan(Callback):
|
|
11
|
+
def __init__(self, learner, params):
|
|
12
|
+
super(TerminateOnNan, self).__init__(learner, params)
|
|
13
|
+
self.metric = Metric(params.get("metric_name"))
|
|
14
|
+
|
|
15
|
+
def on_iteration_end(self, iter_cnt, data):
|
|
16
|
+
loss_train = 0
|
|
17
|
+
if data.get("y_train_predicted") is not None:
|
|
18
|
+
loss_train = self.metric(
|
|
19
|
+
data.get("y_train_true"), data.get("y_train_predicted")
|
|
20
|
+
)
|
|
21
|
+
loss_validation = self.metric(
|
|
22
|
+
data.get("y_validation_true"), data.get("y_validation_predicted")
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
for loss in [loss_train, loss_validation]:
|
|
26
|
+
if np.isnan(loss) or np.isinf(loss) or np.isneginf(loss):
|
|
27
|
+
self.learner.stop_training = True
|
|
28
|
+
log.info("Terminating learning, invalid loss value")
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import time
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from supervised.callbacks.callback import Callback
|
|
7
|
+
from supervised.exceptions import NotTrainedException
|
|
8
|
+
from supervised.utils.config import LOG_LEVEL
|
|
9
|
+
|
|
10
|
+
log = logging.getLogger(__name__)
|
|
11
|
+
log.setLevel(LOG_LEVEL)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class TotalTimeConstraint(Callback):
|
|
15
|
+
def __init__(self, params={}):
|
|
16
|
+
super(TotalTimeConstraint, self).__init__(params)
|
|
17
|
+
self.name = params.get("name", "total_time_constraint")
|
|
18
|
+
self.total_time_limit = params.get("total_time_limit")
|
|
19
|
+
self.total_time_start = params.get("total_time_start")
|
|
20
|
+
self.expected_learners_cnt = params.get("expected_learners_cnt", 1)
|
|
21
|
+
|
|
22
|
+
def on_learner_train_start(self, logs):
|
|
23
|
+
self.train_start_time = time.time()
|
|
24
|
+
|
|
25
|
+
def on_learner_train_end(self, logs):
|
|
26
|
+
if (
|
|
27
|
+
self.total_time_limit is not None
|
|
28
|
+
and len(self.learners) == 1
|
|
29
|
+
and self.expected_learners_cnt > 1
|
|
30
|
+
# just check for the first learner
|
|
31
|
+
# need to have more than 1 learner
|
|
32
|
+
# otherwise it is a finish of the training
|
|
33
|
+
):
|
|
34
|
+
one_fold_time = time.time() - self.train_start_time
|
|
35
|
+
estimate_all_folds = one_fold_time * self.expected_learners_cnt
|
|
36
|
+
|
|
37
|
+
total_elapsed_time = np.round(time.time() - self.total_time_start, 2)
|
|
38
|
+
|
|
39
|
+
# we need to add time for the rest of learners (assuming that all folds training time is the same)
|
|
40
|
+
estimate_elapsed_time = total_elapsed_time + one_fold_time * (
|
|
41
|
+
self.expected_learners_cnt - 1
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
if estimate_elapsed_time >= self.total_time_limit:
|
|
45
|
+
raise NotTrainedException(
|
|
46
|
+
"Stop training after the first fold. "
|
|
47
|
+
f"Time needed to train on the first fold {np.round(one_fold_time)} seconds. "
|
|
48
|
+
"The time estimate for training on all folds is larger than total_time_limit."
|
|
49
|
+
)
|
|
50
|
+
if (
|
|
51
|
+
self.total_time_limit is not None
|
|
52
|
+
and len(self.learners) < self.expected_learners_cnt
|
|
53
|
+
# dont stop for last learner, we are finishing anyway
|
|
54
|
+
):
|
|
55
|
+
total_elapsed_time = np.round(time.time() - self.total_time_start, 2)
|
|
56
|
+
|
|
57
|
+
if total_elapsed_time > self.total_time_limit + 600:
|
|
58
|
+
# add 10 minutes of margin
|
|
59
|
+
# margin is added because of unexpected time changes
|
|
60
|
+
# if training on each fold will be the same
|
|
61
|
+
# then the training will be stopped after first fold (above condition)
|
|
62
|
+
raise NotTrainedException(
|
|
63
|
+
"Force to stop the training. "
|
|
64
|
+
"Total time for AutoML training already exceeded."
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
def on_iteration_end(self, logs, predictions):
|
|
68
|
+
total_elapsed_time = np.round(time.time() - self.total_time_start, 2)
|
|
69
|
+
|
|
70
|
+
if self.total_time_limit is not None:
|
|
71
|
+
log.debug(
|
|
72
|
+
f"Total elapsed time {total_elapsed_time} seconds. "
|
|
73
|
+
+ f"Time left {np.round(self.total_time_limit - total_elapsed_time, 2)} seconds."
|
|
74
|
+
)
|
|
75
|
+
# not time left, stop now
|
|
76
|
+
if total_elapsed_time >= self.total_time_limit:
|
|
77
|
+
self.learner.stop_training = True
|
|
78
|
+
else:
|
|
79
|
+
log.debug(f"Total elapsed time {total_elapsed_time} seconds")
|