Files
smartguide/service/scripts/profiling/founding_potential/run_rq1.py
T
2026-08-27 13:53:10 +02:00

132 lines
6.0 KiB
Python

"""RQ1: build a classifier that identifies founders from non-founders.
Pipeline:
1. Load the leakage-safe full-profile dataset (all 8 institutions).
2. Primary stratified 80/20 split -> train & evaluate primitive baselines and
stronger/state-of-the-art models (+ a stacked ensemble + a PyTorch MLP).
3. McNemar's test between the best baseline and the best overall model.
4. Leave-one-institution-out cross-validation with the top tree models, to
check whether "founder signal" generalizes across universities rather than
just memorizing institution-specific quirks.
5. Permutation importance + SHAP on the best model.
Run with: conda run -n potential python experiments/run_rq1.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, data, evaluate, explain, models, splits
RESULTS_DIR = config.RESULTS_DIR / "rq1"
MODELS_DIR = RESULTS_DIR / "models"
MAX_SVM_TRAIN = 6000
def main():
print("Loading RQ1 dataset (datasets_complete, leakage columns dropped)...")
df_raw = data.load_rq1_raw()
X, y, groups = data.build_rq1_matrix(df_raw, include_institution=True)
print(f" rows={len(X)} features={X.shape[1]} founders={int(y.sum())} non-founders={int((1 - y).sum())}")
X_train, X_test, y_train, y_test = splits.stratified_holdout(X, y, test_size=0.2)
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),
}
try:
from src.nn import TorchMLPClassifier
all_models["torch_mlp"] = TorchMLPClassifier()
except ImportError:
print(" torch not available, skipping the MLP baseline")
rows = []
fitted = {}
curves = {}
for name, model in all_models.items():
print(f"Training {name} ...")
max_train = MAX_SVM_TRAIN 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 / "rq1_model_comparison.csv", RESULTS_DIR / "rq1_model_comparison.md")
best_baseline = evaluate.results_table(
[r for r in rows if r["model"] in models.baseline_models()], sort_by="pr_auc"
).index[0]
best_overall = table.index[0]
print(f"Best baseline: {best_baseline} | Best overall: {best_overall}")
_, pred_baseline, _ = fitted[best_baseline]
_, pred_best, _ = fitted[best_overall]
mcnemar_result = evaluate.mcnemar_test(y_test.values, pred_baseline, pred_best)
print(f"McNemar's test ({best_baseline} vs {best_overall}): {mcnemar_result}")
pd.Series(mcnemar_result).to_csv(RESULTS_DIR / "mcnemar_baseline_vs_best.csv")
evaluate.plot_confusion(y_test, fitted[best_baseline][1], f"Confusion matrix - {best_baseline}", RESULTS_DIR / "plots" / f"confusion_{best_baseline}.png")
evaluate.plot_confusion(y_test, fitted[best_overall][1], f"Confusion matrix - {best_overall}", RESULTS_DIR / "plots" / f"confusion_{best_overall}.png")
top_curve_models = table.head(5).index.tolist()
evaluate.plot_roc_pr({k: curves[k] for k in top_curve_models}, RESULTS_DIR / "plots" / "top5")
MODELS_DIR.mkdir(parents=True, exist_ok=True)
joblib.dump(fitted[best_overall][0], MODELS_DIR / f"{best_overall}.joblib")
# --- Leave-one-institution-out generalization test ---
print("\nLeave-one-institution-out generalization test...")
X_logo, y_logo, groups_logo = data.build_rq1_matrix(df_raw, include_institution=False)
logo_rows = []
logo_model_names = ["random_forest", "xgboost", "lightgbm"]
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()
candidates = models.advanced_models(scale_pos_weight=spw)
for name in logo_model_names:
model = candidates[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)
metrics = evaluate.compute_metrics(y_logo.iloc[test_idx], pred, proba)
logo_rows.append({"held_out_institution": held_out, "model": name, **metrics})
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 / "rq1_leave_one_institution_out.csv", RESULTS_DIR / "rq1_leave_one_institution_out.md")
print(logo_df.groupby("model")[["roc_auc", "pr_auc", "mcc"]].mean())
# --- Explainability; falls back to a tree model since SHAP TreeExplainer
# needs one ---
tree_models = {"random_forest", "xgboost", "lightgbm", "catboost"}
explain_target = best_overall if best_overall in tree_models else next((m for m in table.index if m in tree_models), None)
if explain_target is not None:
print(f"\nExplainability on {explain_target} ...")
explain_model = fitted[explain_target][0]
explain.permutation_importance_report(
explain_model, X_test, y_test,
RESULTS_DIR / "permutation_importance.csv", RESULTS_DIR / "plots" / "permutation_importance.png",
)
sample = X_test.sample(min(500, len(X_test)), random_state=config.RANDOM_STATE)
try:
explain.shap_summary(explain_model, sample, RESULTS_DIR / "plots" / "shap_summary.png")
except Exception as exc: # SHAP TreeExplainer support varies by model internals
print(f" SHAP summary skipped: {exc}")
print(f"\nAll RQ1 results written to {RESULTS_DIR}")
if __name__ == "__main__":
main()