workbench 0.8.205__py3-none-any.whl → 0.8.213__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.
- workbench/algorithms/models/noise_model.py +388 -0
- workbench/api/endpoint.py +3 -6
- workbench/api/feature_set.py +1 -1
- workbench/api/model.py +5 -11
- workbench/cached/cached_model.py +4 -4
- workbench/core/artifacts/endpoint_core.py +63 -153
- workbench/core/artifacts/model_core.py +21 -19
- workbench/core/transforms/features_to_model/features_to_model.py +2 -2
- workbench/core/transforms/model_to_endpoint/model_to_endpoint.py +1 -1
- workbench/model_script_utils/model_script_utils.py +335 -0
- workbench/model_script_utils/pytorch_utils.py +395 -0
- workbench/model_script_utils/uq_harness.py +278 -0
- workbench/model_scripts/chemprop/chemprop.template +289 -666
- workbench/model_scripts/chemprop/generated_model_script.py +292 -669
- workbench/model_scripts/chemprop/model_script_utils.py +335 -0
- workbench/model_scripts/chemprop/requirements.txt +2 -10
- workbench/model_scripts/pytorch_model/generated_model_script.py +355 -612
- workbench/model_scripts/pytorch_model/model_script_utils.py +335 -0
- workbench/model_scripts/pytorch_model/pytorch.template +350 -607
- workbench/model_scripts/pytorch_model/pytorch_utils.py +395 -0
- workbench/model_scripts/pytorch_model/requirements.txt +1 -1
- workbench/model_scripts/pytorch_model/uq_harness.py +278 -0
- workbench/model_scripts/script_generation.py +2 -5
- workbench/model_scripts/uq_models/generated_model_script.py +65 -422
- workbench/model_scripts/xgb_model/generated_model_script.py +349 -412
- workbench/model_scripts/xgb_model/model_script_utils.py +335 -0
- workbench/model_scripts/xgb_model/uq_harness.py +278 -0
- workbench/model_scripts/xgb_model/xgb_model.template +344 -407
- workbench/scripts/training_test.py +85 -0
- workbench/utils/chemprop_utils.py +18 -656
- workbench/utils/metrics_utils.py +172 -0
- workbench/utils/model_utils.py +104 -47
- workbench/utils/pytorch_utils.py +32 -472
- workbench/utils/xgboost_local_crossfold.py +267 -0
- workbench/utils/xgboost_model_utils.py +49 -356
- workbench/web_interface/components/plugins/model_details.py +30 -68
- {workbench-0.8.205.dist-info → workbench-0.8.213.dist-info}/METADATA +5 -5
- {workbench-0.8.205.dist-info → workbench-0.8.213.dist-info}/RECORD +42 -31
- {workbench-0.8.205.dist-info → workbench-0.8.213.dist-info}/entry_points.txt +1 -0
- workbench/model_scripts/uq_models/mapie.template +0 -605
- workbench/model_scripts/uq_models/requirements.txt +0 -1
- {workbench-0.8.205.dist-info → workbench-0.8.213.dist-info}/WHEEL +0 -0
- {workbench-0.8.205.dist-info → workbench-0.8.213.dist-info}/licenses/LICENSE +0 -0
- {workbench-0.8.205.dist-info → workbench-0.8.213.dist-info}/top_level.txt +0 -0
workbench/utils/pytorch_utils.py
CHANGED
|
@@ -1,169 +1,53 @@
|
|
|
1
1
|
"""PyTorch Tabular utilities for Workbench models."""
|
|
2
2
|
|
|
3
|
-
# flake8: noqa: E402
|
|
4
3
|
import logging
|
|
5
4
|
import os
|
|
5
|
+
import tarfile
|
|
6
6
|
import tempfile
|
|
7
|
-
from pprint import pformat
|
|
8
7
|
from typing import Any, Tuple
|
|
9
8
|
|
|
10
|
-
|
|
11
|
-
# (libomp from LLVM vs libiomp from Intel). Must be set before importing numpy/sklearn/torch.
|
|
12
|
-
# See: https://github.com/scikit-learn/scikit-learn/issues/21302
|
|
13
|
-
os.environ.setdefault("OMP_NUM_THREADS", "1")
|
|
14
|
-
os.environ.setdefault("MKL_NUM_THREADS", "1")
|
|
15
|
-
|
|
16
|
-
import numpy as np
|
|
9
|
+
import awswrangler as wr
|
|
17
10
|
import pandas as pd
|
|
18
|
-
from scipy.stats import spearmanr
|
|
19
|
-
from sklearn.metrics import (
|
|
20
|
-
mean_absolute_error,
|
|
21
|
-
mean_squared_error,
|
|
22
|
-
median_absolute_error,
|
|
23
|
-
precision_recall_fscore_support,
|
|
24
|
-
r2_score,
|
|
25
|
-
roc_auc_score,
|
|
26
|
-
)
|
|
27
|
-
from sklearn.model_selection import KFold, StratifiedKFold
|
|
28
|
-
from sklearn.preprocessing import LabelEncoder
|
|
29
11
|
|
|
30
|
-
from workbench.utils.model_utils import safe_extract_tarfile
|
|
31
|
-
from workbench.utils.pandas_utils import expand_proba_column
|
|
32
12
|
from workbench.utils.aws_utils import pull_s3_data
|
|
13
|
+
from workbench.utils.metrics_utils import compute_metrics_from_predictions
|
|
33
14
|
|
|
34
15
|
log = logging.getLogger("workbench")
|
|
35
16
|
|
|
36
17
|
|
|
37
18
|
def download_and_extract_model(s3_uri: str, model_dir: str) -> None:
|
|
38
|
-
"""Download model artifact from S3
|
|
39
|
-
|
|
40
|
-
Args:
|
|
41
|
-
s3_uri: S3 URI to the model artifact (model.tar.gz)
|
|
42
|
-
model_dir: Directory to extract model artifacts to
|
|
43
|
-
"""
|
|
44
|
-
import awswrangler as wr
|
|
45
|
-
|
|
46
|
-
log.info(f"Downloading model from {s3_uri}...")
|
|
47
|
-
|
|
48
|
-
# Download to temp file
|
|
49
|
-
local_tar_path = os.path.join(model_dir, "model.tar.gz")
|
|
50
|
-
wr.s3.download(path=s3_uri, local_file=local_tar_path)
|
|
51
|
-
|
|
52
|
-
# Extract using safe extraction
|
|
53
|
-
log.info(f"Extracting to {model_dir}...")
|
|
54
|
-
safe_extract_tarfile(local_tar_path, model_dir)
|
|
55
|
-
|
|
56
|
-
# Cleanup tar file
|
|
57
|
-
os.unlink(local_tar_path)
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
def load_pytorch_model_artifacts(model_dir: str) -> Tuple[Any, dict]:
|
|
61
|
-
"""Load PyTorch Tabular model and artifacts from an extracted model directory.
|
|
19
|
+
"""Download and extract a PyTorch model artifact from S3.
|
|
62
20
|
|
|
63
21
|
Args:
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
Returns:
|
|
67
|
-
Tuple of (TabularModel, artifacts_dict).
|
|
68
|
-
artifacts_dict contains 'label_encoder' and 'category_mappings' if present.
|
|
22
|
+
s3_uri: S3 URI of the model.tar.gz artifact
|
|
23
|
+
model_dir: Local directory to extract the model to
|
|
69
24
|
"""
|
|
70
|
-
|
|
25
|
+
with tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) as tmp:
|
|
26
|
+
tmp_path = tmp.name
|
|
71
27
|
|
|
72
|
-
import joblib
|
|
73
|
-
|
|
74
|
-
# pytorch-tabular saves complex objects, use legacy loading behavior
|
|
75
|
-
os.environ["TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD"] = "1"
|
|
76
|
-
from pytorch_tabular import TabularModel
|
|
77
|
-
|
|
78
|
-
model_path = os.path.join(model_dir, "tabular_model")
|
|
79
|
-
if not os.path.exists(model_path):
|
|
80
|
-
raise FileNotFoundError(f"No tabular_model directory found in {model_dir}")
|
|
81
|
-
|
|
82
|
-
# PyTorch Tabular needs write access, so chdir to /tmp
|
|
83
|
-
original_cwd = os.getcwd()
|
|
84
28
|
try:
|
|
85
|
-
|
|
86
|
-
|
|
29
|
+
wr.s3.download(path=s3_uri, local_file=tmp_path)
|
|
30
|
+
with tarfile.open(tmp_path, "r:gz") as tar:
|
|
31
|
+
tar.extractall(model_dir)
|
|
32
|
+
log.info(f"Extracted model to {model_dir}")
|
|
87
33
|
finally:
|
|
88
|
-
os.
|
|
89
|
-
|
|
90
|
-
# Load additional artifacts
|
|
91
|
-
artifacts = {}
|
|
92
|
-
|
|
93
|
-
label_encoder_path = os.path.join(model_dir, "label_encoder.joblib")
|
|
94
|
-
if os.path.exists(label_encoder_path):
|
|
95
|
-
artifacts["label_encoder"] = joblib.load(label_encoder_path)
|
|
96
|
-
|
|
97
|
-
category_mappings_path = os.path.join(model_dir, "category_mappings.json")
|
|
98
|
-
if os.path.exists(category_mappings_path):
|
|
99
|
-
with open(category_mappings_path) as f:
|
|
100
|
-
artifacts["category_mappings"] = json.load(f)
|
|
101
|
-
|
|
102
|
-
return model, artifacts
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
def _extract_model_configs(loaded_model: Any, n_train: int) -> dict:
|
|
106
|
-
"""Extract trainer and model configs from a loaded PyTorch Tabular model.
|
|
107
|
-
|
|
108
|
-
Args:
|
|
109
|
-
loaded_model: Loaded TabularModel instance
|
|
110
|
-
n_train: Number of training samples (used for batch_size calculation)
|
|
111
|
-
|
|
112
|
-
Returns:
|
|
113
|
-
Dictionary with 'trainer' and 'model' config dictionaries
|
|
114
|
-
"""
|
|
115
|
-
config = loaded_model.config
|
|
116
|
-
|
|
117
|
-
# Trainer config - extract from loaded model, matching template defaults
|
|
118
|
-
trainer_defaults = {
|
|
119
|
-
"auto_lr_find": False,
|
|
120
|
-
"batch_size": min(128, max(32, n_train // 16)),
|
|
121
|
-
"max_epochs": 100,
|
|
122
|
-
"min_epochs": 10,
|
|
123
|
-
"early_stopping": "valid_loss",
|
|
124
|
-
"early_stopping_patience": 10,
|
|
125
|
-
"gradient_clip_val": 1.0,
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
trainer_config = {}
|
|
129
|
-
for key, default in trainer_defaults.items():
|
|
130
|
-
value = getattr(config, key, default)
|
|
131
|
-
if value == default and not hasattr(config, key):
|
|
132
|
-
log.warning(f"Trainer config '{key}' not found in loaded model, using default: {default}")
|
|
133
|
-
trainer_config[key] = value
|
|
134
|
-
|
|
135
|
-
# Model config - extract from loaded model, matching template defaults
|
|
136
|
-
model_defaults = {
|
|
137
|
-
"layers": "256-128-64",
|
|
138
|
-
"activation": "LeakyReLU",
|
|
139
|
-
"learning_rate": 1e-3,
|
|
140
|
-
"dropout": 0.3,
|
|
141
|
-
"use_batch_norm": True,
|
|
142
|
-
"initialization": "kaiming",
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
model_config = {}
|
|
146
|
-
for key, default in model_defaults.items():
|
|
147
|
-
value = getattr(config, key, default)
|
|
148
|
-
if value == default and not hasattr(config, key):
|
|
149
|
-
log.warning(f"Model config '{key}' not found in loaded model, using default: {default}")
|
|
150
|
-
model_config[key] = value
|
|
151
|
-
|
|
152
|
-
return {"trainer": trainer_config, "model": model_config}
|
|
34
|
+
if os.path.exists(tmp_path):
|
|
35
|
+
os.remove(tmp_path)
|
|
153
36
|
|
|
154
37
|
|
|
155
38
|
def pull_cv_results(workbench_model: Any) -> Tuple[pd.DataFrame, pd.DataFrame]:
|
|
156
39
|
"""Pull cross-validation results from AWS training artifacts.
|
|
157
40
|
|
|
158
|
-
This retrieves the validation predictions
|
|
159
|
-
|
|
41
|
+
This retrieves the validation predictions saved during model training and
|
|
42
|
+
computes metrics directly from them. For PyTorch models trained with
|
|
43
|
+
n_folds > 1, these are out-of-fold predictions from k-fold cross-validation.
|
|
160
44
|
|
|
161
45
|
Args:
|
|
162
46
|
workbench_model: Workbench model object
|
|
163
47
|
|
|
164
48
|
Returns:
|
|
165
49
|
Tuple of:
|
|
166
|
-
- DataFrame with
|
|
50
|
+
- DataFrame with computed metrics
|
|
167
51
|
- DataFrame with validation predictions
|
|
168
52
|
"""
|
|
169
53
|
# Get the validation predictions from S3
|
|
@@ -175,353 +59,29 @@ def pull_cv_results(workbench_model: Any) -> Tuple[pd.DataFrame, pd.DataFrame]:
|
|
|
175
59
|
|
|
176
60
|
log.info(f"Pulled {len(predictions_df)} validation predictions from {s3_path}")
|
|
177
61
|
|
|
178
|
-
#
|
|
179
|
-
|
|
62
|
+
# Compute metrics from predictions
|
|
63
|
+
target = workbench_model.target()
|
|
64
|
+
class_labels = workbench_model.class_labels()
|
|
180
65
|
|
|
181
|
-
if
|
|
182
|
-
|
|
183
|
-
metrics_df = pd.DataFrame({"error": [f"No training metrics found for {workbench_model.model_name}"]})
|
|
66
|
+
if target in predictions_df.columns and "prediction" in predictions_df.columns:
|
|
67
|
+
metrics_df = compute_metrics_from_predictions(predictions_df, target, class_labels)
|
|
184
68
|
else:
|
|
185
|
-
metrics_df = pd.DataFrame
|
|
186
|
-
log.info(f"Metrics summary:\n{metrics_df.to_string(index=False)}")
|
|
69
|
+
metrics_df = pd.DataFrame()
|
|
187
70
|
|
|
188
71
|
return metrics_df, predictions_df
|
|
189
72
|
|
|
190
73
|
|
|
191
|
-
def cross_fold_inference(
|
|
192
|
-
workbench_model: Any,
|
|
193
|
-
nfolds: int = 5,
|
|
194
|
-
) -> Tuple[pd.DataFrame, pd.DataFrame]:
|
|
195
|
-
"""Performs K-fold cross-validation for PyTorch Tabular models.
|
|
196
|
-
|
|
197
|
-
Replicates the training setup from the original model to ensure
|
|
198
|
-
cross-validation results are comparable to the deployed model.
|
|
199
|
-
|
|
200
|
-
Args:
|
|
201
|
-
workbench_model: Workbench model object
|
|
202
|
-
nfolds: Number of folds for cross-validation (default is 5)
|
|
203
|
-
|
|
204
|
-
Returns:
|
|
205
|
-
Tuple of:
|
|
206
|
-
- DataFrame with per-class metrics (and 'all' row for overall metrics)
|
|
207
|
-
- DataFrame with columns: id, target, prediction, and *_proba columns (for classifiers)
|
|
208
|
-
"""
|
|
209
|
-
import shutil
|
|
210
|
-
|
|
211
|
-
from pytorch_tabular import TabularModel
|
|
212
|
-
from pytorch_tabular.config import DataConfig, OptimizerConfig, TrainerConfig
|
|
213
|
-
from pytorch_tabular.models import CategoryEmbeddingModelConfig
|
|
214
|
-
|
|
215
|
-
from workbench.api import FeatureSet
|
|
216
|
-
|
|
217
|
-
# Create a temporary model directory
|
|
218
|
-
model_dir = tempfile.mkdtemp(prefix="pytorch_cv_")
|
|
219
|
-
log.info(f"Using model directory: {model_dir}")
|
|
220
|
-
|
|
221
|
-
try:
|
|
222
|
-
# Download and extract model artifacts to get config and artifacts
|
|
223
|
-
model_artifact_uri = workbench_model.model_data_url()
|
|
224
|
-
download_and_extract_model(model_artifact_uri, model_dir)
|
|
225
|
-
|
|
226
|
-
# Load model and artifacts
|
|
227
|
-
loaded_model, artifacts = load_pytorch_model_artifacts(model_dir)
|
|
228
|
-
category_mappings = artifacts.get("category_mappings", {})
|
|
229
|
-
|
|
230
|
-
# Determine if classifier from the loaded model's config
|
|
231
|
-
is_classifier = loaded_model.config.task == "classification"
|
|
232
|
-
|
|
233
|
-
# Use saved label encoder if available, otherwise create fresh one
|
|
234
|
-
if is_classifier:
|
|
235
|
-
label_encoder = artifacts.get("label_encoder")
|
|
236
|
-
if label_encoder is None:
|
|
237
|
-
log.warning("No saved label encoder found, creating fresh one")
|
|
238
|
-
label_encoder = LabelEncoder()
|
|
239
|
-
else:
|
|
240
|
-
label_encoder = None
|
|
241
|
-
|
|
242
|
-
# Prepare data
|
|
243
|
-
fs = FeatureSet(workbench_model.get_input())
|
|
244
|
-
df = workbench_model.training_view().pull_dataframe()
|
|
245
|
-
|
|
246
|
-
# Get columns
|
|
247
|
-
id_col = fs.id_column
|
|
248
|
-
target_col = workbench_model.target()
|
|
249
|
-
feature_cols = workbench_model.features()
|
|
250
|
-
print(f"Target column: {target_col}")
|
|
251
|
-
print(f"Feature columns: {len(feature_cols)} features")
|
|
252
|
-
|
|
253
|
-
# Convert string columns to category for PyTorch Tabular compatibility
|
|
254
|
-
for col in feature_cols:
|
|
255
|
-
if pd.api.types.is_string_dtype(df[col]):
|
|
256
|
-
if col in category_mappings:
|
|
257
|
-
df[col] = pd.Categorical(df[col], categories=category_mappings[col])
|
|
258
|
-
else:
|
|
259
|
-
df[col] = df[col].astype("category")
|
|
260
|
-
|
|
261
|
-
# Determine categorical and continuous columns
|
|
262
|
-
categorical_cols = [col for col in feature_cols if df[col].dtype.name == "category"]
|
|
263
|
-
continuous_cols = [col for col in feature_cols if col not in categorical_cols]
|
|
264
|
-
|
|
265
|
-
# Cast continuous columns to float
|
|
266
|
-
if continuous_cols:
|
|
267
|
-
df[continuous_cols] = df[continuous_cols].astype("float64")
|
|
268
|
-
|
|
269
|
-
# Drop rows with NaN features or target (PyTorch Tabular cannot handle NaN values)
|
|
270
|
-
nan_mask = df[feature_cols].isna().any(axis=1) | df[target_col].isna()
|
|
271
|
-
if nan_mask.any():
|
|
272
|
-
n_nan_rows = nan_mask.sum()
|
|
273
|
-
log.warning(
|
|
274
|
-
f"Dropping {n_nan_rows} rows ({100*n_nan_rows/len(df):.1f}%) with NaN values for cross-validation"
|
|
275
|
-
)
|
|
276
|
-
df = df[~nan_mask].reset_index(drop=True)
|
|
277
|
-
|
|
278
|
-
X = df[feature_cols]
|
|
279
|
-
y = df[target_col]
|
|
280
|
-
ids = df[id_col]
|
|
281
|
-
|
|
282
|
-
# Encode target if classifier
|
|
283
|
-
if label_encoder is not None:
|
|
284
|
-
if not hasattr(label_encoder, "classes_"):
|
|
285
|
-
label_encoder.fit(y)
|
|
286
|
-
y_encoded = label_encoder.transform(y)
|
|
287
|
-
y_for_cv = pd.Series(y_encoded, index=y.index, name=target_col)
|
|
288
|
-
else:
|
|
289
|
-
y_for_cv = y
|
|
290
|
-
|
|
291
|
-
# Extract configs from loaded model (pass approx train size for batch_size calculation)
|
|
292
|
-
n_train_approx = int(len(df) * (1 - 1 / nfolds))
|
|
293
|
-
configs = _extract_model_configs(loaded_model, n_train_approx)
|
|
294
|
-
trainer_params = configs["trainer"]
|
|
295
|
-
model_params = configs["model"]
|
|
296
|
-
|
|
297
|
-
log.info(f"Trainer config:\n{pformat(trainer_params)}")
|
|
298
|
-
log.info(f"Model config:\n{pformat(model_params)}")
|
|
299
|
-
|
|
300
|
-
# Prepare KFold
|
|
301
|
-
kfold = (StratifiedKFold if is_classifier else KFold)(n_splits=nfolds, shuffle=True, random_state=42)
|
|
302
|
-
|
|
303
|
-
# Initialize results collection
|
|
304
|
-
fold_metrics = []
|
|
305
|
-
predictions_df = pd.DataFrame({id_col: ids, target_col: y})
|
|
306
|
-
if is_classifier:
|
|
307
|
-
predictions_df["pred_proba"] = [None] * len(predictions_df)
|
|
308
|
-
|
|
309
|
-
# Perform cross-validation
|
|
310
|
-
for fold_idx, (train_idx, val_idx) in enumerate(kfold.split(X, y_for_cv), 1):
|
|
311
|
-
print(f"\n{'='*50}")
|
|
312
|
-
print(f"Fold {fold_idx}/{nfolds}")
|
|
313
|
-
print(f"{'='*50}")
|
|
314
|
-
|
|
315
|
-
# Split data
|
|
316
|
-
df_train = df.iloc[train_idx].copy()
|
|
317
|
-
df_val = df.iloc[val_idx].copy()
|
|
318
|
-
|
|
319
|
-
# Encode target for this fold
|
|
320
|
-
if is_classifier:
|
|
321
|
-
df_train[target_col] = label_encoder.transform(df_train[target_col])
|
|
322
|
-
df_val[target_col] = label_encoder.transform(df_val[target_col])
|
|
323
|
-
|
|
324
|
-
# Create configs for this fold - matching the training template exactly
|
|
325
|
-
data_config = DataConfig(
|
|
326
|
-
target=[target_col],
|
|
327
|
-
continuous_cols=continuous_cols,
|
|
328
|
-
categorical_cols=categorical_cols,
|
|
329
|
-
)
|
|
330
|
-
|
|
331
|
-
trainer_config = TrainerConfig(
|
|
332
|
-
auto_lr_find=trainer_params["auto_lr_find"],
|
|
333
|
-
batch_size=trainer_params["batch_size"],
|
|
334
|
-
max_epochs=trainer_params["max_epochs"],
|
|
335
|
-
min_epochs=trainer_params["min_epochs"],
|
|
336
|
-
early_stopping=trainer_params["early_stopping"],
|
|
337
|
-
early_stopping_patience=trainer_params["early_stopping_patience"],
|
|
338
|
-
gradient_clip_val=trainer_params["gradient_clip_val"],
|
|
339
|
-
checkpoints="valid_loss", # Save best model based on validation loss
|
|
340
|
-
accelerator="cpu",
|
|
341
|
-
)
|
|
342
|
-
|
|
343
|
-
optimizer_config = OptimizerConfig()
|
|
344
|
-
|
|
345
|
-
model_config = CategoryEmbeddingModelConfig(
|
|
346
|
-
task="classification" if is_classifier else "regression",
|
|
347
|
-
layers=model_params["layers"],
|
|
348
|
-
activation=model_params["activation"],
|
|
349
|
-
learning_rate=model_params["learning_rate"],
|
|
350
|
-
dropout=model_params["dropout"],
|
|
351
|
-
use_batch_norm=model_params["use_batch_norm"],
|
|
352
|
-
initialization=model_params["initialization"],
|
|
353
|
-
)
|
|
354
|
-
|
|
355
|
-
# Create and train fresh model
|
|
356
|
-
tabular_model = TabularModel(
|
|
357
|
-
data_config=data_config,
|
|
358
|
-
model_config=model_config,
|
|
359
|
-
optimizer_config=optimizer_config,
|
|
360
|
-
trainer_config=trainer_config,
|
|
361
|
-
)
|
|
362
|
-
|
|
363
|
-
# Change to /tmp for training (PyTorch Tabular needs write access)
|
|
364
|
-
original_cwd = os.getcwd()
|
|
365
|
-
try:
|
|
366
|
-
os.chdir("/tmp")
|
|
367
|
-
# Clean up checkpoint directory from previous fold
|
|
368
|
-
checkpoint_dir = "/tmp/saved_models"
|
|
369
|
-
if os.path.exists(checkpoint_dir):
|
|
370
|
-
shutil.rmtree(checkpoint_dir)
|
|
371
|
-
tabular_model.fit(train=df_train, validation=df_val)
|
|
372
|
-
finally:
|
|
373
|
-
os.chdir(original_cwd)
|
|
374
|
-
|
|
375
|
-
# Make predictions
|
|
376
|
-
result = tabular_model.predict(df_val[feature_cols])
|
|
377
|
-
|
|
378
|
-
# Extract predictions
|
|
379
|
-
prediction_col = f"{target_col}_prediction"
|
|
380
|
-
preds = result[prediction_col].values
|
|
381
|
-
|
|
382
|
-
# Store predictions at the correct indices
|
|
383
|
-
val_indices = df.iloc[val_idx].index
|
|
384
|
-
if is_classifier:
|
|
385
|
-
preds_decoded = label_encoder.inverse_transform(preds.astype(int))
|
|
386
|
-
predictions_df.loc[val_indices, "prediction"] = preds_decoded
|
|
387
|
-
|
|
388
|
-
# Get probabilities and store at validation indices only
|
|
389
|
-
prob_cols = sorted([col for col in result.columns if col.endswith("_probability")])
|
|
390
|
-
if prob_cols:
|
|
391
|
-
probs = result[prob_cols].values
|
|
392
|
-
for i, idx in enumerate(val_indices):
|
|
393
|
-
predictions_df.at[idx, "pred_proba"] = probs[i].tolist()
|
|
394
|
-
else:
|
|
395
|
-
predictions_df.loc[val_indices, "prediction"] = preds
|
|
396
|
-
|
|
397
|
-
# Calculate fold metrics
|
|
398
|
-
if is_classifier:
|
|
399
|
-
y_val_orig = label_encoder.inverse_transform(df_val[target_col])
|
|
400
|
-
preds_orig = preds_decoded
|
|
401
|
-
|
|
402
|
-
prec, rec, f1, _ = precision_recall_fscore_support(
|
|
403
|
-
y_val_orig, preds_orig, average="weighted", zero_division=0
|
|
404
|
-
)
|
|
405
|
-
|
|
406
|
-
prec_per_class, rec_per_class, f1_per_class, _ = precision_recall_fscore_support(
|
|
407
|
-
y_val_orig, preds_orig, average=None, zero_division=0, labels=label_encoder.classes_
|
|
408
|
-
)
|
|
409
|
-
|
|
410
|
-
y_val_encoded = df_val[target_col].values
|
|
411
|
-
roc_auc_overall = roc_auc_score(y_val_encoded, probs, multi_class="ovr", average="macro")
|
|
412
|
-
roc_auc_per_class = roc_auc_score(y_val_encoded, probs, multi_class="ovr", average=None)
|
|
413
|
-
|
|
414
|
-
fold_metrics.append(
|
|
415
|
-
{
|
|
416
|
-
"fold": fold_idx,
|
|
417
|
-
"precision": prec,
|
|
418
|
-
"recall": rec,
|
|
419
|
-
"f1": f1,
|
|
420
|
-
"roc_auc": roc_auc_overall,
|
|
421
|
-
"precision_per_class": prec_per_class,
|
|
422
|
-
"recall_per_class": rec_per_class,
|
|
423
|
-
"f1_per_class": f1_per_class,
|
|
424
|
-
"roc_auc_per_class": roc_auc_per_class,
|
|
425
|
-
}
|
|
426
|
-
)
|
|
427
|
-
|
|
428
|
-
print(f"Fold {fold_idx} - F1: {f1:.4f}, ROC-AUC: {roc_auc_overall:.4f}")
|
|
429
|
-
else:
|
|
430
|
-
y_val = df_val[target_col].values
|
|
431
|
-
spearman_corr, _ = spearmanr(y_val, preds)
|
|
432
|
-
rmse = np.sqrt(mean_squared_error(y_val, preds))
|
|
433
|
-
|
|
434
|
-
fold_metrics.append(
|
|
435
|
-
{
|
|
436
|
-
"fold": fold_idx,
|
|
437
|
-
"rmse": rmse,
|
|
438
|
-
"mae": mean_absolute_error(y_val, preds),
|
|
439
|
-
"medae": median_absolute_error(y_val, preds),
|
|
440
|
-
"r2": r2_score(y_val, preds),
|
|
441
|
-
"spearmanr": spearman_corr,
|
|
442
|
-
}
|
|
443
|
-
)
|
|
444
|
-
|
|
445
|
-
print(f"Fold {fold_idx} - RMSE: {rmse:.4f}, R2: {fold_metrics[-1]['r2']:.4f}")
|
|
446
|
-
|
|
447
|
-
# Calculate summary metrics
|
|
448
|
-
fold_df = pd.DataFrame(fold_metrics)
|
|
449
|
-
|
|
450
|
-
if is_classifier:
|
|
451
|
-
if "pred_proba" in predictions_df.columns:
|
|
452
|
-
predictions_df = expand_proba_column(predictions_df, label_encoder.classes_)
|
|
453
|
-
|
|
454
|
-
metric_rows = []
|
|
455
|
-
for idx, class_name in enumerate(label_encoder.classes_):
|
|
456
|
-
prec_scores = np.array([fold["precision_per_class"][idx] for fold in fold_metrics])
|
|
457
|
-
rec_scores = np.array([fold["recall_per_class"][idx] for fold in fold_metrics])
|
|
458
|
-
f1_scores = np.array([fold["f1_per_class"][idx] for fold in fold_metrics])
|
|
459
|
-
roc_auc_scores = np.array([fold["roc_auc_per_class"][idx] for fold in fold_metrics])
|
|
460
|
-
|
|
461
|
-
y_orig = label_encoder.inverse_transform(y_for_cv)
|
|
462
|
-
support = int((y_orig == class_name).sum())
|
|
463
|
-
|
|
464
|
-
metric_rows.append(
|
|
465
|
-
{
|
|
466
|
-
"class": class_name,
|
|
467
|
-
"precision": prec_scores.mean(),
|
|
468
|
-
"recall": rec_scores.mean(),
|
|
469
|
-
"f1": f1_scores.mean(),
|
|
470
|
-
"roc_auc": roc_auc_scores.mean(),
|
|
471
|
-
"support": support,
|
|
472
|
-
}
|
|
473
|
-
)
|
|
474
|
-
|
|
475
|
-
metric_rows.append(
|
|
476
|
-
{
|
|
477
|
-
"class": "all",
|
|
478
|
-
"precision": fold_df["precision"].mean(),
|
|
479
|
-
"recall": fold_df["recall"].mean(),
|
|
480
|
-
"f1": fold_df["f1"].mean(),
|
|
481
|
-
"roc_auc": fold_df["roc_auc"].mean(),
|
|
482
|
-
"support": len(y_for_cv),
|
|
483
|
-
}
|
|
484
|
-
)
|
|
485
|
-
|
|
486
|
-
metrics_df = pd.DataFrame(metric_rows)
|
|
487
|
-
else:
|
|
488
|
-
metrics_df = pd.DataFrame(
|
|
489
|
-
[
|
|
490
|
-
{
|
|
491
|
-
"rmse": fold_df["rmse"].mean(),
|
|
492
|
-
"mae": fold_df["mae"].mean(),
|
|
493
|
-
"medae": fold_df["medae"].mean(),
|
|
494
|
-
"r2": fold_df["r2"].mean(),
|
|
495
|
-
"spearmanr": fold_df["spearmanr"].mean(),
|
|
496
|
-
"support": len(y_for_cv),
|
|
497
|
-
}
|
|
498
|
-
]
|
|
499
|
-
)
|
|
500
|
-
|
|
501
|
-
print(f"\n{'='*50}")
|
|
502
|
-
print("Cross-Validation Summary")
|
|
503
|
-
print(f"{'='*50}")
|
|
504
|
-
print(metrics_df.to_string(index=False))
|
|
505
|
-
|
|
506
|
-
return metrics_df, predictions_df
|
|
507
|
-
|
|
508
|
-
finally:
|
|
509
|
-
log.info(f"Cleaning up model directory: {model_dir}")
|
|
510
|
-
shutil.rmtree(model_dir, ignore_errors=True)
|
|
511
|
-
|
|
512
|
-
|
|
513
74
|
if __name__ == "__main__":
|
|
75
|
+
from workbench.api import Model
|
|
514
76
|
|
|
515
|
-
#
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
# Initialize Workbench model
|
|
519
|
-
model_name = "caco2-er-reg-pytorch-test"
|
|
520
|
-
# model_name = "aqsol-pytorch-reg"
|
|
77
|
+
# Test pulling CV results
|
|
78
|
+
model_name = "aqsol-pytorch-reg"
|
|
521
79
|
print(f"Loading Workbench model: {model_name}")
|
|
522
80
|
model = Model(model_name)
|
|
523
81
|
print(f"Model Framework: {model.model_framework}")
|
|
524
82
|
|
|
525
|
-
#
|
|
526
|
-
|
|
527
|
-
|
|
83
|
+
# Pull CV results from training artifacts
|
|
84
|
+
metrics_df, predictions_df = pull_cv_results(model)
|
|
85
|
+
print(f"\nMetrics:\n{metrics_df}")
|
|
86
|
+
print(f"\nPredictions shape: {predictions_df.shape}")
|
|
87
|
+
print(f"Predictions columns: {predictions_df.columns.tolist()}")
|