adjusted the profiling pipelines: multipliers & (potential) founders, explorative analyses
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
2026-08-27 13:53:10 +02:00
parent 88e0b44d54
commit c26c3f33f5
154 changed files with 18795 additions and 0 deletions
@@ -0,0 +1,147 @@
"""Empirical career-trajectory curves for index-date truncation of totals.
Estimates, from the founders' raw trajectories, the average cumulative-share
curve F(u) = fraction of lifetime output accumulated by career fraction
u = (index_year - first_year) / (last_year + 1 - first_year), per activity type
and career-length stratum, so totals truncate as `total * F(u)`.
The construction is applied to BOTH classes: founders' exact counts only fit and
validate the curves. Giving founders exact counts and non-founders smoothed ones
would let the residual noise texture separate the classes on its own — the exact
artifact the symmetric redesign removes. See docs/DESIGN_NOTES.md.
"""
import numpy as np
import pandas as pd
from . import config
GRID = np.linspace(0.0, 1.0, 101)
MIN_TOTAL_FOR_FIT = 5 # people with fewer records give degenerate share curves
MIN_CAREER_YEARS = 5
CAREER_LENGTH_BINS = [0, 12, 25, np.inf] # short / medium / long careers
CAREER_LENGTH_LABELS = ["short", "medium", "long"]
def load_yearly(insts=None):
from .yearly_counts import YEARLY_DIR
insts = insts or config.INSTITUTIONS
frames = []
for inst in insts:
df = pd.read_csv(YEARLY_DIR / f"{inst}_person_year.csv")
df["institution"] = inst
frames.append(df)
return pd.concat(frames, ignore_index=True)
def _person_curves(yearly, value_col):
"""Per-person (career_fraction, cumulative_share) trajectories."""
df = yearly[yearly[value_col] > 0][["author_people", "year", value_col]].copy()
g = df.groupby("author_people")
stats = g.agg(first=("year", "min"), last=("year", "max"), total=(value_col, "sum"))
stats["length"] = stats["last"] + 1 - stats["first"]
keep = stats[(stats["total"] >= MIN_TOTAL_FOR_FIT) & (stats["length"] >= MIN_CAREER_YEARS)]
df = df[df["author_people"].isin(keep.index)]
df = df.merge(keep, left_on="author_people", right_index=True)
df = df.sort_values(["author_people", "year"])
df["cum"] = df.groupby("author_people")[value_col].cumsum()
# share accumulated by the END of that year; career fraction of that year-end
df["u"] = (df["year"] + 1 - df["first"]) / df["length"]
df["share"] = df["cum"] / df["total"]
df["stratum"] = pd.cut(df["length"], CAREER_LENGTH_BINS, labels=CAREER_LENGTH_LABELS)
return df
def fit_curves(yearly):
"""Mean cumulative-share curve on GRID, per activity type and career-length
stratum. Returns {metric: {stratum: np.array over GRID}}."""
curves = {}
for metric in ["pubs", "patents", "grants_capped"]:
pc = _person_curves(yearly, metric)
curves[metric] = {}
for stratum in CAREER_LENGTH_LABELS:
sub = pc[pc["stratum"] == stratum]
if len(sub) < 100: # too few trajectories: fall back to all strata pooled
sub = pc
# interpolate each person's step curve onto GRID, then average
per_person = []
for _, grp in sub.groupby("author_people"):
per_person.append(np.interp(GRID, grp["u"], grp["share"], left=0.0, right=1.0))
mean_curve = np.mean(per_person, axis=0)
mean_curve = np.clip(np.maximum.accumulate(mean_curve), 0.0, 1.0)
mean_curve[0], mean_curve[-1] = 0.0, 1.0
curves[metric][stratum] = mean_curve
return curves
def curve_fraction(curves, metric, career_length, u):
"""F(u) lookup with career-length stratification. Vectorized over u."""
stratum = pd.cut(pd.Series([career_length]), CAREER_LENGTH_BINS, labels=CAREER_LENGTH_LABELS).iloc[0]
return np.interp(np.clip(u, 0.0, 1.0), GRID, curves[metric][str(stratum)])
def truncate_total(curves, metric, total, first_year, last_year, index_year):
"""`total * F(u)` truncation used identically for both classes.
Index at/before career start -> 0; index beyond last active year -> total.
"""
if pd.isna(total) or total <= 0 or pd.isna(first_year) or pd.isna(last_year):
return 0.0
length = last_year + 1 - first_year
if length <= 0:
return 0.0
u = (index_year - first_year) / length
return float(total) * float(curve_fraction(curves, metric, length, u))
def validate_on_founders(yearly, curves, index_years):
"""Exact vs curve-predicted pre-index counts, on founders' raw trajectories.
`index_years`: Series of index year per author_people (their founding year).
Returns a tidy frame with exact, predicted, and naive-uniform predictions,
for error reporting per metric.
"""
rows = []
for metric in ["pubs", "patents", "grants_capped"]:
df = yearly[yearly[metric] > 0]
g = df.groupby("author_people")
stats = g.agg(first=("year", "min"), last=("year", "max"), total=(metric, "sum"))
stats = stats.join(index_years.rename("index_year"), how="inner")
stats = stats[(stats["total"] >= MIN_TOTAL_FOR_FIT)]
exact = (
df[df["author_people"].isin(stats.index)]
.merge(stats[["index_year"]], left_on="author_people", right_index=True)
.query("year < index_year")
.groupby("author_people")[metric]
.sum()
)
for person, s in stats.iterrows():
length = s["last"] + 1 - s["first"]
u = np.clip((s["index_year"] - s["first"]) / length, 0.0, 1.0)
pred = s["total"] * curve_fraction(curves, metric, length, u)
rows.append({
"metric": metric,
"author_people": person,
"total": s["total"],
"exact_before": float(exact.get(person, 0.0)),
"curve_pred": float(pred),
"uniform_pred": float(s["total"] * u),
})
return pd.DataFrame(rows)
def save_curves(curves, path):
rows = []
for metric, strata in curves.items():
for stratum, arr in strata.items():
for u, f in zip(GRID, arr):
rows.append({"metric": metric, "stratum": stratum, "u": u, "F": f})
pd.DataFrame(rows).to_csv(path, index=False)
def load_curves(path):
df = pd.read_csv(path)
curves = {}
for (metric, stratum), grp in df.groupby(["metric", "stratum"]):
curves.setdefault(metric, {})[stratum] = grp.sort_values("u")["F"].to_numpy()
return curves
@@ -0,0 +1,135 @@
"""Shared paths, constants and column allow-lists for the founder-potential experiments.
Whole column families are excluded from RQ1 because they are computed relative
to a founding event and are identically zero for non-founders — see
docs/DESIGN_NOTES.md, "config.py".
"""
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
EVAL_DIR = ROOT / "evaluation"
EXPERIMENTS_DIR = ROOT / "experiments"
RESULTS_DIR = EXPERIMENTS_DIR / "results"
COMPLETE_DIR = EVAL_DIR / "datasets_complete"
HALFPROFILE_DIRS = {
1: EVAL_DIR / "datasets_halfprofiles_offset1",
2: EVAL_DIR / "datasets_halfprofiles_offset2",
3: EVAL_DIR / "datasets_halfprofiles_offset3",
}
VALIDATION_HALFPROFILE_DIRS = {
3: EVAL_DIR / "datasets_halfprofiles_validation_offset3",
5: EVAL_DIR / "datasets_halfprofiles_validation_offset5",
}
INSTITUTIONS = [
"berkeley",
"harvard",
"muenchen",
"oxford",
"stanford",
"telaviv",
"toronto",
"ude",
]
RANDOM_STATE = 42
LABEL_COLUMN = "Company_founded"
# Identifier / non-feature columns present in every raw file.
ID_COLUMNS = ["name", "company", "company_details", "founded_on"]
# Degenerate/leaky for RQ1: all zero for non-founders.
_HIST_LEAK_COLUMNS = [
f"hist_{kind}_FN{sign}{k}"
for kind in ("pub", "pat", "grant")
for sign in ("+", "-")
for k in range(1, 21)
] + [f"hist_{kind}_FN" for kind in ("pub", "pat", "grant")]
_BEFORE_AFTER_LEAK_COLUMNS = [
f"{metric}_{when}_founding"
for metric in ("publications", "patents", "grants", "activities")
for when in ("before", "after")
]
RQ1_DROP_COLUMNS = (
ID_COLUMNS + [LABEL_COLUMN] + _HIST_LEAK_COLUMNS + _BEFORE_AFTER_LEAK_COLUMNS
)
RQ1_CATEGORICAL_COLUMNS = [
"publication_research_area",
"patent_research_area",
"grant_research_area",
"institution",
]
# Everything else numeric in datasets_complete that is NOT dropped/categorical.
RQ1_NUMERIC_COLUMNS = [
"h-index",
"i10-index",
"publications",
"pub_citation_mean",
"pub_citation_sum",
"first_publication_year",
"last_publication_year",
"linked_patents_to_publications",
"patents",
"pat_citation_mean",
"pat_citation_sum",
"first_patent_year",
"last_patent_year",
"grants",
"first_grant_year",
"last_grant_year",
"affiliations",
"activities_total",
"g-index",
"industry_collab_papers",
"grant_research_impact",
"grant_innovation_impact",
]
# Skewed count-like columns worth a log1p transform.
RQ1_LOG_COLUMNS = [
"publications",
"pub_citation_sum",
"patents",
"pat_citation_sum",
"grants",
"affiliations",
"activities_total",
"linked_patents_to_publications",
]
# Curated feature set already used for the half-profile (RQ2) datasets.
RQ2_NUMERIC_COLUMNS = [
"pub_citation_mean",
"publications",
"h-index",
"i10-index",
"g-index",
"industry_collab_papers",
"linked_patents_to_publications",
"patents",
"pat_citation_mean",
"grants",
"grant_research_impact",
"grant_innovation_impact",
"affiliations",
]
RQ2_CATEGORICAL_COLUMNS = ["institution"]
RQ2_LOG_COLUMNS = ["publications", "patents", "grants", "affiliations"]
RQ2_TRAIN_OFFSETS = [1, 2, 3]
RQ2_VALIDATION_OFFSETS = [3, 5]
RQ2_NONFOUNDER_TRAIN_FRACTION = 0.7 # rest reserved for horizon-validation, see data.py
# Founders' lifetime totals include post-founding activity (reverse-causation
# confound); for these 4 metrics a validated `_before_founding` split exists.
RQ1_PREFOUNDING_PAIRS = {
"publications": "publications_before_founding",
"patents": "patents_before_founding",
"grants": "grants_before_founding",
"activities_total": "activities_before_founding",
}
@@ -0,0 +1,177 @@
"""Leakage-safe loading of the founder / non-founder datasets for RQ1 and RQ2.
RQ1 reads `evaluation/datasets_complete` minus identifier and leaky columns;
RQ2 pairs the curated half-profile datasets with non-founders split 70/30 per
institution once, so no individual appears in both training and
horizon-generalization testing. Rationale: docs/DESIGN_NOTES.md, "data.py".
"""
from functools import lru_cache
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from . import config, outliers
def _read_csv(path, usecols=None):
return pd.read_csv(path, usecols=usecols)
def _broad_research_area(series):
"""Collapse the ~100+ specific Dimensions research-area codes (e.g. '3205
Medical Biochemistry and Metabolomics') down to their ~25 broad parent
categories (e.g. '32') so one-hot encoding doesn't explode into hundreds of
sparse, mostly-empty columns."""
return series.fillna("n.a.").astype(str).str.strip().str.slice(0, 2)
def _apply_prefounding_equivalent(df):
"""Make lifetime-total columns comparable across classes (see config.RQ1_PREFOUNDING_PAIRS).
For founders, replace each lifetime total with its validated `_before_founding`
split (falling back to the lifetime total when that split is missing, e.g. due
to an unparseable `founded_on` date). Non-founders are left untouched: with no
founding event, their full lifetime total is already "pre-founding".
"""
df = df.copy()
is_founder = df[config.LABEL_COLUMN] == 1
for total_col, before_col in config.RQ1_PREFOUNDING_PAIRS.items():
corrected = df[total_col].copy()
before = pd.to_numeric(df[before_col], errors="coerce")
use_before = is_founder & before.notna()
corrected.loc[use_before] = before.loc[use_before]
df[total_col] = corrected
return df
# ---------------------------------------------------------------------------
# RQ1: full-profile founder vs. non-founder
# ---------------------------------------------------------------------------
def load_rq1_raw(drop_outliers=True, apply_prefounding_fix=True):
"""Concatenate founders + non-founders across all institutions, tagged with
an `institution` column and the `Company_founded` label.
Applies the pre-founding-equivalent correction (see
`_apply_prefounding_equivalent`) and, by default, drops rows flagged as
multivariate outliers by `outliers.flag_outliers` (Isolation Forest in
log-space -- see `src/outliers.py` for why this replaced a hard `< 1000` cutoff).
`apply_prefounding_fix=False` is only for the before/after ablation comparison
in `run_rq1_robustness.py`; leave it True otherwise.
"""
frames = []
for inst in config.INSTITUTIONS:
founders = _read_csv(config.COMPLETE_DIR / f"{inst}_features_dataset.csv")
nonfounders = _read_csv(config.COMPLETE_DIR / f"{inst}_nonfounders_features_dataset.csv")
founders["institution"] = inst
nonfounders["institution"] = inst
frames.append(founders)
frames.append(nonfounders)
df = pd.concat(frames, ignore_index=True)
if apply_prefounding_fix:
df = _apply_prefounding_equivalent(df)
if drop_outliers:
df = df[~outliers.flag_outliers(df)]
return df.reset_index(drop=True)
def build_rq1_matrix(df, include_institution=True):
"""Turn the raw RQ1 dataframe into a model-ready (X, y) pair.
`include_institution=False` drops the institution one-hot columns, used for
the leave-one-institution-out generalization test so the model cannot key
off an institution indicator it never saw during that fold.
"""
y = df[config.LABEL_COLUMN].astype(int)
numeric = df[config.RQ1_NUMERIC_COLUMNS].apply(pd.to_numeric, errors="coerce").fillna(0)
for col in config.RQ1_LOG_COLUMNS:
numeric[col] = np.log1p(numeric[col].clip(lower=0))
research_area_cols = ["publication_research_area", "patent_research_area", "grant_research_area"]
cat_df = pd.DataFrame({col: _broad_research_area(df[col]) for col in research_area_cols})
if include_institution:
cat_df["institution"] = df["institution"]
categorical = pd.get_dummies(cat_df, prefix=cat_df.columns.tolist())
X = pd.concat([numeric, categorical], axis=1)
groups = df["institution"]
return X, y, groups
# ---------------------------------------------------------------------------
# RQ2: founds-within-N-years (half-profile / multi-horizon)
# ---------------------------------------------------------------------------
_RQ2_USECOLS = ["name", config.LABEL_COLUMN] + config.RQ2_NUMERIC_COLUMNS
@lru_cache(maxsize=None)
def _nonfounder_pool_split(institution):
"""Deterministic 70/30 split of an institution's non-founders into a
training pool (offsets 1-3) and a horizon-validation holdout (offsets 3/5)."""
df = _read_csv(config.COMPLETE_DIR / f"{institution}_nonfounders_features_dataset.csv", usecols=_RQ2_USECOLS)
train_pool, holdout_pool = train_test_split(
df, train_size=config.RQ2_NONFOUNDER_TRAIN_FRACTION, random_state=config.RANDOM_STATE
)
return train_pool.reset_index(drop=True), holdout_pool.reset_index(drop=True)
def load_rq2_train_dataset(offset):
"""Founders truncated at `offset` years pre-founding + the non-founder training pool."""
assert offset in config.RQ2_TRAIN_OFFSETS
frames = []
for inst in config.INSTITUTIONS:
founders = _read_csv(config.HALFPROFILE_DIRS[offset] / f"{inst}_features_dataset.csv")
founders = founders[["name", config.LABEL_COLUMN] + config.RQ2_NUMERIC_COLUMNS]
founders["institution"] = inst
nonfounders, _ = _nonfounder_pool_split(inst)
nonfounders = nonfounders.copy()
nonfounders["institution"] = inst
frames.append(founders)
frames.append(nonfounders)
df = pd.concat(frames, ignore_index=True)
df["offset"] = offset
return df.reset_index(drop=True)
def load_rq2_validation_dataset(offset):
"""Held-out horizon-generalization set: unseen founders truncated at `offset`
years pre-founding + the reserved (never-trained-on) non-founder holdout pool."""
assert offset in config.RQ2_VALIDATION_OFFSETS
frames = []
for inst in config.INSTITUTIONS:
founders = _read_csv(config.VALIDATION_HALFPROFILE_DIRS[offset] / f"{inst}_features_dataset.csv")
founders = founders[["name", config.LABEL_COLUMN] + config.RQ2_NUMERIC_COLUMNS]
founders["institution"] = inst
_, holdout = _nonfounder_pool_split(inst)
holdout = holdout.copy()
holdout["institution"] = inst
frames.append(founders)
frames.append(holdout)
df = pd.concat(frames, ignore_index=True)
df["offset"] = offset
return df.reset_index(drop=True)
def build_rq2_matrix(df, include_offset=False):
y = df[config.LABEL_COLUMN].astype(int)
numeric = df[config.RQ2_NUMERIC_COLUMNS].apply(pd.to_numeric, errors="coerce").fillna(0)
for col in config.RQ2_LOG_COLUMNS:
numeric[col] = np.log1p(numeric[col].clip(lower=0))
if include_offset and "offset" in df.columns:
numeric["offset"] = df["offset"]
institution = pd.Categorical(df["institution"], categories=config.INSTITUTIONS)
categorical = pd.get_dummies(institution, prefix="institution")
X = pd.concat([numeric.reset_index(drop=True), categorical.reset_index(drop=True)], axis=1)
groups = df["institution"].reset_index(drop=True)
return X, y, groups
def load_survival_raw():
"""Raw RQ1 dataframe, reused by src/survival.py to build durations/events."""
return load_rq1_raw()
@@ -0,0 +1,245 @@
"""Metrics, plots and statistical model-comparison utilities."""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.calibration import calibration_curve
from sklearn.metrics import (
accuracy_score,
average_precision_score,
brier_score_loss,
confusion_matrix,
f1_score,
matthews_corrcoef,
mean_absolute_error,
precision_recall_curve,
precision_score,
r2_score,
recall_score,
roc_auc_score,
roc_curve,
root_mean_squared_error,
)
from sklearn.model_selection import StratifiedKFold
from statsmodels.stats.contingency_tables import mcnemar
def compute_metrics(y_true, y_pred, y_proba):
return {
"accuracy": accuracy_score(y_true, y_pred),
"precision": precision_score(y_true, y_pred, zero_division=0),
"recall": recall_score(y_true, y_pred, zero_division=0),
"f1": f1_score(y_true, y_pred, zero_division=0),
"roc_auc": roc_auc_score(y_true, y_proba),
"pr_auc": average_precision_score(y_true, y_proba),
"mcc": matthews_corrcoef(y_true, y_pred),
"brier": brier_score_loss(y_true, y_proba),
}
def fit_and_evaluate(model, X_train, y_train, X_test, y_test, max_train_size=None, random_state=42):
if max_train_size is not None and len(X_train) > max_train_size:
rng = np.random.RandomState(random_state)
idx = rng.choice(len(X_train), size=max_train_size, replace=False)
X_train = X_train.iloc[idx] if hasattr(X_train, "iloc") else X_train[idx]
y_train = y_train.iloc[idx] if hasattr(y_train, "iloc") else y_train[idx]
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
pred = (proba >= 0.5).astype(int)
metrics = compute_metrics(y_test, pred, proba)
return model, metrics, pred, proba
def results_table(rows, sort_by="pr_auc"):
"""`rows`: list of dicts, each with a 'model' key plus metric keys."""
df = pd.DataFrame(rows).set_index("model")
return df.sort_values(sort_by, ascending=False)
def save_table(df, csv_path, md_path=None):
csv_path.parent.mkdir(parents=True, exist_ok=True)
df.to_csv(csv_path)
if md_path is not None:
md_path.write_text(df.to_markdown())
def plot_confusion(y_true, y_pred, title, save_path):
cm = confusion_matrix(y_true, y_pred)
fig, ax = plt.subplots(figsize=(4, 4))
ax.imshow(cm, cmap="Blues")
for (i, j), v in np.ndenumerate(cm):
ax.text(j, i, str(v), ha="center", va="center")
ax.set_xticks([0, 1])
ax.set_xticklabels(["non-founder", "founder"])
ax.set_yticks([0, 1])
ax.set_yticklabels(["non-founder", "founder"])
ax.set_xlabel("Predicted")
ax.set_ylabel("Actual")
ax.set_title(title)
save_path.parent.mkdir(parents=True, exist_ok=True)
fig.tight_layout()
fig.savefig(save_path, dpi=150)
plt.close(fig)
def plot_roc_pr(curves, save_path_prefix):
"""`curves`: dict[model_name] -> (y_true, y_proba)."""
save_path_prefix.parent.mkdir(parents=True, exist_ok=True)
fig, ax = plt.subplots(figsize=(5, 5))
for name, (y_true, y_proba) in curves.items():
fpr, tpr, _ = roc_curve(y_true, y_proba)
ax.plot(fpr, tpr, label=f"{name} (AUC={roc_auc_score(y_true, y_proba):.3f})")
ax.plot([0, 1], [0, 1], "--", color="grey")
ax.set_xlabel("False positive rate")
ax.set_ylabel("True positive rate")
ax.set_title("ROC curves")
ax.legend(fontsize=8)
fig.tight_layout()
fig.savefig(f"{save_path_prefix}_roc.png", dpi=150)
plt.close(fig)
fig, ax = plt.subplots(figsize=(5, 5))
for name, (y_true, y_proba) in curves.items():
precision, recall, _ = precision_recall_curve(y_true, y_proba)
ax.plot(recall, precision, label=f"{name} (AP={average_precision_score(y_true, y_proba):.3f})")
ax.set_xlabel("Recall")
ax.set_ylabel("Precision")
ax.set_title("Precision-Recall curves")
ax.legend(fontsize=8)
fig.tight_layout()
fig.savefig(f"{save_path_prefix}_pr.png", dpi=150)
plt.close(fig)
def mcnemar_test(y_true, pred_a, pred_b):
y_true, pred_a, pred_b = np.asarray(y_true), np.asarray(pred_a), np.asarray(pred_b)
a_correct = pred_a == y_true
b_correct = pred_b == y_true
table = [
[np.sum(a_correct & b_correct), np.sum(a_correct & ~b_correct)],
[np.sum(~a_correct & b_correct), np.sum(~a_correct & ~b_correct)],
]
result = mcnemar(table, exact=False, correction=True)
return {"statistic": float(result.statistic), "p_value": float(result.pvalue)}
def cross_validate_model(model_factory, X, y, cv=5, random_state=42):
"""K-fold stratified CV, refitting a fresh model each fold via `model_factory()`
(a zero-arg callable returning an unfitted estimator). Returns a DataFrame with
one row per fold plus a final 'mean' row and a 95% CI (normal approximation
across fold scores) for each metric."""
skf = StratifiedKFold(n_splits=cv, shuffle=True, random_state=random_state)
X_arr = X.reset_index(drop=True) if hasattr(X, "reset_index") else X
y_arr = y.reset_index(drop=True) if hasattr(y, "reset_index") else y
fold_rows = []
for fold, (train_idx, test_idx) in enumerate(skf.split(X_arr, y_arr)):
model = model_factory()
model.fit(X_arr.iloc[train_idx], y_arr.iloc[train_idx])
proba = model.predict_proba(X_arr.iloc[test_idx])[:, 1]
pred = (proba >= 0.5).astype(int)
metrics = compute_metrics(y_arr.iloc[test_idx], pred, proba)
fold_rows.append({"fold": fold, **metrics})
fold_df = pd.DataFrame(fold_rows).set_index("fold")
n = len(fold_df)
mean = fold_df.mean()
std = fold_df.std(ddof=1)
ci95 = 1.96 * std / np.sqrt(n)
summary = pd.DataFrame({"mean": mean, "std": std, "ci95_low": mean - ci95, "ci95_high": mean + ci95})
return fold_df, summary
def bootstrap_metric_ci(y_true, y_proba, n_boot=1000, random_state=42, threshold=0.5):
"""Percentile bootstrap CI (2.5/97.5%) for roc_auc/pr_auc/mcc/f1, resampling
the held-out test set with replacement `n_boot` times."""
y_true = np.asarray(y_true)
y_proba = np.asarray(y_proba)
rng = np.random.RandomState(random_state)
n = len(y_true)
boot_rows = []
for _ in range(n_boot):
idx = rng.randint(0, n, size=n)
yt, yp = y_true[idx], y_proba[idx]
if yt.sum() == 0 or yt.sum() == n:
continue # a resample with only one class breaks roc_auc/pr_auc
pred = (yp >= threshold).astype(int)
boot_rows.append(compute_metrics(yt, pred, yp))
boot_df = pd.DataFrame(boot_rows)
point = pd.Series(compute_metrics(y_true, (y_proba >= threshold).astype(int), y_proba))
summary = pd.DataFrame(
{
"point_estimate": point,
"ci95_low": boot_df.quantile(0.025),
"ci95_high": boot_df.quantile(0.975),
}
)
return summary
def stratified_metrics(y_true, y_pred, y_proba, group):
"""Break down `compute_metrics` by the values of `group`. All four arguments
must be positionally aligned (same row order) -- pandas Index labels are
ignored on purpose since y_pred/y_proba are typically plain numpy arrays
with no meaningful index of their own."""
y_true = np.asarray(y_true)
y_pred = np.asarray(y_pred)
y_proba = np.asarray(y_proba)
group = np.asarray(group)
rows = []
for value in pd.unique(group):
mask = group == value
yt, yp, ypr = y_true[mask], y_pred[mask], y_proba[mask]
if len(np.unique(yt)) < 2:
continue # AUC undefined with a single class present
rows.append({"group": value, "n": int(mask.sum()), "founder_rate": float(yt.mean()), **compute_metrics(yt, yp, ypr)})
return pd.DataFrame(rows).set_index("group").sort_values("n", ascending=False)
def regression_metrics(y_true, y_pred):
return {
"mae": mean_absolute_error(y_true, y_pred),
"rmse": root_mean_squared_error(y_true, y_pred),
"r2": r2_score(y_true, y_pred),
}
def plot_predicted_vs_actual(curves, save_path):
"""`curves`: dict[model_name] -> (y_true, y_pred), one scatter subplot each."""
save_path.parent.mkdir(parents=True, exist_ok=True)
n = len(curves)
fig, axes = plt.subplots(1, n, figsize=(4 * n, 4), sharex=True, sharey=True)
axes = np.atleast_1d(axes)
for ax, (name, (y_true, y_pred)) in zip(axes, curves.items()):
ax.scatter(y_true, y_pred, alpha=0.3, s=10)
lims = [min(np.min(y_true), np.min(y_pred)), max(np.max(y_true), np.max(y_pred))]
ax.plot(lims, lims, "--", color="grey")
ax.set_xlabel("Actual founding_age")
ax.set_ylabel("Predicted founding_age")
ax.set_title(name)
fig.tight_layout()
fig.savefig(save_path, dpi=150)
plt.close(fig)
def plot_calibration(curves, save_path, n_bins=10):
"""`curves`: dict[model_name] -> (y_true, y_proba). Reliability diagram."""
save_path.parent.mkdir(parents=True, exist_ok=True)
fig, ax = plt.subplots(figsize=(5, 5))
ax.plot([0, 1], [0, 1], "--", color="grey", label="perfectly calibrated")
for name, (y_true, y_proba) in curves.items():
frac_pos, mean_pred = calibration_curve(y_true, y_proba, n_bins=n_bins, strategy="quantile")
ax.plot(mean_pred, frac_pos, marker="o", label=name)
ax.set_xlabel("Mean predicted probability")
ax.set_ylabel("Fraction of positives")
ax.set_title("Calibration (reliability diagram)")
ax.legend(fontsize=8)
fig.tight_layout()
fig.savefig(save_path, dpi=150)
plt.close(fig)
@@ -0,0 +1,43 @@
"""Permutation importance and SHAP explainability for the best-performing model."""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd
import shap
from sklearn.inspection import permutation_importance
def permutation_importance_report(model, X_test, y_test, save_csv, save_plot, n_repeats=20, random_state=42):
result = permutation_importance(
model, X_test, y_test, n_repeats=n_repeats, random_state=random_state, scoring="average_precision", n_jobs=-1
)
df = pd.DataFrame(
{
"feature": X_test.columns,
"importance_mean": result.importances_mean,
"importance_std": result.importances_std,
}
).sort_values("importance_mean", ascending=False)
save_csv.parent.mkdir(parents=True, exist_ok=True)
df.to_csv(save_csv, index=False)
top = df.head(20).iloc[::-1]
fig, ax = plt.subplots(figsize=(6, 8))
ax.barh(top["feature"], top["importance_mean"], xerr=top["importance_std"])
ax.set_xlabel("Permutation importance (avg. precision drop)")
fig.tight_layout()
fig.savefig(save_plot, dpi=150)
plt.close(fig)
return df
def shap_summary(model, X_sample, save_plot, max_display=20):
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_sample)
fig = plt.figure()
shap.summary_plot(shap_values, X_sample, max_display=max_display, show=False)
save_plot.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(save_plot, dpi=150, bbox_inches="tight")
plt.close(fig)
@@ -0,0 +1,102 @@
"""Model registries: primitive baselines and stronger/state-of-the-art models."""
from catboost import CatBoostClassifier
from lightgbm import LGBMClassifier
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import RandomForestClassifier, StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from xgboost import XGBClassifier
from . import config
def baseline_models(random_state=config.RANDOM_STATE):
"""Primitive models used as the accuracy floor.
The feature matrix mixes raw year values (~2000), log1p-scaled counts and
0/1 dummies, so the scale-sensitive models (logistic regression, Naive
Bayes, kNN) are wrapped in a `StandardScaler` pipeline -- otherwise a
feature like `first_publication_year` (~2000) would dominate distance/
gradient computations over e.g. a 0-1 dummy or a log1p count in [0, 8].
Tree-based models are scale-invariant and stay unscaled.
"""
return {
"dummy_most_frequent": DummyClassifier(strategy="most_frequent"),
"logistic_regression": make_pipeline(
StandardScaler(),
LogisticRegression(max_iter=2000, class_weight="balanced", random_state=random_state),
),
"gaussian_nb": make_pipeline(StandardScaler(), GaussianNB()),
"knn": make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=15)),
"decision_tree": DecisionTreeClassifier(
max_depth=6, min_samples_leaf=5, class_weight="balanced", random_state=random_state
),
}
def advanced_models(random_state=config.RANDOM_STATE, scale_pos_weight=1.0):
"""Stronger / state-of-the-art tabular models."""
return {
"random_forest": RandomForestClassifier(
n_estimators=400,
max_depth=12,
min_samples_leaf=2,
class_weight="balanced",
random_state=random_state,
n_jobs=-1,
),
"svm_rbf": make_pipeline(
StandardScaler(),
SVC(kernel="rbf", C=2.0, class_weight="balanced", probability=True, random_state=random_state),
),
"xgboost": XGBClassifier(
n_estimators=400,
max_depth=5,
learning_rate=0.05,
subsample=0.8,
colsample_bytree=0.8,
objective="binary:logistic",
eval_metric="logloss",
scale_pos_weight=scale_pos_weight,
random_state=random_state,
n_jobs=-1,
),
"lightgbm": LGBMClassifier(
n_estimators=400,
num_leaves=31,
learning_rate=0.05,
class_weight="balanced",
random_state=random_state,
n_jobs=-1,
verbose=-1,
),
"catboost": CatBoostClassifier(
iterations=400,
depth=6,
learning_rate=0.05,
auto_class_weights="Balanced",
random_seed=random_state,
verbose=False,
),
}
def stacking_model(random_state=config.RANDOM_STATE, scale_pos_weight=1.0):
"""Stacked ensemble of the three tree-based models with a logistic meta-learner."""
base = advanced_models(random_state=random_state, scale_pos_weight=scale_pos_weight)
estimators = [
("random_forest", base["random_forest"]),
("xgboost", base["xgboost"]),
("lightgbm", base["lightgbm"]),
]
return StackingClassifier(
estimators=estimators,
final_estimator=LogisticRegression(max_iter=2000, class_weight="balanced", random_state=random_state),
stack_method="predict_proba",
n_jobs=-1,
)
@@ -0,0 +1,106 @@
"""A minimal sklearn-style PyTorch MLP, used as the deep-learning baseline."""
import numpy as np
import torch
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from torch import nn
from . import config
class _Net(nn.Module):
def __init__(self, n_features, hidden_sizes, dropout):
super().__init__()
layers = []
prev = n_features
for h in hidden_sizes:
layers += [nn.Linear(prev, h), nn.ReLU(), nn.Dropout(dropout)]
prev = h
layers.append(nn.Linear(prev, 1))
self.net = nn.Sequential(*layers)
def forward(self, x):
return self.net(x).squeeze(-1)
class TorchMLPClassifier:
"""Feed-forward MLP with class-weighted BCE loss and early stopping on a validation split."""
def __init__(
self,
hidden_sizes=(128, 64),
dropout=0.3,
lr=1e-3,
max_epochs=300,
batch_size=64,
patience=20,
random_state=config.RANDOM_STATE,
):
self.hidden_sizes = hidden_sizes
self.dropout = dropout
self.lr = lr
self.max_epochs = max_epochs
self.batch_size = batch_size
self.patience = patience
self.random_state = random_state
def fit(self, X, y):
torch.manual_seed(self.random_state)
X = np.asarray(X, dtype=np.float32)
y = np.asarray(y, dtype=np.float32)
self.scaler_ = StandardScaler().fit(X)
X = self.scaler_.transform(X)
X_tr, X_val, y_tr, y_val = train_test_split(
X, y, test_size=0.15, stratify=y, random_state=self.random_state
)
X_tr, y_tr = torch.tensor(X_tr), torch.tensor(y_tr)
X_val, y_val = torch.tensor(X_val), torch.tensor(y_val)
pos_weight = torch.tensor([(y_tr == 0).sum() / max((y_tr == 1).sum().item(), 1)])
self.model_ = _Net(X.shape[1], self.hidden_sizes, self.dropout)
optimizer = torch.optim.Adam(self.model_.parameters(), lr=self.lr, weight_decay=1e-4)
loss_fn = nn.BCEWithLogitsLoss(pos_weight=pos_weight)
best_val_loss = float("inf")
best_state = None
epochs_since_improvement = 0
n = X_tr.shape[0]
for _ in range(self.max_epochs):
self.model_.train()
perm = torch.randperm(n)
for start in range(0, n, self.batch_size):
idx = perm[start : start + self.batch_size]
optimizer.zero_grad()
loss = loss_fn(self.model_(X_tr[idx]), y_tr[idx])
loss.backward()
optimizer.step()
self.model_.eval()
with torch.no_grad():
val_loss = loss_fn(self.model_(X_val), y_val).item()
if val_loss < best_val_loss - 1e-4:
best_val_loss = val_loss
best_state = {k: v.clone() for k, v in self.model_.state_dict().items()}
epochs_since_improvement = 0
else:
epochs_since_improvement += 1
if epochs_since_improvement >= self.patience:
break
if best_state is not None:
self.model_.load_state_dict(best_state)
return self
def predict_proba(self, X):
X = np.asarray(X, dtype=np.float32)
X = self.scaler_.transform(X)
self.model_.eval()
with torch.no_grad():
p1 = torch.sigmoid(self.model_(torch.tensor(X))).numpy()
return np.column_stack([1 - p1, p1])
def predict(self, X):
return (self.predict_proba(X)[:, 1] >= 0.5).astype(int)
@@ -0,0 +1,38 @@
"""Multivariate outlier detection for the RQ1 feature set.
Two stages: a sanity ceiling (>5,000 lifetime publications or patents) to drop
flagrant name-collision aggregates, then an Isolation Forest in log-space over
the full numeric feature set. Why not a single threshold:
docs/DESIGN_NOTES.md, "outliers.py".
"""
import numpy as np
import pandas as pd
from sklearn.ensemble import IsolationForest
from . import config
SANITY_CEILING = 5000 # any one individual having more than this is implausible
OUTLIER_CONTAMINATION = 0.01 # drop the ~1% most anomalous *remaining* rows
_OUTLIER_COLUMNS = [c for c in config.RQ1_NUMERIC_COLUMNS if "_year" not in c]
def flag_outliers(df, contamination=OUTLIER_CONTAMINATION, random_state=config.RANDOM_STATE):
"""Return a boolean Series (True = flagged as an outlier), combining the
sanity-ceiling and Isolation Forest stages described in the module docstring."""
sanity_flagged = (
pd.to_numeric(df["publications"], errors="coerce").fillna(0) > SANITY_CEILING
) | (pd.to_numeric(df["patents"], errors="coerce").fillna(0) > SANITY_CEILING)
remaining = df.loc[~sanity_flagged]
X = remaining[_OUTLIER_COLUMNS].apply(pd.to_numeric, errors="coerce").fillna(0)
X = np.log1p(X.clip(lower=0))
model = IsolationForest(
n_estimators=300, contamination=contamination, random_state=random_state
)
labels = model.fit_predict(X) # -1 = outlier, 1 = inlier
iforest_flagged = pd.Series(labels == -1, index=remaining.index)
flagged = sanity_flagged.copy()
flagged.loc[iforest_flagged.index] = flagged.loc[iforest_flagged.index] | iforest_flagged
return flagged
@@ -0,0 +1,102 @@
"""Founder-only sequence dataset for career-relative founding-timing prediction.
Inputs are the `hist_{pub,pat,grant}_FN-1..FN-20` yearly counts; the target is
`founding_age = founded_on - first_publication_year`. Non-founders have no valid
equivalent sequence in the extracted data, and rows with
`founding_age > WINDOW` are excluded as structurally right-censored (the
excluded count is always reported). Both points are explained in
docs/DESIGN_NOTES.md, "sequence_data.py".
"""
import numpy as np
import pandas as pd
from . import config
CHANNELS = ["pub", "pat", "grant"]
WINDOW = 20
MIN_PLAUSIBLE_YEAR = 1950
MAX_PLAUSIBLE_YEAR = 2024
def _hist_columns(kind):
"""Chronological order: FN-20 (earliest) ... FN-1 (year right before founding)."""
return [f"hist_{kind}_FN-{k}" for k in range(WINDOW, 0, -1)]
def build_founder_sequence_dataset(min_founding_age=1, max_founding_age=WINDOW, verbose=True):
"""Returns (sequences, founding_age, meta).
sequences: float32 array (n, WINDOW, len(CHANNELS)), log1p-transformed
chronological pre-founding yearly counts.
founding_age: float32 array (n,), the regression target.
meta: DataFrame (name, institution, founding_age) for bookkeeping/inspection.
"""
frames = []
for inst in config.INSTITUTIONS:
df = pd.read_csv(config.COMPLETE_DIR / f"{inst}_features_dataset.csv")
df["institution"] = inst
frames.append(df)
df = pd.concat(frames, ignore_index=True)
n_total = len(df)
founded_on = pd.to_numeric(df["founded_on"], errors="coerce")
fpy = pd.to_numeric(df["first_publication_year"], errors="coerce")
plausible_years = founded_on.between(MIN_PLAUSIBLE_YEAR, MAX_PLAUSIBLE_YEAR) & fpy.between(
MIN_PLAUSIBLE_YEAR, MAX_PLAUSIBLE_YEAR
)
founding_age = founded_on - fpy
in_window = founding_age.between(min_founding_age, max_founding_age)
keep = plausible_years & in_window
if verbose:
print(f" sequence dataset scoping: {n_total} founders total")
print(f" dropped {int((~plausible_years).sum())} with an implausible founded_on/first_publication_year "
f"(e.g. sentinel 0 from an unparseable founding date)")
print(f" dropped {int((plausible_years & ~in_window).sum())} more outside "
f"[{min_founding_age}, {max_founding_age}] founding_age (mostly founding_age > {max_founding_age}: "
"the 20-year window can't distinguish these from the >=20 case)")
print(f" kept {int(keep.sum())} founders for the sequence task")
df = df.loc[keep].reset_index(drop=True)
founding_age = founding_age.loc[keep].reset_index(drop=True)
channel_arrays = []
for kind in CHANNELS:
cols = _hist_columns(kind)
arr = df[cols].apply(pd.to_numeric, errors="coerce").fillna(0).clip(lower=0).to_numpy(dtype=np.float32)
arr = np.log1p(arr)
channel_arrays.append(arr)
sequences = np.stack(channel_arrays, axis=-1) # (n, WINDOW, 3)
meta = df[["name", "institution"]].copy()
meta["founding_age"] = founding_age.values
return sequences, founding_age.values.astype(np.float32), meta
def naive_first_activity_baseline(sequences):
"""Deterministic, non-fitted heuristic: founding_age := WINDOW - (number of
leading all-zero years across all 3 channels). If activity starts at
position `WINDOW - founding_age` (0-indexed) that is exactly `founding_age`
-- this is the "structural" floor the learned models should be compared
against, since counting leading zeros is trivial for a sequence model too."""
any_activity = sequences.sum(axis=-1) > 0 # (n, WINDOW) bool, any channel nonzero that year
n = sequences.shape[0]
preds = np.full(n, float(WINDOW), dtype=np.float32)
for i in range(n):
nonzero_idx = np.flatnonzero(any_activity[i])
if len(nonzero_idx) > 0:
preds[i] = WINDOW - nonzero_idx[0]
return preds
def aggregate_features(sequences):
"""Simple hand-crafted summary stats per sequence (for a non-sequential
fitted baseline): total activity, nonzero-year count, and activity in the
most recent 3 years, per channel."""
feats = []
for c in range(sequences.shape[-1]):
chan = sequences[:, :, c]
feats.append(chan.sum(axis=1))
feats.append((chan > 0).sum(axis=1))
feats.append(chan[:, -3:].sum(axis=1))
return np.column_stack(feats)
@@ -0,0 +1,139 @@
"""Sequence regressors for the founder-only "predict founding_age from
pre-founding activity" task: an LSTM and a small Transformer encoder, both
sklearn-style (fit/predict) like `nn.py`'s `TorchMLPClassifier`.
Input: float array (n, WINDOW, n_channels) -- see `sequence_data.py`.
Output: continuous `founding_age` prediction.
"""
import numpy as np
import torch
from sklearn.model_selection import train_test_split
from torch import nn
from . import config
class _SequenceScaler:
"""Per-channel standardization (mean/std computed over all rows x timesteps)."""
def fit(self, X):
self.mean_ = X.mean(axis=(0, 1), keepdims=True)
self.std_ = X.std(axis=(0, 1), keepdims=True) + 1e-6
return self
def transform(self, X):
return (X - self.mean_) / self.std_
class _LSTMNet(nn.Module):
def __init__(self, n_channels, hidden_size=64, num_layers=1, dropout=0.2):
super().__init__()
self.lstm = nn.LSTM(
input_size=n_channels, hidden_size=hidden_size, num_layers=num_layers,
batch_first=True, dropout=dropout if num_layers > 1 else 0.0,
)
self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(hidden_size, 1))
def forward(self, x):
_, (h_n, _) = self.lstm(x)
return self.head(h_n[-1]).squeeze(-1)
class _TransformerNet(nn.Module):
def __init__(self, n_channels, seq_len, d_model=32, n_heads=4, n_layers=2, dropout=0.2):
super().__init__()
self.input_proj = nn.Linear(n_channels, d_model)
self.pos_embedding = nn.Parameter(torch.zeros(1, seq_len, d_model))
encoder_layer = nn.TransformerEncoderLayer(
d_model=d_model, nhead=n_heads, dim_feedforward=d_model * 4,
dropout=dropout, batch_first=True,
)
self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=n_layers)
self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(d_model, 1))
def forward(self, x):
h = self.input_proj(x) + self.pos_embedding
h = self.encoder(h)
pooled = h.mean(dim=1) # mean-pool over the time dimension
return self.head(pooled).squeeze(-1)
class _BaseSequenceRegressor:
"""Shared fit/predict scaffolding (train loop, early stopping, scaling)."""
net_cls = None
def __init__(self, lr=1e-3, max_epochs=300, batch_size=64, patience=25, random_state=config.RANDOM_STATE, **net_kwargs):
self.lr = lr
self.max_epochs = max_epochs
self.batch_size = batch_size
self.patience = patience
self.random_state = random_state
self.net_kwargs = net_kwargs
def _build_net(self, n_channels, seq_len):
raise NotImplementedError
def fit(self, X, y):
torch.manual_seed(self.random_state)
X = np.asarray(X, dtype=np.float32)
y = np.asarray(y, dtype=np.float32)
self.scaler_ = _SequenceScaler().fit(X)
X = self.scaler_.transform(X).astype(np.float32)
X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.15, random_state=self.random_state)
X_tr, y_tr = torch.tensor(X_tr), torch.tensor(y_tr)
X_val, y_val = torch.tensor(X_val), torch.tensor(y_val)
self.model_ = self._build_net(n_channels=X.shape[2], seq_len=X.shape[1])
optimizer = torch.optim.Adam(self.model_.parameters(), lr=self.lr, weight_decay=1e-4)
loss_fn = nn.MSELoss()
best_val_loss = float("inf")
best_state = None
epochs_since_improvement = 0
n = X_tr.shape[0]
for _ in range(self.max_epochs):
self.model_.train()
perm = torch.randperm(n)
for start in range(0, n, self.batch_size):
idx = perm[start : start + self.batch_size]
optimizer.zero_grad()
loss = loss_fn(self.model_(X_tr[idx]), y_tr[idx])
loss.backward()
optimizer.step()
self.model_.eval()
with torch.no_grad():
val_loss = loss_fn(self.model_(X_val), y_val).item()
if val_loss < best_val_loss - 1e-4:
best_val_loss = val_loss
best_state = {k: v.clone() for k, v in self.model_.state_dict().items()}
epochs_since_improvement = 0
else:
epochs_since_improvement += 1
if epochs_since_improvement >= self.patience:
break
if best_state is not None:
self.model_.load_state_dict(best_state)
return self
def predict(self, X):
X = np.asarray(X, dtype=np.float32)
X = self.scaler_.transform(X).astype(np.float32)
self.model_.eval()
with torch.no_grad():
return self.model_(torch.tensor(X)).numpy()
class LSTMRegressor(_BaseSequenceRegressor):
def _build_net(self, n_channels, seq_len):
return _LSTMNet(n_channels, **self.net_kwargs)
class TransformerRegressor(_BaseSequenceRegressor):
def _build_net(self, n_channels, seq_len):
return _TransformerNet(n_channels, seq_len, **self.net_kwargs)
@@ -0,0 +1,17 @@
"""Generic train/test and cross-institution split helpers."""
from sklearn.model_selection import LeaveOneGroupOut, train_test_split
from . import config
def stratified_holdout(X, y, test_size=0.2, random_state=config.RANDOM_STATE):
return train_test_split(X, y, test_size=test_size, stratify=y, random_state=random_state)
def leave_one_institution_out(X, y, groups):
"""Yields (institution_name, train_idx, test_idx) for each held-out institution."""
logo = LeaveOneGroupOut()
group_codes, group_names = groups.factorize()
for train_idx, test_idx in logo.split(X, y, groups=group_codes):
held_out = group_names[group_codes[test_idx[0]]]
yield held_out, train_idx, test_idx
@@ -0,0 +1,69 @@
"""Cox proportional hazards survival analysis for RQ2 (time-to-founding).
Complements the fixed-horizon classifiers in run_rq2.py: instead of one yes/no
label at a chosen cutoff, this fits a single time-to-event model and reads off
P(founds within k years | features) for any k, correctly treating non-founders
still under observation as censored rather than as permanent negatives.
Simplification: covariates are the same full-career aggregates used for RQ1
(observed up to the founding year for founders, up to the last observed year for
non-founders) rather than a fully time-varying design. A stricter version would
use a counting-process (start, stop, event) long format with the half-profile
snapshots as time-varying covariates; noted as future work in the README.
"""
import numpy as np
import pandas as pd
from lifelines import CoxPHFitter
from lifelines.utils import concordance_index
from . import config
def build_survival_frame(df_raw):
df = df_raw.copy()
is_founder = df[config.LABEL_COLUMN] == 1
duration = np.where(
is_founder,
df["founded_on"] - df["first_publication_year"],
df["last_publication_year"] - df["first_publication_year"],
)
event = is_founder.astype(int)
frame = pd.DataFrame({"duration": duration, "event": event})
numeric_cols = [c for c in config.RQ1_NUMERIC_COLUMNS if not c.endswith("_year")]
numeric = df[numeric_cols].apply(pd.to_numeric, errors="coerce").fillna(0)
for col in config.RQ1_LOG_COLUMNS:
if col in numeric.columns:
numeric[col] = np.log1p(numeric[col].clip(lower=0))
institution = pd.get_dummies(df["institution"], prefix="institution", drop_first=True)
frame = pd.concat([frame, numeric.reset_index(drop=True), institution.reset_index(drop=True)], axis=1)
frame = frame[frame["duration"] > 0]
frame = frame.replace([np.inf, -np.inf], np.nan).dropna()
return frame.reset_index(drop=True)
def fit_coxph(train_frame, penalizer=0.1):
cph = CoxPHFitter(penalizer=penalizer)
cph.fit(train_frame, duration_col="duration", event_col="event")
return cph
def evaluate_concordance(cph, test_frame):
partial_hazard = cph.predict_partial_hazard(test_frame)
return concordance_index(test_frame["duration"], -partial_hazard, test_frame["event"])
def probability_of_founding_within(cph, frame, years):
survival = cph.predict_survival_function(frame, times=[years])
return 1 - survival.loc[years].values
def landmark_labels(frame, years):
"""Rows with enough follow-up to know the true within-`years` outcome, plus
the corresponding binary label, avoiding immortal-time bias."""
eligible = ((frame["event"] == 1) & (frame["duration"] <= years)) | (frame["duration"] >= years)
label = ((frame["event"] == 1) & (frame["duration"] <= years)).astype(int)
return eligible, label
@@ -0,0 +1,264 @@
"""Symmetric (landmark-design) founder / non-founder datasets.
Replaces the asymmetric RQ1/RQ2 preprocessing in `data.py`, where observation
window length was a function of the label. Here every person gets an index year
(real founding year, or a cohort-matched pseudo-founding year), features are
built identically for both classes via `career_curves.py`, citation features are
excluded as non-historicizable, and `grants` is de-inflated through the per-paper
cap from `yearly_counts.py`.
Two filters apply to BOTH classes: a >=4-publication population rule and a
plausibility filter for name-collision aggregates. Why each of these exists:
docs/DESIGN_NOTES.md, "symmetric.py".
"""
import numpy as np
import pandas as pd
from . import career_curves as cc
from . import config
SYMMETRIC_DIR = config.EVAL_DIR / "datasets_symmetric"
CURVES_PATH = config.EVAL_DIR / "yearly_counts" / "career_curves.csv"
# Minimal academic record at the index date, applied to BOTH classes: without
# it a sampling-frame clash dominates the thin-profile region.
MIN_PUBS_AT_INDEX = 4
VALID_FOUNDING = (1950, 2026)
VALID_FIRST_YEAR = (1930, 2025)
MAX_CAREER_AGE_AT_FOUNDING = 60
COHORT_BIN_YEARS = 10
SYMMETRIC_NUMERIC_COLUMNS = [
"pubs_at_index",
"patents_at_index",
"grants_at_index",
"activities_at_index",
"industry_collab_at_index",
"linked_pat_pub_at_index",
"career_age_at_index",
"first_publication_year",
"pub_rate",
"patent_rate",
"grant_rate",
"has_patents_at_index",
"has_grants_at_index",
"years_since_first_patent",
"years_since_first_grant",
]
SYMMETRIC_LOG_COLUMNS = [
"pubs_at_index",
"patents_at_index",
"grants_at_index",
"activities_at_index",
"industry_collab_at_index",
"linked_pat_pub_at_index",
]
SYMMETRIC_CATEGORICAL_COLUMNS = [
"publication_research_area",
"patent_research_area",
"grant_research_area",
"institution",
]
_RAW_USECOLS = [
"name", "founded_on", "publications", "patents", "grants",
"first_publication_year", "last_publication_year",
"first_patent_year", "last_patent_year",
"first_grant_year", "last_grant_year",
"industry_collab_papers", "linked_patents_to_publications",
"publication_research_area", "patent_research_area", "grant_research_area",
config.LABEL_COLUMN,
]
def load_people():
"""All founders + non-founders with cleaned year fields. Returns the frame
plus a per-step attrition log (how many rows each cleaning rule removed)."""
frames = []
for inst in config.INSTITUTIONS:
for kind in ["features", "nonfounders_features"]:
df = pd.read_csv(config.COMPLETE_DIR / f"{inst}_{kind}_dataset.csv")
df = df[[c for c in _RAW_USECOLS if c in df.columns]].copy()
df["institution"] = inst
frames.append(df)
df = pd.concat(frames, ignore_index=True)
attrition = {"initial": len(df)}
for col in ["founded_on", "publications", "patents", "grants",
"industry_collab_papers", "linked_patents_to_publications"]:
df[col] = pd.to_numeric(df.get(col), errors="coerce")
for col in ["first_publication_year", "last_publication_year", "first_patent_year",
"last_patent_year", "first_grant_year", "last_grant_year"]:
y = pd.to_numeric(df.get(col), errors="coerce")
df[col] = y.where((y >= VALID_FIRST_YEAR[0]) & (y <= VALID_FIRST_YEAR[1]))
df["name"] = df["name"].astype(str).str.strip()
df = df[df["first_publication_year"].notna() & (df["publications"] > 0)]
attrition["no_publication_anchor"] = attrition["initial"] - len(df)
# Plausibility filter (BOTH classes): a >60-year span or >25 papers/year
# sustained marks a name-collision aggregate, not one researcher.
career = df["last_publication_year"] - df["first_publication_year"] + 1
rate = df["publications"] / career.clip(lower=1)
implausible = (career > 60) | (rate > 25)
by_class = implausible.groupby(df[config.LABEL_COLUMN]).sum()
attrition["implausible_profile_founders"] = int(by_class.get(1, 0))
attrition["implausible_profile_nonfounders"] = int(by_class.get(0, 0))
df = df[~implausible]
is_founder = df[config.LABEL_COLUMN] == 1
bad_year = is_founder & ~df["founded_on"].between(*VALID_FOUNDING)
df = df[~bad_year]
attrition["founder_bad_founding_year"] = int(bad_year.sum())
ca = df["founded_on"] - df["first_publication_year"]
is_founder = df[config.LABEL_COLUMN] == 1
bad_ca = is_founder & ~ca.between(1, MAX_CAREER_AGE_AT_FOUNDING)
df = df[~bad_ca]
attrition["founder_bad_career_age"] = int(bad_ca.sum())
df = df.drop_duplicates(subset=["name", "institution", config.LABEL_COLUMN])
attrition["duplicates"] = attrition["initial"] - sum(
v for k, v in attrition.items() if k != "initial"
) - len(df)
return df.reset_index(drop=True), attrition
def assign_index_years(df, random_state=config.RANDOM_STATE):
"""Founders: real founding year. Non-founders: career-age-at-founding sampled
from founders in the same career-start cohort (decade of first publication),
clipped to the person's observed active span."""
df = df.copy()
is_founder = df[config.LABEL_COLUMN] == 1
df.loc[is_founder, "index_year"] = df.loc[is_founder, "founded_on"]
founders = df[is_founder]
founder_ca = (founders["founded_on"] - founders["first_publication_year"]).astype(float)
cohort = (founders["first_publication_year"] // COHORT_BIN_YEARS) * COHORT_BIN_YEARS
ca_by_cohort = {c: founder_ca[cohort == c].to_numpy() for c in cohort.unique()}
all_ca = founder_ca.to_numpy()
rng = np.random.default_rng(random_state)
nonf = df[~is_founder]
sampled = []
for first, last in zip(nonf["first_publication_year"], nonf["last_publication_year"]):
c = (first // COHORT_BIN_YEARS) * COHORT_BIN_YEARS
pool = ca_by_cohort.get(c)
if pool is None or len(pool) < 20:
pool = all_ca
ca = float(rng.choice(pool))
span = (last - first) if pd.notna(last) else ca
sampled.append(first + min(max(ca, 1.0), max(span, 1.0)))
df.loc[~is_founder, "index_year"] = sampled
return df
def _fit_grants_cap_ratio(yearly):
"""Monotone binned mapping r -> capped_share, where r = grants per publication
and capped_share = grants_capped / grants, fitted on the raw founder records.
Applied identically to both classes (non-founders lack raw records)."""
per_person = yearly.groupby("author_people").agg(
pubs=("pubs", "sum"), grants=("grants", "sum"), capped=("grants_capped", "sum")
)
per_person = per_person[per_person["grants"] > 0]
r = per_person["grants"] / per_person["pubs"].clip(lower=1)
share = per_person["capped"] / per_person["grants"]
bins = np.quantile(r, np.linspace(0, 1, 21))
bins = np.unique(bins)
idx = np.clip(np.digitize(r, bins) - 1, 0, len(bins) - 2)
binned = pd.DataFrame({"bin": idx, "share": share}).groupby("bin")["share"].median()
centers = (bins[:-1] + bins[1:]) / 2
def apply(grants_total, pubs_total):
rr = np.asarray(grants_total, dtype=float) / np.clip(np.asarray(pubs_total, dtype=float), 1, None)
shares = np.interp(rr, centers[binned.index], binned.to_numpy())
return np.asarray(grants_total, dtype=float) * np.clip(shares, 0.0, 1.0)
return apply
def build_features(df, curves, grants_cap_fn, offset=0):
"""Feature table with every person's profile truncated at (index_year - offset).
Identical construction for both classes -- see module docstring."""
out = df[["name", "institution", config.LABEL_COLUMN, "index_year",
"publication_research_area", "patent_research_area", "grant_research_area"]].copy()
idx = df["index_year"] - offset
out["index_year_effective"] = idx
grants_capped_total = grants_cap_fn(df["grants"].fillna(0), df["publications"].fillna(0))
def trunc(metric, total, first, last):
return np.array([
cc.truncate_total(curves, metric, t, f, l, i)
for t, f, l, i in zip(total, first, last, idx)
])
pubs = trunc("pubs", df["publications"], df["first_publication_year"], df["last_publication_year"])
pats = trunc("patents", df["patents"], df["first_patent_year"], df["last_patent_year"])
grants = trunc("grants_capped", grants_capped_total, df["first_grant_year"], df["last_grant_year"])
pub_frac = np.divide(pubs, df["publications"].to_numpy(dtype=float),
out=np.zeros(len(df)), where=df["publications"].to_numpy(dtype=float) > 0)
pat_frac = np.divide(pats, df["patents"].to_numpy(dtype=float),
out=np.zeros(len(df)), where=df["patents"].to_numpy(dtype=float) > 0)
out["pubs_at_index"] = pubs
out["patents_at_index"] = pats
out["grants_at_index"] = grants
out["activities_at_index"] = pubs + pats + grants
out["industry_collab_at_index"] = df["industry_collab_papers"].fillna(0).to_numpy() * pub_frac
out["linked_pat_pub_at_index"] = df["linked_patents_to_publications"].fillna(0).to_numpy() * pat_frac
career_age = (idx - df["first_publication_year"]).clip(lower=1)
out["career_age_at_index"] = career_age
out["first_publication_year"] = df["first_publication_year"]
out["pub_rate"] = pubs / career_age
out["patent_rate"] = pats / career_age
out["grant_rate"] = grants / career_age
out["has_patents_at_index"] = ((df["first_patent_year"].notna()) & (df["first_patent_year"] <= idx)).astype(int)
out["has_grants_at_index"] = ((df["first_grant_year"].notna()) & (df["first_grant_year"] <= idx)).astype(int)
out["years_since_first_patent"] = np.where(
out["has_patents_at_index"] == 1, (idx - df["first_patent_year"]).clip(lower=0), 0)
out["years_since_first_grant"] = np.where(
out["has_grants_at_index"] == 1, (idx - df["first_grant_year"]).clip(lower=0), 0)
return out
def build_matrix(feat_df, include_institution=True):
"""(X, y, groups) from a symmetric feature table, mirroring data.build_rq1_matrix."""
from .data import _broad_research_area
y = feat_df[config.LABEL_COLUMN].astype(int)
numeric = feat_df[SYMMETRIC_NUMERIC_COLUMNS].apply(pd.to_numeric, errors="coerce").fillna(0)
for col in SYMMETRIC_LOG_COLUMNS:
numeric[col] = np.log1p(numeric[col].clip(lower=0))
cat_cols = ["publication_research_area", "patent_research_area", "grant_research_area"]
cat_df = pd.DataFrame({c: _broad_research_area(feat_df[c]) for c in cat_cols})
if include_institution:
cat_df["institution"] = feat_df["institution"]
categorical = pd.get_dummies(cat_df, prefix=cat_df.columns.tolist())
X = pd.concat([numeric.reset_index(drop=True), categorical.reset_index(drop=True)], axis=1)
return X, y.reset_index(drop=True), feat_df["institution"].reset_index(drop=True)
def build_symmetric_dataset(offset=0, random_state=config.RANDOM_STATE,
min_pubs_at_index=MIN_PUBS_AT_INDEX):
"""End-to-end: load, clean, assign index years, build features, apply the
population filter (see MIN_PUBS_AT_INDEX). Returns (feature_table,
attrition_dict)."""
people, attrition = load_people()
people = assign_index_years(people, random_state=random_state)
yearly = cc.load_yearly()
curves = cc.load_curves(CURVES_PATH)
grants_cap_fn = _fit_grants_cap_ratio(yearly)
feats = build_features(people, curves, grants_cap_fn, offset=offset)
if min_pubs_at_index:
in_pop = feats["pubs_at_index"] >= min_pubs_at_index
by_class = (~in_pop).groupby(feats[config.LABEL_COLUMN]).sum()
attrition["below_min_pubs_at_index_founders"] = int(by_class.get(1, 0))
attrition["below_min_pubs_at_index_nonfounders"] = int(by_class.get(0, 0))
feats = feats[in_pop].reset_index(drop=True)
return feats, attrition
@@ -0,0 +1,68 @@
"""Hyperparameter search spaces + a thin RandomizedSearchCV wrapper for the top
tree-based models. Kept separate from `models.py` so the default (untuned)
model factories used for the main comparison stay simple and fast."""
import pandas as pd
from scipy.stats import randint, uniform
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import RandomizedSearchCV
from xgboost import XGBClassifier
from lightgbm import LGBMClassifier
from . import config
PARAM_DISTRIBUTIONS = {
"random_forest": {
"n_estimators": randint(200, 800),
"max_depth": randint(4, 20),
"min_samples_leaf": randint(1, 10),
"max_features": uniform(0.3, 0.7),
},
"xgboost": {
"n_estimators": randint(150, 700),
"max_depth": randint(3, 9),
"learning_rate": uniform(0.01, 0.19),
"subsample": uniform(0.6, 0.4),
"colsample_bytree": uniform(0.5, 0.5),
"min_child_weight": randint(1, 10),
},
"lightgbm": {
"n_estimators": randint(150, 700),
"num_leaves": randint(15, 127),
"learning_rate": uniform(0.01, 0.19),
"subsample": uniform(0.6, 0.4),
"colsample_bytree": uniform(0.5, 0.5),
"min_child_samples": randint(5, 60),
},
}
def _base_estimator(name, random_state, scale_pos_weight):
if name == "random_forest":
return RandomForestClassifier(class_weight="balanced", random_state=random_state, n_jobs=1)
if name == "xgboost":
return XGBClassifier(
objective="binary:logistic", eval_metric="logloss",
scale_pos_weight=scale_pos_weight, random_state=random_state, n_jobs=1,
)
if name == "lightgbm":
return LGBMClassifier(class_weight="balanced", random_state=random_state, n_jobs=1, verbose=-1)
raise ValueError(f"No tuning search space registered for '{name}'")
def tune_model(name, X_train, y_train, n_iter=20, cv=3, scoring="average_precision",
random_state=config.RANDOM_STATE, scale_pos_weight=1.0):
"""Randomized hyperparameter search for `name` in {random_forest, xgboost, lightgbm}.
Returns (best_estimator, best_params, cv_results_dataframe)."""
estimator = _base_estimator(name, random_state, scale_pos_weight)
search = RandomizedSearchCV(
estimator,
PARAM_DISTRIBUTIONS[name],
n_iter=n_iter,
cv=cv,
scoring=scoring,
random_state=random_state,
n_jobs=-1,
refit=True,
)
search.fit(X_train, y_train)
return search.best_estimator_, search.best_params_, pd.DataFrame(search.cv_results_)
@@ -0,0 +1,113 @@
"""Per-person, per-year activity counts rebuilt from the raw Dimensions exports.
Founder cohort only — non-founders were extracted live and their per-record data
was never saved. Used to truncate founder features exactly at the founding year
and to fit the career curves in `career_curves.py`. Also emits a grants variant
capped at GRANTS_PER_PAPER_CAP distinct grant ids per publication, since a single
consortium paper can otherwise contribute 100+ "grants".
Details: docs/DESIGN_NOTES.md, "yearly_counts.py".
"""
import ast
import sys
from pathlib import Path
import pandas as pd
from . import config
YEARLY_DIR = config.EVAL_DIR / "yearly_counts"
# Distinct grant IDs credited per publication, at most. Sits above ordinary
# multi-grant papers (p90 ~6-14) and below the consortium tail (up to 409).
GRANTS_PER_PAPER_CAP = 10
VALID_YEARS = (1900, 2026)
def _clean_year(series):
y = pd.to_numeric(series, errors="coerce")
return y.where((y >= VALID_YEARS[0]) & (y <= VALID_YEARS[1]))
def _person_year_counts(path, id_col, kind, chunksize=200_000):
"""Distinct-record counts per (person, year) from one raw CSV."""
frames = []
usecols = [id_col, "year", "author_people"]
for chunk in pd.read_csv(path, usecols=usecols, chunksize=chunksize, low_memory=False):
chunk["year"] = _clean_year(chunk["year"])
chunk = chunk.dropna(subset=["year", "author_people", id_col])
chunk = chunk.drop_duplicates(subset=["author_people", id_col])
frames.append(chunk)
df = pd.concat(frames, ignore_index=True)
df = df.drop_duplicates(subset=["author_people", id_col])
out = (
df.groupby(["author_people", "year"])[id_col]
.nunique()
.rename(kind)
.reset_index()
)
return out
def _grant_year_counts(path, chunksize=200_000):
"""Grant credit per (person, year): distinct grant IDs acknowledged on that
year's linked publications, both raw and capped per publication."""
rows = []
usecols = ["doi", "supporting_grant_ids", "year", "author_people"]
for chunk in pd.read_csv(path, usecols=usecols, chunksize=chunksize, low_memory=False):
chunk["year"] = _clean_year(chunk["year"])
chunk = chunk.dropna(subset=["year", "author_people", "supporting_grant_ids"])
for person, year, doi, raw in zip(
chunk["author_people"], chunk["year"], chunk["doi"], chunk["supporting_grant_ids"]
):
try:
ids = ast.literal_eval(raw)
except (ValueError, SyntaxError):
continue
if isinstance(ids, list) and ids:
rows.append((person, year, doi, tuple(ids)))
if not rows:
return pd.DataFrame(columns=["author_people", "year", "grants", "grants_capped"])
df = pd.DataFrame(rows, columns=["author_people", "year", "doi", "grant_ids"])
df = df.drop_duplicates(subset=["author_people", "doi"])
def _agg(group):
seen, seen_capped = set(), set()
for ids in group["grant_ids"]:
new = [g for g in ids if g not in seen]
seen.update(new)
seen_capped.update(new[:GRANTS_PER_PAPER_CAP])
return pd.Series({"grants": len(seen), "grants_capped": len(seen_capped)})
return df.groupby(["author_people", "year"]).apply(_agg, include_groups=False).reset_index()
def build_institution(inst):
data_dir = config.ROOT / "dimensions_data"
pubs = _person_year_counts(data_dir / f"{inst}_papers.csv", "id", "pubs")
pats = _person_year_counts(data_dir / f"{inst}_patents.csv", "id", "patents")
grants = _grant_year_counts(data_dir / f"{inst}_publications_linked_grants.csv")
merged = pubs.merge(pats, on=["author_people", "year"], how="outer")
merged = merged.merge(grants, on=["author_people", "year"], how="outer")
merged = merged.fillna(0)
for col in ["pubs", "patents", "grants", "grants_capped"]:
merged[col] = merged[col].astype(int)
merged["year"] = merged["year"].astype(int)
return merged.sort_values(["author_people", "year"]).reset_index(drop=True)
def main():
YEARLY_DIR.mkdir(exist_ok=True)
insts = sys.argv[1:] or config.INSTITUTIONS
for inst in insts:
out_path = YEARLY_DIR / f"{inst}_person_year.csv"
if out_path.exists():
print(f"{inst}: exists, skipping", flush=True)
continue
df = build_institution(inst)
df.to_csv(out_path, index=False)
print(f"{inst}: {df['author_people'].nunique()} people, {len(df)} person-years", flush=True)
if __name__ == "__main__":
main()