File size: 11,305 Bytes
4636192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Run aggressive hyperparameter tuned pipeline 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

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:
    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(benchmark_dir) -> pd.DataFrame:
    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 _tune_threshold(y_true: np.ndarray, prob: np.ndarray, steps: int) -> Tuple[float, float]:
    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 _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("🚀 AGGRESSIVE HYPERPARAMETER TUNING PIPELINE")
    print("=" * 80)

    per_split_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(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]
            x_all = data[feature_cols].astype(float).values

            y_all = data["unknown_present"].astype(int).values
            partition = data["partition"].values
            train_idx, dev_idx, test_idx = partition == "train", partition == "dev", partition == "test"

            x_train, y_train = x_all[train_idx], y_all[train_idx]
            x_dev, y_dev = x_all[dev_idx], y_all[dev_idx]
            x_test, y_test = x_all[test_idx], y_all[test_idx]

            if SMOTE_AVAILABLE:
                smote = SMOTE(random_state=42, k_neighbors=3)  # Reduced k_neighbors
                x_train, y_train = smote.fit_resample(x_train, y_train)

            scaler = StandardScaler()
            x_train = scaler.fit_transform(x_train)
            x_dev = scaler.transform(x_dev)
            x_test = 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))

            # AGGRESSIVE HYPERPARAMETERS
            lgbm = LGBMClassifier(
                n_estimators=2000,  # More trees
                learning_rate=0.005,  # Slower learning
                num_leaves=50,  # Fewer leaves (less overfitting)
                subsample=0.7,  # Lower subsample
                colsample_bytree=0.7,
                min_child_samples=40,  # Stricter constraints
                lambda_l1=5.0,  # More L1 regularization
                lambda_l2=5.0,
                class_weight="balanced",
                random_state=42,
                verbose=-1,
                n_jobs=-1,
            )

            xgb = XGBClassifier(
                n_estimators=2000,
                learning_rate=0.005,
                max_depth=5,  # Shallower trees
                min_child_weight=10,  # Stricter constraints
                subsample=0.7,
                colsample_bytree=0.7,
                reg_alpha=5.0,  # More regularization
                reg_lambda=5.0,
                scale_pos_weight=spw,
                eval_metric="logloss",
                random_state=42,
                n_jobs=-1,
            )

            cb = CatBoostClassifier(
                iterations=2000,
                learning_rate=0.005,
                depth=5,
                l2_leaf_reg=5.0,
                scale_pos_weight=spw,
                random_state=42,
                verbose=0,
                task_type="CPU",
            )

            lgbm.fit(x_train, y_train)
            xgb.fit(x_train, y_train)
            cb.fit(x_train, y_train)

            p_dev_l = lgbm.predict_proba(x_dev)[:, 1]
            p_dev_x = xgb.predict_proba(x_dev)[:, 1]
            p_dev_c = cb.predict_proba(x_dev)[:, 1]
            p_test_l = lgbm.predict_proba(x_test)[:, 1]
            p_test_x = xgb.predict_proba(x_test)[:, 1]
            p_test_c = cb.predict_proba(x_test)[:, 1]

            th_l, dev_f1_l = _tune_threshold(y_dev, p_dev_l, args.threshold_steps)
            th_x, dev_f1_x = _tune_threshold(y_dev, p_dev_x, args.threshold_steps)
            th_c, dev_f1_c = _tune_threshold(y_dev, p_dev_c, args.threshold_steps)

            # Best ensemble
            best_weight = [1/3, 1/3, 1/3]
            best_th = 0.5
            best_f1 = -1.0
            for w_l in np.linspace(0, 1, 6):
                for w_x in np.linspace(0, 1-w_l, 6):
                    w_c = 1.0 - w_l - w_x
                    p_dev = (w_l * p_dev_l) + (w_x * p_dev_x) + (w_c * p_dev_c)
                    th, dev_f1 = _tune_threshold(y_dev, p_dev, args.threshold_steps)
                    if dev_f1 > best_f1:
                        best_f1, best_th = dev_f1, th
                        best_weight = [w_l, w_x, w_c]

            p_test_ens = (best_weight[0] * p_test_l) + (best_weight[1] * p_test_x) + (best_weight[2] * p_test_c)

            for name, prob, th in [("lgbm", p_test_l, th_l), ("xgb", p_test_x, th_x), ("cb", p_test_c, th_c), ("ensemble", p_test_ens, best_th)]:
                m = _metrics(y_test, prob, th)
                per_split_rows.append({"benchmark": benchmark_name, "split_id": split_id, "model": name, **m})

            print(f"✅ {time.time() - split_start:.1f}s")

    per_split = pd.DataFrame(per_split_rows).sort_values(["benchmark", "model", "split_id"])
    summary = per_split.groupby(["benchmark", "model"], as_index=False).agg(
        f1_mean=("f1", "mean"), f1_std=("f1", "std"),
        precision_mean=("precision", "mean"), recall_mean=("recall", "mean"),
    )

    per_split.to_csv(args.out_dir / "aggressive_tuning_per_split.csv", index=False)
    summary.to_csv(args.out_dir / "aggressive_tuning_summary.csv", index=False)

    print(f"\n{'='*80}\nTotal: {(time.time()-total_start)/60:.1f} min\n{'='*80}\n")
    return per_split, summary


def main() -> None:
    parser = argparse.ArgumentParser()
    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/aggressive_tuning"))
    parser.add_argument("--threshold-steps", type=int, default=199)
    args = parser.parse_args()

    _, summary = run(args)
    print("\n📊 RESULTS:")
    print(summary[["benchmark", "model", "f1_mean", "precision_mean", "recall_mean"]].to_string(index=False))

    best_f1 = summary["f1_mean"].max()
    if best_f1 > 0.5:
        print(f"\n✅ SUCCESS! Best F1 = {best_f1:.4f}")
    else:
        print(f"\n⚠️  Target not met. Best F1 = {best_f1:.4f}")


if __name__ == "__main__":
    main()