"""RQ1 retrained on the symmetric (landmark-design) dataset -- see src/symmetric.py. Compared to run_rq1.py (asymmetric preprocessing) this answers: how well can founders be distinguished from non-founders when BOTH classes are observed over comparable windows and features are constructed identically? Expect honest (lower) numbers than the 0.976 ROC-AUC of the asymmetric design, which was inflated by window-length leakage. Adds production-relevant checks the original run lacked: - temporal split (train on pre-2016 index years, test on 2016+): the prospective deployment setting; - monotonicity probe of P(founder) vs. publications-at-index (the shipped asymmetric model was an inverse-productivity score: 1 pub -> 0.996, 800 -> 0.0002); - reference score distribution saved for percentile-ranking in production. Run with: conda run -n potential python experiments/run_rq1_symmetric.py """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import joblib import numpy as np import pandas as pd from src import config, evaluate, models, splits, symmetric RESULTS_DIR = config.RESULTS_DIR / "rq1_symmetric" MODELS_DIR = RESULTS_DIR / "models" TEMPORAL_SPLIT_YEAR = 2016 # train index_year < this, test >= this def probability_by_pubs_decile(model, X_test, feats_test): """Median predicted P(founder) per pubs-at-index decile -- the check that caught the inverse-productivity artifact in the shipped model.""" proba = model.predict_proba(X_test)[:, 1] pubs = feats_test["pubs_at_index"].reset_index(drop=True) dec = pd.qcut(pubs, 10, labels=False, duplicates="drop") return pd.DataFrame({ "pubs_decile": dec, "pubs_at_index": pubs, "p_founder": proba }).groupby("pubs_decile").agg( pubs_median=("pubs_at_index", "median"), p_founder_median=("p_founder", "median"), n=("p_founder", "size") ) def main(): RESULTS_DIR.mkdir(parents=True, exist_ok=True) MODELS_DIR.mkdir(parents=True, exist_ok=True) (RESULTS_DIR / "plots").mkdir(exist_ok=True) print("Building symmetric RQ1 dataset ...") feats, attrition = symmetric.build_symmetric_dataset() pd.Series(attrition).to_csv(RESULTS_DIR / "attrition.csv") X, y, groups = symmetric.build_matrix(feats, include_institution=True) print(f" rows={len(X)} features={X.shape[1]} founders={int(y.sum())} non-founders={int((1 - y).sum())}") idx_train, idx_test, _, _ = splits.stratified_holdout(X.index.to_series(), y, test_size=0.2) idx_train, idx_test = idx_train.values, idx_test.values X_train, X_test = X.loc[idx_train], X.loc[idx_test] y_train, y_test = y.loc[idx_train], y.loc[idx_test] feats_test = feats.loc[idx_test] scale_pos_weight = (y_train == 0).sum() / (y_train == 1).sum() all_models = { **models.baseline_models(), **models.advanced_models(scale_pos_weight=scale_pos_weight), "stacking_ensemble": models.stacking_model(scale_pos_weight=scale_pos_weight), } rows, fitted, curves = [], {}, {} for name, model in all_models.items(): print(f"Training {name} ...") max_train = 6000 if name == "svm_rbf" else None model, metrics, pred, proba = evaluate.fit_and_evaluate( model, X_train, y_train, X_test, y_test, max_train_size=max_train ) rows.append({"model": name, **metrics}) fitted[name] = (model, pred, proba) curves[name] = (y_test.values, proba) table = evaluate.results_table(rows, sort_by="pr_auc") print(table) evaluate.save_table(table, RESULTS_DIR / "model_comparison.csv", RESULTS_DIR / "model_comparison.md") best_overall = table.index[0] best_model = fitted[best_overall][0] print(f"Best overall: {best_overall}") joblib.dump(best_model, MODELS_DIR / f"{best_overall}.joblib") # --- Monotonicity probe ------------------------------------------------- probe = probability_by_pubs_decile(best_model, X_test, feats_test) print("\nP(founder) by pubs-at-index decile (was strictly decreasing in the shipped model):") print(probe) probe.to_csv(RESULTS_DIR / "probability_by_pubs_decile.csv") # --- Temporal (prospective) split -------------------------------------- print(f"\nTemporal split: train index_year < {TEMPORAL_SPLIT_YEAR}, test >= {TEMPORAL_SPLIT_YEAR} ...") is_late = feats["index_year"] >= TEMPORAL_SPLIT_YEAR Xtr, ytr = X[~is_late.values], y[~is_late.values] Xte, yte = X[is_late.values], y[is_late.values] print(f" train: {len(Xtr)} rows ({int(ytr.sum())} founders) | test: {len(Xte)} rows ({int(yte.sum())} founders)") spw = (ytr == 0).sum() / (ytr == 1).sum() temporal_rows = [] for name, model in models.advanced_models(scale_pos_weight=spw).items(): if name == "svm_rbf": continue model.fit(Xtr, ytr) proba = model.predict_proba(Xte)[:, 1] pred = (proba >= 0.5).astype(int) temporal_rows.append({"model": name, **evaluate.compute_metrics(yte, pred, proba)}) temporal_table = evaluate.results_table(temporal_rows, sort_by="pr_auc") print(temporal_table) evaluate.save_table(temporal_table, RESULTS_DIR / "temporal_split.csv", RESULTS_DIR / "temporal_split.md") # --- Leave-one-institution-out ------------------------------------------ print("\nLeave-one-institution-out ...") X_logo, y_logo, groups_logo = symmetric.build_matrix(feats, include_institution=False) logo_rows = [] for held_out, train_idx, test_idx in splits.leave_one_institution_out(X_logo, y_logo, groups_logo): spw = (y_logo.iloc[train_idx] == 0).sum() / (y_logo.iloc[train_idx] == 1).sum() for name in ["random_forest", "xgboost", "lightgbm"]: model = models.advanced_models(scale_pos_weight=spw)[name] model.fit(X_logo.iloc[train_idx], y_logo.iloc[train_idx]) proba = model.predict_proba(X_logo.iloc[test_idx])[:, 1] pred = (proba >= 0.5).astype(int) logo_rows.append({"held_out_institution": held_out, "model": name, **evaluate.compute_metrics(y_logo.iloc[test_idx], pred, proba)}) print(f" held out {held_out}: done") logo_df = pd.DataFrame(logo_rows) evaluate.save_table(logo_df.set_index(["held_out_institution", "model"]), RESULTS_DIR / "leave_one_institution_out.csv", RESULTS_DIR / "leave_one_institution_out.md") print(logo_df.groupby("model")[["roc_auc", "pr_auc", "mcc"]].mean()) # --- Permutation importance --------------------------------------------- from src import explain tree_models = {"random_forest", "xgboost", "lightgbm", "catboost"} target = best_overall if best_overall in tree_models else next((m for m in table.index if m in tree_models), None) if target: explain.permutation_importance_report( fitted[target][0], X_test, y_test, RESULTS_DIR / "permutation_importance.csv", RESULTS_DIR / "plots" / "permutation_importance.png", ) # --- Reference score distribution for production percentile ranking ----- ref_scores = best_model.predict_proba(X)[:, 1] ref = pd.DataFrame({ "quantile": np.linspace(0, 1, 1001), "score": np.quantile(ref_scores, np.linspace(0, 1, 1001)), }) ref.to_csv(MODELS_DIR / "reference_score_quantiles.csv", index=False) print(f"\nAll results written to {RESULTS_DIR}") if __name__ == "__main__": main()