mljar-supervised 1.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. mljar_supervised-1.2.1.dist-info/METADATA +657 -0
  2. mljar_supervised-1.2.1.dist-info/RECORD +94 -0
  3. mljar_supervised-1.2.1.dist-info/WHEEL +5 -0
  4. mljar_supervised-1.2.1.dist-info/licenses/LICENSE +21 -0
  5. mljar_supervised-1.2.1.dist-info/top_level.txt +1 -0
  6. supervised/__init__.py +14 -0
  7. supervised/algorithms/__init__.py +0 -0
  8. supervised/algorithms/algorithm.py +151 -0
  9. supervised/algorithms/baseline.py +90 -0
  10. supervised/algorithms/catboost.py +436 -0
  11. supervised/algorithms/decision_tree.py +305 -0
  12. supervised/algorithms/extra_trees.py +176 -0
  13. supervised/algorithms/factory.py +28 -0
  14. supervised/algorithms/knn.py +137 -0
  15. supervised/algorithms/lightgbm.py +406 -0
  16. supervised/algorithms/linear.py +211 -0
  17. supervised/algorithms/nn.py +180 -0
  18. supervised/algorithms/random_forest.py +181 -0
  19. supervised/algorithms/registry.py +76 -0
  20. supervised/algorithms/sklearn.py +197 -0
  21. supervised/algorithms/xgboost.py +413 -0
  22. supervised/automl.py +568 -0
  23. supervised/base_automl.py +2542 -0
  24. supervised/callbacks/__init__.py +0 -0
  25. supervised/callbacks/callback.py +25 -0
  26. supervised/callbacks/callback_list.py +33 -0
  27. supervised/callbacks/early_stopping.py +213 -0
  28. supervised/callbacks/learner_time_constraint.py +47 -0
  29. supervised/callbacks/max_iters_constraint.py +16 -0
  30. supervised/callbacks/metric_logger.py +48 -0
  31. supervised/callbacks/terminate_on_nan.py +28 -0
  32. supervised/callbacks/total_time_constraint.py +79 -0
  33. supervised/ensemble.py +583 -0
  34. supervised/exceptions.py +21 -0
  35. supervised/fairness/__init__.py +0 -0
  36. supervised/fairness/metrics.py +654 -0
  37. supervised/fairness/optimization.py +414 -0
  38. supervised/fairness/plots.py +131 -0
  39. supervised/fairness/report.py +116 -0
  40. supervised/fairness/utils.py +40 -0
  41. supervised/model_framework.py +734 -0
  42. supervised/preprocessing/__init__.py +0 -0
  43. supervised/preprocessing/datetime_transformer.py +106 -0
  44. supervised/preprocessing/encoding_selector.py +30 -0
  45. supervised/preprocessing/exclude_missing_target.py +46 -0
  46. supervised/preprocessing/goldenfeatures_transformer.py +310 -0
  47. supervised/preprocessing/kmeans_transformer.py +115 -0
  48. supervised/preprocessing/label_binarizer.py +81 -0
  49. supervised/preprocessing/label_encoder.py +54 -0
  50. supervised/preprocessing/preprocessing.py +652 -0
  51. supervised/preprocessing/preprocessing_categorical.py +117 -0
  52. supervised/preprocessing/preprocessing_missing.py +97 -0
  53. supervised/preprocessing/preprocessing_utils.py +136 -0
  54. supervised/preprocessing/scale.py +92 -0
  55. supervised/preprocessing/text_transformer.py +73 -0
  56. supervised/tuner/__init__.py +0 -0
  57. supervised/tuner/data_info.py +64 -0
  58. supervised/tuner/hill_climbing.py +80 -0
  59. supervised/tuner/mljar_tuner.py +1501 -0
  60. supervised/tuner/optuna/__init__.py +0 -0
  61. supervised/tuner/optuna/catboost.py +148 -0
  62. supervised/tuner/optuna/extra_trees.py +80 -0
  63. supervised/tuner/optuna/knn.py +64 -0
  64. supervised/tuner/optuna/lightgbm.py +165 -0
  65. supervised/tuner/optuna/nn.py +66 -0
  66. supervised/tuner/optuna/random_forest.py +77 -0
  67. supervised/tuner/optuna/tuner.py +335 -0
  68. supervised/tuner/optuna/xgboost.py +130 -0
  69. supervised/tuner/preprocessing_tuner.py +137 -0
  70. supervised/tuner/random_parameters.py +22 -0
  71. supervised/tuner/time_controller.py +273 -0
  72. supervised/utils/__init__.py +11 -0
  73. supervised/utils/additional_metrics.py +955 -0
  74. supervised/utils/additional_plots.py +228 -0
  75. supervised/utils/automl_plots.py +368 -0
  76. supervised/utils/common.py +39 -0
  77. supervised/utils/config.py +25 -0
  78. supervised/utils/constants.py +4 -0
  79. supervised/utils/data_validation.py +48 -0
  80. supervised/utils/importance.py +93 -0
  81. supervised/utils/jsonencoder.py +33 -0
  82. supervised/utils/leaderboard_plots.py +137 -0
  83. supervised/utils/learning_curves.py +145 -0
  84. supervised/utils/metric.py +450 -0
  85. supervised/utils/report_structured.py +525 -0
  86. supervised/utils/shap.py +373 -0
  87. supervised/utils/subsample.py +17 -0
  88. supervised/utils/utils.py +29 -0
  89. supervised/validation/__init__.py +0 -0
  90. supervised/validation/validation_step.py +37 -0
  91. supervised/validation/validator_base.py +17 -0
  92. supervised/validation/validator_custom.py +112 -0
  93. supervised/validation/validator_kfold.py +153 -0
  94. supervised/validation/validator_split.py +143 -0
@@ -0,0 +1,525 @@
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
+
11
+ def _get_package_version():
12
+ try:
13
+ return version("mljar-supervised")
14
+ except PackageNotFoundError:
15
+ return "unknown"
16
+
17
+
18
+ def _to_float_or_none(value):
19
+ if value is None:
20
+ return None
21
+ try:
22
+ return float(value)
23
+ except Exception:
24
+ return None
25
+
26
+
27
+ def _to_bool(value):
28
+ try:
29
+ return bool(value)
30
+ except Exception:
31
+ return False
32
+
33
+
34
+ def _serialize_metrics_value(value):
35
+ if value is None:
36
+ return None
37
+ if isinstance(value, pd.DataFrame):
38
+ return value.to_dict(orient="split")
39
+ if isinstance(value, pd.Series):
40
+ return value.to_dict()
41
+ return value
42
+
43
+
44
+ def _extract_additional_metrics(model):
45
+ try:
46
+ additional = model.get_additional_metrics()
47
+ if additional is None:
48
+ return None
49
+
50
+ metrics = {}
51
+ for key in [
52
+ "max_metrics",
53
+ "accuracy_threshold_metrics",
54
+ "confusion_matrix",
55
+ "threshold",
56
+ ]:
57
+ if key in additional:
58
+ metrics[key] = _serialize_metrics_value(additional.get(key))
59
+ return metrics
60
+ except Exception:
61
+ return None
62
+
63
+
64
+ def _compute_feature_importance_summary(model_dir):
65
+ imp_files = []
66
+ try:
67
+ imp_files = [
68
+ f
69
+ for f in os.listdir(model_dir)
70
+ if f.endswith("_importance.csv") and "shap" not in f
71
+ ]
72
+ except Exception:
73
+ return {"available": False, "reason": "model_dir_unreadable"}
74
+
75
+ if not imp_files:
76
+ return {"available": False, "reason": "no_importance_files"}
77
+
78
+ frames = []
79
+ for fname in imp_files:
80
+ fpath = os.path.join(model_dir, fname)
81
+ try:
82
+ df = pd.read_csv(fpath, index_col=0)
83
+ if df.empty:
84
+ continue
85
+ numeric_df = df.select_dtypes(include=np.number)
86
+ if numeric_df.empty:
87
+ continue
88
+ frames.append(numeric_df)
89
+ except Exception:
90
+ continue
91
+
92
+ if not frames:
93
+ return {"available": False, "reason": "no_valid_importance_data"}
94
+
95
+ concat = pd.concat(frames, axis=1, join="outer")
96
+ mean_importance = concat.mean(axis=1).fillna(0.0)
97
+ mean_importance = mean_importance.sort_values(ascending=False)
98
+ n = int(mean_importance.shape[0])
99
+
100
+ if n == 0:
101
+ return {"available": False, "reason": "empty_importance"}
102
+
103
+ if n < 10:
104
+ k = 3
105
+ elif n < 20:
106
+ k = 5
107
+ else:
108
+ k = 10
109
+ k = min(k, n)
110
+
111
+ top_slice = mean_importance.head(k)
112
+ worst_slice = mean_importance.tail(k)
113
+
114
+ return {
115
+ "available": True,
116
+ "n_features": n,
117
+ "selection_k": k,
118
+ "top": [
119
+ {"feature": str(feature), "importance": float(value)}
120
+ for feature, value in top_slice.items()
121
+ ],
122
+ "worst": [
123
+ {"feature": str(feature), "importance": float(value)}
124
+ for feature, value in worst_slice.items()
125
+ ],
126
+ }
127
+
128
+
129
+ def _model_to_dict(automl, model):
130
+ model_name = model.get_name()
131
+ model_dir = os.path.join(automl._results_path, model_name)
132
+
133
+ model_dict = {
134
+ "name": model_name,
135
+ "model_type": model.get_type(),
136
+ "metric_type": automl._eval_metric,
137
+ "metric_value": _to_float_or_none(model.get_final_loss()),
138
+ "train_time": _to_float_or_none(model.get_train_time()),
139
+ "is_valid": _to_bool(model.is_valid()),
140
+ "is_stacked": _to_bool(getattr(model, "_is_stacked", False)),
141
+ "involved_models": model.involved_model_names(),
142
+ "artifacts": {
143
+ "model_dir": model_dir,
144
+ "readme_md": os.path.join(model_dir, "README.md"),
145
+ "readme_html": os.path.join(model_dir, "README.html"),
146
+ },
147
+ }
148
+ model_dict["metrics"] = _extract_additional_metrics(model)
149
+ model_dict["feature_importance"] = _compute_feature_importance_summary(model_dir)
150
+
151
+ if automl._fairness_metric is not None:
152
+ sensitive = []
153
+ for sf in model.get_sensitive_features_names():
154
+ sensitive.append(
155
+ {
156
+ "feature": sf,
157
+ "fairness_metric_value": _to_float_or_none(
158
+ model.get_fairness_metric(sf)
159
+ ),
160
+ }
161
+ )
162
+ model_dict["fairness"] = {
163
+ "is_fair": _to_bool(model.is_fair()),
164
+ "worst_fairness": _to_float_or_none(model.get_worst_fairness()),
165
+ "best_fairness": _to_float_or_none(model.get_best_fairness()),
166
+ "sensitive_features": sensitive,
167
+ }
168
+
169
+ return model_dict
170
+
171
+
172
+ def build_structured_report(automl):
173
+ leaderboard_df = automl.get_leaderboard(original_metric_values=True)
174
+ leaderboard = leaderboard_df.to_dict(orient="records")
175
+
176
+ best_model = None
177
+ if automl._best_model is not None:
178
+ best_model = _model_to_dict(automl, automl._best_model)
179
+
180
+ fairness_summary = None
181
+ if automl._fairness_metric is not None and automl._best_model is not None:
182
+ fairness_summary = {
183
+ "fairness_metric": automl._fairness_metric,
184
+ "fairness_threshold": automl._fairness_threshold,
185
+ "best_model_is_fair": _to_bool(automl._best_model.is_fair()),
186
+ "best_model_worst_fairness": _to_float_or_none(
187
+ automl._best_model.get_worst_fairness()
188
+ ),
189
+ "best_model_best_fairness": _to_float_or_none(
190
+ automl._best_model.get_best_fairness()
191
+ ),
192
+ "sensitive_features": [
193
+ {
194
+ "feature": sf,
195
+ "fairness_metric_value": _to_float_or_none(
196
+ automl._best_model.get_fairness_metric(sf)
197
+ ),
198
+ }
199
+ for sf in automl._best_model.get_sensitive_features_names()
200
+ ],
201
+ }
202
+
203
+ payload = {
204
+ "created_at_utc": datetime.now(timezone.utc).isoformat(),
205
+ "mljar_supervised_version": _get_package_version(),
206
+ "results_path": automl._results_path,
207
+ "run_summary": {
208
+ "mode": automl._mode,
209
+ "ml_task": automl._ml_task,
210
+ "eval_metric": automl._eval_metric,
211
+ "n_rows": getattr(automl, "n_rows_in_", None),
212
+ "n_features": getattr(automl, "n_features_in_", None),
213
+ "n_classes": getattr(automl, "n_classes", None),
214
+ "n_models": len(automl._models),
215
+ "best_model_name": None
216
+ if automl._best_model is None
217
+ else automl._best_model.get_name(),
218
+ "fit_level": automl._fit_level,
219
+ "total_time_limit": automl._total_time_limit,
220
+ "model_time_limit": automl._model_time_limit,
221
+ "validation_strategy": automl._validation_strategy,
222
+ "train_ensemble": automl._train_ensemble,
223
+ "stack_models": automl._stack_models,
224
+ "fairness_metric": automl._fairness_metric,
225
+ "fairness_threshold": automl._fairness_threshold,
226
+ },
227
+ "leaderboard": leaderboard,
228
+ "best_model": best_model,
229
+ "fairness_summary": fairness_summary,
230
+ "models": [_model_to_dict(automl, m) for m in automl._models],
231
+ "artifacts": {
232
+ "leaderboard_csv": os.path.join(automl._results_path, "leaderboard.csv"),
233
+ "main_readme_md": os.path.join(automl._results_path, "README.md"),
234
+ "main_readme_html": os.path.join(automl._results_path, "README.html"),
235
+ "report_structured_json": os.path.join(
236
+ automl._results_path, "report_structured.json"
237
+ ),
238
+ "errors_md": os.path.join(automl._results_path, "errors.md"),
239
+ },
240
+ }
241
+ return payload
242
+
243
+
244
+ def save_structured_report(payload, results_path):
245
+ fname = os.path.join(results_path, "report_structured.json")
246
+ with open(fname, "w") as fout:
247
+ json.dump(payload, fout, indent=4)
248
+ return fname
249
+
250
+
251
+ def _append_split_table(lines, title, table_obj):
252
+ if table_obj is None:
253
+ return
254
+ columns = table_obj.get("columns", [])
255
+ data = table_obj.get("data", [])
256
+ index = table_obj.get("index")
257
+ show_index = False
258
+ if index is not None and len(index) == len(data):
259
+ # Hide synthetic/default row index (0..n-1) to keep tables readable.
260
+ try:
261
+ show_index = list(index) != list(range(len(data)))
262
+ except Exception:
263
+ show_index = True
264
+ if show_index:
265
+ columns = ["index"] + list(columns)
266
+ data = [[index[i]] + row for i, row in enumerate(data)]
267
+ lines.append(f"### {title}")
268
+ lines.append("")
269
+ lines.append(tabulate(data, headers=columns, tablefmt="pipe"))
270
+ lines.append("")
271
+
272
+
273
+ def to_markdown(payload, model_details=True):
274
+ lines = []
275
+ lines.append("# MLJAR AutoML Report")
276
+ lines.append("")
277
+ lines.append("## Run Summary")
278
+ lines.append("")
279
+ run_summary = payload.get("run_summary", {})
280
+ for key, value in run_summary.items():
281
+ lines.append(f"- **{key}**: {value}")
282
+ lines.append("")
283
+
284
+ lines.append("## Leaderboard")
285
+ lines.append("")
286
+ leaderboard = payload.get("leaderboard", [])
287
+ if leaderboard:
288
+ df = pd.DataFrame(leaderboard)
289
+ preferred_cols = [
290
+ c
291
+ for c in ["name", "model_type", "metric_type", "metric_value", "train_time"]
292
+ if c in df.columns
293
+ ]
294
+ if preferred_cols:
295
+ df = df[preferred_cols]
296
+ lines.append(tabulate(df.values, headers=list(df.columns), tablefmt="pipe"))
297
+ else:
298
+ lines.append("_No models found._")
299
+ lines.append("")
300
+
301
+ lines.append("## Best Model")
302
+ lines.append("")
303
+ best_model = payload.get("best_model")
304
+ if best_model is None:
305
+ lines.append("_No best model available._")
306
+ else:
307
+ scalar_keys = [
308
+ "name",
309
+ "model_type",
310
+ "metric_type",
311
+ "metric_value",
312
+ "train_time",
313
+ "is_valid",
314
+ "is_stacked",
315
+ ]
316
+ for key in scalar_keys:
317
+ if key in best_model:
318
+ lines.append(f"- **{key}**: {best_model.get(key)}")
319
+ if best_model.get("involved_models"):
320
+ lines.append("- **involved_models**:")
321
+ for model_name in best_model.get("involved_models", []):
322
+ lines.append(f" - {model_name}")
323
+ lines.append("")
324
+
325
+ best_metrics = best_model.get("metrics") or {}
326
+ _append_split_table(lines, "Metric details", best_metrics.get("max_metrics"))
327
+ _append_split_table(
328
+ lines,
329
+ "Metric details with threshold from accuracy metric",
330
+ best_metrics.get("accuracy_threshold_metrics"),
331
+ )
332
+ _append_split_table(
333
+ lines, "Confusion matrix", best_metrics.get("confusion_matrix")
334
+ )
335
+ threshold = best_metrics.get("threshold")
336
+ if threshold is not None:
337
+ lines.append(f"Threshold: `{threshold}`")
338
+ lines.append("")
339
+
340
+ best_fi = best_model.get("feature_importance") or {}
341
+ if best_fi.get("available"):
342
+ k = best_fi.get("selection_k")
343
+ top_rows = [
344
+ [row.get("feature"), row.get("importance")]
345
+ for row in best_fi.get("top", [])
346
+ ]
347
+ worst_rows = [
348
+ [row.get("feature"), row.get("importance")]
349
+ for row in best_fi.get("worst", [])
350
+ ]
351
+ lines.append(
352
+ f"### Most Influential Features (Top {k} by permutation importance)"
353
+ )
354
+ lines.append("")
355
+ lines.append(
356
+ tabulate(top_rows, headers=["Feature", "Importance"], tablefmt="pipe")
357
+ )
358
+ lines.append("")
359
+ lines.append(
360
+ f"### Least Influential Features (Bottom {k} by permutation importance)"
361
+ )
362
+ lines.append("")
363
+ lines.append(
364
+ tabulate(
365
+ worst_rows, headers=["Feature", "Importance"], tablefmt="pipe"
366
+ )
367
+ )
368
+ lines.append("")
369
+
370
+ best_fairness = best_model.get("fairness")
371
+ if best_fairness is not None:
372
+ lines.append("### Fairness (Best Model)")
373
+ lines.append("")
374
+ fairness_rows = [
375
+ ["is_fair", best_fairness.get("is_fair")],
376
+ ["worst_fairness", best_fairness.get("worst_fairness")],
377
+ ["best_fairness", best_fairness.get("best_fairness")],
378
+ ]
379
+ lines.append(
380
+ tabulate(fairness_rows, headers=["Field", "Value"], tablefmt="pipe")
381
+ )
382
+ sf = best_fairness.get("sensitive_features", [])
383
+ if sf:
384
+ lines.append("")
385
+ lines.append(
386
+ tabulate(
387
+ [[s.get("feature"), s.get("fairness_metric_value")] for s in sf],
388
+ headers=["Sensitive Feature", "Fairness Metric Value"],
389
+ tablefmt="pipe",
390
+ )
391
+ )
392
+ lines.append("")
393
+ lines.append("")
394
+
395
+ fairness = payload.get("fairness_summary")
396
+ if fairness is not None:
397
+ lines.append("## Fairness Summary")
398
+ lines.append("")
399
+ rows = []
400
+ for key in [
401
+ "fairness_metric",
402
+ "fairness_threshold",
403
+ "best_model_is_fair",
404
+ "best_model_worst_fairness",
405
+ "best_model_best_fairness",
406
+ ]:
407
+ rows.append([key, fairness.get(key)])
408
+ lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="pipe"))
409
+ sf = fairness.get("sensitive_features", [])
410
+ if sf:
411
+ lines.append("")
412
+ lines.append(
413
+ tabulate(
414
+ [[s.get("feature"), s.get("fairness_metric_value")] for s in sf],
415
+ headers=["Sensitive Feature", "Fairness Metric Value"],
416
+ tablefmt="pipe",
417
+ )
418
+ )
419
+ lines.append("")
420
+
421
+ if model_details:
422
+ lines.append("## Model Details")
423
+ lines.append("")
424
+ models = payload.get("models", [])
425
+ if not models:
426
+ lines.append("_No model details available._")
427
+ lines.append("")
428
+ for model in models:
429
+ lines.append(f"## {model.get('name')}")
430
+ lines.append("")
431
+ summary_rows = [
432
+ ["model_type", model.get("model_type")],
433
+ ["metric_type", model.get("metric_type")],
434
+ ["metric_value", model.get("metric_value")],
435
+ ["train_time", model.get("train_time")],
436
+ ["is_valid", model.get("is_valid")],
437
+ ["is_stacked", model.get("is_stacked")],
438
+ ]
439
+ lines.append(
440
+ tabulate(summary_rows, headers=["Field", "Value"], tablefmt="pipe")
441
+ )
442
+ lines.append("")
443
+
444
+ metrics = model.get("metrics") or {}
445
+ _append_split_table(lines, "Metric details", metrics.get("max_metrics"))
446
+ _append_split_table(
447
+ lines,
448
+ "Metric details with threshold from accuracy metric",
449
+ metrics.get("accuracy_threshold_metrics"),
450
+ )
451
+ _append_split_table(
452
+ lines, "Confusion matrix", metrics.get("confusion_matrix")
453
+ )
454
+ threshold = metrics.get("threshold")
455
+ if threshold is not None:
456
+ lines.append(f"Threshold: `{threshold}`")
457
+ lines.append("")
458
+
459
+ fi = model.get("feature_importance") or {}
460
+ if fi.get("available"):
461
+ k = fi.get("selection_k")
462
+ top_rows = [
463
+ [row.get("feature"), row.get("importance")]
464
+ for row in fi.get("top", [])
465
+ ]
466
+ worst_rows = [
467
+ [row.get("feature"), row.get("importance")]
468
+ for row in fi.get("worst", [])
469
+ ]
470
+ lines.append(
471
+ f"### Most Influential Features (Top {k} by permutation importance)"
472
+ )
473
+ lines.append("")
474
+ lines.append(
475
+ tabulate(
476
+ top_rows,
477
+ headers=["Feature", "Importance"],
478
+ tablefmt="pipe",
479
+ )
480
+ )
481
+ lines.append("")
482
+
483
+ lines.append(
484
+ f"### Least Influential Features (Bottom {k} by permutation importance)"
485
+ )
486
+ lines.append("")
487
+ lines.append(
488
+ tabulate(
489
+ worst_rows,
490
+ headers=["Feature", "Importance"],
491
+ tablefmt="pipe",
492
+ )
493
+ )
494
+ lines.append("")
495
+
496
+ fairness = model.get("fairness")
497
+ if fairness is not None:
498
+ lines.append("### Fairness")
499
+ lines.append("")
500
+ fairness_rows = [
501
+ ["is_fair", fairness.get("is_fair")],
502
+ ["worst_fairness", fairness.get("worst_fairness")],
503
+ ["best_fairness", fairness.get("best_fairness")],
504
+ ]
505
+ lines.append(
506
+ tabulate(
507
+ fairness_rows, headers=["Field", "Value"], tablefmt="pipe"
508
+ )
509
+ )
510
+ sf = fairness.get("sensitive_features", [])
511
+ if sf:
512
+ lines.append("")
513
+ lines.append(
514
+ tabulate(
515
+ [
516
+ [s.get("feature"), s.get("fairness_metric_value")]
517
+ for s in sf
518
+ ],
519
+ headers=["Sensitive Feature", "Fairness Metric Value"],
520
+ tablefmt="pipe",
521
+ )
522
+ )
523
+ lines.append("")
524
+
525
+ return "\n".join(lines)