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,718 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
from tabulate import tabulate
|
|
9
|
+
|
|
10
|
+
from supervised.fairness.certificate import build_certificate_info
|
|
11
|
+
from supervised.utils.importance import load_model_importance
|
|
12
|
+
|
|
13
|
+
AUTOMATION_DISCLOSURE_TEXT = (
|
|
14
|
+
"Models in this report were generated and selected automatically by MLJAR "
|
|
15
|
+
"AutoML. Review model behavior, data suitability, and decision impact "
|
|
16
|
+
"before important use."
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
AUTOMATION_CONSOLE_TEXT = (
|
|
20
|
+
"AutoML is generating and selecting models automatically. Review outputs "
|
|
21
|
+
"before important use."
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _append_automation_disclosure(lines):
|
|
26
|
+
lines.append(f"> {AUTOMATION_DISCLOSURE_TEXT}")
|
|
27
|
+
lines.append("")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _get_package_version():
|
|
31
|
+
try:
|
|
32
|
+
return version("mljar-supervised")
|
|
33
|
+
except PackageNotFoundError:
|
|
34
|
+
return "unknown"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _to_float_or_none(value):
|
|
38
|
+
if value is None:
|
|
39
|
+
return None
|
|
40
|
+
try:
|
|
41
|
+
return float(value)
|
|
42
|
+
except Exception:
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _to_bool(value):
|
|
47
|
+
try:
|
|
48
|
+
return bool(value)
|
|
49
|
+
except Exception:
|
|
50
|
+
return False
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _serialize_metrics_value(value):
|
|
54
|
+
if value is None:
|
|
55
|
+
return None
|
|
56
|
+
if isinstance(value, pd.DataFrame):
|
|
57
|
+
return value.to_dict(orient="split")
|
|
58
|
+
if isinstance(value, pd.Series):
|
|
59
|
+
return value.to_dict()
|
|
60
|
+
return value
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _to_json_safe(value):
|
|
64
|
+
if isinstance(value, dict):
|
|
65
|
+
return {str(k): _to_json_safe(v) for k, v in value.items()}
|
|
66
|
+
if isinstance(value, (list, tuple)):
|
|
67
|
+
return [_to_json_safe(v) for v in value]
|
|
68
|
+
if isinstance(value, np.generic):
|
|
69
|
+
return value.item()
|
|
70
|
+
if isinstance(value, (str, int, float, bool)) or value is None:
|
|
71
|
+
return value
|
|
72
|
+
return str(value)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _extract_hyperparameters(model):
|
|
76
|
+
try:
|
|
77
|
+
if hasattr(model, "learner_params") and isinstance(model.learner_params, dict):
|
|
78
|
+
return _to_json_safe(model.learner_params)
|
|
79
|
+
except Exception:
|
|
80
|
+
pass
|
|
81
|
+
|
|
82
|
+
# Fallback for models without learner_params (e.g. Ensemble).
|
|
83
|
+
try:
|
|
84
|
+
model_type = model.get_type()
|
|
85
|
+
except Exception:
|
|
86
|
+
model_type = None
|
|
87
|
+
if model_type is not None:
|
|
88
|
+
return {"model_type": model_type}
|
|
89
|
+
return {}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _extract_additional_metrics(model):
|
|
93
|
+
try:
|
|
94
|
+
additional = model.get_additional_metrics()
|
|
95
|
+
if additional is None:
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
metrics = {}
|
|
99
|
+
for key in [
|
|
100
|
+
"max_metrics",
|
|
101
|
+
"accuracy_threshold_metrics",
|
|
102
|
+
"confusion_matrix",
|
|
103
|
+
"threshold",
|
|
104
|
+
]:
|
|
105
|
+
if key in additional:
|
|
106
|
+
metrics[key] = _serialize_metrics_value(additional.get(key))
|
|
107
|
+
if "fairness_metrics" in additional:
|
|
108
|
+
metrics["fairness_metrics_details"] = _extract_fairness_metrics_details(
|
|
109
|
+
additional.get("fairness_metrics")
|
|
110
|
+
)
|
|
111
|
+
return metrics
|
|
112
|
+
except Exception:
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _extract_fairness_metrics_details(fairness_metrics):
|
|
117
|
+
if not isinstance(fairness_metrics, dict):
|
|
118
|
+
return None
|
|
119
|
+
|
|
120
|
+
fairness_threshold = None
|
|
121
|
+
optimization = fairness_metrics.get("fairness_optimization")
|
|
122
|
+
if isinstance(optimization, dict):
|
|
123
|
+
fairness_threshold = optimization.get("fairness_threshold")
|
|
124
|
+
|
|
125
|
+
details = {}
|
|
126
|
+
for feature_name, values in fairness_metrics.items():
|
|
127
|
+
if feature_name == "fairness_optimization" or not isinstance(values, dict):
|
|
128
|
+
continue
|
|
129
|
+
details[feature_name] = {
|
|
130
|
+
"metrics": _serialize_metrics_value(values.get("metrics")),
|
|
131
|
+
"stats": _serialize_metrics_value(values.get("stats")),
|
|
132
|
+
"fairness_metric_name": values.get("fairness_metric_name"),
|
|
133
|
+
"fairness_metric_value": _to_float_or_none(values.get("fairness_metric_value")),
|
|
134
|
+
"is_fair": _to_bool(values.get("is_fair")),
|
|
135
|
+
"privileged_value": values.get("privileged_value"),
|
|
136
|
+
"underprivileged_value": values.get("underprivileged_value"),
|
|
137
|
+
"fairness_threshold": fairness_threshold,
|
|
138
|
+
}
|
|
139
|
+
return details
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _append_certificate_info(target, certificate_info):
|
|
143
|
+
if certificate_info is None:
|
|
144
|
+
return
|
|
145
|
+
target["certificate_url"] = certificate_info.get("certificate_url")
|
|
146
|
+
target["certificate_params"] = certificate_info.get("certificate_params")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _compute_feature_importance_summary(model_dir):
|
|
150
|
+
imp_files = []
|
|
151
|
+
try:
|
|
152
|
+
imp_files = [
|
|
153
|
+
f
|
|
154
|
+
for f in os.listdir(model_dir)
|
|
155
|
+
if f.endswith("_importance.csv") and "shap" not in f
|
|
156
|
+
]
|
|
157
|
+
except Exception:
|
|
158
|
+
return {"available": False, "reason": "model_dir_unreadable"}
|
|
159
|
+
|
|
160
|
+
if not imp_files:
|
|
161
|
+
return {"available": False, "reason": "no_importance_files"}
|
|
162
|
+
|
|
163
|
+
mean_importance = load_model_importance(model_dir)
|
|
164
|
+
if mean_importance is None:
|
|
165
|
+
return {"available": False, "reason": "no_valid_importance_data"}
|
|
166
|
+
|
|
167
|
+
mean_importance = mean_importance.sort_values(ascending=False)
|
|
168
|
+
n = int(mean_importance.shape[0])
|
|
169
|
+
|
|
170
|
+
if n == 0:
|
|
171
|
+
return {"available": False, "reason": "empty_importance"}
|
|
172
|
+
|
|
173
|
+
if n < 10:
|
|
174
|
+
k = 3
|
|
175
|
+
elif n < 20:
|
|
176
|
+
k = 5
|
|
177
|
+
else:
|
|
178
|
+
k = 10
|
|
179
|
+
k = min(k, n)
|
|
180
|
+
|
|
181
|
+
top_slice = mean_importance.head(k)
|
|
182
|
+
worst_slice = mean_importance.tail(k)
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
"available": True,
|
|
186
|
+
"n_features": n,
|
|
187
|
+
"selection_k": k,
|
|
188
|
+
"top": [
|
|
189
|
+
{"feature": str(feature), "importance": float(value)}
|
|
190
|
+
for feature, value in top_slice.items()
|
|
191
|
+
],
|
|
192
|
+
"worst": [
|
|
193
|
+
{"feature": str(feature), "importance": float(value)}
|
|
194
|
+
for feature, value in worst_slice.items()
|
|
195
|
+
],
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _load_model_importance_vector(model_dir):
|
|
200
|
+
return load_model_importance(model_dir)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _compute_global_feature_importance(automl):
|
|
204
|
+
rank_series = []
|
|
205
|
+
for model in automl._models:
|
|
206
|
+
model_dir = os.path.join(automl._results_path, model.get_name())
|
|
207
|
+
importance = _load_model_importance_vector(model_dir)
|
|
208
|
+
if importance is None:
|
|
209
|
+
continue
|
|
210
|
+
# 1 = most important feature, higher rank = less important.
|
|
211
|
+
rank_series.append(importance.rank(ascending=False, method="average"))
|
|
212
|
+
|
|
213
|
+
if not rank_series:
|
|
214
|
+
return {"available": False, "reason": "no_importance_files"}
|
|
215
|
+
|
|
216
|
+
rank_df = pd.concat(rank_series, axis=1)
|
|
217
|
+
n_models_used = int(rank_df.shape[1])
|
|
218
|
+
n_features = int(rank_df.shape[0])
|
|
219
|
+
if n_features == 0:
|
|
220
|
+
return {"available": False, "reason": "empty_rank_data"}
|
|
221
|
+
|
|
222
|
+
models_present = rank_df.notna().sum(axis=1)
|
|
223
|
+
fill_values = pd.Series([s.max() + 1.0 for s in rank_series], index=rank_df.columns)
|
|
224
|
+
rank_df = rank_df.fillna(fill_values)
|
|
225
|
+
mean_rank = rank_df.mean(axis=1).sort_values(ascending=True)
|
|
226
|
+
|
|
227
|
+
if n_features < 10:
|
|
228
|
+
k = 3
|
|
229
|
+
elif n_features < 20:
|
|
230
|
+
k = 5
|
|
231
|
+
else:
|
|
232
|
+
k = 10
|
|
233
|
+
k = min(k, n_features)
|
|
234
|
+
|
|
235
|
+
top_slice = mean_rank.head(k)
|
|
236
|
+
bottom_slice = mean_rank.tail(k)
|
|
237
|
+
|
|
238
|
+
return {
|
|
239
|
+
"available": True,
|
|
240
|
+
"method": "mean_rank_across_models",
|
|
241
|
+
"n_models_used": n_models_used,
|
|
242
|
+
"n_features": n_features,
|
|
243
|
+
"selection_k": k,
|
|
244
|
+
"top": [
|
|
245
|
+
{
|
|
246
|
+
"feature": str(feature),
|
|
247
|
+
"mean_rank": float(rank_value),
|
|
248
|
+
"models_present": int(models_present.get(feature, 0)),
|
|
249
|
+
}
|
|
250
|
+
for feature, rank_value in top_slice.items()
|
|
251
|
+
],
|
|
252
|
+
"bottom": [
|
|
253
|
+
{
|
|
254
|
+
"feature": str(feature),
|
|
255
|
+
"mean_rank": float(rank_value),
|
|
256
|
+
"models_present": int(models_present.get(feature, 0)),
|
|
257
|
+
}
|
|
258
|
+
for feature, rank_value in bottom_slice.items()
|
|
259
|
+
],
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _model_to_dict(automl, model):
|
|
264
|
+
model_name = model.get_name()
|
|
265
|
+
model_dir = os.path.join(automl._results_path, model_name)
|
|
266
|
+
|
|
267
|
+
model_dict = {
|
|
268
|
+
"name": model_name,
|
|
269
|
+
"model_type": model.get_type(),
|
|
270
|
+
"metric_type": automl._eval_metric,
|
|
271
|
+
"metric_value": _to_float_or_none(model.get_final_loss()),
|
|
272
|
+
"train_time": _to_float_or_none(model.get_train_time()),
|
|
273
|
+
"is_valid": _to_bool(model.is_valid()),
|
|
274
|
+
"is_stacked": _to_bool(getattr(model, "_is_stacked", False)),
|
|
275
|
+
"involved_models": model.involved_model_names(),
|
|
276
|
+
"artifacts": {
|
|
277
|
+
"model_dir": model_dir,
|
|
278
|
+
"readme_md": os.path.join(model_dir, "README.md"),
|
|
279
|
+
"readme_html": os.path.join(model_dir, "README.html"),
|
|
280
|
+
},
|
|
281
|
+
}
|
|
282
|
+
model_dict["hyperparameters"] = _extract_hyperparameters(model)
|
|
283
|
+
model_dict["metrics"] = _extract_additional_metrics(model)
|
|
284
|
+
model_dict["feature_importance"] = _compute_feature_importance_summary(model_dir)
|
|
285
|
+
|
|
286
|
+
if automl._fairness_metric is not None:
|
|
287
|
+
sensitive = []
|
|
288
|
+
for sf in model.get_sensitive_features_names():
|
|
289
|
+
sensitive.append(
|
|
290
|
+
{
|
|
291
|
+
"feature": sf,
|
|
292
|
+
"fairness_metric_value": _to_float_or_none(
|
|
293
|
+
model.get_fairness_metric(sf)
|
|
294
|
+
),
|
|
295
|
+
}
|
|
296
|
+
)
|
|
297
|
+
model_dict["fairness"] = {
|
|
298
|
+
"is_fair": _to_bool(model.is_fair()),
|
|
299
|
+
"worst_fairness": _to_float_or_none(model.get_worst_fairness()),
|
|
300
|
+
"best_fairness": _to_float_or_none(model.get_best_fairness()),
|
|
301
|
+
"sensitive_features": sensitive,
|
|
302
|
+
}
|
|
303
|
+
_append_certificate_info(
|
|
304
|
+
model_dict["fairness"],
|
|
305
|
+
build_certificate_info(
|
|
306
|
+
model_name,
|
|
307
|
+
automl._ml_task,
|
|
308
|
+
(model_dict.get("metrics") or {}).get("fairness_metrics_details"),
|
|
309
|
+
worst_fairness=model_dict["fairness"]["worst_fairness"],
|
|
310
|
+
is_fair=model_dict["fairness"]["is_fair"],
|
|
311
|
+
),
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
return model_dict
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def build_structured_report(automl):
|
|
318
|
+
leaderboard_df = automl.get_leaderboard(original_metric_values=True)
|
|
319
|
+
leaderboard = leaderboard_df.to_dict(orient="records")
|
|
320
|
+
|
|
321
|
+
best_model = None
|
|
322
|
+
if automl._best_model is not None:
|
|
323
|
+
best_model = _model_to_dict(automl, automl._best_model)
|
|
324
|
+
|
|
325
|
+
fairness_summary = None
|
|
326
|
+
if automl._fairness_metric is not None and automl._best_model is not None:
|
|
327
|
+
fairness_summary = {
|
|
328
|
+
"fairness_metric": automl._fairness_metric,
|
|
329
|
+
"fairness_threshold": automl._fairness_threshold,
|
|
330
|
+
"best_model_is_fair": _to_bool(automl._best_model.is_fair()),
|
|
331
|
+
"best_model_worst_fairness": _to_float_or_none(
|
|
332
|
+
automl._best_model.get_worst_fairness()
|
|
333
|
+
),
|
|
334
|
+
"best_model_best_fairness": _to_float_or_none(
|
|
335
|
+
automl._best_model.get_best_fairness()
|
|
336
|
+
),
|
|
337
|
+
"sensitive_features": [
|
|
338
|
+
{
|
|
339
|
+
"feature": sf,
|
|
340
|
+
"fairness_metric_value": _to_float_or_none(
|
|
341
|
+
automl._best_model.get_fairness_metric(sf)
|
|
342
|
+
),
|
|
343
|
+
}
|
|
344
|
+
for sf in automl._best_model.get_sensitive_features_names()
|
|
345
|
+
],
|
|
346
|
+
}
|
|
347
|
+
if best_model is not None:
|
|
348
|
+
_append_certificate_info(
|
|
349
|
+
fairness_summary,
|
|
350
|
+
{
|
|
351
|
+
"certificate_url": (best_model.get("fairness") or {}).get(
|
|
352
|
+
"certificate_url"
|
|
353
|
+
),
|
|
354
|
+
"certificate_params": (best_model.get("fairness") or {}).get(
|
|
355
|
+
"certificate_params"
|
|
356
|
+
),
|
|
357
|
+
},
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
payload = {
|
|
361
|
+
"created_at_utc": datetime.now(timezone.utc).isoformat(),
|
|
362
|
+
"mljar_supervised_version": _get_package_version(),
|
|
363
|
+
"results_path": automl._results_path,
|
|
364
|
+
"run_summary": {
|
|
365
|
+
"mode": automl._mode,
|
|
366
|
+
"ml_task": automl._ml_task,
|
|
367
|
+
"eval_metric": automl._eval_metric,
|
|
368
|
+
"n_rows": getattr(automl, "n_rows_in_", None),
|
|
369
|
+
"n_features": getattr(automl, "n_features_in_", None),
|
|
370
|
+
"n_classes": getattr(automl, "n_classes", None),
|
|
371
|
+
"n_models": len(automl._models),
|
|
372
|
+
"best_model_name": None
|
|
373
|
+
if automl._best_model is None
|
|
374
|
+
else automl._best_model.get_name(),
|
|
375
|
+
"fit_level": automl._fit_level,
|
|
376
|
+
"total_time_limit": automl._total_time_limit,
|
|
377
|
+
"model_time_limit": automl._model_time_limit,
|
|
378
|
+
"validation_strategy": automl._validation_strategy,
|
|
379
|
+
"train_ensemble": automl._train_ensemble,
|
|
380
|
+
"stack_models": automl._stack_models,
|
|
381
|
+
"fairness_metric": automl._fairness_metric,
|
|
382
|
+
"fairness_threshold": automl._fairness_threshold,
|
|
383
|
+
},
|
|
384
|
+
"leaderboard": leaderboard,
|
|
385
|
+
"global_feature_importance": _compute_global_feature_importance(automl),
|
|
386
|
+
"best_model": best_model,
|
|
387
|
+
"fairness_summary": fairness_summary,
|
|
388
|
+
"models": [_model_to_dict(automl, m) for m in automl._models],
|
|
389
|
+
"artifacts": {
|
|
390
|
+
"leaderboard_csv": os.path.join(automl._results_path, "leaderboard.csv"),
|
|
391
|
+
"main_readme_md": os.path.join(automl._results_path, "README.md"),
|
|
392
|
+
"main_readme_html": os.path.join(automl._results_path, "README.html"),
|
|
393
|
+
"report_structured_json": os.path.join(
|
|
394
|
+
automl._results_path, "report_structured.json"
|
|
395
|
+
),
|
|
396
|
+
"errors_md": os.path.join(automl._results_path, "errors.md"),
|
|
397
|
+
},
|
|
398
|
+
}
|
|
399
|
+
return payload
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def save_structured_report(payload, results_path):
|
|
403
|
+
fname = os.path.join(results_path, "report_structured.json")
|
|
404
|
+
with open(fname, "w") as fout:
|
|
405
|
+
json.dump(payload, fout, indent=4)
|
|
406
|
+
return fname
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _append_split_table(lines, title, table_obj, heading_level="###"):
|
|
410
|
+
if table_obj is None:
|
|
411
|
+
return
|
|
412
|
+
columns = table_obj.get("columns", [])
|
|
413
|
+
data = table_obj.get("data", [])
|
|
414
|
+
index = table_obj.get("index")
|
|
415
|
+
show_index = False
|
|
416
|
+
if index is not None and len(index) == len(data):
|
|
417
|
+
# Hide synthetic/default row index (0..n-1) to keep tables readable.
|
|
418
|
+
try:
|
|
419
|
+
show_index = list(index) != list(range(len(data)))
|
|
420
|
+
except Exception:
|
|
421
|
+
show_index = True
|
|
422
|
+
if show_index:
|
|
423
|
+
columns = ["index"] + list(columns)
|
|
424
|
+
data = [[index[i]] + row for i, row in enumerate(data)]
|
|
425
|
+
lines.append(f"{heading_level} {title}")
|
|
426
|
+
lines.append("")
|
|
427
|
+
lines.append(tabulate(data, headers=columns, tablefmt="pipe"))
|
|
428
|
+
lines.append("")
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _append_model_metrics(lines, model):
|
|
432
|
+
metrics = model.get("metrics") or {}
|
|
433
|
+
_append_split_table(
|
|
434
|
+
lines, "Metric details", metrics.get("max_metrics"), heading_level="##"
|
|
435
|
+
)
|
|
436
|
+
_append_split_table(
|
|
437
|
+
lines, "Confusion matrix", metrics.get("confusion_matrix"), heading_level="##"
|
|
438
|
+
)
|
|
439
|
+
threshold = metrics.get("threshold")
|
|
440
|
+
if threshold is not None:
|
|
441
|
+
lines.append(f"Threshold: `{threshold}`")
|
|
442
|
+
lines.append("")
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _append_hyperparameters(lines, model):
|
|
446
|
+
hyperparameters = dict(model.get("hyperparameters") or {})
|
|
447
|
+
hyperparameters.pop("model_type", None)
|
|
448
|
+
model_type = str(model.get("model_type") or "")
|
|
449
|
+
if model_type in {"Baseline", "Decision Tree", "Neural Network"}:
|
|
450
|
+
hyperparameters.pop("n_jobs", None)
|
|
451
|
+
lines.append("## Hyperparameters")
|
|
452
|
+
lines.append("")
|
|
453
|
+
if not hyperparameters:
|
|
454
|
+
lines.append("_No hyperparameters available._")
|
|
455
|
+
lines.append("")
|
|
456
|
+
return
|
|
457
|
+
|
|
458
|
+
rows = [[str(k), hyperparameters.get(k)] for k in sorted(hyperparameters.keys())]
|
|
459
|
+
lines.append(tabulate(rows, headers=["Parameter", "Value"], tablefmt="pipe"))
|
|
460
|
+
lines.append("")
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _append_feature_importance(lines, model, heading_level="###"):
|
|
464
|
+
fi = model.get("feature_importance") or {}
|
|
465
|
+
if fi.get("available"):
|
|
466
|
+
k = fi.get("selection_k")
|
|
467
|
+
top_rows = [[row.get("feature"), row.get("importance")] for row in fi.get("top", [])]
|
|
468
|
+
worst_rows = [
|
|
469
|
+
[row.get("feature"), row.get("importance")] for row in fi.get("worst", [])
|
|
470
|
+
]
|
|
471
|
+
lines.append(
|
|
472
|
+
f"{heading_level} Most Influential Features (Top {k} by permutation importance)"
|
|
473
|
+
)
|
|
474
|
+
lines.append("")
|
|
475
|
+
lines.append(tabulate(top_rows, headers=["Feature", "Importance"], tablefmt="pipe"))
|
|
476
|
+
lines.append("")
|
|
477
|
+
lines.append(
|
|
478
|
+
f"{heading_level} Least Influential Features (Bottom {k} by permutation importance)"
|
|
479
|
+
)
|
|
480
|
+
lines.append("")
|
|
481
|
+
lines.append(
|
|
482
|
+
tabulate(worst_rows, headers=["Feature", "Importance"], tablefmt="pipe")
|
|
483
|
+
)
|
|
484
|
+
lines.append("")
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _append_fairness(lines, model, title):
|
|
488
|
+
fairness = model.get("fairness")
|
|
489
|
+
if fairness is None:
|
|
490
|
+
return
|
|
491
|
+
lines.append(title)
|
|
492
|
+
lines.append("")
|
|
493
|
+
fairness_rows = [
|
|
494
|
+
["is_fair", fairness.get("is_fair")],
|
|
495
|
+
["worst_fairness", fairness.get("worst_fairness")],
|
|
496
|
+
["best_fairness", fairness.get("best_fairness")],
|
|
497
|
+
]
|
|
498
|
+
lines.append(tabulate(fairness_rows, headers=["Field", "Value"], tablefmt="pipe"))
|
|
499
|
+
sf = fairness.get("sensitive_features", [])
|
|
500
|
+
if sf:
|
|
501
|
+
lines.append("")
|
|
502
|
+
lines.append(
|
|
503
|
+
tabulate(
|
|
504
|
+
[[s.get("feature"), s.get("fairness_metric_value")] for s in sf],
|
|
505
|
+
headers=["Sensitive Feature", "Fairness Metric Value"],
|
|
506
|
+
tablefmt="pipe",
|
|
507
|
+
)
|
|
508
|
+
)
|
|
509
|
+
lines.append("")
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def _append_main_fairness_summary(lines, fairness_summary):
|
|
513
|
+
if fairness_summary is None:
|
|
514
|
+
return
|
|
515
|
+
lines.append("## Fairness Summary")
|
|
516
|
+
lines.append("")
|
|
517
|
+
fairness_rows = [
|
|
518
|
+
["fairness_metric", fairness_summary.get("fairness_metric")],
|
|
519
|
+
["fairness_threshold", fairness_summary.get("fairness_threshold")],
|
|
520
|
+
["best_model_is_fair", fairness_summary.get("best_model_is_fair")],
|
|
521
|
+
["best_model_worst_fairness", fairness_summary.get("best_model_worst_fairness")],
|
|
522
|
+
["best_model_best_fairness", fairness_summary.get("best_model_best_fairness")],
|
|
523
|
+
]
|
|
524
|
+
lines.append(tabulate(fairness_rows, headers=["Field", "Value"], tablefmt="pipe"))
|
|
525
|
+
sf = fairness_summary.get("sensitive_features", [])
|
|
526
|
+
if sf:
|
|
527
|
+
lines.append("")
|
|
528
|
+
lines.append(
|
|
529
|
+
tabulate(
|
|
530
|
+
[[s.get("feature"), s.get("fairness_metric_value")] for s in sf],
|
|
531
|
+
headers=["Sensitive Feature", "Fairness Metric Value"],
|
|
532
|
+
tablefmt="pipe",
|
|
533
|
+
)
|
|
534
|
+
)
|
|
535
|
+
lines.append("")
|
|
536
|
+
_append_certificate_section(lines, fairness_summary, heading_level="##")
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def _append_fairness_metrics_details(lines, model, heading_level="###"):
|
|
540
|
+
metrics = model.get("metrics") or {}
|
|
541
|
+
fairness_details = metrics.get("fairness_metrics_details") or {}
|
|
542
|
+
if not fairness_details:
|
|
543
|
+
return
|
|
544
|
+
|
|
545
|
+
for feature_name, values in fairness_details.items():
|
|
546
|
+
lines.append(f"{heading_level} Fairness metrics for {feature_name} feature")
|
|
547
|
+
lines.append("")
|
|
548
|
+
|
|
549
|
+
_append_split_table(lines, "Fairness group metrics", values.get("metrics"))
|
|
550
|
+
_append_split_table(lines, "Fairness summary statistics", values.get("stats"))
|
|
551
|
+
|
|
552
|
+
fairness_metric_name = values.get("fairness_metric_name")
|
|
553
|
+
fairness_metric_value = values.get("fairness_metric_value")
|
|
554
|
+
is_fair = values.get("is_fair")
|
|
555
|
+
fairness_threshold = values.get("fairness_threshold")
|
|
556
|
+
privileged_value = values.get("privileged_value")
|
|
557
|
+
underprivileged_value = values.get("underprivileged_value")
|
|
558
|
+
|
|
559
|
+
fair_str = "fair" if is_fair else "unfair"
|
|
560
|
+
lines.append(f"{heading_level} Is model fair for {feature_name} feature?")
|
|
561
|
+
lines.append("")
|
|
562
|
+
|
|
563
|
+
threshold_str = ""
|
|
564
|
+
if fairness_threshold is not None and fairness_metric_name is not None:
|
|
565
|
+
if "ratio" in str(fairness_metric_name).lower():
|
|
566
|
+
threshold_str = f"It should be higher than {fairness_threshold}."
|
|
567
|
+
else:
|
|
568
|
+
threshold_str = f"It should be lower than {fairness_threshold}."
|
|
569
|
+
|
|
570
|
+
lines.append(f"Model is {fair_str} for {feature_name} feature.")
|
|
571
|
+
if fairness_metric_name is not None and fairness_metric_value is not None:
|
|
572
|
+
lines.append(
|
|
573
|
+
f"The {fairness_metric_name} is {fairness_metric_value}. {threshold_str}".strip()
|
|
574
|
+
)
|
|
575
|
+
if is_fair is False:
|
|
576
|
+
if underprivileged_value is not None:
|
|
577
|
+
lines.append(f"Underprivileged value is {underprivileged_value}.")
|
|
578
|
+
if privileged_value is not None:
|
|
579
|
+
lines.append(f"Privileged value is {privileged_value}.")
|
|
580
|
+
lines.append("")
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def _append_certificate_section(lines, payload, heading_level):
|
|
584
|
+
certificate_url = (payload or {}).get("certificate_url")
|
|
585
|
+
if not certificate_url:
|
|
586
|
+
return
|
|
587
|
+
lines.append(f"{heading_level} Fairness Certificate")
|
|
588
|
+
lines.append("")
|
|
589
|
+
lines.append(f"[View and download fairness certificate]({certificate_url})")
|
|
590
|
+
lines.append("")
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _find_model(models, model_name):
|
|
594
|
+
for model in models:
|
|
595
|
+
if model.get("name") == model_name:
|
|
596
|
+
return model
|
|
597
|
+
return None
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def build_compact_view(payload, model_name=None):
|
|
601
|
+
compact = {
|
|
602
|
+
"created_at_utc": payload.get("created_at_utc"),
|
|
603
|
+
"mljar_supervised_version": payload.get("mljar_supervised_version"),
|
|
604
|
+
"results_path": payload.get("results_path"),
|
|
605
|
+
"leaderboard": payload.get("leaderboard", []),
|
|
606
|
+
"global_feature_importance": payload.get("global_feature_importance"),
|
|
607
|
+
"fairness_summary": payload.get("fairness_summary"),
|
|
608
|
+
}
|
|
609
|
+
if model_name is not None:
|
|
610
|
+
selected = _find_model(payload.get("models", []), model_name)
|
|
611
|
+
if selected is None:
|
|
612
|
+
available_models = sorted(
|
|
613
|
+
[m.get("name") for m in payload.get("models", []) if m.get("name")]
|
|
614
|
+
)
|
|
615
|
+
raise ValueError(
|
|
616
|
+
f"Model '{model_name}' not found. Available models: {available_models}"
|
|
617
|
+
)
|
|
618
|
+
compact["selected_model"] = selected
|
|
619
|
+
return compact
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
def to_markdown(payload, model_name=None):
|
|
623
|
+
lines = []
|
|
624
|
+
selected_model = payload.get("selected_model")
|
|
625
|
+
if selected_model is None:
|
|
626
|
+
lines.append("# MLJAR AutoML Report")
|
|
627
|
+
else:
|
|
628
|
+
lines.append(f"# MLJAR AutoML report for {selected_model.get('name')}")
|
|
629
|
+
lines.append("")
|
|
630
|
+
_append_automation_disclosure(lines)
|
|
631
|
+
|
|
632
|
+
if selected_model is None:
|
|
633
|
+
lines.append("## Leaderboard")
|
|
634
|
+
lines.append("")
|
|
635
|
+
leaderboard = payload.get("leaderboard", [])
|
|
636
|
+
if leaderboard:
|
|
637
|
+
df = pd.DataFrame(leaderboard)
|
|
638
|
+
base_cols = [
|
|
639
|
+
c
|
|
640
|
+
for c in ["name", "model_type", "metric_type", "metric_value", "train_time"]
|
|
641
|
+
if c in df.columns
|
|
642
|
+
]
|
|
643
|
+
fairness_cols = [
|
|
644
|
+
c
|
|
645
|
+
for c in df.columns
|
|
646
|
+
if (c == "fairness_metric" or c.startswith("fairness_") or c == "is_fair")
|
|
647
|
+
and c not in base_cols
|
|
648
|
+
]
|
|
649
|
+
preferred_cols = base_cols + fairness_cols
|
|
650
|
+
if preferred_cols:
|
|
651
|
+
df = df[preferred_cols]
|
|
652
|
+
lines.append(tabulate(df.values, headers=list(df.columns), tablefmt="pipe"))
|
|
653
|
+
else:
|
|
654
|
+
lines.append("_No models found._")
|
|
655
|
+
lines.append("")
|
|
656
|
+
|
|
657
|
+
global_fi = payload.get("global_feature_importance") or {}
|
|
658
|
+
if global_fi.get("available"):
|
|
659
|
+
k = global_fi.get("selection_k")
|
|
660
|
+
lines.append("## Global Feature Importance (Averaged Across Models)")
|
|
661
|
+
lines.append("")
|
|
662
|
+
lines.append(f"Method: `{global_fi.get('method')}`")
|
|
663
|
+
lines.append("")
|
|
664
|
+
lines.append(
|
|
665
|
+
f"Models used: `{global_fi.get('n_models_used')}`, Features: `{global_fi.get('n_features')}`"
|
|
666
|
+
)
|
|
667
|
+
lines.append("")
|
|
668
|
+
|
|
669
|
+
top_rows = [
|
|
670
|
+
[row.get("feature"), row.get("mean_rank")]
|
|
671
|
+
for row in global_fi.get("top", [])
|
|
672
|
+
]
|
|
673
|
+
bottom_rows = [
|
|
674
|
+
[row.get("feature"), row.get("mean_rank")]
|
|
675
|
+
for row in global_fi.get("bottom", [])
|
|
676
|
+
]
|
|
677
|
+
|
|
678
|
+
lines.append(f"### Most Influential Features (Top {k} by mean rank)")
|
|
679
|
+
lines.append("")
|
|
680
|
+
lines.append(
|
|
681
|
+
tabulate(
|
|
682
|
+
top_rows,
|
|
683
|
+
headers=["Feature", "Mean Rank"],
|
|
684
|
+
tablefmt="pipe",
|
|
685
|
+
)
|
|
686
|
+
)
|
|
687
|
+
lines.append("")
|
|
688
|
+
|
|
689
|
+
lines.append(f"### Least Influential Features (Bottom {k} by mean rank)")
|
|
690
|
+
lines.append("")
|
|
691
|
+
lines.append(
|
|
692
|
+
tabulate(
|
|
693
|
+
bottom_rows,
|
|
694
|
+
headers=["Feature", "Mean Rank"],
|
|
695
|
+
tablefmt="pipe",
|
|
696
|
+
)
|
|
697
|
+
)
|
|
698
|
+
lines.append("")
|
|
699
|
+
_append_main_fairness_summary(lines, payload.get("fairness_summary"))
|
|
700
|
+
else:
|
|
701
|
+
summary_rows = [
|
|
702
|
+
["model_type", selected_model.get("model_type")],
|
|
703
|
+
["metric_type", selected_model.get("metric_type")],
|
|
704
|
+
["metric_value", selected_model.get("metric_value")],
|
|
705
|
+
["train_time", selected_model.get("train_time")],
|
|
706
|
+
["is_valid", selected_model.get("is_valid")],
|
|
707
|
+
["is_stacked", selected_model.get("is_stacked")],
|
|
708
|
+
]
|
|
709
|
+
lines.append(tabulate(summary_rows, headers=["Field", "Value"], tablefmt="pipe"))
|
|
710
|
+
lines.append("")
|
|
711
|
+
_append_fairness(lines, selected_model, "## Fairness Summary")
|
|
712
|
+
_append_certificate_section(lines, selected_model.get("fairness"), heading_level="###")
|
|
713
|
+
_append_hyperparameters(lines, selected_model)
|
|
714
|
+
_append_model_metrics(lines, selected_model)
|
|
715
|
+
_append_feature_importance(lines, selected_model, heading_level="##")
|
|
716
|
+
_append_fairness_metrics_details(lines, selected_model, heading_level="##")
|
|
717
|
+
|
|
718
|
+
return "\n".join(lines)
|