Spaces:
Runtime error
Runtime error
File size: 32,234 Bytes
0ad96be | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 | import argparse
import json
import os
import warnings
from datetime import datetime
from pathlib import Path
from time import perf_counter
os.environ.setdefault("LOKY_MAX_CPU_COUNT", "1")
import joblib
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import (
HistGradientBoostingClassifier,
HistGradientBoostingRegressor,
RandomForestClassifier,
RandomForestRegressor,
)
from sklearn.impute import SimpleImputer
from sklearn.inspection import permutation_importance
from sklearn.linear_model import LogisticRegression, Ridge
from sklearn.metrics import (
accuracy_score,
average_precision_score,
classification_report,
confusion_matrix,
f1_score,
log_loss,
mean_absolute_error,
mean_squared_error,
r2_score,
roc_auc_score,
)
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.svm import SVC, SVR
from tqdm import tqdm
from nn.torch_ft_transformer import (
TorchFTTransformerClassifier,
TorchFTTransformerRegressor,
)
from nn.torch_mlp import TorchMLPClassifier, TorchMLPRegressor
from preprocessing import (
CommaSeparatedMultiLabelBinarizer,
UnixTimestampTransformer,
infer_task_type,
to_bool_if_binary,
)
from utils import vis
from utils.logger import logger
warnings.filterwarnings("ignore", category=UserWarning)
def load_json(path: str) -> dict:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def write_progress(path: Path | None, payload: dict) -> None:
if path is None:
return
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = path.with_suffix(path.suffix + ".tmp")
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(payload, f, indent=2)
os.replace(tmp_path, path)
def build_preprocessor(
input_features, cols_string, cols_date, cols_multi, use_scaler=True
):
transformers = []
numeric_cols = [
c for c in input_features if c not in cols_string + cols_date + cols_multi
]
if numeric_cols:
steps = [("imputer", SimpleImputer(strategy="median"))]
if use_scaler:
steps.append(("scaler", StandardScaler()))
transformers.append(("numeric", Pipeline(steps), numeric_cols))
if cols_string:
steps = [
("imputer", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore", sparse_output=False)),
]
transformers.append(("categorical", Pipeline(steps), cols_string))
if cols_date:
steps = [
("unix_ts", UnixTimestampTransformer()),
("imputer", SimpleImputer(strategy="median")),
]
if use_scaler:
steps.append(("scaler", StandardScaler()))
transformers.append(("date", Pipeline(steps), cols_date))
if cols_multi:
steps = [
("imputer", SimpleImputer(strategy="constant", fill_value="")),
("multilabel", CommaSeparatedMultiLabelBinarizer()),
]
transformers.append(("multi", Pipeline(steps), cols_multi))
return ColumnTransformer(transformers=transformers, remainder="drop")
def get_model(model_name: str, task_type: str, params: dict):
registry = {
"binary": {
"hgb": HistGradientBoostingClassifier,
"rf": RandomForestClassifier,
"lr": LogisticRegression,
"svc": SVC,
"torch_mlp": TorchMLPClassifier,
"torch_ft_transformer": TorchFTTransformerClassifier,
},
"categorical": {
"hgb": HistGradientBoostingClassifier,
"rf": RandomForestClassifier,
"lr": LogisticRegression,
"svc": SVC,
"torch_mlp": TorchMLPClassifier,
"torch_ft_transformer": TorchFTTransformerClassifier,
},
"continuous": {
"hgb": HistGradientBoostingRegressor,
"rf": RandomForestRegressor,
"ridge": Ridge,
"svc": SVR,
"torch_mlp": TorchMLPRegressor,
"torch_ft_transformer": TorchFTTransformerRegressor,
},
}
if model_name not in registry[task_type]:
raise ValueError(f"Model '{model_name}' not valid for task '{task_type}'.")
return registry[task_type][model_name](**params)
def balanced_weights_from_y(y_series):
y_np = np.asarray(y_series)
classes, counts = np.unique(y_np, return_counts=True)
n_samples = len(y_np)
n_classes = len(classes)
return {
cls: float(n_samples / (n_classes * count))
for cls, count in zip(classes, counts, strict=False)
}
def sample_weight_from_y(y_series):
class_weights = balanced_weights_from_y(y_series)
y_np = np.asarray(y_series)
return np.asarray([class_weights[v] for v in y_np], dtype=float)
def normalize_class_weight_keys(class_weight: dict, task_type: str):
normalized = {}
for key, value in class_weight.items():
new_key = key
if task_type == "binary":
if isinstance(key, str):
lk = key.strip().lower()
if lk in {"true", "1"}:
new_key = True
elif lk in {"false", "0"}:
new_key = False
normalized[new_key] = value
return normalized
def apply_imbalance_strategy(model_name: str, task_type: str, params: dict, y_train):
new_params = dict(params)
if "class_weight" in new_params and isinstance(new_params["class_weight"], dict):
new_params["class_weight"] = normalize_class_weight_keys(
new_params["class_weight"], task_type
)
if task_type not in {"binary", "categorical"}:
return new_params
weights = balanced_weights_from_y(y_train)
if not weights:
return new_params
if model_name in {"rf", "lr", "svc"} and "class_weight" not in new_params:
new_params["class_weight"] = {
k.item() if hasattr(k, "item") else k: v for k, v in weights.items()
}
if model_name in {"torch_mlp", "torch_ft_transformer"}:
classes_sorted = sorted(weights.keys())
if task_type == "binary" and "pos_weight" not in new_params:
neg_label, pos_label = classes_sorted[0], classes_sorted[-1]
neg_w = weights[neg_label]
pos_w = weights[pos_label]
if neg_w > 0:
new_params["pos_weight"] = float(pos_w / neg_w)
elif task_type == "categorical" and "class_weights" not in new_params:
new_params["class_weights"] = [float(weights[c]) for c in classes_sorted]
return new_params
def binary_confusion_metrics(y_true_bin, y_pred_bin, beta=2.0, fn_cost=5.0, fp_cost=1.0):
tn, fp, fn, tp = confusion_matrix(y_true_bin, y_pred_bin, labels=[0, 1]).ravel()
recall = tp / (tp + fn) if (tp + fn) else 0.0
precision = tp / (tp + fp) if (tp + fp) else 0.0
specificity = tn / (tn + fp) if (tn + fp) else 0.0
npv = tn / (tn + fn) if (tn + fn) else 0.0
beta2 = beta * beta
f_beta = (
(1 + beta2) * precision * recall / (beta2 * precision + recall)
if (precision + recall)
else 0.0
)
expected_cost = fn_cost * fn + fp_cost * fp
return {
"tn": int(tn),
"fp": int(fp),
"fn": int(fn),
"tp": int(tp),
"recall": float(recall),
"precision": float(precision),
"specificity": float(specificity),
"npv": float(npv),
"f_beta": float(f_beta),
"expected_cost": float(expected_cost),
}
def select_binary_threshold(
y_true_bin, y_prob_pos, min_recall=0.9, beta=2.0, fn_cost=5.0, fp_cost=1.0
):
thresholds = np.linspace(0.01, 0.99, 199)
candidates = []
for thr in thresholds:
y_pred_bin = (y_prob_pos >= thr).astype(int)
metric = binary_confusion_metrics(
y_true_bin, y_pred_bin, beta=beta, fn_cost=fn_cost, fp_cost=fp_cost
)
metric["threshold"] = float(thr)
candidates.append(metric)
feasible = [c for c in candidates if c["recall"] >= min_recall]
if feasible:
best = max(
feasible,
key=lambda c: (c["precision"], c["f_beta"], -c["expected_cost"]),
)
best["meets_recall_constraint"] = True
return best
best = max(
candidates,
key=lambda c: (c["recall"], c["precision"], c["f_beta"], -c["expected_cost"]),
)
best["meets_recall_constraint"] = False
return best
def evaluate_and_save(
model_name: str,
pipeline: Pipeline,
X_test,
y_test,
task_type: str,
out_dir: Path,
feature_importance: bool = False,
decision_threshold: float | None = None,
threshold_selection: dict | None = None,
f_beta: float = 2.0,
fn_cost: float = 5.0,
fp_cost: float = 1.0,
):
metrics = {}
plot_data = {}
model_dir = out_dir / model_name
model_dir.mkdir(parents=True, exist_ok=True)
y_pred = pipeline.predict(X_test)
y_prob = (
pipeline.predict_proba(X_test) if hasattr(pipeline, "predict_proba") else None
)
if task_type == "continuous":
metrics["r2"] = float(r2_score(y_test, y_pred))
metrics["rmse"] = float(np.sqrt(mean_squared_error(y_test, y_pred)))
metrics["mae"] = float(mean_absolute_error(y_test, y_pred))
vis.plot_regression_scatter(
y_test,
y_pred,
f"Actual vs Predicted - {model_name.upper()}",
model_dir / "actual_vs_predicted.png",
)
else:
classes = getattr(pipeline.named_steps["model"], "classes_", np.unique(y_test))
if task_type == "binary" and y_prob is not None:
pos_idx = 1 if y_prob.shape[1] > 1 else 0
neg_idx = 1 - pos_idx if len(classes) > 1 else 0
y_prob_pos = y_prob[:, pos_idx]
threshold = 0.5 if decision_threshold is None else float(decision_threshold)
pos_label = classes[pos_idx]
neg_label = classes[neg_idx]
y_pred_bin = (y_prob_pos >= threshold).astype(int)
y_pred = np.where(y_pred_bin == 1, pos_label, neg_label)
y_true_bin = (y_test == pos_label).astype(int).to_numpy()
metrics["selected_threshold"] = float(threshold)
metrics["roc_auc"] = float(roc_auc_score(y_true_bin, y_prob_pos))
metrics["average_precision"] = float(
average_precision_score(y_true_bin, y_prob_pos)
)
metrics["log_loss"] = float(log_loss(y_true_bin, y_prob_pos))
metrics.update(
binary_confusion_metrics(
y_true_bin,
y_pred_bin,
beta=f_beta,
fn_cost=fn_cost,
fp_cost=fp_cost,
)
)
if threshold_selection:
metrics["threshold_selection"] = threshold_selection
vis.plot_roc_curve(
y_true_bin,
y_prob_pos,
f"ROC Curve - {model_name.upper()}",
model_dir / "roc_curve.png",
)
vis.plot_pr_curve(
y_true_bin,
y_prob_pos,
f"Precision-Recall Curve - {model_name.upper()}",
model_dir / "pr_curve.png",
)
plot_data["y_true_bin"] = y_true_bin
plot_data["y_prob_pos"] = y_prob_pos
policy = {
"threshold": float(threshold),
"f_beta": float(f_beta),
"fn_cost": float(fn_cost),
"fp_cost": float(fp_cost),
}
if threshold_selection:
policy["selection_on_validation"] = threshold_selection
with open(model_dir / "decision_policy.json", "w", encoding="utf-8") as f:
json.dump(policy, f, indent=4)
elif task_type == "categorical" and y_prob is not None:
metrics["roc_auc_ovr"] = float(roc_auc_score(y_test, y_prob, multi_class="ovr"))
metrics["log_loss"] = float(log_loss(y_test, y_prob))
metrics["f1_macro"] = float(f1_score(y_test, y_pred, average="macro"))
metrics["accuracy"] = float(accuracy_score(y_test, y_pred))
metrics["confusion_matrix"] = confusion_matrix(y_test, y_pred).tolist()
metrics["classification_report"] = classification_report(
y_test, y_pred, output_dict=True, zero_division=0
)
vis.plot_confusion_matrix(
y_test,
y_pred,
classes,
f"Confusion Matrix - {model_name.upper()}",
model_dir / "confusion_matrix.png",
)
joblib.dump(pipeline, model_dir / "pipeline.joblib")
with open(model_dir / "metrics.json", "w") as f:
json.dump(metrics, f, indent=4)
if feature_importance:
try:
scoring = "accuracy"
if (
task_type == "binary"
and hasattr(pipeline, "predict_proba")
and model_name not in {"torch_mlp", "torch_ft_transformer"}
):
scoring = "roc_auc"
elif task_type == "continuous":
scoring = "r2"
pi_results = permutation_importance(
pipeline,
X_test,
y_test,
scoring=scoring,
n_repeats=5,
random_state=42,
n_jobs=1,
)
features = X_test.columns.tolist()
importances_mean = pi_results.importances_mean
importances_std = pi_results.importances_std
sorted_idx = importances_mean.argsort()
sorted_features = [features[i] for i in sorted_idx]
sorted_importances = importances_mean[sorted_idx]
sorted_std = importances_std[sorted_idx]
fi_df = pd.DataFrame(
{
"Feature": sorted_features[::-1],
"Importance": sorted_importances[::-1],
"Std": sorted_std[::-1],
}
)
fi_df.to_csv(model_dir / "feature_importance.csv", index=False)
vis.plot_feature_importance(
sorted_features,
sorted_importances,
sorted_std,
f"Feature Importance ({model_name.upper()})",
model_dir / "feature_importance.png",
)
except Exception as e:
from utils.logger import logger
logger.warning(
f"Could not compute feature importance for {model_name}: {e}"
)
return metrics, plot_data
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--target", required=True, help="Output column name to predict."
)
parser.add_argument(
"--data_config", default="data_config.json", help="Data configuration"
)
parser.add_argument(
"--model_config", default="parameters.json", help="Model hyperparameters"
)
parser.add_argument(
"--output_folder", default="benchmark_output", help="Output directory"
)
parser.add_argument(
"--models",
default=None,
help="Comma-separated list of models to train (e.g., hgb,rf,torch_mlp). If empty, trains all.",
)
parser.add_argument(
"--split_strategy",
choices=["random", "predefined", "temporal"],
default="random",
help="Strategy to split the train and test sets.",
)
parser.add_argument(
"--test_size",
type=float,
default=0.2,
help="Proportion of the dataset to include in the test split (for random and temporal).",
)
parser.add_argument(
"--split_column",
default="Split",
help="Column name used for predefined split (e.g., 'Train' and 'Test').",
)
parser.add_argument(
"--date_column",
default="Date of surgery",
help="Column name used for temporal split sorting.",
)
parser.add_argument(
"--feature_importance",
action="store_true",
help="Whether to compute and visualize permutation feature importance.",
)
parser.add_argument(
"--threshold_val_size",
type=float,
default=0.2,
help="Validation fraction carved from train set to choose binary threshold.",
)
parser.add_argument(
"--min_recall",
type=float,
default=0.9,
help="Minimum target recall for binary threshold selection.",
)
parser.add_argument(
"--f_beta",
type=float,
default=2.0,
help="Beta used in F-beta for binary operating-point selection.",
)
parser.add_argument(
"--fn_cost",
type=float,
default=5.0,
help="Relative cost of false negatives for threshold selection.",
)
parser.add_argument(
"--fp_cost",
type=float,
default=1.0,
help="Relative cost of false positives for threshold selection.",
)
parser.add_argument(
"--progress_path",
default=None,
help="Optional JSON file path used to report training progress.",
)
args = parser.parse_args()
out_dir = Path(args.output_folder)
out_dir.mkdir(parents=True, exist_ok=True)
progress_path = Path(args.progress_path) if args.progress_path else None
data_config = load_json(args.data_config)
models_config = load_json(args.model_config)
if args.models:
selected_models = [m.strip() for m in args.models.split(",") if m.strip()]
models_to_train = {
k: v
for k, v in models_config.items()
if k in selected_models and isinstance(v, dict)
}
else:
models_to_train = {k: v for k, v in models_config.items() if isinstance(v, dict)}
write_progress(
progress_path,
{
"status": "running",
"target": args.target,
"total_models": len(models_to_train),
"completed_models": 0,
"current_model": None,
"current_step": "Loading data...",
"message": "Loading dataset and preparing split...",
"updated_at": datetime.utcnow().isoformat(timespec="seconds") + "Z",
},
)
input_file_path = data_config["input_file"]
logger.info(f"Loading data from {input_file_path}...")
if str(input_file_path).endswith((".xlsx", ".xls")):
df = pd.read_excel(input_file_path)
else:
try:
df = pd.read_csv(input_file_path, encoding="utf-8")
except UnicodeDecodeError:
df = pd.read_csv(input_file_path, encoding="latin1")
col_output = args.target
if col_output not in df.columns:
raise ValueError(f"Target column '{col_output}' not found in the dataset.")
df = df.dropna(subset=[col_output]).copy()
task_type = infer_task_type(df[col_output])
logger.info(f"Target: '{col_output}' | Inferred task type: {task_type}")
if task_type == "binary":
df[col_output] = to_bool_if_binary(df[col_output])
y = df[col_output]
logger.info(f"Applying '{args.split_strategy}' split strategy...")
if args.split_strategy == "predefined":
if args.split_column not in df.columns:
raise ValueError(
f"Predefined split failed: column '{args.split_column}' not found."
)
split_col = df[args.split_column].astype(str).str.lower()
train_mask = split_col.str.contains("train")
test_mask = split_col.str.contains("test")
X_train, X_test = df[train_mask], df[test_mask]
y_train, y_test = y[train_mask], y[test_mask]
elif args.split_strategy == "temporal":
if args.date_column not in df.columns:
raise ValueError(
f"Temporal split failed: column '{args.date_column}' not found."
)
df_temp = df.copy()
df_temp["_temp_date"] = pd.to_datetime(
df_temp[args.date_column], errors="coerce"
)
df_temp = df_temp.dropna(subset=["_temp_date"]).sort_values(by="_temp_date")
df_temp = df_temp.drop(columns=["_temp_date"])
split_idx = int(len(df_temp) * (1 - args.test_size))
X_train, X_test = df_temp.iloc[:split_idx], df_temp.iloc[split_idx:]
y_train, y_test = X_train[col_output], X_test[col_output]
else: # random
stratify = y if task_type != "continuous" else None
X_train, X_test, y_train, y_test = train_test_split(
df, y, test_size=args.test_size, random_state=42, stratify=stratify
)
logger.info(f"Data split successful: {len(X_train)} Train, {len(X_test)} Test")
# Keep only configured model inputs to avoid reporting/importancing dropped columns.
input_features = data_config["input_features"]
missing_features = [c for c in input_features if c not in df.columns]
if missing_features:
raise ValueError(
f"These input_features are missing from dataset: {missing_features}"
)
X_train = X_train[input_features].copy()
X_test = X_test[input_features].copy()
X_fit, y_fit = X_train, y_train
X_val_threshold, y_val_threshold = None, None
if task_type == "binary" and args.threshold_val_size > 0:
can_split = len(X_train) > 20 and y_train.nunique() > 1
if can_split and args.split_strategy == "temporal":
val_n = int(len(X_train) * args.threshold_val_size)
if 0 < val_n < len(X_train):
X_fit = X_train.iloc[:-val_n]
y_fit = y_train.iloc[:-val_n]
X_val_threshold = X_train.iloc[-val_n:]
y_val_threshold = y_train.iloc[-val_n:]
elif can_split:
try:
X_fit, X_val_threshold, y_fit, y_val_threshold = train_test_split(
X_train,
y_train,
test_size=args.threshold_val_size,
random_state=42,
stratify=y_train,
)
except Exception:
X_fit, y_fit = X_train, y_train
formatted_cols = "\n".join(f" - {col}" for col in df.columns.tolist())
logger.info(f"Pre-processing done. Found columns:\n{formatted_cols}")
experiment_metadata = {
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"target_column": col_output,
"task_type": task_type,
"split_strategy": args.split_strategy,
"split_config": {
"test_size": (
args.test_size if args.split_strategy != "predefined" else None
),
"split_column": (
args.split_column if args.split_strategy == "predefined" else None
),
"date_column": (
args.date_column if args.split_strategy == "temporal" else None
),
},
"dataset_info": {
"total_samples": len(df),
"train_samples": len(X_train),
"test_samples": len(X_test),
"fit_samples": len(X_fit),
"threshold_validation_samples": (
len(X_val_threshold) if X_val_threshold is not None else 0
),
},
"models_trained": list(models_to_train.keys()),
"data_configuration": data_config,
"model_hyperparameters": models_to_train,
"binary_decision_policy": {
"threshold_val_size": (
args.threshold_val_size if task_type == "binary" else None
),
"min_recall": args.min_recall if task_type == "binary" else None,
"f_beta": args.f_beta if task_type == "binary" else None,
"fn_cost": args.fn_cost if task_type == "binary" else None,
"fp_cost": args.fp_cost if task_type == "binary" else None,
},
}
with open(out_dir / "metadata.json", "w", encoding="utf-8") as f:
json.dump(experiment_metadata, f, indent=4)
benchmark_results = []
# Dictionaries to store data for combined plots
all_models_y_prob = {}
shared_y_true_bin = None
pbar = tqdm(models_to_train.items(), desc="Overall Training Progress", unit="model")
for model_name, params in pbar:
pbar.set_postfix({"Current Model": model_name})
start_time = perf_counter()
write_progress(
progress_path,
{
"status": "running",
"target": args.target,
"total_models": len(models_to_train),
"completed_models": len(benchmark_results),
"current_model": model_name,
"current_step": f"Training {model_name}...",
"message": f"Training model {model_name} ({len(benchmark_results) + 1}/{len(models_to_train)})",
"updated_at": datetime.utcnow().isoformat(timespec="seconds") + "Z",
},
)
try:
tuned_params = apply_imbalance_strategy(model_name, task_type, params, y_fit)
use_scaler = model_name in {
"lr",
"ridge",
"svc",
"torch_mlp",
"torch_ft_transformer",
}
preprocessor = build_preprocessor(
data_config["input_features"],
data_config["cols_string"],
data_config["cols_date"],
data_config["cols_multi"],
use_scaler,
)
model = get_model(model_name, task_type, tuned_params)
pipeline = Pipeline([("preprocess", preprocessor), ("model", model)])
if model_name in {"torch_mlp", "torch_ft_transformer"}:
X_train_t = pipeline.named_steps["preprocess"].fit_transform(
X_fit, y_fit
)
if X_val_threshold is not None:
X_eval_t = pipeline.named_steps["preprocess"].transform(
X_val_threshold
)
pipeline.named_steps["model"].fit(
X_train_t, y_fit, eval_set=(X_eval_t, y_val_threshold)
)
else:
pipeline.named_steps["model"].fit(X_train_t, y_fit)
else:
fit_kwargs = {}
if model_name == "hgb" and task_type in {"binary", "categorical"}:
fit_kwargs["model__sample_weight"] = sample_weight_from_y(y_fit)
pipeline.fit(X_fit, y_fit, **fit_kwargs)
fit_seconds = round(perf_counter() - start_time, 3)
selected_threshold = None
threshold_selection = None
if (
task_type == "binary"
and X_val_threshold is not None
and hasattr(pipeline, "predict_proba")
):
y_val_prob = pipeline.predict_proba(X_val_threshold)
pos_idx = 1 if y_val_prob.shape[1] > 1 else 0
classes = getattr(
pipeline.named_steps["model"], "classes_", np.unique(y_val_threshold)
)
pos_label = classes[pos_idx]
y_val_bin = (y_val_threshold == pos_label).astype(int).to_numpy()
threshold_selection = select_binary_threshold(
y_val_bin,
y_val_prob[:, pos_idx],
min_recall=args.min_recall,
beta=args.f_beta,
fn_cost=args.fn_cost,
fp_cost=args.fp_cost,
)
selected_threshold = threshold_selection["threshold"]
logger.info(
"Model %s selected threshold=%.3f (val recall=%.3f, precision=%.3f, meets_recall=%s)",
model_name,
selected_threshold,
threshold_selection["recall"],
threshold_selection["precision"],
threshold_selection["meets_recall_constraint"],
)
metrics, plot_data = evaluate_and_save(
model_name,
pipeline,
X_test,
y_test,
task_type,
out_dir,
args.feature_importance,
decision_threshold=selected_threshold,
threshold_selection=threshold_selection,
f_beta=args.f_beta,
fn_cost=args.fn_cost,
fp_cost=args.fp_cost,
)
row = {"model": model_name, "status": "ok", "fit_seconds": fit_seconds}
row.update(
{k: v for k, v in metrics.items() if not isinstance(v, (list, dict))}
)
benchmark_results.append(row)
write_progress(
progress_path,
{
"status": "running",
"target": args.target,
"total_models": len(models_to_train),
"completed_models": len(benchmark_results),
"current_model": model_name,
"current_step": f"Completed {model_name}.",
"message": f"Completed model {model_name} ({len(benchmark_results)}/{len(models_to_train)})",
"updated_at": datetime.utcnow().isoformat(timespec="seconds") + "Z",
},
)
# Save plotting data for the combined charts
if "y_prob_pos" in plot_data:
all_models_y_prob[model_name] = plot_data["y_prob_pos"]
shared_y_true_bin = plot_data["y_true_bin"]
except Exception as e:
logger.error(f"Failed to train {model_name}: {e}")
benchmark_results.append(
{
"model": model_name,
"status": "failed",
"error": str(e),
"fit_seconds": round(perf_counter() - start_time, 3),
}
)
write_progress(
progress_path,
{
"status": "running",
"target": args.target,
"total_models": len(models_to_train),
"completed_models": len(benchmark_results),
"current_model": model_name,
"current_step": f"Failed {model_name}.",
"message": f"Model {model_name} failed ({len(benchmark_results)}/{len(models_to_train)})",
"updated_at": datetime.utcnow().isoformat(timespec="seconds") + "Z",
},
)
summary_df = pd.DataFrame(benchmark_results)
summary_path = out_dir / "benchmark_summary.csv"
summary_df.to_csv(summary_path, index=False)
# Generate combined plots if applicable
if task_type == "binary" and all_models_y_prob:
vis.plot_combined_roc_curve(
shared_y_true_bin,
all_models_y_prob,
f"Combined ROC Curve ({col_output})",
out_dir / "combined_roc_curve.png",
)
vis.plot_combined_pr_curve(
shared_y_true_bin,
all_models_y_prob,
f"Combined PR Curve ({col_output})",
out_dir / "combined_pr_curve.png",
)
print("\n" + "=" * 50)
logger.info(f"Benchmark complete! Summary and plots saved to {out_dir}")
print("=" * 50 + "\n")
write_progress(
progress_path,
{
"status": "completed",
"target": args.target,
"total_models": len(models_to_train),
"completed_models": len(models_to_train),
"current_model": None,
"current_step": "Training completed.",
"message": f"Completed target {args.target}.",
"updated_at": datetime.utcnow().isoformat(timespec="seconds") + "Z",
},
)
if __name__ == "__main__":
main()
|