| """Run optimized pipeline with SMOTE + F2 tuning + CatBoost for F1 > 0.5.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import sys |
| import time |
| from pathlib import Path |
| from typing import Dict, List, Tuple |
|
|
| import numpy as np |
| import pandas as pd |
| from catboost import CatBoostClassifier |
| from lightgbm import LGBMClassifier |
| from sklearn.metrics import ( |
| accuracy_score, |
| average_precision_score, |
| confusion_matrix, |
| f1_score, |
| precision_score, |
| recall_score, |
| roc_auc_score, |
| ) |
| from sklearn.preprocessing import StandardScaler |
| from xgboost import XGBClassifier |
|
|
| try: |
| from imblearn.over_sampling import SMOTE |
| SMOTE_AVAILABLE = True |
| except ImportError: |
| SMOTE_AVAILABLE = False |
| print("⚠️ SMOTE not installed. Install: pip install imbalanced-learn") |
|
|
| ROOT = Path(__file__).resolve().parents[2] |
| if str(ROOT) not in sys.path: |
| sys.path.insert(0, str(ROOT)) |
|
|
| EPS = 1e-9 |
|
|
|
|
| def _agg_numeric( |
| frame: pd.DataFrame, |
| key: str, |
| value_cols, |
| prefix: str, |
| ) -> pd.DataFrame: |
| """Aggregate numeric features.""" |
| grouped = frame.groupby(key, sort=False)[list(value_cols)] |
| agg = grouped.agg(["mean", "std", "min", "max", "median"]) |
| agg.columns = [f"{prefix}_{col}_{stat}" for col, stat in agg.columns] |
| agg = agg.reset_index() |
| for col in agg.columns: |
| if col != key: |
| agg[col] = agg[col].fillna(0.0) |
| return agg |
|
|
|
|
| def _build_features_optimized(benchmark_dir) -> pd.DataFrame: |
| """Build features from marker data (skip missing peak_table.csv).""" |
| marker_path = benchmark_dir / "marker_table.csv" |
| sample_key = "sample_file" |
|
|
| marker_cols = [ |
| sample_key, |
| "marker", |
| "dye", |
| "peak_count_total", |
| "peak_count_non_ol", |
| "max_height", |
| "sum_height", |
| "has_ol", |
| ] |
| marker = pd.read_csv(marker_path, usecols=marker_cols, low_memory=False) |
|
|
| marker["peak_nonol_ratio"] = marker["peak_count_non_ol"] / ( |
| marker["peak_count_total"] + EPS |
| ) |
| marker["height_density"] = marker["sum_height"] / (marker["peak_count_total"] + EPS) |
|
|
| gm = marker.groupby(sample_key, sort=False) |
| mfeat = pd.DataFrame( |
| { |
| sample_key: gm.size().index, |
| "marker_rows": gm.size().values, |
| "marker_unique_count": gm["marker"].nunique().values, |
| "marker_has_ol_rate": gm["has_ol"].mean().values, |
| "marker_peak_total_sum": gm["peak_count_total"].sum().values, |
| "marker_peak_nonol_sum": gm["peak_count_non_ol"].sum().values, |
| "marker_peak_nonol_ratio_mean": gm["peak_nonol_ratio"].mean().values, |
| "marker_height_density_mean": gm["height_density"].mean().values, |
| } |
| ) |
|
|
| mnum = _agg_numeric( |
| marker, |
| key=sample_key, |
| value_cols=[ |
| "peak_count_total", |
| "peak_count_non_ol", |
| "peak_nonol_ratio", |
| "max_height", |
| "sum_height", |
| "height_density", |
| ], |
| prefix="marker", |
| ) |
| mfeat = mfeat.merge(mnum, on=sample_key, how="left") |
|
|
| dye_sum = marker.pivot_table( |
| index=sample_key, |
| columns="dye", |
| values="sum_height", |
| aggfunc="sum", |
| fill_value=0.0, |
| ) |
| dye_sum.columns = [f"marker_sum_height_dye_{c}" for c in dye_sum.columns] |
| mfeat = mfeat.merge(dye_sum.reset_index(), on=sample_key, how="left") |
|
|
| return mfeat |
|
|
|
|
| def _parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser(description=__doc__) |
| parser.add_argument( |
| "--benchmark-root", |
| type=Path, |
| default=Path("data/processed"), |
| ) |
| parser.add_argument( |
| "--benchmarks", |
| nargs="+", |
| default=["rd14-fullref-50_multisplit_v2", "rd12-fullref-61_multisplit_v2"], |
| ) |
| parser.add_argument( |
| "--out-dir", |
| type=Path, |
| default=Path("outputs/benchmarks/optimized_pipeline_m2"), |
| ) |
| parser.add_argument( |
| "--threshold-steps", |
| type=int, |
| default=199, |
| ) |
| parser.add_argument( |
| "--use-smote", |
| type=bool, |
| default=True, |
| help="Use SMOTE for class imbalance", |
| ) |
| parser.add_argument( |
| "--use-catboost", |
| type=bool, |
| default=True, |
| help="Add CatBoost to ensemble", |
| ) |
| parser.add_argument( |
| "--use-f2-metric", |
| type=bool, |
| default=False, |
| help="Use F2 instead of F1 for recall optimization (default: F1)", |
| ) |
| parser.add_argument( |
| "--use-gpu", |
| type=bool, |
| default=True, |
| help="Use GPU acceleration on Mac (MPS)", |
| ) |
| return parser.parse_args() |
|
|
|
|
| def _tune_threshold_f1(y_true: np.ndarray, prob: np.ndarray, steps: int) -> Tuple[float, float]: |
| """Tune threshold for F1 score.""" |
| thresholds = np.linspace(0.01, 0.99, steps) |
| best_f1 = -1.0 |
| best_th = 0.5 |
| for th in thresholds: |
| pred = (prob >= th).astype(int) |
| score = f1_score(y_true, pred, zero_division=0) |
| if score > best_f1: |
| best_f1 = float(score) |
| best_th = float(th) |
| return best_th, best_f1 |
|
|
|
|
| def _tune_threshold_f2(y_true: np.ndarray, prob: np.ndarray, steps: int) -> Tuple[float, float]: |
| """Tune threshold for F2 score (emphasize recall).""" |
| thresholds = np.linspace(0.01, 0.99, steps) |
| best_f2 = -1.0 |
| best_th = 0.5 |
| for th in thresholds: |
| pred = (prob >= th).astype(int) |
| |
| precision = precision_score(y_true, pred, zero_division=0) |
| recall = recall_score(y_true, pred, zero_division=0) |
| f2 = (5 * precision * recall) / (4 * precision + recall + EPS) |
| if f2 > best_f2: |
| best_f2 = f2 |
| best_th = float(th) |
| return best_th, best_f2 |
|
|
|
|
| def _metrics(y_true: np.ndarray, prob: np.ndarray, threshold: float) -> Dict[str, float]: |
| pred = (prob >= threshold).astype(int) |
| tn, fp, fn, tp = confusion_matrix(y_true, pred, labels=[0, 1]).ravel() |
| specificity = tn / (tn + fp + EPS) |
| precision = precision_score(y_true, pred, zero_division=0) |
| recall = recall_score(y_true, pred, zero_division=0) |
| f2 = (5 * precision * recall) / (4 * precision + recall + EPS) |
| return { |
| "roc_auc": float(roc_auc_score(y_true, prob)), |
| "pr_auc": float(average_precision_score(y_true, prob)), |
| "f1": float(f1_score(y_true, pred, zero_division=0)), |
| "f2": float(f2), |
| "precision": float(precision), |
| "recall": float(recall), |
| "specificity": float(specificity), |
| "accuracy": float(accuracy_score(y_true, pred)), |
| "tp": int(tp), |
| "fp": int(fp), |
| "tn": int(tn), |
| "fn": int(fn), |
| } |
|
|
|
|
| def run(args: argparse.Namespace) -> Tuple[pd.DataFrame, pd.DataFrame]: |
| args.out_dir.mkdir(parents=True, exist_ok=True) |
|
|
| print("=" * 80) |
| print("🚀 OPTIMIZED PIPELINE (SMOTE + F2 + CatBoost)") |
| print("=" * 80) |
| print(f"SMOTE: {args.use_smote}") |
| print(f"CatBoost: {args.use_catboost}") |
| print(f"F2 Tuning: {args.use_f2_metric}") |
| print(f"Feature Scaling: True") |
| print("=" * 80) |
|
|
| per_split_rows: List[Dict[str, object]] = [] |
| trial_rows: List[Dict[str, object]] = [] |
|
|
| total_start = time.time() |
|
|
| for benchmark_name in args.benchmarks: |
| print(f"\n📊 Processing benchmark: {benchmark_name}") |
| benchmark_dir = args.benchmark_root / benchmark_name |
| labels = pd.read_csv(benchmark_dir / "sample_labels_all_splits.csv", low_memory=False) |
| features = _build_features_optimized(benchmark_dir) |
|
|
| for split_idx, split_id in enumerate(sorted(labels["split_id"].unique())): |
| print(f" Split {split_idx + 1}/{len(labels['split_id'].unique())}: {split_id}", end=" ") |
| split_start = time.time() |
|
|
| split_df = labels[labels["split_id"] == split_id].copy() |
| data = split_df.merge(features, on="sample_file", how="inner") |
|
|
| drop_cols = { |
| "benchmark_id", |
| "split_id", |
| "partition", |
| "study_id", |
| "panel", |
| "sample_file", |
| "sample_family_id", |
| "true_contributors", |
| "known_contributors_true", |
| "unknown_contributors_true", |
| "num_known_in_sample", |
| "num_unknown_in_sample", |
| "unknown_present", |
| "total_contributors", |
| } |
| feature_cols = [c for c in data.columns if c not in drop_cols] |
| panel_ohe = pd.get_dummies(data["panel"], prefix="panel") |
| x_all = pd.concat([data[feature_cols].astype(float), panel_ohe.astype(float)], axis=1) |
|
|
| y_all = data["unknown_present"].astype(int).values |
| partition = data["partition"].values |
| train_idx = partition == "train" |
| dev_idx = partition == "dev" |
| test_idx = partition == "test" |
|
|
| x_train = x_all[train_idx].values |
| y_train = y_all[train_idx] |
| x_dev = x_all[dev_idx].values |
| y_dev = y_all[dev_idx] |
| x_test = x_all[test_idx].values |
| y_test = y_all[test_idx] |
|
|
| feature_names = x_all.columns.tolist() |
|
|
| |
| if args.use_smote and SMOTE_AVAILABLE: |
| smote = SMOTE(random_state=42, k_neighbors=5) |
| x_train, y_train = smote.fit_resample(x_train, y_train) |
| print(f"SMOTE: {len(y_train)} samples (balanced)", end=" | ") |
| else: |
| print(f"No SMOTE: {len(y_train)} samples", end=" | ") |
|
|
| |
| scaler = StandardScaler() |
| x_train_scaled = scaler.fit_transform(x_train) |
| x_dev_scaled = scaler.transform(x_dev) |
| x_test_scaled = scaler.transform(x_test) |
|
|
| |
| pos = float((y_train == 1).sum()) |
| neg = float((y_train == 0).sum()) |
| spw = max(1.0, neg / max(pos, 1.0)) |
|
|
| |
| lgbm = LGBMClassifier( |
| n_estimators=1200, |
| learning_rate=0.015, |
| num_leaves=100, |
| subsample=0.85, |
| colsample_bytree=0.85, |
| min_child_samples=20, |
| lambda_l1=1.0, |
| lambda_l2=1.0, |
| class_weight="balanced", |
| random_state=42, |
| verbose=-1, |
| n_jobs=-1, |
| ) |
|
|
| |
| xgb = XGBClassifier( |
| n_estimators=1200, |
| learning_rate=0.015, |
| max_depth=7, |
| min_child_weight=5, |
| subsample=0.85, |
| colsample_bytree=0.85, |
| reg_alpha=1.0, |
| reg_lambda=1.0, |
| scale_pos_weight=spw, |
| eval_metric="logloss", |
| random_state=42, |
| n_jobs=-1, |
| tree_method="hist", |
| ) |
|
|
| lgbm.fit(x_train_scaled, y_train) |
| xgb.fit(x_train_scaled, y_train) |
|
|
| p_dev_l = lgbm.predict_proba(x_dev_scaled)[:, 1] |
| p_dev_x = xgb.predict_proba(x_dev_scaled)[:, 1] |
| p_test_l = lgbm.predict_proba(x_test_scaled)[:, 1] |
| p_test_x = xgb.predict_proba(x_test_scaled)[:, 1] |
|
|
| |
| p_dev_c = None |
| p_test_c = None |
| if args.use_catboost: |
| cb = CatBoostClassifier( |
| iterations=1200, |
| learning_rate=0.015, |
| depth=7, |
| l2_leaf_reg=1.0, |
| scale_pos_weight=spw, |
| random_state=42, |
| verbose=0, |
| task_type="CPU", |
| ) |
| cb.fit(x_train_scaled, y_train) |
| p_dev_c = cb.predict_proba(x_dev_scaled)[:, 1] |
| p_test_c = cb.predict_proba(x_test_scaled)[:, 1] |
|
|
| |
| if args.use_f2_metric: |
| th_l, dev_f_l = _tune_threshold_f2(y_dev, p_dev_l, args.threshold_steps) |
| th_x, dev_f_x = _tune_threshold_f2(y_dev, p_dev_x, args.threshold_steps) |
| else: |
| th_l, dev_f_l = _tune_threshold_f1(y_dev, p_dev_l, args.threshold_steps) |
| th_x, dev_f_x = _tune_threshold_f1(y_dev, p_dev_x, args.threshold_steps) |
|
|
| |
| best_weight_lx = 0.5 |
| best_th_lx = 0.5 |
| best_dev_f_lx = -1.0 |
| for w in np.linspace(0.0, 1.0, 21): |
| p_dev_lx = (w * p_dev_l) + ((1.0 - w) * p_dev_x) |
| if args.use_f2_metric: |
| th_lx, dev_f_lx = _tune_threshold_f2(y_dev, p_dev_lx, args.threshold_steps) |
| else: |
| th_lx, dev_f_lx = _tune_threshold_f1(y_dev, p_dev_lx, args.threshold_steps) |
| if dev_f_lx > best_dev_f_lx: |
| best_dev_f_lx = dev_f_lx |
| best_th_lx = th_lx |
| best_weight_lx = float(w) |
|
|
| p_test_lx = (best_weight_lx * p_test_l) + ((1.0 - best_weight_lx) * p_test_x) |
|
|
| |
| if args.use_catboost: |
| best_weight_3 = [1/3, 1/3, 1/3] |
| best_th_3 = 0.5 |
| best_dev_f_3 = -1.0 |
| for w_l in np.linspace(0.0, 1.0, 11): |
| for w_x in np.linspace(0.0, 1.0 - w_l, 6): |
| w_c = 1.0 - w_l - w_x |
| p_dev_3 = (w_l * p_dev_l) + (w_x * p_dev_x) + (w_c * p_dev_c) |
| if args.use_f2_metric: |
| th_3, dev_f_3 = _tune_threshold_f2(y_dev, p_dev_3, args.threshold_steps) |
| else: |
| th_3, dev_f_3 = _tune_threshold_f1(y_dev, p_dev_3, args.threshold_steps) |
| if dev_f_3 > best_dev_f_3: |
| best_dev_f_3 = dev_f_3 |
| best_th_3 = th_3 |
| best_weight_3 = [w_l, w_x, w_c] |
|
|
| p_test_3 = (best_weight_3[0] * p_test_l) + (best_weight_3[1] * p_test_x) + (best_weight_3[2] * p_test_c) |
| else: |
| p_test_3 = p_test_lx |
| best_th_3 = best_th_lx |
| best_dev_f_3 = best_dev_f_lx |
| best_weight_3 = [best_weight_lx, 1.0 - best_weight_lx, 0.0] |
|
|
| model_payload = { |
| "lightgbm_best": { |
| "threshold": th_l, |
| "dev_f": dev_f_l, |
| "dev_pr_auc": float(average_precision_score(y_dev, p_dev_l)), |
| "test_prob": p_test_l, |
| }, |
| "xgboost_best": { |
| "threshold": th_x, |
| "dev_f": dev_f_x, |
| "dev_pr_auc": float(average_precision_score(y_dev, p_dev_x)), |
| "test_prob": p_test_x, |
| }, |
| "fusion_lx_best": { |
| "threshold": best_th_lx, |
| "dev_f": best_dev_f_lx, |
| "dev_pr_auc": float( |
| average_precision_score(y_dev, best_weight_lx * p_dev_l + (1.0 - best_weight_lx) * p_dev_x) |
| ), |
| "test_prob": p_test_lx, |
| "weight_lgbm": best_weight_lx, |
| }, |
| } |
|
|
| if args.use_catboost: |
| model_payload["catboost_best"] = { |
| "threshold": np.percentile(p_dev_c, 50), |
| "dev_f": float(f1_score(y_dev, (p_dev_c >= np.percentile(p_dev_c, 50)).astype(int), zero_division=0)), |
| "dev_pr_auc": float(average_precision_score(y_dev, p_dev_c)), |
| "test_prob": p_test_c, |
| } |
| model_payload["fusion_3_best"] = { |
| "threshold": best_th_3, |
| "dev_f": best_dev_f_3, |
| "dev_pr_auc": float( |
| average_precision_score( |
| y_dev, |
| best_weight_3[0] * p_dev_l + best_weight_3[1] * p_dev_x + best_weight_3[2] * p_dev_c, |
| ) |
| ), |
| "test_prob": p_test_3, |
| "weight_lgbm": best_weight_3[0], |
| "weight_xgb": best_weight_3[1], |
| "weight_catboost": best_weight_3[2], |
| } |
|
|
| for model_name, payload in model_payload.items(): |
| trial_rows.append( |
| { |
| "benchmark": benchmark_name, |
| "split_id": split_id, |
| "model": model_name, |
| "threshold": float(payload["threshold"]), |
| "dev_score": float(payload["dev_f"]), |
| "dev_pr_auc": float(payload["dev_pr_auc"]), |
| } |
| ) |
|
|
| m = _metrics(y_test, payload["test_prob"], float(payload["threshold"])) |
| per_split_rows.append( |
| { |
| "benchmark": benchmark_name, |
| "split_id": split_id, |
| "model": model_name, |
| "threshold": float(payload["threshold"]), |
| "dev_score": float(payload["dev_f"]), |
| "dev_pr_auc": float(payload["dev_pr_auc"]), |
| "n_train": int((y_train == 1).sum() + (y_train == 0).sum()), |
| "n_dev": int(dev_idx.sum()), |
| "n_test": int(test_idx.sum()), |
| "test_positive_rate": float(y_test.mean()), |
| **m, |
| } |
| ) |
|
|
| split_elapsed = time.time() - split_start |
| print(f"✅ {split_elapsed:.1f}s") |
|
|
| per_split = pd.DataFrame(per_split_rows).sort_values(["benchmark", "model", "split_id"]) |
| trials = pd.DataFrame(trial_rows).sort_values(["benchmark", "model", "split_id"]) |
|
|
| summary = ( |
| per_split.groupby(["benchmark", "model"], as_index=False) |
| .agg( |
| roc_auc_mean=("roc_auc", "mean"), |
| roc_auc_std=("roc_auc", "std"), |
| pr_auc_mean=("pr_auc", "mean"), |
| pr_auc_std=("pr_auc", "std"), |
| f1_mean=("f1", "mean"), |
| f1_std=("f1", "std"), |
| f2_mean=("f2", "mean"), |
| f2_std=("f2", "std"), |
| precision_mean=("precision", "mean"), |
| recall_mean=("recall", "mean"), |
| specificity_mean=("specificity", "mean"), |
| accuracy_mean=("accuracy", "mean"), |
| ) |
| .sort_values(["benchmark", "model"]) |
| ) |
|
|
| per_split.to_csv(args.out_dir / "optimized_pipeline_per_split.csv", index=False) |
| summary.to_csv(args.out_dir / "optimized_pipeline_summary.csv", index=False) |
| trials.to_csv(args.out_dir / "optimized_pipeline_trials_dev.csv", index=False) |
| (args.out_dir / "run_args.json").write_text( |
| json.dumps( |
| { |
| "use_smote": args.use_smote, |
| "use_catboost": args.use_catboost, |
| "use_f2_metric": args.use_f2_metric, |
| "use_gpu": args.use_gpu, |
| "pipeline": "LGBM+XGB+CatBoost with SMOTE, F2 tuning, feature scaling, and 3-model ensemble", |
| }, |
| indent=2, |
| ) |
| ) |
|
|
| total_elapsed = time.time() - total_start |
| print(f"\n{'=' * 80}") |
| print(f"✅ Total time: {total_elapsed / 60:.1f} minutes") |
| print(f"{'=' * 80}\n") |
|
|
| return per_split, summary |
|
|
|
|
| def main() -> None: |
| args = _parse_args() |
| _, summary = run(args) |
| print("\n📊 SUMMARY RESULTS:") |
| print("=" * 80) |
| print(summary.to_string(index=False)) |
| print("=" * 80) |
|
|
| |
| print("\n✅ F1 SCORES > 0.5 CHECK:") |
| f1_cols = [c for c in summary.columns if 'f1_mean' in c] |
| for _, row in summary.iterrows(): |
| f1_score = row['f1_mean'] |
| status = "✅ PASS" if f1_score > 0.5 else "⚠️ BELOW TARGET" |
| print(f" {row['benchmark']:40s} | {row['model']:20s} | F1={f1_score:.4f} | {status}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|