Download src/cli/run_bayesian_tuning.py from manhngvu/dna_noc: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/datasets/manhngvu/dna_noc/resolve/main/src/cli/run_bayesian_tuning.py
- Command line
-
hf download hf://datasets/manhngvu/dna_noc/src/cli/run_bayesian_tuning.py
-
curl -L -o run_bayesian_tuning.py https://huggingface.co/datasets/manhngvu/dna_noc/resolve/main/src/cli/run_bayesian_tuning.py
12.9 kB
| """Bayesian hyperparameter optimization using Optuna 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 | |
| import numpy as np | |
| import optuna | |
| import pandas as pd | |
| from catboost import CatBoostClassifier | |
| from lightgbm import LGBMClassifier | |
| from sklearn.metrics import f1_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: | |
| """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.""" | |
| 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/bayesian_tuning")) | |
| parser.add_argument("--n-trials", type=int, default=100, help="Number of Bayesian trials") | |
| parser.add_argument("--timeout", type=int, default=20000, help="Timeout in seconds") | |
| parser.add_argument("--n-jobs", type=int, default=-1, help="Parallel jobs") | |
| return parser.parse_args() | |
| def objective( | |
| trial: optuna.Trial, | |
| benchmark_data: Dict, | |
| model_name: str = "catboost", | |
| ) -> float: | |
| """Objective function for Optuna.""" | |
| # Hyperparameter space | |
| learning_rate = trial.suggest_float("learning_rate", 0.001, 0.1, log=True) | |
| num_leaves = trial.suggest_int("num_leaves", 15, 200) | |
| lambda_l1 = trial.suggest_float("lambda_l1", 0, 10) | |
| lambda_l2 = trial.suggest_float("lambda_l2", 0, 10) | |
| subsample = trial.suggest_float("subsample", 0.5, 1.0) | |
| colsample_bytree = trial.suggest_float("colsample_bytree", 0.5, 1.0) | |
| min_child_samples = trial.suggest_int("min_child_samples", 5, 50) | |
| f1_scores = [] | |
| for data_split in benchmark_data["splits"]: | |
| x_train = data_split["x_train"] | |
| y_train = data_split["y_train"] | |
| x_dev = data_split["x_dev"] | |
| y_dev = data_split["y_dev"] | |
| # Apply SMOTE | |
| if SMOTE_AVAILABLE: | |
| smote = SMOTE(random_state=42, k_neighbors=5) | |
| x_train, y_train = smote.fit_resample(x_train, y_train) | |
| # Scale features | |
| scaler = StandardScaler() | |
| x_train = scaler.fit_transform(x_train) | |
| x_dev = scaler.transform(x_dev) | |
| # Train model based on selection | |
| if model_name == "lgbm": | |
| model = LGBMClassifier( | |
| n_estimators=1000, | |
| learning_rate=learning_rate, | |
| num_leaves=num_leaves, | |
| lambda_l1=lambda_l1, | |
| lambda_l2=lambda_l2, | |
| subsample=subsample, | |
| colsample_bytree=colsample_bytree, | |
| min_child_samples=min_child_samples, | |
| class_weight="balanced", | |
| random_state=42, | |
| verbose=-1, | |
| n_jobs=-1, | |
| ) | |
| elif model_name == "xgb": | |
| pos = float((y_train == 1).sum()) | |
| neg = float((y_train == 0).sum()) | |
| scale_pos_weight = max(1.0, neg / max(pos, 1.0)) | |
| model = XGBClassifier( | |
| n_estimators=1000, | |
| learning_rate=learning_rate, | |
| max_depth=int(np.sqrt(num_leaves)), | |
| subsample=subsample, | |
| colsample_bytree=colsample_bytree, | |
| reg_alpha=lambda_l1, | |
| reg_lambda=lambda_l2, | |
| scale_pos_weight=scale_pos_weight, | |
| random_state=42, | |
| n_jobs=-1, | |
| ) | |
| else: # catboost | |
| pos = float((y_train == 1).sum()) | |
| neg = float((y_train == 0).sum()) | |
| scale_pos_weight = max(1.0, neg / max(pos, 1.0)) | |
| model = CatBoostClassifier( | |
| iterations=1000, | |
| learning_rate=learning_rate, | |
| depth=int(np.sqrt(num_leaves)), | |
| subsample=subsample, | |
| colsample_bylevel=colsample_bytree, | |
| l2_leaf_reg=lambda_l2, | |
| scale_pos_weight=scale_pos_weight, | |
| random_state=42, | |
| verbose=0, | |
| task_type="CPU", | |
| ) | |
| model.fit(x_train, y_train) | |
| p_dev = model.predict_proba(x_dev)[:, 1] | |
| # Find best F1 threshold | |
| best_f1 = 0.0 | |
| thresholds = np.linspace(0.01, 0.99, 99) | |
| for th in thresholds: | |
| pred = (p_dev >= th).astype(int) | |
| f1 = f1_score(y_dev, pred, zero_division=0) | |
| if f1 > best_f1: | |
| best_f1 = f1 | |
| f1_scores.append(best_f1) | |
| return np.mean(f1_scores) | |
| def run(args: argparse.Namespace) -> None: | |
| args.out_dir.mkdir(parents=True, exist_ok=True) | |
| print("=" * 80) | |
| print("๐ฌ BAYESIAN HYPERPARAMETER OPTIMIZATION (Optuna)") | |
| print("=" * 80) | |
| print(f"Trials: {args.n_trials}") | |
| print(f"Timeout: {args.timeout}s (~{args.timeout/3600:.1f} hours)") | |
| print(f"Benchmarks: {', '.join(args.benchmarks)}") | |
| print("=" * 80) | |
| # Load and prepare data | |
| print("\n๐ Loading benchmark data...") | |
| benchmark_data = {"splits": []} | |
| for benchmark_name in args.benchmarks: | |
| print(f" Loading {benchmark_name}...", end=" ") | |
| 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_id in sorted(labels["split_id"].unique())[:3]: # Use first 3 splits for speed | |
| 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" | |
| benchmark_data["splits"].append( | |
| { | |
| "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], | |
| } | |
| ) | |
| print(f"โ ({len(benchmark_data['splits'])} splits)") | |
| print(f"Total splits: {len(benchmark_data['splits'])}") | |
| # Run Bayesian optimization | |
| print("\n๐ฌ Running Bayesian optimization...") | |
| print(f"Testing model: CatBoost (best performer)") | |
| print("=" * 80) | |
| start_time = time.time() | |
| sampler = optuna.samplers.TPESampler(seed=42) | |
| study = optuna.create_study( | |
| direction="maximize", | |
| sampler=sampler, | |
| study_name="bayesian_tuning", | |
| ) | |
| study.optimize( | |
| lambda trial: objective(trial, benchmark_data, model_name="catboost"), | |
| n_trials=args.n_trials, | |
| timeout=args.timeout, | |
| show_progress_bar=True, | |
| ) | |
| elapsed = time.time() - start_time | |
| # Results | |
| print("\n" + "=" * 80) | |
| print(f"โ Optimization complete! ({elapsed/60:.1f} minutes)") | |
| print("=" * 80) | |
| best_trial = study.best_trial | |
| print(f"\n๐ Best Trial: #{best_trial.number}") | |
| print(f" F1 Score: {best_trial.value:.4f}") | |
| print(f"\n๐ Best Hyperparameters:") | |
| for key, value in sorted(best_trial.params.items()): | |
| print(f" {key:25s}: {value}") | |
| # Save results | |
| results_df = pd.DataFrame([ | |
| {"trial": t.number, "f1": t.value, **t.params} | |
| for t in study.trials | |
| ]).sort_values("f1", ascending=False) | |
| results_df.to_csv(args.out_dir / "bayesian_summary.csv", index=False) | |
| with open(args.out_dir / "best_params.json", "w") as f: | |
| json.dump(best_trial.params, f, indent=2) | |
| with open(args.out_dir / "optimization_log.txt", "w") as f: | |
| f.write(f"Bayesian Optimization Results\n") | |
| f.write(f"{'=' * 80}\n") | |
| f.write(f"Best F1 Score: {best_trial.value:.4f}\n") | |
| f.write(f"Best Trial: #{best_trial.number}\n") | |
| f.write(f"Total Trials: {len(study.trials)}\n") | |
| f.write(f"Time Elapsed: {elapsed/60:.1f} minutes\n") | |
| f.write(f"\nBest Hyperparameters:\n") | |
| for key, value in sorted(best_trial.params.items()): | |
| f.write(f" {key}: {value}\n") | |
| print(f"\n๐ Results saved to {args.out_dir}/") | |
| print(f" - bayesian_summary.csv (all trials)") | |
| print(f" - best_params.json (best hyperparameters)") | |
| print(f" - optimization_log.txt (summary)") | |
| # Top 10 trials | |
| print(f"\n๐ Top 10 Trials:") | |
| print("=" * 80) | |
| for i, (_, row) in enumerate(results_df.head(10).iterrows(), 1): | |
| f1 = row["f1"] | |
| status = "โ GOOD" if f1 > 0.4 else "โ ๏ธ OK" if f1 > 0.35 else "โ POOR" | |
| print(f"{i:2d}. F1={f1:.4f} {status}") | |
| if best_trial.value > 0.4: | |
| print(f"\n๐ SUCCESS! F1 > 0.4 achieved!") | |
| print(f" Recommendation: Use best params above") | |
| elif best_trial.value > 0.35: | |
| print(f"\nโ ๏ธ Moderate improvement (F1={best_trial.value:.4f})") | |
| print(f" Recommendation: Try with peak_table.csv if available") | |
| else: | |
| print(f"\nโ Limited improvement (F1={best_trial.value:.4f})") | |
| print(f" Recommendation: Find peak_table.csv (critical missing data)") | |
| def main() -> None: | |
| args = _parse_args() | |
| run(args) | |
| if __name__ == "__main__": | |
| main() | |