"""RQ2: how far in advance can we tell that a researcher will found a company within N years, using only information available at that point in time? Pipeline: 1. Per-offset comparison: baselines vs. advanced models trained/evaluated separately at offsets 1, 2 and 3 years before founding (half-profiles). 2. Pooled multi-horizon model: one model trained across offsets 1-3 with `offset` as an explicit feature, then evaluated on genuinely unseen founders/non-founders at offset 3 (in-range) and offset 5 (extrapolation beyond anything seen in training) -- the direct answer to "up to how many years out can we predict founding". 3. Survival analysis (CoxPH): a principled alternative to picking a fixed horizon -- gives P(founds within k years) for any k and treats still-active non-founders as censored rather than as permanent negatives. Run with: conda run -n potential python experiments/run_rq2.py """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import joblib import pandas as pd from sklearn.metrics import roc_auc_score from src import config, data, evaluate, models, splits, survival RESULTS_DIR = config.RESULTS_DIR / "rq2" MODELS_DIR = RESULTS_DIR / "models" def run_single_offset_comparison(): all_rows = [] for offset in config.RQ2_TRAIN_OFFSETS: print(f"\n=== offset={offset} year(s) before founding ===") df = data.load_rq2_train_dataset(offset) X, y, _ = data.build_rq2_matrix(df, include_offset=False) 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() baselines = models.baseline_models() advanced = models.advanced_models(scale_pos_weight=spw) candidates = { "dummy_most_frequent": baselines["dummy_most_frequent"], "logistic_regression": baselines["logistic_regression"], "decision_tree": baselines["decision_tree"], "random_forest": advanced["random_forest"], "xgboost": advanced["xgboost"], "lightgbm": advanced["lightgbm"], } for name, model in candidates.items(): _, metrics, _, _ = evaluate.fit_and_evaluate(model, X_train, y_train, X_test, y_test) all_rows.append({"offset_years": offset, "model": name, **metrics}) df_results = pd.DataFrame(all_rows) evaluate.save_table( df_results.set_index(["offset_years", "model"]), RESULTS_DIR / "rq2_offset_comparison.csv", RESULTS_DIR / "rq2_offset_comparison.md", ) print(df_results.pivot_table(index="model", columns="offset_years", values="pr_auc")) return df_results def run_pooled_horizon_model(): print("\n=== Pooled multi-horizon model (offsets 1-3 train) ===") train_frames = [data.load_rq2_train_dataset(o) for o in config.RQ2_TRAIN_OFFSETS] df_train_all = pd.concat(train_frames, ignore_index=True) X, y, _ = data.build_rq2_matrix(df_train_all, include_offset=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() pooled_model_name = "lightgbm" pooled_model = models.advanced_models(scale_pos_weight=spw)[pooled_model_name] pooled_model, metrics, _, _ = evaluate.fit_and_evaluate(pooled_model, X_train, y_train, X_test, y_test) print(f"Pooled {pooled_model_name} held-out metrics: {metrics}") MODELS_DIR.mkdir(parents=True, exist_ok=True) joblib.dump(pooled_model, MODELS_DIR / f"pooled_{pooled_model_name}.joblib") validation_rows = [] for offset in config.RQ2_VALIDATION_OFFSETS: df_val = data.load_rq2_validation_dataset(offset) X_val, y_val, _ = data.build_rq2_matrix(df_val, include_offset=True) X_val = X_val.reindex(columns=X_train.columns, fill_value=0) proba_val = pooled_model.predict_proba(X_val)[:, 1] pred_val = (proba_val >= 0.5).astype(int) val_metrics = evaluate.compute_metrics(y_val, pred_val, proba_val) regime = "in-range" if offset in config.RQ2_TRAIN_OFFSETS else "extrapolation" validation_rows.append({"offset_years": offset, "regime": regime, **val_metrics}) print(f" offset={offset} ({regime}) held-out validation: {val_metrics}") val_df = pd.DataFrame(validation_rows).set_index("offset_years") evaluate.save_table(val_df, RESULTS_DIR / "rq2_horizon_validation.csv", RESULTS_DIR / "rq2_horizon_validation.md") return pooled_model, X_train.columns, val_df def run_survival_analysis(pooled_val_df): print("\n=== Survival analysis (CoxPH) ===") df_raw = data.load_survival_raw() frame = survival.build_survival_frame(df_raw) train_frame, test_frame, _, _ = splits.stratified_holdout(frame, frame["event"], test_size=0.2) cph = survival.fit_coxph(train_frame) c_index = survival.evaluate_concordance(cph, test_frame) print(f"CoxPH concordance index (held-out): {c_index:.3f}") eligible, label_5y = survival.landmark_labels(test_frame, years=5) eligible_frame = test_frame[eligible] eligible_label = label_5y[eligible] proba_5y = survival.probability_of_founding_within(cph, eligible_frame, years=5) survival_auc = roc_auc_score(eligible_label, proba_5y) print(f"CoxPH P(founds within 5y) AUC on eligible held-out rows: {survival_auc:.3f} (n={len(eligible_frame)})") summary_rows = [ {"method": "CoxPH survival model", "metric": "concordance_index", "value": c_index}, {"method": "CoxPH survival model", "metric": "auc_within_5y", "value": survival_auc}, ] if pooled_val_df is not None and 5 in pooled_val_df.index: summary_rows.append( { "method": "Pooled classifier (offset=5, extrapolation)", "metric": "roc_auc", "value": pooled_val_df.loc[5, "roc_auc"], } ) summary = pd.DataFrame(summary_rows) evaluate.save_table(summary.set_index(["method", "metric"]), RESULTS_DIR / "rq2_survival_vs_classifier.csv") cph.print_summary() return cph def main(): RESULTS_DIR.mkdir(parents=True, exist_ok=True) run_single_offset_comparison() _, _, val_df = run_pooled_horizon_model() run_survival_analysis(val_df) print(f"\nAll RQ2 results written to {RESULTS_DIR}") if __name__ == "__main__": main()