210 lines
10 KiB
Python
210 lines
10 KiB
Python
"""RQ1 robustness / foolproofing pass: cross-validation with confidence
|
|
intervals, hyperparameter tuning, calibration, bootstrap CIs, and analysis of
|
|
how research-area field differences affect the model -- all requested as
|
|
follow-ups after the initial RQ1/RQ2 results.
|
|
|
|
Sections (each independent, run in order):
|
|
1. Ablation: pre-founding-equivalent fix ON vs OFF (quantifies the
|
|
reverse-causation confound found while investigating the "n.a. research
|
|
area" group -- see README for the full writeup).
|
|
2. 5-fold stratified CV with 95% CIs for the headline models (replaces relying
|
|
on a single 80/20 split for the topline numbers).
|
|
3. Hyperparameter tuning (RandomizedSearchCV) for random_forest/xgboost/lightgbm.
|
|
4. Calibration curves (reliability diagrams) for logistic_regression vs default
|
|
vs tuned LightGBM.
|
|
5. Bootstrap 95% CIs for the tuned model's held-out metrics.
|
|
6. Stratified evaluation of the tuned pooled model, broken out by broad
|
|
research area, to check whether it works uniformly or is riding field
|
|
base-rates.
|
|
7. Per-area specialist models vs. the pooled generalist model, on the same
|
|
per-area test subsets, for the largest research areas.
|
|
|
|
Run with: conda run -n potential python experiments/run_rq1_robustness.py
|
|
"""
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
|
|
import json
|
|
|
|
import pandas as pd
|
|
|
|
from src import config, data, evaluate, models, splits, tuning
|
|
|
|
RESULTS_DIR = config.RESULTS_DIR / "rq1_robustness"
|
|
|
|
|
|
def section_ablation():
|
|
print("=== 1. Pre-founding-equivalent fix: ablation ===")
|
|
rows = []
|
|
for label, kwargs in [("fix_on", {}), ("fix_off", {"apply_prefounding_fix": False})]:
|
|
df_raw = data.load_rq1_raw(**kwargs)
|
|
X, y, _ = data.build_rq1_matrix(df_raw, include_institution=True)
|
|
X_train, X_test, y_train, y_test = splits.stratified_holdout(X, y, test_size=0.2)
|
|
spw = (y_train == 0).sum() / (y_train == 1).sum()
|
|
model = models.advanced_models(scale_pos_weight=spw)["lightgbm"]
|
|
_, metrics, _, _ = evaluate.fit_and_evaluate(model, X_train, y_train, X_test, y_test)
|
|
rows.append({"pipeline": label, "n_rows": len(X), **metrics})
|
|
print(f" {label}: n={len(X)} roc_auc={metrics['roc_auc']:.4f} pr_auc={metrics['pr_auc']:.4f}")
|
|
table = pd.DataFrame(rows).set_index("pipeline")
|
|
evaluate.save_table(table, RESULTS_DIR / "ablation_prefounding_fix.csv", RESULTS_DIR / "ablation_prefounding_fix.md")
|
|
print(" (fix_on = corrected pipeline used everywhere else; fix_off = original\n"
|
|
" lifetime-total features, kept only for this comparison)\n")
|
|
|
|
|
|
def load_clean():
|
|
df_raw = data.load_rq1_raw()
|
|
X, y, groups = data.build_rq1_matrix(df_raw, include_institution=True)
|
|
return df_raw, X, y, groups
|
|
|
|
|
|
def section_cross_validation(X, y):
|
|
print("=== 2. 5-fold stratified CV with 95% CIs ===")
|
|
# StratifiedKFold preserves the class ratio per fold, so one overall
|
|
# scale_pos_weight approximates the per-fold value for xgboost.
|
|
spw = (y == 0).sum() / (y == 1).sum()
|
|
factories = {
|
|
"dummy_most_frequent": lambda: models.baseline_models()["dummy_most_frequent"],
|
|
"logistic_regression": lambda: models.baseline_models()["logistic_regression"],
|
|
"random_forest": lambda: models.advanced_models()["random_forest"],
|
|
"xgboost": lambda: models.advanced_models(scale_pos_weight=spw)["xgboost"],
|
|
"lightgbm": lambda: models.advanced_models()["lightgbm"],
|
|
}
|
|
summaries = {}
|
|
for name, factory in factories.items():
|
|
_, summary = evaluate.cross_validate_model(factory, X, y, cv=5)
|
|
summaries[name] = summary["mean"]
|
|
print(f" {name}: pr_auc={summary.loc['pr_auc','mean']:.4f} "
|
|
f"[{summary.loc['pr_auc','ci95_low']:.4f}, {summary.loc['pr_auc','ci95_high']:.4f}] "
|
|
f"roc_auc={summary.loc['roc_auc','mean']:.4f} "
|
|
f"[{summary.loc['roc_auc','ci95_low']:.4f}, {summary.loc['roc_auc','ci95_high']:.4f}]")
|
|
summary.to_csv(RESULTS_DIR / f"cv_{name}.csv")
|
|
table = pd.DataFrame(summaries).T
|
|
evaluate.save_table(table, RESULTS_DIR / "cv_summary_mean.csv", RESULTS_DIR / "cv_summary_mean.md")
|
|
print()
|
|
|
|
|
|
def section_tuning(X_train, y_train, X_test, y_test):
|
|
print("=== 3. Hyperparameter tuning (RandomizedSearchCV) ===")
|
|
spw = (y_train == 0).sum() / (y_train == 1).sum()
|
|
rows = []
|
|
tuned_models = {}
|
|
best_params = {}
|
|
for name in ["random_forest", "xgboost", "lightgbm"]:
|
|
default_model = models.advanced_models(scale_pos_weight=spw)[name]
|
|
_, default_metrics, _, default_proba = evaluate.fit_and_evaluate(default_model, X_train, y_train, X_test, y_test)
|
|
rows.append({"model": name, "variant": "default", **default_metrics})
|
|
|
|
print(f" tuning {name} (n_iter=20, cv=3, scoring=average_precision) ...")
|
|
best_est, params, _ = tuning.tune_model(name, X_train, y_train, n_iter=20, cv=3, scale_pos_weight=spw)
|
|
proba = best_est.predict_proba(X_test)[:, 1]
|
|
pred = (proba >= 0.5).astype(int)
|
|
tuned_metrics = evaluate.compute_metrics(y_test, pred, proba)
|
|
rows.append({"model": name, "variant": "tuned", **tuned_metrics})
|
|
tuned_models[name] = (best_est, pred, proba)
|
|
best_params[name] = params
|
|
print(f" default pr_auc={default_metrics['pr_auc']:.4f} -> tuned pr_auc={tuned_metrics['pr_auc']:.4f}")
|
|
|
|
table = pd.DataFrame(rows).set_index(["model", "variant"])
|
|
evaluate.save_table(table, RESULTS_DIR / "tuning_comparison.csv", RESULTS_DIR / "tuning_comparison.md")
|
|
(RESULTS_DIR / "tuning_best_params.json").write_text(json.dumps(best_params, indent=2, default=str))
|
|
print()
|
|
return tuned_models
|
|
|
|
|
|
def section_calibration(X_train, y_train, X_test, y_test, tuned_models):
|
|
print("=== 4. Calibration curves ===")
|
|
logistic = models.baseline_models()["logistic_regression"]
|
|
logistic.fit(X_train, y_train)
|
|
logistic_proba = logistic.predict_proba(X_test)[:, 1]
|
|
|
|
default_lgbm = models.advanced_models()["lightgbm"]
|
|
default_lgbm.fit(X_train, y_train)
|
|
default_proba = default_lgbm.predict_proba(X_test)[:, 1]
|
|
|
|
tuned_proba = tuned_models["lightgbm"][2]
|
|
|
|
curves = {
|
|
"logistic_regression": (y_test.values, logistic_proba),
|
|
"lightgbm_default": (y_test.values, default_proba),
|
|
"lightgbm_tuned": (y_test.values, tuned_proba),
|
|
}
|
|
evaluate.plot_calibration(curves, RESULTS_DIR / "plots" / "calibration.png")
|
|
print(f" saved to {RESULTS_DIR / 'plots' / 'calibration.png'}\n")
|
|
|
|
|
|
def section_bootstrap(y_test, tuned_models, best_model_name="lightgbm"):
|
|
print("=== 5. Bootstrap 95% CIs (tuned model, 1000 resamples) ===")
|
|
_, _, proba = tuned_models[best_model_name]
|
|
summary = evaluate.bootstrap_metric_ci(y_test.values, proba, n_boot=1000)
|
|
print(summary)
|
|
evaluate.save_table(summary, RESULTS_DIR / "bootstrap_ci.csv", RESULTS_DIR / "bootstrap_ci.md")
|
|
print()
|
|
|
|
|
|
def section_area_stratified(df_raw, X_test, y_test, tuned_models, best_model_name="lightgbm"):
|
|
print("=== 6. Stratified evaluation by broad research area (tuned pooled model) ===")
|
|
_, pred, proba = tuned_models[best_model_name]
|
|
broad_area = data._broad_research_area(df_raw["publication_research_area"]).loc[X_test.index]
|
|
table = evaluate.stratified_metrics(y_test, pred, proba, broad_area)
|
|
print(table[["n", "founder_rate", "roc_auc", "pr_auc", "mcc"]])
|
|
evaluate.save_table(table, RESULTS_DIR / "area_stratified_pooled_model.csv", RESULTS_DIR / "area_stratified_pooled_model.md")
|
|
print()
|
|
return broad_area
|
|
|
|
|
|
def section_per_area_specialists(df_raw, X, y, X_test, y_test, tuned_models, broad_area_all, best_model_name="lightgbm", min_n=500):
|
|
print("=== 7. Per-area specialist models vs. pooled generalist ===")
|
|
broad_area_full = data._broad_research_area(df_raw["publication_research_area"])
|
|
counts = broad_area_full.value_counts()
|
|
areas = [a for a in counts[counts >= min_n].index if a != "n."]
|
|
|
|
_, pooled_pred, pooled_proba = tuned_models[best_model_name]
|
|
rows = []
|
|
for area in areas:
|
|
area_idx_all = broad_area_full[broad_area_full == area].index
|
|
X_area, y_area = X.loc[area_idx_all], y.loc[area_idx_all]
|
|
X_tr, X_te, y_tr, y_te = splits.stratified_holdout(X_area, y_area, test_size=0.2)
|
|
spw = (y_tr == 0).sum() / max((y_tr == 1).sum(), 1)
|
|
specialist = models.advanced_models(scale_pos_weight=spw)["lightgbm"]
|
|
_, spec_metrics, _, _ = evaluate.fit_and_evaluate(specialist, X_tr, y_tr, X_te, y_te)
|
|
rows.append({"area": area, "model": "specialist", "n_train": len(X_tr), "n_test": len(X_te), **spec_metrics})
|
|
|
|
pooled_area_test_idx = broad_area_all[broad_area_all == area].index
|
|
if len(pooled_area_test_idx) >= 20:
|
|
yt = y_test.loc[pooled_area_test_idx]
|
|
ypred = pd.Series(pooled_pred, index=X_test.index).loc[pooled_area_test_idx]
|
|
yproba = pd.Series(pooled_proba, index=X_test.index).loc[pooled_area_test_idx]
|
|
if yt.nunique() == 2:
|
|
pooled_metrics = evaluate.compute_metrics(yt, ypred, yproba)
|
|
rows.append({"area": area, "model": "pooled_on_subset", "n_train": None, "n_test": len(pooled_area_test_idx), **pooled_metrics})
|
|
print(f" area {area}: specialist pr_auc={spec_metrics['pr_auc']:.4f} (n_train={len(X_tr)})")
|
|
|
|
table = pd.DataFrame(rows).set_index(["area", "model"])
|
|
evaluate.save_table(table, RESULTS_DIR / "per_area_specialist_vs_pooled.csv", RESULTS_DIR / "per_area_specialist_vs_pooled.md")
|
|
print()
|
|
|
|
|
|
def main():
|
|
section_ablation()
|
|
|
|
print("Loading clean RQ1 dataset for CV/tuning/calibration/bootstrap/stratification...")
|
|
df_raw, X, y, groups = load_clean()
|
|
print(f" rows={len(X)} features={X.shape[1]}\n")
|
|
|
|
section_cross_validation(X, y)
|
|
|
|
X_train, X_test, y_train, y_test = splits.stratified_holdout(X, y, test_size=0.2)
|
|
tuned_models = section_tuning(X_train, y_train, X_test, y_test)
|
|
section_calibration(X_train, y_train, X_test, y_test, tuned_models)
|
|
section_bootstrap(y_test, tuned_models)
|
|
broad_area_test = section_area_stratified(df_raw, X_test, y_test, tuned_models)
|
|
section_per_area_specialists(df_raw, X, y, X_test, y_test, tuned_models, broad_area_test)
|
|
|
|
print(f"All RQ1 robustness results written to {RESULTS_DIR}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|