mljar-supervised 1.4.0rc2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mljar_supervised-1.4.0rc2.dist-info/METADATA +759 -0
- mljar_supervised-1.4.0rc2.dist-info/RECORD +117 -0
- mljar_supervised-1.4.0rc2.dist-info/WHEEL +5 -0
- mljar_supervised-1.4.0rc2.dist-info/licenses/LICENSE +21 -0
- mljar_supervised-1.4.0rc2.dist-info/licenses/LICENSE-pytabkit.txt +201 -0
- mljar_supervised-1.4.0rc2.dist-info/top_level.txt +1 -0
- supervised/__init__.py +14 -0
- supervised/algorithms/__init__.py +0 -0
- supervised/algorithms/_pytabkit_compat.py +128 -0
- supervised/algorithms/_realmlp_backend.py +84 -0
- supervised/algorithms/_sdm_backend.py +75 -0
- supervised/algorithms/_tabm_backend.py +221 -0
- supervised/algorithms/algorithm.py +169 -0
- supervised/algorithms/baseline.py +90 -0
- supervised/algorithms/catboost.py +451 -0
- supervised/algorithms/decision_tree.py +310 -0
- supervised/algorithms/extra_trees.py +178 -0
- supervised/algorithms/factory.py +28 -0
- supervised/algorithms/knn.py +277 -0
- supervised/algorithms/lightgbm.py +418 -0
- supervised/algorithms/linear.py +213 -0
- supervised/algorithms/nn.py +201 -0
- supervised/algorithms/random_forest.py +183 -0
- supervised/algorithms/realmlp.py +586 -0
- supervised/algorithms/realmlp_resources.py +153 -0
- supervised/algorithms/registry.py +85 -0
- supervised/algorithms/sdm.py +577 -0
- supervised/algorithms/sklearn.py +197 -0
- supervised/algorithms/tabm.py +345 -0
- supervised/algorithms/tabm_resources.py +94 -0
- supervised/algorithms/xgboost.py +420 -0
- supervised/apps/__init__.py +5 -0
- supervised/apps/generator.py +231 -0
- supervised/apps/local_runner.py +120 -0
- supervised/apps/metadata.py +380 -0
- supervised/apps/publisher.py +497 -0
- supervised/apps/templates.py +633 -0
- supervised/automl.py +680 -0
- supervised/base_automl.py +2758 -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 +224 -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 +588 -0
- supervised/exceptions.py +20 -0
- supervised/fairness/__init__.py +0 -0
- supervised/fairness/certificate.py +129 -0
- supervised/fairness/metrics.py +654 -0
- supervised/fairness/optimization.py +414 -0
- supervised/fairness/plots.py +131 -0
- supervised/fairness/report.py +169 -0
- supervised/fairness/utils.py +40 -0
- supervised/model_framework.py +779 -0
- supervised/preprocessing/__init__.py +0 -0
- supervised/preprocessing/datetime_transformer.py +106 -0
- supervised/preprocessing/encoding_selector.py +31 -0
- supervised/preprocessing/exclude_missing_target.py +46 -0
- supervised/preprocessing/goldenfeatures_transformer.py +310 -0
- supervised/preprocessing/ip_transformer.py +94 -0
- supervised/preprocessing/kmeans_transformer.py +119 -0
- supervised/preprocessing/label_binarizer.py +81 -0
- supervised/preprocessing/label_encoder.py +116 -0
- supervised/preprocessing/preprocessing.py +705 -0
- supervised/preprocessing/preprocessing_categorical.py +115 -0
- supervised/preprocessing/preprocessing_missing.py +105 -0
- supervised/preprocessing/preprocessing_utils.py +201 -0
- supervised/preprocessing/scale.py +92 -0
- supervised/preprocessing/text_transformer.py +73 -0
- supervised/tuner/__init__.py +0 -0
- supervised/tuner/custom_parameters.py +62 -0
- supervised/tuner/data_info.py +83 -0
- supervised/tuner/hill_climbing.py +80 -0
- supervised/tuner/mljar_tuner.py +1566 -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 +170 -0
- supervised/tuner/optuna/nn.py +68 -0
- supervised/tuner/optuna/random_forest.py +77 -0
- supervised/tuner/optuna/tuner.py +338 -0
- supervised/tuner/optuna/xgboost.py +136 -0
- supervised/tuner/preprocessing_tuner.py +147 -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 +992 -0
- supervised/utils/additional_plots.py +228 -0
- supervised/utils/artifact_paths.py +14 -0
- supervised/utils/automl_plots.py +329 -0
- supervised/utils/blueprint.py +494 -0
- supervised/utils/column_scan.py +58 -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/feature_importance.py +266 -0
- supervised/utils/importance.py +150 -0
- supervised/utils/jsonencoder.py +33 -0
- supervised/utils/leaderboard_plots.py +153 -0
- supervised/utils/learning_curves.py +145 -0
- supervised/utils/metric.py +470 -0
- supervised/utils/report_structured.py +718 -0
- supervised/utils/shap.py +383 -0
- supervised/utils/subsample.py +17 -0
- supervised/utils/utils.py +94 -0
- supervised/validation/__init__.py +0 -0
- supervised/validation/validation_step.py +38 -0
- supervised/validation/validator_base.py +36 -0
- supervised/validation/validator_custom.py +88 -0
- supervised/validation/validator_kfold.py +135 -0
- supervised/validation/validator_split.py +111 -0
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Lazy pytabkit TabM-mini adapter with bounded training and checkpoint history.
|
|
2
|
+
|
|
3
|
+
Adapted from pytabkit 1.7's TabM implementation (Apache-2.0), by David
|
|
4
|
+
Holzmüller and contributors: https://github.com/dholzmueller/pytabkit.
|
|
5
|
+
See LICENSE-pytabkit.txt for the upstream license.
|
|
6
|
+
The architecture/embeddings remain provided by pytabkit; MLJAR owns the loop.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import copy
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
import torch
|
|
14
|
+
from pytabkit import TabM_D_Classifier, TabM_D_Regressor
|
|
15
|
+
from pytabkit.models.alg_interfaces.sub_split_interfaces import (
|
|
16
|
+
SingleSplitWrapperAlgInterface,
|
|
17
|
+
)
|
|
18
|
+
from pytabkit.models.alg_interfaces.tabm_interface import (
|
|
19
|
+
TabMSubSplitInterface,
|
|
20
|
+
get_tabm_auto_batch_size,
|
|
21
|
+
)
|
|
22
|
+
from pytabkit.models.nn_models import rtdl_num_embeddings
|
|
23
|
+
from pytabkit.models.nn_models.models import PreprocessingFactory
|
|
24
|
+
from pytabkit.models.nn_models.tabm import Model, make_parameter_groups
|
|
25
|
+
from pytabkit.models.training.metrics import Metrics
|
|
26
|
+
|
|
27
|
+
from supervised.algorithms._pytabkit_compat import (
|
|
28
|
+
PytabkitCompatibilityMixin,
|
|
29
|
+
single_bin_diagnostics,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TimedTabMInterface(TabMSubSplitInterface):
|
|
34
|
+
@single_bin_diagnostics()
|
|
35
|
+
def fit(self, ds, idxs_list, interface_resources, logger, tmp_folders, name):
|
|
36
|
+
split = idxs_list[0]
|
|
37
|
+
if split.val_idxs is None:
|
|
38
|
+
raise ValueError("TabM requires an explicit validation fold")
|
|
39
|
+
cfg = self.config
|
|
40
|
+
deadline = cfg.get("deadline")
|
|
41
|
+
|
|
42
|
+
def expired():
|
|
43
|
+
return deadline is not None and time.monotonic() >= deadline
|
|
44
|
+
|
|
45
|
+
if expired():
|
|
46
|
+
raise ValueError("TabM time budget exhausted before training")
|
|
47
|
+
torch.manual_seed(split.sub_split_seeds[0])
|
|
48
|
+
self.n_classes_ = ds.get_n_classes()
|
|
49
|
+
self.task_type_ = "regression" if self.n_classes_ == 0 else "classification"
|
|
50
|
+
self.device_ = torch.device(
|
|
51
|
+
interface_resources.gpu_devices[0]
|
|
52
|
+
if interface_resources.gpu_devices
|
|
53
|
+
else "cpu"
|
|
54
|
+
)
|
|
55
|
+
train = ds.get_sub_dataset(split.train_idxs[0])
|
|
56
|
+
valid = ds.get_sub_dataset(split.val_idxs[0])
|
|
57
|
+
factory = PreprocessingFactory(tfms=["quantile_tabr"])
|
|
58
|
+
self.tfm_, train = factory.create(ds.tensor_infos).fit_transform(train)
|
|
59
|
+
valid = self.tfm_(valid)
|
|
60
|
+
x = train.tensors["x_cont"]
|
|
61
|
+
self.num_col_mask_ = ~torch.all(x == x[0:1], dim=0)
|
|
62
|
+
data = {}
|
|
63
|
+
for key, part in [("train", train), ("val", valid)]:
|
|
64
|
+
part.tensors["x_cont"] = part.tensors["x_cont"][:, self.num_col_mask_]
|
|
65
|
+
data[key] = part.to(self.device_).tensors
|
|
66
|
+
n_train = train.n_samples
|
|
67
|
+
y_train = data["train"]["y"].clone()
|
|
68
|
+
if self.n_classes_ == 0:
|
|
69
|
+
self.y_mean_ = y_train.mean().item()
|
|
70
|
+
self.y_std_ = y_train.std(correction=0).item()
|
|
71
|
+
y_train = (y_train - self.y_mean_) / (self.y_std_ + 1e-30)
|
|
72
|
+
n_numeric = data["train"]["x_cont"].shape[1]
|
|
73
|
+
bins = None
|
|
74
|
+
if n_numeric and n_train > 2:
|
|
75
|
+
bins = rtdl_num_embeddings.compute_bins(
|
|
76
|
+
data["train"]["x_cont"], n_bins=min(cfg["num_emb_n_bins"], n_train - 1)
|
|
77
|
+
)
|
|
78
|
+
self.single_bin_feature_count = sum(len(edges) == 2 for edges in (bins or []))
|
|
79
|
+
self.model_ = Model(
|
|
80
|
+
n_num_features=n_numeric,
|
|
81
|
+
cat_cardinalities=ds.tensor_infos["x_cat"].get_cat_sizes().numpy().tolist(),
|
|
82
|
+
n_classes=max(1, self.n_classes_),
|
|
83
|
+
backbone={
|
|
84
|
+
"type": "MLP",
|
|
85
|
+
"n_blocks": cfg["n_blocks"],
|
|
86
|
+
"d_block": cfg["d_block"],
|
|
87
|
+
"dropout": cfg["dropout"],
|
|
88
|
+
},
|
|
89
|
+
bins=bins,
|
|
90
|
+
num_embeddings=(
|
|
91
|
+
None
|
|
92
|
+
if bins is None
|
|
93
|
+
else {
|
|
94
|
+
"type": "PiecewiseLinearEmbeddings",
|
|
95
|
+
"d_embedding": cfg["d_embedding"],
|
|
96
|
+
"activation": False,
|
|
97
|
+
"version": "B",
|
|
98
|
+
}
|
|
99
|
+
),
|
|
100
|
+
arch_type="tabm-mini",
|
|
101
|
+
k=cfg["tabm_k"],
|
|
102
|
+
share_training_batches=False,
|
|
103
|
+
).to(self.device_)
|
|
104
|
+
optimizer = torch.optim.AdamW(
|
|
105
|
+
make_parameter_groups(self.model_),
|
|
106
|
+
lr=cfg["lr"],
|
|
107
|
+
weight_decay=cfg["weight_decay"],
|
|
108
|
+
)
|
|
109
|
+
batch_size = cfg["batch_size"]
|
|
110
|
+
if batch_size == "auto":
|
|
111
|
+
batch_size = get_tabm_auto_batch_size(n_train)
|
|
112
|
+
metric = cfg["val_metric_name"]
|
|
113
|
+
self.history = []
|
|
114
|
+
self.best_epoch = None
|
|
115
|
+
self.stop_reason = "max_epochs"
|
|
116
|
+
best_score, best_state, bad_epochs = float("inf"), None, 0
|
|
117
|
+
|
|
118
|
+
def forward(part, index):
|
|
119
|
+
values = data[part]
|
|
120
|
+
return self.model_(
|
|
121
|
+
values["x_cont"][index],
|
|
122
|
+
values["x_cat"][index] if values["x_cat"].shape[1] else None,
|
|
123
|
+
).float()
|
|
124
|
+
|
|
125
|
+
for epoch in range(1, cfg["n_epochs"] + 1):
|
|
126
|
+
if expired():
|
|
127
|
+
self.stop_reason = "time_limit"
|
|
128
|
+
break
|
|
129
|
+
# Independent permutations per ensemble member, matching upstream.
|
|
130
|
+
order = torch.rand((cfg["tabm_k"], n_train), device=self.device_).argsort(
|
|
131
|
+
dim=1
|
|
132
|
+
)
|
|
133
|
+
self.model_.train()
|
|
134
|
+
for indices in order.split(batch_size, dim=1):
|
|
135
|
+
if expired():
|
|
136
|
+
self.stop_reason = "time_limit"
|
|
137
|
+
break
|
|
138
|
+
indices = indices.T.flatten()
|
|
139
|
+
optimizer.zero_grad(set_to_none=True)
|
|
140
|
+
output = forward("train", indices).flatten(0, 1)
|
|
141
|
+
target = y_train[indices]
|
|
142
|
+
loss = (
|
|
143
|
+
torch.nn.functional.mse_loss(output, target)
|
|
144
|
+
if self.n_classes_ == 0
|
|
145
|
+
else torch.nn.functional.cross_entropy(output, target.squeeze(-1))
|
|
146
|
+
)
|
|
147
|
+
if not torch.isfinite(loss):
|
|
148
|
+
raise ValueError("TabM training loss is not finite")
|
|
149
|
+
loss.backward()
|
|
150
|
+
torch.nn.utils.clip_grad_norm_(self.model_.parameters(), 1.0)
|
|
151
|
+
optimizer.step()
|
|
152
|
+
if self.stop_reason == "time_limit":
|
|
153
|
+
break
|
|
154
|
+
self.model_.eval()
|
|
155
|
+
predictions = []
|
|
156
|
+
with torch.no_grad():
|
|
157
|
+
for indices in torch.arange(valid.n_samples, device=self.device_).split(
|
|
158
|
+
1024
|
|
159
|
+
):
|
|
160
|
+
if expired():
|
|
161
|
+
self.stop_reason = "time_limit"
|
|
162
|
+
break
|
|
163
|
+
output = forward("val", indices)
|
|
164
|
+
if self.n_classes_:
|
|
165
|
+
output = output.softmax(dim=-1)
|
|
166
|
+
else:
|
|
167
|
+
output = output * self.y_std_ + self.y_mean_
|
|
168
|
+
predictions.append(output.mean(dim=1).cpu())
|
|
169
|
+
if self.stop_reason == "time_limit":
|
|
170
|
+
break
|
|
171
|
+
prediction = torch.cat(predictions)
|
|
172
|
+
# pytabkit metrics expect logits; log(mean probabilities) preserves
|
|
173
|
+
# the ensemble distribution when the metric applies softmax.
|
|
174
|
+
if self.n_classes_:
|
|
175
|
+
prediction = torch.log(prediction + 1e-30)
|
|
176
|
+
score = float(Metrics.apply(prediction, data["val"]["y"].cpu(), metric))
|
|
177
|
+
if not np.isfinite(score):
|
|
178
|
+
raise ValueError("TabM validation score is not finite")
|
|
179
|
+
self.history.append({"epoch": epoch, "metric": metric, "validation": score})
|
|
180
|
+
if score < best_score:
|
|
181
|
+
best_score, self.best_epoch, bad_epochs = score, epoch, 0
|
|
182
|
+
best_state = copy.deepcopy(self.model_.state_dict())
|
|
183
|
+
else:
|
|
184
|
+
bad_epochs += 1
|
|
185
|
+
if bad_epochs > cfg["patience"]:
|
|
186
|
+
self.stop_reason = "early_stopping"
|
|
187
|
+
break
|
|
188
|
+
if best_state is None:
|
|
189
|
+
raise ValueError(
|
|
190
|
+
"TabM finished without a validation checkpoint; increase the time budget"
|
|
191
|
+
)
|
|
192
|
+
self.model_.load_state_dict(best_state)
|
|
193
|
+
self.fit_params = [{"best_epoch": self.best_epoch}]
|
|
194
|
+
return None
|
|
195
|
+
|
|
196
|
+
def to(self, device):
|
|
197
|
+
self.device_ = torch.device(device)
|
|
198
|
+
self.model_.to(device)
|
|
199
|
+
self.num_col_mask_ = self.num_col_mask_.to(device)
|
|
200
|
+
# Preprocessing is performed on CPU before transfer in upstream predict.
|
|
201
|
+
self.tfm_.to("cpu")
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class TabMMixin(PytabkitCompatibilityMixin):
|
|
205
|
+
def _create_alg_interface(self, n_cv):
|
|
206
|
+
if n_cv != 1:
|
|
207
|
+
raise ValueError("MLJAR owns TabM cross-validation")
|
|
208
|
+
config = dict(self.get_config(), deadline=getattr(self, "deadline", None))
|
|
209
|
+
return SingleSplitWrapperAlgInterface([TimedTabMInterface(**config)], **config)
|
|
210
|
+
|
|
211
|
+
def to(self, device):
|
|
212
|
+
for interface in self.cv_alg_interface_.sub_split_interfaces:
|
|
213
|
+
interface.to(device)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class TabMClassifier(TabMMixin, TabM_D_Classifier):
|
|
217
|
+
pass
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class TabMRegressor(TabMMixin, TabM_D_Regressor):
|
|
221
|
+
pass
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import uuid
|
|
2
|
+
from abc import ABC, abstractmethod
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from sklearn.base import BaseEstimator
|
|
7
|
+
|
|
8
|
+
from supervised.utils.common import construct_learner_name
|
|
9
|
+
from supervised.utils.importance import PermutationImportance
|
|
10
|
+
from supervised.utils.shap import PlotSHAP
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class BaseAlgorithm(BaseEstimator, ABC):
|
|
14
|
+
"""
|
|
15
|
+
This is an abstract class.
|
|
16
|
+
All algorithms inherit from BaseAlgorithm.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
algorithm_name = "Unknown"
|
|
20
|
+
algorithm_short_name = "Unknown"
|
|
21
|
+
|
|
22
|
+
def __init__(self, params):
|
|
23
|
+
self.params = params
|
|
24
|
+
self.stop_training = False
|
|
25
|
+
self.library_version = None
|
|
26
|
+
self.model = None
|
|
27
|
+
self.uid = params.get("uid", str(uuid.uuid4()))
|
|
28
|
+
self.ml_task = params.get("ml_task")
|
|
29
|
+
self.model_file_path = None
|
|
30
|
+
self.name = "amazing_learner"
|
|
31
|
+
|
|
32
|
+
def set_learner_name(self, fold, repeat, repeats):
|
|
33
|
+
self.name = construct_learner_name(fold, repeat, repeats)
|
|
34
|
+
|
|
35
|
+
@abstractmethod
|
|
36
|
+
def is_fitted(self):
|
|
37
|
+
"""Return whether the model is loaded and ready for prediction."""
|
|
38
|
+
raise NotImplementedError
|
|
39
|
+
|
|
40
|
+
def reload(self):
|
|
41
|
+
if not self.is_fitted() and self.model_file_path is not None:
|
|
42
|
+
self.load(self.model_file_path)
|
|
43
|
+
|
|
44
|
+
@abstractmethod
|
|
45
|
+
def fit(
|
|
46
|
+
self,
|
|
47
|
+
X,
|
|
48
|
+
y,
|
|
49
|
+
sample_weight=None,
|
|
50
|
+
X_validation=None,
|
|
51
|
+
y_validation=None,
|
|
52
|
+
sample_weight_validation=None,
|
|
53
|
+
log_to_file=None,
|
|
54
|
+
max_time=None,
|
|
55
|
+
):
|
|
56
|
+
"""Train the model using the supplied training and validation data."""
|
|
57
|
+
raise NotImplementedError
|
|
58
|
+
|
|
59
|
+
@abstractmethod
|
|
60
|
+
def predict(self, X):
|
|
61
|
+
"""Return predictions in the format expected for the model's task."""
|
|
62
|
+
raise NotImplementedError
|
|
63
|
+
|
|
64
|
+
# needed for feature importance
|
|
65
|
+
def predict_proba(self, X):
|
|
66
|
+
y = self.predict(X)
|
|
67
|
+
if "num_class" in self.params and self.params["num_class"] > 2:
|
|
68
|
+
return y
|
|
69
|
+
return np.column_stack((1 - y, y))
|
|
70
|
+
|
|
71
|
+
def update(self, update_params):
|
|
72
|
+
"""Optional hook for updating parameters between training iterations."""
|
|
73
|
+
pass
|
|
74
|
+
|
|
75
|
+
@abstractmethod
|
|
76
|
+
def copy(self):
|
|
77
|
+
"""Return an independent copy, including the current model state."""
|
|
78
|
+
raise NotImplementedError
|
|
79
|
+
|
|
80
|
+
@abstractmethod
|
|
81
|
+
def save(self, model_file_path):
|
|
82
|
+
"""Save the model state to the supplied path."""
|
|
83
|
+
raise NotImplementedError
|
|
84
|
+
|
|
85
|
+
@abstractmethod
|
|
86
|
+
def load(self, model_file_path):
|
|
87
|
+
"""Load the model state from the supplied path."""
|
|
88
|
+
raise NotImplementedError
|
|
89
|
+
|
|
90
|
+
@abstractmethod
|
|
91
|
+
def file_extension(self):
|
|
92
|
+
"""Return the model artifact extension without a leading dot."""
|
|
93
|
+
raise NotImplementedError
|
|
94
|
+
|
|
95
|
+
def get_fname(self):
|
|
96
|
+
return f"{self.name}.{self.file_extension()}"
|
|
97
|
+
|
|
98
|
+
def interpret(
|
|
99
|
+
self,
|
|
100
|
+
X_train,
|
|
101
|
+
y_train,
|
|
102
|
+
X_validation,
|
|
103
|
+
y_validation,
|
|
104
|
+
model_file_path,
|
|
105
|
+
learner_name,
|
|
106
|
+
target_name=None,
|
|
107
|
+
class_names=None,
|
|
108
|
+
metric_name=None,
|
|
109
|
+
ml_task=None,
|
|
110
|
+
explain_level=2,
|
|
111
|
+
):
|
|
112
|
+
# do not produce feature importance for Baseline
|
|
113
|
+
if self.algorithm_short_name == "Baseline":
|
|
114
|
+
return
|
|
115
|
+
if explain_level > 0:
|
|
116
|
+
PermutationImportance.compute_and_plot(
|
|
117
|
+
self,
|
|
118
|
+
X_validation,
|
|
119
|
+
y_validation,
|
|
120
|
+
model_file_path,
|
|
121
|
+
learner_name,
|
|
122
|
+
metric_name,
|
|
123
|
+
ml_task,
|
|
124
|
+
self.params.get("n_jobs", -1),
|
|
125
|
+
)
|
|
126
|
+
if explain_level > 1:
|
|
127
|
+
PlotSHAP.compute(
|
|
128
|
+
self,
|
|
129
|
+
X_train,
|
|
130
|
+
y_train,
|
|
131
|
+
X_validation,
|
|
132
|
+
y_validation,
|
|
133
|
+
model_file_path,
|
|
134
|
+
learner_name,
|
|
135
|
+
class_names,
|
|
136
|
+
ml_task,
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
def get_metric_name(self):
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
def get_params(self):
|
|
143
|
+
params = {
|
|
144
|
+
"library_version": self.library_version,
|
|
145
|
+
"algorithm_name": self.algorithm_name,
|
|
146
|
+
"algorithm_short_name": self.algorithm_short_name,
|
|
147
|
+
"uid": self.uid,
|
|
148
|
+
"params": self.params,
|
|
149
|
+
"name": self.name,
|
|
150
|
+
}
|
|
151
|
+
if hasattr(self, "best_ntree_limit") and self.best_ntree_limit is not None:
|
|
152
|
+
params["best_ntree_limit"] = self.best_ntree_limit
|
|
153
|
+
return params
|
|
154
|
+
|
|
155
|
+
def set_params(self, json_desc, learner_path):
|
|
156
|
+
self.library_version = json_desc.get("library_version", self.library_version)
|
|
157
|
+
self.algorithm_name = json_desc.get("algorithm_name", self.algorithm_name)
|
|
158
|
+
self.algorithm_short_name = json_desc.get(
|
|
159
|
+
"algorithm_short_name", self.algorithm_short_name
|
|
160
|
+
)
|
|
161
|
+
self.uid = json_desc.get("uid", self.uid)
|
|
162
|
+
self.params = json_desc.get("params", self.params)
|
|
163
|
+
self.name = json_desc.get("name", self.name)
|
|
164
|
+
self.model_file_path = learner_path
|
|
165
|
+
|
|
166
|
+
if hasattr(self, "best_ntree_limit"):
|
|
167
|
+
self.best_ntree_limit = json_desc.get(
|
|
168
|
+
"best_ntree_limit", self.best_ntree_limit
|
|
169
|
+
)
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
import sklearn
|
|
4
|
+
from sklearn.base import ClassifierMixin, RegressorMixin
|
|
5
|
+
from sklearn.dummy import DummyClassifier, DummyRegressor
|
|
6
|
+
|
|
7
|
+
from supervised.algorithms.registry import (
|
|
8
|
+
BINARY_CLASSIFICATION,
|
|
9
|
+
MULTICLASS_CLASSIFICATION,
|
|
10
|
+
REGRESSION,
|
|
11
|
+
AlgorithmsRegistry,
|
|
12
|
+
)
|
|
13
|
+
from supervised.algorithms.sklearn import SklearnAlgorithm
|
|
14
|
+
from supervised.utils.config import LOG_LEVEL
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
logger.setLevel(LOG_LEVEL)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class BaselineClassifierAlgorithm(ClassifierMixin, SklearnAlgorithm):
|
|
21
|
+
algorithm_name = "Baseline Classifier"
|
|
22
|
+
algorithm_short_name = "Baseline"
|
|
23
|
+
|
|
24
|
+
def __init__(self, params):
|
|
25
|
+
super(BaselineClassifierAlgorithm, self).__init__(params)
|
|
26
|
+
logger.debug("BaselineClassifierAlgorithm.__init__")
|
|
27
|
+
|
|
28
|
+
self.library_version = sklearn.__version__
|
|
29
|
+
self.max_iters = additional.get("max_steps", 1)
|
|
30
|
+
self.model = DummyClassifier(
|
|
31
|
+
strategy="prior", random_state=params.get("seed", 1)
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
def file_extension(self):
|
|
35
|
+
return "baseline"
|
|
36
|
+
|
|
37
|
+
def is_fitted(self):
|
|
38
|
+
return (
|
|
39
|
+
hasattr(self.model, "n_outputs_")
|
|
40
|
+
and self.model.n_outputs_ is not None
|
|
41
|
+
and self.model.n_outputs_ > 0
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class BaselineRegressorAlgorithm(RegressorMixin, SklearnAlgorithm):
|
|
46
|
+
algorithm_name = "Baseline Regressor"
|
|
47
|
+
algorithm_short_name = "Baseline"
|
|
48
|
+
|
|
49
|
+
def __init__(self, params):
|
|
50
|
+
super(BaselineRegressorAlgorithm, self).__init__(params)
|
|
51
|
+
logger.debug("BaselineRegressorAlgorithm.__init__")
|
|
52
|
+
|
|
53
|
+
self.library_version = sklearn.__version__
|
|
54
|
+
self.max_iters = additional.get("max_steps", 1)
|
|
55
|
+
self.model = DummyRegressor(strategy="mean")
|
|
56
|
+
|
|
57
|
+
def file_extension(self):
|
|
58
|
+
return "baseline"
|
|
59
|
+
|
|
60
|
+
def is_fitted(self):
|
|
61
|
+
return (
|
|
62
|
+
hasattr(self.model, "n_outputs_")
|
|
63
|
+
and self.model.n_outputs_ is not None
|
|
64
|
+
and self.model.n_outputs_ > 0
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
additional = {"max_steps": 1, "max_rows_limit": None, "max_cols_limit": None}
|
|
69
|
+
required_preprocessing = ["target_as_integer"]
|
|
70
|
+
|
|
71
|
+
AlgorithmsRegistry.add(
|
|
72
|
+
BINARY_CLASSIFICATION,
|
|
73
|
+
BaselineClassifierAlgorithm,
|
|
74
|
+
{},
|
|
75
|
+
required_preprocessing,
|
|
76
|
+
additional,
|
|
77
|
+
{},
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
AlgorithmsRegistry.add(
|
|
81
|
+
MULTICLASS_CLASSIFICATION,
|
|
82
|
+
BaselineClassifierAlgorithm,
|
|
83
|
+
{},
|
|
84
|
+
required_preprocessing,
|
|
85
|
+
additional,
|
|
86
|
+
{},
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
AlgorithmsRegistry.add(REGRESSION, BaselineRegressorAlgorithm, {}, {}, additional, {})
|