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,48 @@
1
+ def check_greater_than_zero_integer(value, original_var_name):
2
+ if not isinstance(value, int):
3
+ raise ValueError(
4
+ f"'{original_var_name}' must be an integer, got '{type(value)}'."
5
+ )
6
+
7
+ if value <= 0:
8
+ raise ValueError(
9
+ f"'{original_var_name}' must be greater than zero, got '{value}'."
10
+ )
11
+
12
+
13
+ def check_positive_integer(value, original_var_name):
14
+ if not isinstance(value, int):
15
+ raise ValueError(
16
+ f"'{original_var_name}' must be an integer, got '{type(value)}'."
17
+ )
18
+
19
+ if value < 0:
20
+ raise ValueError(
21
+ f"'{original_var_name}' must be equal or greater than zero, got '{value}'."
22
+ )
23
+
24
+
25
+ def check_integer(value, original_var_name):
26
+ if not isinstance(value, int):
27
+ raise ValueError(
28
+ f"'{original_var_name}' must be an integer, got '{type(value)}'."
29
+ )
30
+
31
+
32
+ def check_bool(value, original_var_name):
33
+ if not isinstance(value, bool):
34
+ raise ValueError(
35
+ f"'{original_var_name}' must be a boolean, got '{type(value)}'."
36
+ )
37
+
38
+
39
+ def check_greater_than_zero_integer_or_float(value, original_var_name):
40
+ if not (isinstance(value, int) or isinstance(value, float)):
41
+ raise ValueError(
42
+ f"'{original_var_name}' must be an integer or float, got '{type(value)}'."
43
+ )
44
+
45
+ if value <= 0:
46
+ raise ValueError(
47
+ f"'{original_var_name}' must be greater than zero, got '{value}'."
48
+ )
@@ -0,0 +1,93 @@
1
+ import logging
2
+ import os
3
+ import warnings
4
+
5
+ import pandas as pd
6
+ from sklearn.inspection import permutation_importance
7
+
8
+ from supervised.algorithms.registry import (
9
+ BINARY_CLASSIFICATION,
10
+ MULTICLASS_CLASSIFICATION,
11
+ )
12
+ from supervised.utils.subsample import subsample
13
+
14
+ logger = logging.getLogger(__name__)
15
+ from supervised.utils.config import LOG_LEVEL
16
+
17
+ logger.setLevel(LOG_LEVEL)
18
+
19
+ from sklearn.metrics import log_loss, make_scorer
20
+
21
+
22
+ def log_loss_eps(y_true, y_pred):
23
+ ll = log_loss(y_true, y_pred)
24
+ return ll
25
+
26
+
27
+ log_loss_scorer = make_scorer(log_loss_eps, greater_is_better=False, response_method="predict_proba")
28
+
29
+
30
+ class PermutationImportance:
31
+ @staticmethod
32
+ def compute_and_plot(
33
+ model,
34
+ X_validation,
35
+ y_validation,
36
+ model_file_path,
37
+ learner_name,
38
+ metric_name=None,
39
+ ml_task=None,
40
+ n_jobs=-1,
41
+ ):
42
+ # for scoring check https://scikit-learn.org/stable/modules/model_evaluation.html#scoring-parameter
43
+ if ml_task == BINARY_CLASSIFICATION:
44
+ scoring = log_loss_scorer
45
+ elif ml_task == MULTICLASS_CLASSIFICATION:
46
+ scoring = log_loss_scorer
47
+ else:
48
+ scoring = "neg_mean_squared_error"
49
+
50
+ try:
51
+ with warnings.catch_warnings():
52
+ warnings.simplefilter("ignore")
53
+ # subsample validation data to speed-up importance computation
54
+ # in the case of large number of columns, it can take a lot of time
55
+ rows, cols = X_validation.shape
56
+ if cols > 5000 and rows > 100:
57
+ X_vald, _, y_vald, _ = subsample(
58
+ X_validation, y_validation, train_size=100, ml_task=ml_task
59
+ )
60
+ elif cols > 50 and rows * cols > 200000 and rows > 1000:
61
+ X_vald, _, y_vald, _ = subsample(
62
+ X_validation, y_validation, train_size=1000, ml_task=ml_task
63
+ )
64
+ else:
65
+ X_vald = X_validation
66
+ y_vald = y_validation
67
+
68
+ importance = permutation_importance(
69
+ model,
70
+ X_vald,
71
+ y_vald,
72
+ scoring=scoring,
73
+ n_jobs=n_jobs,
74
+ random_state=12,
75
+ n_repeats=5, # default
76
+ )
77
+
78
+ sorted_idx = importance["importances_mean"].argsort()
79
+
80
+ # save detailed importance
81
+ df_imp = pd.DataFrame(
82
+ {
83
+ "feature": X_vald.columns[sorted_idx],
84
+ "mean_importance": importance["importances_mean"][sorted_idx],
85
+ }
86
+ )
87
+ df_imp.to_csv(
88
+ os.path.join(model_file_path, f"{learner_name}_importance.csv"),
89
+ index=False,
90
+ )
91
+ except Exception as e:
92
+ print(str(e))
93
+ print("Problem during computing permutation importance. Skipping ...")
@@ -0,0 +1,33 @@
1
+ import json
2
+ from datetime import date
3
+
4
+ import numpy as np
5
+
6
+
7
+ class MLJSONEncoder(json.JSONEncoder):
8
+ def default(self, o):
9
+ if isinstance(
10
+ o,
11
+ (
12
+ np.int_,
13
+ np.intc,
14
+ np.intp,
15
+ np.int8,
16
+ np.int16,
17
+ np.int32,
18
+ np.int64,
19
+ np.uint8,
20
+ np.uint16,
21
+ np.uint32,
22
+ np.uint64,
23
+ ),
24
+ ):
25
+ return int(o)
26
+ elif isinstance(o, (np.float_, np.float16, np.float32, np.float64)):
27
+ return float(o)
28
+ elif isinstance(o, np.ndarray):
29
+ return o.tolist()
30
+ elif isinstance(obj, date):
31
+ return obj.strftime("%Y-%m-%d")
32
+
33
+ return super(MLJSONEncoder, self).default(o)
@@ -0,0 +1,137 @@
1
+ import logging
2
+ import os
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+
7
+ logger = logging.getLogger(__name__)
8
+ from supervised.utils.config import LOG_LEVEL
9
+ from supervised.utils.metric import Metric
10
+
11
+ logger.setLevel(LOG_LEVEL)
12
+
13
+ import warnings
14
+
15
+ import matplotlib.pyplot as plt
16
+
17
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
18
+
19
+
20
+ markers = {
21
+ "Baseline": {"color": "tab:cyan", "marker": "8"},
22
+ "Linear": {"color": "tab:pink", "marker": "s"},
23
+ "Decision Tree": {"color": "tab:gray", "marker": "^"},
24
+ "Random Forest": {"color": "tab:green", "marker": "o"},
25
+ "Extra Trees": {"color": "tab:brown", "marker": "v"},
26
+ "LightGBM": {"color": "tab:purple", "marker": "P"},
27
+ "Xgboost": {"color": "tab:blue", "marker": "*"},
28
+ "CatBoost": {"color": "tab:orange", "marker": "D"},
29
+ "Neural Network": {"color": "tab:red", "marker": "x"},
30
+ "Nearest Neighbors": {"color": "tab:olive", "marker": "+"},
31
+ "Ensemble": {"color": "black", "marker": "p"},
32
+ }
33
+
34
+
35
+ class LeaderboardPlots:
36
+ performance_fname = "ldb_performance.png"
37
+ performance_boxplot_fname = "ldb_performance_boxplot.png"
38
+
39
+ @staticmethod
40
+ def compute(ldb, model_path, fout, fairness_threshold=None):
41
+ if ldb.shape[0] < 2:
42
+ return
43
+ # Scatter plot
44
+ plt.figure(figsize=(10, 7))
45
+ for model_type in ldb.model_type.unique():
46
+ ii = ldb.model_type == model_type
47
+ plt.plot(
48
+ ldb.metric_value[ii],
49
+ markers[model_type]["marker"],
50
+ markersize=12,
51
+ alpha=0.75,
52
+ color=markers[model_type]["color"],
53
+ label=model_type,
54
+ )
55
+ # plt.plot(ldb.metric_value, "*", markersize=12, alpha=0.75)
56
+
57
+ plt.xlabel("#Iteration")
58
+ plt.ylabel(ldb.metric_type.iloc[0])
59
+ plt.legend()
60
+ plt.title("AutoML Performance")
61
+ plt.tight_layout(pad=2.0)
62
+ plot_path = os.path.join(model_path, LeaderboardPlots.performance_fname)
63
+ plt.savefig(plot_path)
64
+ plt.close("all")
65
+
66
+ fout.write("\n\n### AutoML Performance\n")
67
+ fout.write(f"![AutoML Performance]({LeaderboardPlots.performance_fname})")
68
+
69
+ # Boxplot
70
+ by = "model_type"
71
+ column = "metric_value"
72
+ df2 = pd.DataFrame({col: vals[column] for col, vals in ldb.groupby(by)})
73
+
74
+ ascending_sort = Metric.optimize_negative(ldb.metric_type.iloc[0])
75
+ mins = df2.min().sort_values(ascending=ascending_sort)
76
+
77
+ plt.figure(figsize=(10, 7))
78
+ # plt.title("")
79
+ plt.ylabel(ldb.metric_type.iloc[0])
80
+ df2[mins.index].boxplot(rot=90, fontsize=12)
81
+
82
+ plt.tight_layout(pad=2.0)
83
+ plot_path = os.path.join(model_path, LeaderboardPlots.performance_boxplot_fname)
84
+ plt.savefig(plot_path)
85
+ plt.close("all")
86
+
87
+ fout.write("\n\n### AutoML Performance Boxplot\n")
88
+ fout.write(
89
+ f"![AutoML Performance Boxplot]({LeaderboardPlots.performance_boxplot_fname})"
90
+ )
91
+
92
+ if fairness_threshold is not None:
93
+ fairness_metrics = [
94
+ f for f in ldb.columns if "fairness_" in f and f != "fairness_metric"
95
+ ]
96
+ for fm in fairness_metrics:
97
+ x_axis_name = ldb.metric_type.iloc[0]
98
+ y_axis_name = ldb["fairness_metric"].iloc[0]
99
+
100
+ # Scatter plot
101
+ plt.figure(figsize=(10, 7))
102
+ for model_type in ldb.model_type.unique():
103
+ ii = ldb.model_type == model_type
104
+ plt.plot(
105
+ ldb.metric_value[ii],
106
+ ldb[fm][ii],
107
+ markers[model_type]["marker"],
108
+ markersize=12,
109
+ alpha=0.75,
110
+ color=markers[model_type]["color"],
111
+ label=model_type,
112
+ )
113
+
114
+ plt.xlabel(x_axis_name)
115
+ plt.ylabel(y_axis_name)
116
+ plt.legend()
117
+ plt.title(f"Performance vs {fm}")
118
+ plt.tight_layout(pad=2.0)
119
+
120
+ ymin = 0
121
+ ymax = max(1, ldb[fm].max() * 1.1)
122
+ plt.ylim(0, ymax)
123
+ if "ratio" in y_axis_name:
124
+ plt.axhspan(fairness_threshold, ymax, color="green", alpha=0.05)
125
+ plt.axhspan(ymin, fairness_threshold, color="red", alpha=0.05)
126
+ else:
127
+ # difference metric
128
+ plt.axhspan(ymin, fairness_threshold, color="green", alpha=0.05)
129
+ plt.axhspan(fairness_threshold, ymax, color="red", alpha=0.05)
130
+
131
+ fname = f"performance_vs_{fm}.png"
132
+ plot_path = os.path.join(model_path, fname)
133
+ plt.savefig(plot_path)
134
+ plt.close("all")
135
+
136
+ fout.write(f"\n\n### Performance vs {fm}\n")
137
+ fout.write(f"![Performance vs {fm}]({fname})")
@@ -0,0 +1,145 @@
1
+ import logging
2
+ import os
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+
7
+ logger = logging.getLogger(__name__)
8
+ from supervised.utils.common import learner_name_to_fold_repeat
9
+ from supervised.utils.config import LOG_LEVEL
10
+ from supervised.utils.metric import Metric
11
+
12
+ logger.setLevel(LOG_LEVEL)
13
+
14
+ import matplotlib.colors as mcolors
15
+ import matplotlib.pyplot as plt
16
+
17
+ MY_COLORS = list(mcolors.TABLEAU_COLORS.values())
18
+
19
+
20
+ class LearningCurves:
21
+ output_file_name = "learning_curves.png"
22
+
23
+ @staticmethod
24
+ def single_iteration(learner_names, model_path):
25
+ for ln in learner_names:
26
+ df = pd.read_csv(
27
+ os.path.join(model_path, f"{ln}_training.log"),
28
+ names=["iteration", "train", "test"],
29
+ )
30
+ if df.shape[0] > 1:
31
+ return False
32
+ return True
33
+
34
+ @staticmethod
35
+ def plot(learner_names, metric_name, model_path, trees_in_iteration=None):
36
+ colors = MY_COLORS
37
+ if len(learner_names) > len(colors):
38
+ repeat_colors = int(np.ceil(len(learner_names) / len(colors)))
39
+ colors = colors * repeat_colors
40
+
41
+ if LearningCurves.single_iteration(learner_names, model_path):
42
+ LearningCurves.plot_single_iter(
43
+ learner_names, metric_name, model_path, colors
44
+ )
45
+ else:
46
+ LearningCurves.plot_iterations(
47
+ learner_names, metric_name, model_path, colors, trees_in_iteration
48
+ )
49
+
50
+ @staticmethod
51
+ def plot_single_iter(learner_names, metric_name, model_path, colors):
52
+ plt.figure(figsize=(10, 7))
53
+ for ln in learner_names:
54
+ df = pd.read_csv(
55
+ os.path.join(model_path, f"{ln}_training.log"),
56
+ names=["iteration", "train", "test"],
57
+ )
58
+
59
+ fold, repeat = learner_name_to_fold_repeat(ln)
60
+ repeat_str = f" Reapeat {repeat+1}," if repeat is not None else ""
61
+ plt.bar(
62
+ f"Fold {fold+1},{repeat_str} train",
63
+ df.train[0],
64
+ color="white",
65
+ edgecolor=colors[fold],
66
+ )
67
+ plt.bar(f"Fold {fold+1},{repeat_str} test", df.test[0], color=colors[fold])
68
+
69
+ plt.ylabel(metric_name)
70
+ plt.xticks(rotation=90)
71
+ plt.tight_layout(pad=2.0)
72
+ plot_path = os.path.join(model_path, LearningCurves.output_file_name)
73
+ plt.savefig(plot_path)
74
+ plt.close("all")
75
+
76
+ @staticmethod
77
+ def plot_iterations(
78
+ learner_names, metric_name, model_path, colors, trees_in_iteration=None
79
+ ):
80
+ plt.figure(figsize=(10, 7))
81
+ for ln in learner_names:
82
+ df = pd.read_csv(
83
+ os.path.join(model_path, f"{ln}_training.log"),
84
+ names=["iteration", "train", "test"],
85
+ )
86
+
87
+ fold, repeat = learner_name_to_fold_repeat(ln)
88
+ repeat_str = f" Reapeat {repeat+1}," if repeat is not None else ""
89
+ # if trees_in_iteration is not None:
90
+ # df.iteration = df.iteration * trees_in_iteration
91
+ any_none = np.sum(pd.isnull(df.train))
92
+ if any_none == 0:
93
+ plt.plot(
94
+ df.iteration,
95
+ df.train,
96
+ "--",
97
+ color=colors[fold],
98
+ label=f"Fold {fold+1},{repeat_str} train",
99
+ )
100
+ any_none = np.sum(pd.isnull(df.test))
101
+ if any_none == 0:
102
+ plt.plot(
103
+ df.iteration,
104
+ df.test,
105
+ color=colors[fold],
106
+ label=f"Fold {fold+1},{repeat_str} test",
107
+ )
108
+
109
+
110
+ if not df.test.isnull().values.any():
111
+ best_iter = None
112
+ if Metric.optimize_negative(metric_name):
113
+ best_iter = df.test.argmax()
114
+ else:
115
+ best_iter = df.test.argmin()
116
+
117
+ if best_iter is not None and best_iter != -1:
118
+ plt.axvline(best_iter, color=colors[fold], alpha=0.3)
119
+
120
+ if trees_in_iteration is not None:
121
+ plt.xlabel("#Trees")
122
+ else:
123
+ plt.xlabel("#Iteration")
124
+ plt.ylabel(metric_name)
125
+
126
+ # limit number of learners in the legend
127
+ # too many will raise warnings
128
+ if len(learner_names) <= 15:
129
+ plt.legend(loc="best")
130
+
131
+ plt.tight_layout(pad=2.0)
132
+ plot_path = os.path.join(model_path, LearningCurves.output_file_name)
133
+ plt.savefig(plot_path)
134
+ plt.close("all")
135
+
136
+ @staticmethod
137
+ def plot_for_ensemble(scores, metric_name, model_path):
138
+ plt.figure(figsize=(10, 7))
139
+ plt.plot(range(1, len(scores) + 1), scores, label=f"Ensemble")
140
+ plt.xlabel("#Iteration")
141
+ plt.ylabel(metric_name)
142
+ plt.legend(loc="best")
143
+ plot_path = os.path.join(model_path, LearningCurves.output_file_name)
144
+ plt.savefig(plot_path)
145
+ plt.close("all")