mljar-supervised 1.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mljar_supervised-1.2.1.dist-info/METADATA +657 -0
- mljar_supervised-1.2.1.dist-info/RECORD +94 -0
- mljar_supervised-1.2.1.dist-info/WHEEL +5 -0
- mljar_supervised-1.2.1.dist-info/licenses/LICENSE +21 -0
- mljar_supervised-1.2.1.dist-info/top_level.txt +1 -0
- supervised/__init__.py +14 -0
- supervised/algorithms/__init__.py +0 -0
- supervised/algorithms/algorithm.py +151 -0
- supervised/algorithms/baseline.py +90 -0
- supervised/algorithms/catboost.py +436 -0
- supervised/algorithms/decision_tree.py +305 -0
- supervised/algorithms/extra_trees.py +176 -0
- supervised/algorithms/factory.py +28 -0
- supervised/algorithms/knn.py +137 -0
- supervised/algorithms/lightgbm.py +406 -0
- supervised/algorithms/linear.py +211 -0
- supervised/algorithms/nn.py +180 -0
- supervised/algorithms/random_forest.py +181 -0
- supervised/algorithms/registry.py +76 -0
- supervised/algorithms/sklearn.py +197 -0
- supervised/algorithms/xgboost.py +413 -0
- supervised/automl.py +568 -0
- supervised/base_automl.py +2542 -0
- supervised/callbacks/__init__.py +0 -0
- supervised/callbacks/callback.py +25 -0
- supervised/callbacks/callback_list.py +33 -0
- supervised/callbacks/early_stopping.py +213 -0
- supervised/callbacks/learner_time_constraint.py +47 -0
- supervised/callbacks/max_iters_constraint.py +16 -0
- supervised/callbacks/metric_logger.py +48 -0
- supervised/callbacks/terminate_on_nan.py +28 -0
- supervised/callbacks/total_time_constraint.py +79 -0
- supervised/ensemble.py +583 -0
- supervised/exceptions.py +21 -0
- supervised/fairness/__init__.py +0 -0
- supervised/fairness/metrics.py +654 -0
- supervised/fairness/optimization.py +414 -0
- supervised/fairness/plots.py +131 -0
- supervised/fairness/report.py +116 -0
- supervised/fairness/utils.py +40 -0
- supervised/model_framework.py +734 -0
- supervised/preprocessing/__init__.py +0 -0
- supervised/preprocessing/datetime_transformer.py +106 -0
- supervised/preprocessing/encoding_selector.py +30 -0
- supervised/preprocessing/exclude_missing_target.py +46 -0
- supervised/preprocessing/goldenfeatures_transformer.py +310 -0
- supervised/preprocessing/kmeans_transformer.py +115 -0
- supervised/preprocessing/label_binarizer.py +81 -0
- supervised/preprocessing/label_encoder.py +54 -0
- supervised/preprocessing/preprocessing.py +652 -0
- supervised/preprocessing/preprocessing_categorical.py +117 -0
- supervised/preprocessing/preprocessing_missing.py +97 -0
- supervised/preprocessing/preprocessing_utils.py +136 -0
- supervised/preprocessing/scale.py +92 -0
- supervised/preprocessing/text_transformer.py +73 -0
- supervised/tuner/__init__.py +0 -0
- supervised/tuner/data_info.py +64 -0
- supervised/tuner/hill_climbing.py +80 -0
- supervised/tuner/mljar_tuner.py +1501 -0
- supervised/tuner/optuna/__init__.py +0 -0
- supervised/tuner/optuna/catboost.py +148 -0
- supervised/tuner/optuna/extra_trees.py +80 -0
- supervised/tuner/optuna/knn.py +64 -0
- supervised/tuner/optuna/lightgbm.py +165 -0
- supervised/tuner/optuna/nn.py +66 -0
- supervised/tuner/optuna/random_forest.py +77 -0
- supervised/tuner/optuna/tuner.py +335 -0
- supervised/tuner/optuna/xgboost.py +130 -0
- supervised/tuner/preprocessing_tuner.py +137 -0
- supervised/tuner/random_parameters.py +22 -0
- supervised/tuner/time_controller.py +273 -0
- supervised/utils/__init__.py +11 -0
- supervised/utils/additional_metrics.py +955 -0
- supervised/utils/additional_plots.py +228 -0
- supervised/utils/automl_plots.py +368 -0
- supervised/utils/common.py +39 -0
- supervised/utils/config.py +25 -0
- supervised/utils/constants.py +4 -0
- supervised/utils/data_validation.py +48 -0
- supervised/utils/importance.py +93 -0
- supervised/utils/jsonencoder.py +33 -0
- supervised/utils/leaderboard_plots.py +137 -0
- supervised/utils/learning_curves.py +145 -0
- supervised/utils/metric.py +450 -0
- supervised/utils/report_structured.py +525 -0
- supervised/utils/shap.py +373 -0
- supervised/utils/subsample.py +17 -0
- supervised/utils/utils.py +29 -0
- supervised/validation/__init__.py +0 -0
- supervised/validation/validation_step.py +37 -0
- supervised/validation/validator_base.py +17 -0
- supervised/validation/validator_custom.py +112 -0
- supervised/validation/validator_kfold.py +153 -0
- supervised/validation/validator_split.py +143 -0
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import scikitplot as skplt
|
|
5
|
+
from matplotlib import pyplot as plt
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AdditionalPlots:
|
|
9
|
+
@staticmethod
|
|
10
|
+
def plots_binary(target, predicted_labels, predicted_probas):
|
|
11
|
+
figures = []
|
|
12
|
+
try:
|
|
13
|
+
#
|
|
14
|
+
fig = plt.figure(figsize=(10, 7))
|
|
15
|
+
ax1 = fig.add_subplot(1, 1, 1)
|
|
16
|
+
_ = skplt.metrics.plot_confusion_matrix(
|
|
17
|
+
target, predicted_labels, normalize=False, ax=ax1
|
|
18
|
+
)
|
|
19
|
+
figures += [
|
|
20
|
+
{
|
|
21
|
+
"title": "Confusion Matrix",
|
|
22
|
+
"fname": "confusion_matrix.png",
|
|
23
|
+
"figure": fig,
|
|
24
|
+
}
|
|
25
|
+
]
|
|
26
|
+
#
|
|
27
|
+
fig = plt.figure(figsize=(10, 7))
|
|
28
|
+
ax1 = fig.add_subplot(1, 1, 1)
|
|
29
|
+
_ = skplt.metrics.plot_confusion_matrix(
|
|
30
|
+
target, predicted_labels, normalize=True, ax=ax1
|
|
31
|
+
)
|
|
32
|
+
figures += [
|
|
33
|
+
{
|
|
34
|
+
"title": "Normalized Confusion Matrix",
|
|
35
|
+
"fname": "confusion_matrix_normalized.png",
|
|
36
|
+
"figure": fig,
|
|
37
|
+
}
|
|
38
|
+
]
|
|
39
|
+
#
|
|
40
|
+
fig = plt.figure(figsize=(10, 7))
|
|
41
|
+
ax1 = fig.add_subplot(1, 1, 1)
|
|
42
|
+
_ = skplt.metrics.plot_roc(target, predicted_probas, ax=ax1)
|
|
43
|
+
figures += [{"title": "ROC Curve", "fname": "roc_curve.png", "figure": fig}]
|
|
44
|
+
#
|
|
45
|
+
fig = plt.figure(figsize=(10, 7))
|
|
46
|
+
ax1 = fig.add_subplot(1, 1, 1)
|
|
47
|
+
_ = skplt.metrics.plot_ks_statistic(target, predicted_probas, ax=ax1)
|
|
48
|
+
figures += [
|
|
49
|
+
{
|
|
50
|
+
"title": "Kolmogorov-Smirnov Statistic",
|
|
51
|
+
"fname": "ks_statistic.png",
|
|
52
|
+
"figure": fig,
|
|
53
|
+
}
|
|
54
|
+
]
|
|
55
|
+
#
|
|
56
|
+
fig = plt.figure(figsize=(10, 7))
|
|
57
|
+
ax1 = fig.add_subplot(1, 1, 1)
|
|
58
|
+
_ = skplt.metrics.plot_precision_recall(target, predicted_probas, ax=ax1)
|
|
59
|
+
figures += [
|
|
60
|
+
{
|
|
61
|
+
"title": "Precision-Recall Curve",
|
|
62
|
+
"fname": "precision_recall_curve.png",
|
|
63
|
+
"figure": fig,
|
|
64
|
+
}
|
|
65
|
+
]
|
|
66
|
+
#
|
|
67
|
+
fig = plt.figure(figsize=(10, 7))
|
|
68
|
+
ax1 = fig.add_subplot(1, 1, 1)
|
|
69
|
+
# transform target if needed to be {0, 1}
|
|
70
|
+
target_uniq_values = np.unique(target)
|
|
71
|
+
target_transformed = target.values.ravel()
|
|
72
|
+
if not (0 in target_uniq_values and 1 in target_uniq_values):
|
|
73
|
+
mapping = {target_uniq_values[0]: 0, target_uniq_values[1]: 1}
|
|
74
|
+
target_transformed = target.map(mapping)
|
|
75
|
+
# create a plot
|
|
76
|
+
_ = skplt.metrics.plot_calibration_curve(
|
|
77
|
+
target_transformed, [predicted_probas], ["Classifier"], ax=ax1
|
|
78
|
+
)
|
|
79
|
+
figures += [
|
|
80
|
+
{
|
|
81
|
+
"title": "Calibration Curve",
|
|
82
|
+
"fname": "calibration_curve_curve.png",
|
|
83
|
+
"figure": fig,
|
|
84
|
+
}
|
|
85
|
+
]
|
|
86
|
+
#
|
|
87
|
+
fig = plt.figure(figsize=(10, 7))
|
|
88
|
+
ax1 = fig.add_subplot(1, 1, 1)
|
|
89
|
+
_ = skplt.metrics.plot_cumulative_gain(target, predicted_probas, ax=ax1)
|
|
90
|
+
figures += [
|
|
91
|
+
{
|
|
92
|
+
"title": "Cumulative Gains Curve",
|
|
93
|
+
"fname": "cumulative_gains_curve.png",
|
|
94
|
+
"figure": fig,
|
|
95
|
+
}
|
|
96
|
+
]
|
|
97
|
+
#
|
|
98
|
+
fig = plt.figure(figsize=(10, 7))
|
|
99
|
+
ax1 = fig.add_subplot(1, 1, 1)
|
|
100
|
+
_ = skplt.metrics.plot_lift_curve(target, predicted_probas, ax=ax1)
|
|
101
|
+
figures += [
|
|
102
|
+
{"title": "Lift Curve", "fname": "lift_curve.png", "figure": fig}
|
|
103
|
+
]
|
|
104
|
+
|
|
105
|
+
except Exception as e:
|
|
106
|
+
print(str(e))
|
|
107
|
+
|
|
108
|
+
return figures
|
|
109
|
+
|
|
110
|
+
@staticmethod
|
|
111
|
+
def plots_multiclass(target, predicted_labels, predicted_probas):
|
|
112
|
+
figures = []
|
|
113
|
+
try:
|
|
114
|
+
#
|
|
115
|
+
fig = plt.figure(figsize=(10, 7))
|
|
116
|
+
ax1 = fig.add_subplot(1, 1, 1)
|
|
117
|
+
_ = skplt.metrics.plot_confusion_matrix(
|
|
118
|
+
target, predicted_labels, normalize=False, ax=ax1
|
|
119
|
+
)
|
|
120
|
+
figures += [
|
|
121
|
+
{
|
|
122
|
+
"title": "Confusion Matrix",
|
|
123
|
+
"fname": "confusion_matrix.png",
|
|
124
|
+
"figure": fig,
|
|
125
|
+
}
|
|
126
|
+
]
|
|
127
|
+
#
|
|
128
|
+
fig = plt.figure(figsize=(10, 7))
|
|
129
|
+
ax1 = fig.add_subplot(1, 1, 1)
|
|
130
|
+
_ = skplt.metrics.plot_confusion_matrix(
|
|
131
|
+
target, predicted_labels, normalize=True, ax=ax1
|
|
132
|
+
)
|
|
133
|
+
figures += [
|
|
134
|
+
{
|
|
135
|
+
"title": "Normalized Confusion Matrix",
|
|
136
|
+
"fname": "confusion_matrix_normalized.png",
|
|
137
|
+
"figure": fig,
|
|
138
|
+
}
|
|
139
|
+
]
|
|
140
|
+
#
|
|
141
|
+
fig = plt.figure(figsize=(10, 7))
|
|
142
|
+
ax1 = fig.add_subplot(1, 1, 1)
|
|
143
|
+
_ = skplt.metrics.plot_roc(target, predicted_probas, ax=ax1)
|
|
144
|
+
figures += [{"title": "ROC Curve", "fname": "roc_curve.png", "figure": fig}]
|
|
145
|
+
#
|
|
146
|
+
fig = plt.figure(figsize=(10, 7))
|
|
147
|
+
ax1 = fig.add_subplot(1, 1, 1)
|
|
148
|
+
_ = skplt.metrics.plot_precision_recall(target, predicted_probas, ax=ax1)
|
|
149
|
+
figures += [
|
|
150
|
+
{
|
|
151
|
+
"title": "Precision Recall Curve",
|
|
152
|
+
"fname": "precision_recall_curve.png",
|
|
153
|
+
"figure": fig,
|
|
154
|
+
}
|
|
155
|
+
]
|
|
156
|
+
plt.close("all")
|
|
157
|
+
except Exception as e:
|
|
158
|
+
print(str(e))
|
|
159
|
+
|
|
160
|
+
return figures
|
|
161
|
+
|
|
162
|
+
@staticmethod
|
|
163
|
+
def plots_regression(target, predictions):
|
|
164
|
+
figures = []
|
|
165
|
+
try:
|
|
166
|
+
MAX_SAMPLES = 5000
|
|
167
|
+
fig = plt.figure(figsize=(10, 7))
|
|
168
|
+
ax1 = fig.add_subplot(1, 1, 1)
|
|
169
|
+
samples = target.shape[0]
|
|
170
|
+
if samples > MAX_SAMPLES:
|
|
171
|
+
samples = MAX_SAMPLES
|
|
172
|
+
ax1.scatter(
|
|
173
|
+
target[:samples], predictions[:samples], c="tab:blue", alpha=0.2
|
|
174
|
+
)
|
|
175
|
+
plt.xlabel("True values")
|
|
176
|
+
plt.ylabel("Predicted values")
|
|
177
|
+
plt.title(f"Target values vs Predicted values (samples={samples})")
|
|
178
|
+
plt.tight_layout(pad=5.0)
|
|
179
|
+
figures += [
|
|
180
|
+
{
|
|
181
|
+
"title": "True vs Predicted",
|
|
182
|
+
"fname": "true_vs_predicted.png",
|
|
183
|
+
"figure": fig,
|
|
184
|
+
}
|
|
185
|
+
]
|
|
186
|
+
|
|
187
|
+
# residual plot
|
|
188
|
+
fig = plt.figure(figsize=(10, 7))
|
|
189
|
+
ax1 = fig.add_subplot(1, 1, 1)
|
|
190
|
+
residuals = target[:samples].values - predictions[:samples].values
|
|
191
|
+
ax1.scatter(predictions[:samples], residuals, c="tab:blue", alpha=0.2)
|
|
192
|
+
plt.xlabel("Predicted values")
|
|
193
|
+
plt.ylabel("Residuals")
|
|
194
|
+
plt.title(f"Predicted values vs Residuals (samples={samples})")
|
|
195
|
+
plt.tight_layout(pad=5.0)
|
|
196
|
+
bb = ax1.get_position()
|
|
197
|
+
|
|
198
|
+
ax2 = fig.add_axes((bb.x0 + bb.size[0], bb.y0, 0.05, bb.size[1]))
|
|
199
|
+
ax2.set_xticklabels([])
|
|
200
|
+
ax2.set_yticklabels([])
|
|
201
|
+
ax2.hist(residuals, 50, orientation="horizontal", alpha=0.5)
|
|
202
|
+
ax2.axis("off")
|
|
203
|
+
|
|
204
|
+
figures += [
|
|
205
|
+
{
|
|
206
|
+
"title": "Predicted vs Residuals",
|
|
207
|
+
"fname": "predicted_vs_residuals.png",
|
|
208
|
+
"figure": fig,
|
|
209
|
+
}
|
|
210
|
+
]
|
|
211
|
+
plt.close("all")
|
|
212
|
+
|
|
213
|
+
except Exception as e:
|
|
214
|
+
print(str(e))
|
|
215
|
+
return figures
|
|
216
|
+
|
|
217
|
+
@staticmethod
|
|
218
|
+
def append(fout, model_path, plots):
|
|
219
|
+
try:
|
|
220
|
+
for plot in plots:
|
|
221
|
+
fname = plot.get("fname")
|
|
222
|
+
fig = plot.get("figure")
|
|
223
|
+
title = plot.get("title", "")
|
|
224
|
+
fig.savefig(os.path.join(model_path, fname))
|
|
225
|
+
fout.write(f"\n## {title}\n\n")
|
|
226
|
+
fout.write(f"\n\n")
|
|
227
|
+
except Exception as e:
|
|
228
|
+
print(str(e))
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
import traceback # For exception details
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
import scipy as sp
|
|
8
|
+
# --- Added Import ---
|
|
9
|
+
from sklearn.preprocessing import MinMaxScaler
|
|
10
|
+
# --------------------
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
from supervised.utils.config import LOG_LEVEL
|
|
14
|
+
logger.setLevel(LOG_LEVEL)
|
|
15
|
+
# Add a handler if running standalone for testing
|
|
16
|
+
if not logger.hasHandlers():
|
|
17
|
+
handler = logging.StreamHandler()
|
|
18
|
+
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
|
19
|
+
handler.setFormatter(formatter)
|
|
20
|
+
logger.addHandler(handler)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
import warnings
|
|
24
|
+
import matplotlib.pyplot as plt
|
|
25
|
+
|
|
26
|
+
warnings.filterwarnings("ignore", category=DeprecationWarning)
|
|
27
|
+
|
|
28
|
+
class AutoMLPlots:
|
|
29
|
+
# Original filename definitions
|
|
30
|
+
features_heatmap_fname = "features_heatmap.png"
|
|
31
|
+
correlation_heatmap_fname = "correlation_heatmap.png"
|
|
32
|
+
# Filename for Scaled Plot
|
|
33
|
+
features_heatmap_scaled_fname = "features_heatmap_scaled.png"
|
|
34
|
+
|
|
35
|
+
@staticmethod
|
|
36
|
+
def _plot_feature_heatmap(data_df, title, plot_path, cmap="Blues", vmin=None, vmax=None, cbar_label='Importance'):
|
|
37
|
+
""" Helper method to generate and save a feature importance heatmap. """
|
|
38
|
+
try:
|
|
39
|
+
logger.info(f"Generating heatmap: '{title}'")
|
|
40
|
+
# Adjust height dynamically based on number of features
|
|
41
|
+
plot_height = max(7, len(data_df.index) * 0.35)
|
|
42
|
+
fig, ax = plt.subplots(1, 1, figsize=(10, plot_height))
|
|
43
|
+
|
|
44
|
+
image = ax.imshow(
|
|
45
|
+
data_df,
|
|
46
|
+
interpolation="nearest",
|
|
47
|
+
cmap=plt.cm.get_cmap(cmap),
|
|
48
|
+
aspect="auto",
|
|
49
|
+
vmin=vmin, # Use provided vmin
|
|
50
|
+
vmax=vmax # Use provided vmax
|
|
51
|
+
)
|
|
52
|
+
cbar = plt.colorbar(mappable=image)
|
|
53
|
+
cbar.set_label(cbar_label) # Use provided label
|
|
54
|
+
|
|
55
|
+
x_tick_marks = np.arange(len(data_df.columns))
|
|
56
|
+
y_tick_marks = np.arange(len(data_df.index))
|
|
57
|
+
ax.set_xticks(x_tick_marks)
|
|
58
|
+
ax.set_xticklabels(data_df.columns, rotation=90)
|
|
59
|
+
ax.set_yticks(y_tick_marks)
|
|
60
|
+
ax.set_yticklabels(data_df.index)
|
|
61
|
+
ax.set_title(title)
|
|
62
|
+
|
|
63
|
+
plt.tight_layout(pad=2.0)
|
|
64
|
+
plt.savefig(plot_path)
|
|
65
|
+
logger.info(f"Saved heatmap to: {plot_path}")
|
|
66
|
+
plt.close(fig) # Close the specific figure
|
|
67
|
+
|
|
68
|
+
except Exception as e:
|
|
69
|
+
logger.error(f"Failed to generate heatmap '{title}': {e}")
|
|
70
|
+
logger.error(traceback.format_exc())
|
|
71
|
+
plt.close("all") # Close any potentially open plots on error
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@staticmethod
|
|
75
|
+
def add(results_path, models, fout):
|
|
76
|
+
"""
|
|
77
|
+
Adds plots to the report file stream. Now includes both unscaled and scaled importance.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
results_path (str): Path to results directory.
|
|
81
|
+
models (list): List of model objects.
|
|
82
|
+
fout (file object): Writable file object for the report.
|
|
83
|
+
"""
|
|
84
|
+
# Generate both feature importance plots
|
|
85
|
+
AutoMLPlots.models_feature_importance(results_path, models)
|
|
86
|
+
|
|
87
|
+
# --- Unscaled Feature Importance Section ---
|
|
88
|
+
features_plot_path = os.path.join(
|
|
89
|
+
results_path, AutoMLPlots.features_heatmap_fname # Use original filename
|
|
90
|
+
)
|
|
91
|
+
if os.path.exists(features_plot_path):
|
|
92
|
+
fout.write("\n\n### Features Importance (Original Scale)\n") # Updated title
|
|
93
|
+
fout.write(
|
|
94
|
+
f"\n\n" # Use original filename
|
|
95
|
+
)
|
|
96
|
+
else:
|
|
97
|
+
logger.warning(f"Original feature importance plot not found at: {features_plot_path}")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
# --- Scaled Feature Importance Section ---
|
|
101
|
+
features_scaled_plot_path = os.path.join(
|
|
102
|
+
results_path, AutoMLPlots.features_heatmap_scaled_fname # Use scaled filename
|
|
103
|
+
)
|
|
104
|
+
if os.path.exists(features_scaled_plot_path):
|
|
105
|
+
fout.write("\n\n### Scaled Features Importance (MinMax per Model)\n") # Title for scaled plot
|
|
106
|
+
fout.write(
|
|
107
|
+
f"\n\n" # Use scaled filename
|
|
108
|
+
)
|
|
109
|
+
else:
|
|
110
|
+
logger.warning(f"Scaled feature importance plot not found at: {features_scaled_plot_path}")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# --- Correlation Section (remains the same) ---
|
|
114
|
+
AutoMLPlots.models_correlation(results_path, models)
|
|
115
|
+
|
|
116
|
+
correlation_plot_path = os.path.join(
|
|
117
|
+
results_path, AutoMLPlots.correlation_heatmap_fname
|
|
118
|
+
)
|
|
119
|
+
if os.path.exists(correlation_plot_path):
|
|
120
|
+
fout.write("\n\n### Spearman Correlation of Models\n")
|
|
121
|
+
fout.write(
|
|
122
|
+
f"\n\n"
|
|
123
|
+
)
|
|
124
|
+
else:
|
|
125
|
+
logger.warning(f"Model correlation plot not found at: {correlation_plot_path}")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@staticmethod
|
|
129
|
+
def models_feature_importance(results_path, models):
|
|
130
|
+
"""
|
|
131
|
+
Generates and saves BOTH original and scaled feature importance heatmaps.
|
|
132
|
+
"""
|
|
133
|
+
logger.info("Starting feature importance generation (original and scaled).")
|
|
134
|
+
try:
|
|
135
|
+
# --- Data Aggregation (Common part) ---
|
|
136
|
+
model_feature_imp = {}
|
|
137
|
+
# (Same robust reading logic as before)
|
|
138
|
+
for m in models:
|
|
139
|
+
model_name = m.get_name()
|
|
140
|
+
model_path = os.path.join(results_path, model_name)
|
|
141
|
+
logger.debug(f"Processing model '{model_name}' in '{model_path}'")
|
|
142
|
+
if not os.path.isdir(model_path):
|
|
143
|
+
logger.warning(f"Directory not found for model '{model_name}'. Skipping.")
|
|
144
|
+
continue
|
|
145
|
+
try:
|
|
146
|
+
all_files = os.listdir(model_path)
|
|
147
|
+
except OSError as e:
|
|
148
|
+
logger.error(f"Cannot list directory {model_path}: {e}. Skipping model '{model_name}'.")
|
|
149
|
+
continue
|
|
150
|
+
imp_data = [f for f in all_files if "_importance.csv" in f and "shap" not in f]
|
|
151
|
+
if not imp_data:
|
|
152
|
+
logger.warning(f"No suitable importance files found for model '{model_name}'. Skipping.")
|
|
153
|
+
continue
|
|
154
|
+
df_all = []
|
|
155
|
+
for fname in imp_data:
|
|
156
|
+
file_path = os.path.join(model_path, fname)
|
|
157
|
+
try:
|
|
158
|
+
df = pd.read_csv(file_path, index_col=0)
|
|
159
|
+
numeric_df = df.select_dtypes(include=np.number)
|
|
160
|
+
if numeric_df.empty or numeric_df.isnull().all().all():
|
|
161
|
+
logger.warning(f"File {fname} (model '{model_name}') contains no valid numeric data. Skipping.")
|
|
162
|
+
continue
|
|
163
|
+
df_all.append(df)
|
|
164
|
+
except Exception as read_e:
|
|
165
|
+
logger.error(f"Error reading/processing file {fname} (model '{model_name}'): {read_e}. Skipping.")
|
|
166
|
+
continue
|
|
167
|
+
if not df_all:
|
|
168
|
+
logger.warning(f"No valid importance dataframes read for model '{model_name}'. Skipping.")
|
|
169
|
+
continue
|
|
170
|
+
try:
|
|
171
|
+
df_concat = pd.concat(df_all, axis=1, join='outer')
|
|
172
|
+
numeric_df_concat = df_concat.select_dtypes(include=np.number)
|
|
173
|
+
if not numeric_df_concat.empty:
|
|
174
|
+
model_feature_imp[model_name] = numeric_df_concat.mean(axis=1).fillna(0)
|
|
175
|
+
else:
|
|
176
|
+
logger.warning(f"No numeric data after concat for model '{model_name}'. Skipping.")
|
|
177
|
+
except Exception as concat_e:
|
|
178
|
+
logger.error(f"Error aggregating importance for model '{model_name}': {concat_e}")
|
|
179
|
+
continue
|
|
180
|
+
|
|
181
|
+
logger.info(f"Collected feature importance for {len(model_feature_imp)} models.")
|
|
182
|
+
if len(model_feature_imp) < 2:
|
|
183
|
+
logger.warning("Feature importance heatmaps require at least 2 models with data. Skipping plot generation.")
|
|
184
|
+
return
|
|
185
|
+
|
|
186
|
+
mfi = pd.concat(model_feature_imp, axis=1, join='outer').fillna(0)
|
|
187
|
+
logger.debug(f"Combined importance DataFrame shape: {mfi.shape}")
|
|
188
|
+
|
|
189
|
+
# --- Sorting & Top N (Common part) ---
|
|
190
|
+
mfi["m"] = mfi.mean(axis=1)
|
|
191
|
+
mfi_sorted = mfi.sort_values(by="m", ascending=False)
|
|
192
|
+
mfi_sorted = mfi_sorted.drop("m", axis=1) # Keep original mfi for potential later use if needed
|
|
193
|
+
|
|
194
|
+
num_features_original = mfi_sorted.shape[0]
|
|
195
|
+
mfi_plot_data = mfi_sorted # Default to using all sorted features
|
|
196
|
+
title_suffix = "Feature Importance"
|
|
197
|
+
scaled_title_suffix = "Scaled Feature Importance (MinMax per model)"
|
|
198
|
+
|
|
199
|
+
if num_features_original > 25:
|
|
200
|
+
mfi_plot_data = mfi_sorted.head(25)
|
|
201
|
+
title_suffix = f"Top-25 ({num_features_original} total) Feature Importance"
|
|
202
|
+
scaled_title_suffix = f"Top-25 ({num_features_original} total) Scaled Feature Importance (MinMax per model)"
|
|
203
|
+
logger.info(f"Selecting top 25 features out of {num_features_original} for plotting.")
|
|
204
|
+
else:
|
|
205
|
+
logger.info(f"Using all {num_features_original} features for plotting.")
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
# --- Plotting Unscaled Version ---
|
|
209
|
+
unscaled_plot_path = os.path.join(results_path, AutoMLPlots.features_heatmap_fname)
|
|
210
|
+
AutoMLPlots._plot_feature_heatmap(
|
|
211
|
+
data_df=mfi_plot_data,
|
|
212
|
+
title=title_suffix + " (Original Scale)",
|
|
213
|
+
plot_path=unscaled_plot_path,
|
|
214
|
+
cbar_label='Importance'
|
|
215
|
+
# vmin/vmax are auto-detected by default
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
# --- Scaling Data ---
|
|
219
|
+
logger.debug("Applying Min-Max scaling for the second plot.")
|
|
220
|
+
scaler = MinMaxScaler()
|
|
221
|
+
mfi_scaled_array = scaler.fit_transform(mfi_plot_data) # Scale the potentially filtered data
|
|
222
|
+
mfi_scaled = pd.DataFrame(mfi_scaled_array, index=mfi_plot_data.index, columns=mfi_plot_data.columns)
|
|
223
|
+
|
|
224
|
+
# --- Plotting Scaled Version ---
|
|
225
|
+
scaled_plot_path = os.path.join(results_path, AutoMLPlots.features_heatmap_scaled_fname)
|
|
226
|
+
AutoMLPlots._plot_feature_heatmap(
|
|
227
|
+
data_df=mfi_scaled,
|
|
228
|
+
title=scaled_title_suffix,
|
|
229
|
+
plot_path=scaled_plot_path,
|
|
230
|
+
vmin=0, # Explicit range for scaled data
|
|
231
|
+
vmax=1,
|
|
232
|
+
cbar_label='Scaled Importance (MinMax per model)'
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
logger.info("Finished generating feature importance plots.")
|
|
236
|
+
|
|
237
|
+
except Exception as e:
|
|
238
|
+
logger.error(f"An error occurred during feature importance processing: {e}")
|
|
239
|
+
logger.error(traceback.format_exc())
|
|
240
|
+
plt.close("all") # Ensure plots are closed on unexpected error
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
# --- correlation and models_correlation methods remain the same as in the previous version ---
|
|
244
|
+
# (Include the improved versions from the previous response here)
|
|
245
|
+
@staticmethod
|
|
246
|
+
def correlation(oof1, oof2):
|
|
247
|
+
""" Calculates mean Spearman correlation between prediction columns """
|
|
248
|
+
# (Original code - unchanged)
|
|
249
|
+
cols = [c for c in oof1.columns if "prediction" in c]
|
|
250
|
+
# Check if prediction columns exist
|
|
251
|
+
if not cols or not all(c in oof2.columns for c in cols):
|
|
252
|
+
logger.warning("Prediction columns mismatch or not found for correlation calculation.")
|
|
253
|
+
return np.nan # Return NaN if predictions can't be compared
|
|
254
|
+
|
|
255
|
+
with warnings.catch_warnings():
|
|
256
|
+
warnings.simplefilter(action="ignore")
|
|
257
|
+
v = []
|
|
258
|
+
for c in cols:
|
|
259
|
+
try:
|
|
260
|
+
# Calculate Spearman correlation, ignore p-value
|
|
261
|
+
corr_val, _ = sp.stats.spearmanr(oof1[c], oof2[c])
|
|
262
|
+
# Handle potential NaN result from spearmanr if input variance is zero
|
|
263
|
+
if not np.isnan(corr_val):
|
|
264
|
+
v.append(corr_val)
|
|
265
|
+
else:
|
|
266
|
+
logger.debug(f"NaN result from spearmanr for column {c}. Skipping.")
|
|
267
|
+
except Exception as corr_e:
|
|
268
|
+
logger.warning(f"Could not calculate Spearman correlation for column {c}: {corr_e}")
|
|
269
|
+
|
|
270
|
+
# Return mean correlation, or NaN if no valid correlations were calculated
|
|
271
|
+
return np.mean(v) if v else np.nan
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
@staticmethod
|
|
275
|
+
def models_correlation(results_path, models):
|
|
276
|
+
""" Generates and saves model prediction correlation heatmap """
|
|
277
|
+
# (Original code - minor logging/error handling improvements)
|
|
278
|
+
logger.info("Starting model correlation heatmap generation.")
|
|
279
|
+
try:
|
|
280
|
+
if len(models) < 2:
|
|
281
|
+
logger.warning("Model correlation heatmap requires at least 2 models. Skipping.")
|
|
282
|
+
return
|
|
283
|
+
|
|
284
|
+
names = []
|
|
285
|
+
oofs = []
|
|
286
|
+
valid_models_indices = [] # Keep track of models with valid OOF data
|
|
287
|
+
|
|
288
|
+
for i, m in enumerate(models):
|
|
289
|
+
try:
|
|
290
|
+
oof_data = m.get_out_of_folds()
|
|
291
|
+
# Basic validation of OOF data
|
|
292
|
+
if oof_data is None or oof_data.empty or not any("prediction" in c for c in oof_data.columns):
|
|
293
|
+
logger.warning(f"Model '{m.get_name()}' has invalid or missing out-of-folds prediction data. Excluding from correlation.")
|
|
294
|
+
continue
|
|
295
|
+
|
|
296
|
+
names.append(m.get_name())
|
|
297
|
+
oofs.append(oof_data)
|
|
298
|
+
valid_models_indices.append(i) # Store original index if valid
|
|
299
|
+
logger.debug(f"Got valid OOF data for model '{m.get_name()}'.")
|
|
300
|
+
|
|
301
|
+
except AttributeError:
|
|
302
|
+
logger.warning(f"Model '{m.get_name()}' seems to be missing 'get_out_of_folds' method or it failed. Excluding from correlation.")
|
|
303
|
+
continue
|
|
304
|
+
except Exception as oof_e:
|
|
305
|
+
logger.warning(f"Failed to get OOF data for model '{m.get_name()}': {oof_e}. Excluding from correlation.")
|
|
306
|
+
continue
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
num_valid_models = len(names)
|
|
310
|
+
if num_valid_models < 2:
|
|
311
|
+
logger.warning(f"Fewer than 2 models ({num_valid_models}) have valid OOF data for correlation. Skipping plot generation.")
|
|
312
|
+
return
|
|
313
|
+
|
|
314
|
+
logger.info(f"Calculating correlations for {num_valid_models} models.")
|
|
315
|
+
corrs = np.ones((num_valid_models, num_valid_models)) # Use num_valid_models dimension
|
|
316
|
+
for i in range(num_valid_models):
|
|
317
|
+
for j in range(i + 1, num_valid_models):
|
|
318
|
+
correlation_value = AutoMLPlots.correlation(oofs[i], oofs[j])
|
|
319
|
+
# Fill with NaN if correlation calculation failed
|
|
320
|
+
corrs[i, j] = corrs[j, i] = correlation_value if not np.isnan(correlation_value) else np.nan
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
# Check if all correlations are NaN
|
|
324
|
+
if np.isnan(corrs[np.triu_indices(num_valid_models, k=1)]).all():
|
|
325
|
+
logger.warning("All pairwise model correlations resulted in NaN. Cannot generate heatmap.")
|
|
326
|
+
return
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
logger.info("Generating model correlation heatmap.")
|
|
330
|
+
figsize = (15, 15) if num_valid_models > 15 else (10, 10) # Adjusted threshold
|
|
331
|
+
fig, ax = plt.subplots(1, 1, figsize=figsize)
|
|
332
|
+
|
|
333
|
+
image = ax.imshow(
|
|
334
|
+
corrs,
|
|
335
|
+
interpolation="nearest",
|
|
336
|
+
cmap=plt.cm.get_cmap("Blues"),
|
|
337
|
+
aspect="auto",
|
|
338
|
+
vmin=np.nanmin(corrs), # Use nanmin/nanmax to handle potential NaNs
|
|
339
|
+
vmax=np.nanmax(corrs)
|
|
340
|
+
)
|
|
341
|
+
plt.colorbar(mappable=image)
|
|
342
|
+
|
|
343
|
+
x_tick_marks = np.arange(num_valid_models)
|
|
344
|
+
y_tick_marks = np.arange(num_valid_models)
|
|
345
|
+
ax.set_xticks(x_tick_marks)
|
|
346
|
+
ax.set_xticklabels(names, rotation=90)
|
|
347
|
+
ax.set_yticks(y_tick_marks)
|
|
348
|
+
ax.set_yticklabels(names)
|
|
349
|
+
ax.set_title("Spearman Correlation of Models' OOF Predictions") # Slightly more descriptive title
|
|
350
|
+
|
|
351
|
+
plt.tight_layout(pad=2.0)
|
|
352
|
+
|
|
353
|
+
# --- Saving the Plot ---
|
|
354
|
+
os.makedirs(results_path, exist_ok=True) # Ensure directory exists
|
|
355
|
+
plot_path = os.path.join(
|
|
356
|
+
results_path, AutoMLPlots.correlation_heatmap_fname
|
|
357
|
+
)
|
|
358
|
+
plt.savefig(plot_path)
|
|
359
|
+
logger.info(f"Saved model correlation heatmap to: {plot_path}")
|
|
360
|
+
plt.close("all") # Close plot to free memory
|
|
361
|
+
|
|
362
|
+
except Exception as e:
|
|
363
|
+
# Log the exception with traceback
|
|
364
|
+
logger.error(f"An error occurred during model correlation plotting: {e}")
|
|
365
|
+
logger.error(traceback.format_exc())
|
|
366
|
+
# Ensure plot is closed if error occurred during saving/closing
|
|
367
|
+
plt.close("all")
|
|
368
|
+
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def construct_learner_name(fold, repeat, repeats):
|
|
5
|
+
repeat_str = f"_repeat_{repeat}" if repeats > 1 else ""
|
|
6
|
+
return f"learner_fold_{fold}{repeat_str}"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def learner_name_to_fold_repeat(name):
|
|
10
|
+
fold, repeat = None, None
|
|
11
|
+
arr = name.split("_")
|
|
12
|
+
fold = int(arr[2])
|
|
13
|
+
if "repeat" in name:
|
|
14
|
+
repeat = int(arr[4])
|
|
15
|
+
return fold, repeat
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def get_fold_repeat_cnt(model_path):
|
|
19
|
+
training_logs = [f for f in os.listdir(model_path) if "_training.log" in f]
|
|
20
|
+
fold_cnt, repeat_cnt = 0, 0
|
|
21
|
+
for fname in training_logs:
|
|
22
|
+
fold, repeat = learner_name_to_fold_repeat(fname)
|
|
23
|
+
if fold is not None:
|
|
24
|
+
fold_cnt = max(fold_cnt, fold)
|
|
25
|
+
if repeat is not None:
|
|
26
|
+
repeat_cnt = max(repeat_cnt, repeat)
|
|
27
|
+
|
|
28
|
+
fold_cnt += 1 # counting from 0
|
|
29
|
+
repeat_cnt += 1
|
|
30
|
+
|
|
31
|
+
return fold_cnt, repeat_cnt
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def get_learners_names(model_path):
|
|
35
|
+
postfix = "_training.log"
|
|
36
|
+
learner_names = [
|
|
37
|
+
f.repleace(postfix, "") for f in os.listdir(model_path) if postfix in f
|
|
38
|
+
]
|
|
39
|
+
return learner_names
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
LOG_LEVEL = logging.ERROR
|
|
4
|
+
|
|
5
|
+
# from guppy import hpy
|
|
6
|
+
# from pympler import summary
|
|
7
|
+
# from pympler import muppy
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def mem(msg=""):
|
|
14
|
+
"""Memory usage in MB"""
|
|
15
|
+
|
|
16
|
+
time.sleep(5)
|
|
17
|
+
|
|
18
|
+
with open("/proc/self/status") as f:
|
|
19
|
+
memusage = f.read().split("VmRSS:")[1].split("\n")[0][:-3]
|
|
20
|
+
|
|
21
|
+
print(msg, "- memory:", np.round(float(memusage.strip()) / 1024.0), "MB")
|
|
22
|
+
|
|
23
|
+
# all_objects = muppy.get_objects()
|
|
24
|
+
# sum1 = summary.summarize(all_objects)
|
|
25
|
+
# summary.print_(sum1)
|