adjusted the profiling pipelines: multipliers & (potential) founders, explorative analyses
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
This commit is contained in:
@@ -0,0 +1,255 @@
|
||||
# Founder-Potential Classifier — Production Guide
|
||||
|
||||
Predicts whether a researcher will found a company ("founder" vs. "non-founder")
|
||||
from their **full career profile** (publications, patents, grants, affiliations).
|
||||
This is the RQ1 model from the research pipeline, re-packaged and validated for
|
||||
an OpenAlex + patents + grants production data source.
|
||||
|
||||
## 1. Which two models, and why
|
||||
|
||||
Ranked empirically on the actual production feature set (87 columns — see
|
||||
§3), by PR-AUC on a held-out 20% stratified split (`validated_holdout_metrics.csv`):
|
||||
|
||||
| rank | model | roc_auc | pr_auc | mcc | f1 | notes |
|
||||
|------|----------------------|---------|--------|-------|-------|-------|
|
||||
| 1 | **lightgbm** | 0.9764 | 0.9681 | 0.848 | 0.903 | single model, 1.3 MB, fastest |
|
||||
| 2 | **stacking_ensemble**| 0.9748 | 0.9657 | 0.846 | 0.903 | RF+XGBoost+LightGBM blended by a logistic meta-learner, 29 MB, ~3x slower |
|
||||
| 3 | xgboost | 0.9728 | 0.9640 | 0.843 | 0.900 | close 3rd, not shipped |
|
||||
| 4 | catboost | 0.9710 | 0.9616 | 0.834 | 0.894 | not shipped |
|
||||
|
||||
`lightgbm` and `stacking_ensemble` are shipped in `models/`. They are within
|
||||
noise of each other (Δpr_auc = 0.002); `lightgbm` is recommended as the default
|
||||
for a production system (simpler, smaller, faster, marginally best), with
|
||||
`stacking_ensemble` as a fallback/cross-check if you want a second opinion or
|
||||
slightly better recall (0.905 vs. 0.890).
|
||||
|
||||
## 2. Files
|
||||
|
||||
```
|
||||
production/classifier/
|
||||
founder_classifier.py <- self-contained wrapper (pandas/numpy/joblib only)
|
||||
models/
|
||||
lightgbm.joblib <- recommended default
|
||||
stacking_ensemble.joblib <- alternative / second opinion
|
||||
feature_importance_lightgbm.csv
|
||||
feature_importance_stacking_ensemble.csv
|
||||
validated_holdout_metrics.csv <- honest held-out metrics for every candidate model
|
||||
manifest.json
|
||||
export_classifier.py <- reproducible export/training script
|
||||
```
|
||||
|
||||
Each `.joblib` is a single self-contained bundle: `{model, feature_columns,
|
||||
numeric_columns, log_columns, research_area_columns, research_area_categories,
|
||||
label_meaning}`. You only need `founder_classifier.py` + one `.joblib` file to
|
||||
run predictions — no dependency on the rest of this repository.
|
||||
|
||||
## 3. OpenAlex / production data compatibility
|
||||
|
||||
Your data comes from OpenAlex (publications + author metrics) with patents and
|
||||
grants matched separately to OpenAlex author IDs. Two adjustments were made
|
||||
relative to the original research pipeline, **both validated empirically, no
|
||||
other change to the model was needed**:
|
||||
|
||||
### 3.1 Institution one-hot dropped
|
||||
|
||||
The research dataset one-hot-encodes 8 training institutions. A model trained
|
||||
that way cannot be meaningfully applied to a 9th, unseen institution (its
|
||||
one-hot vector would be all zeros — out of distribution). This production
|
||||
model was trained **without** institution one-hot at all, so it works for any
|
||||
institution, including yours. Cost: ROC-AUC drops from ~0.976 to ~0.95 in a
|
||||
leave-one-institution-out test (see `experiments/README.md` §RQ1) — a modest,
|
||||
worthwhile trade for portability.
|
||||
|
||||
### 3.2 Four Dimensions-specific columns dropped
|
||||
|
||||
| column | what it needs | why it's likely unavailable to you |
|
||||
|---|---|---|
|
||||
| `pat_citation_mean`, `pat_citation_sum` | citation counts **to** each patent | requires a patent source that tracks patent-citing-patent counts (e.g. USPTO/PatentsView citation graph); a simple OpenAlex-author-matched patent list usually won't have this |
|
||||
| `linked_patents_to_publications` | patents that **cite the person's own papers** (non-patent-literature citations) | requires patent-to-paper citation linkage, which most patent sources don't expose |
|
||||
| `grant_innovation_impact` | count of patents **linked to a specific grant** the person received | requires grant-to-patent linkage, on top of grant-to-person matching |
|
||||
|
||||
These were the exact "things we don't have" flagged as a concern. An ablation
|
||||
(same data, same models, same split, only these 4 of 87 columns removed)
|
||||
showed the difference is within noise:
|
||||
|
||||
| feature set | model | roc_auc | pr_auc | mcc |
|
||||
|---|---|---|---|---|
|
||||
| full (includes the 4 columns) | lightgbm | 0.9763 | 0.9685 | 0.8483 |
|
||||
| **without the 4 columns** | lightgbm | 0.9765 | 0.9689 | 0.8514 |
|
||||
| full (includes the 4 columns) | xgboost | 0.9744 | 0.9666 | 0.8426 |
|
||||
| **without the 4 columns** | xgboost | 0.9741 | 0.9657 | 0.8437 |
|
||||
|
||||
Performance doesn't degrade (if anything, it's marginally better without
|
||||
them — consistent with their near-zero permutation importance, see §6). **No
|
||||
architecture/feature-engineering change was made** beyond simply not including
|
||||
these 4 columns — per "if the model can function without it, don't adjust the
|
||||
model," this is confirmed and no further adaptation was necessary.
|
||||
|
||||
### 3.3 Research-area categories
|
||||
|
||||
`publication_research_area`, `patent_research_area`, `grant_research_area` were
|
||||
trained on the first 2 characters of Dimensions' FOR classification codes
|
||||
(e.g. `"3202 Clinical Sciences"` → `"32"`). If your OpenAlex pipeline classifies
|
||||
research area using OpenAlex Topics/Fields/Domains instead, the exact string
|
||||
values will differ. You have two options:
|
||||
1. **Do nothing.** Pass whatever string/code you have; unrecognized values
|
||||
fall into an all-zero ("unknown") one-hot block for that column, which
|
||||
tree models handle gracefully — you just lose the (modest, ~1-2% combined
|
||||
importance, see §6) signal those columns carry.
|
||||
2. **Map your OpenAlex field/domain names to the 2-digit codes** this model
|
||||
was trained on for full signal. The 21 broad codes used are Dimensions
|
||||
FOR 2-digit divisions (30=Agriculture, 31=Biological Sciences, 32=Biomedical
|
||||
and Clinical Sciences, 33=Built Environment and Design, 34=Chemical
|
||||
Sciences, 35=Commerce/Management/Tourism/Services, 36=Creative Arts and
|
||||
Writing, 37=Earth Sciences, 38=Economics, 39=Education, 40=Engineering,
|
||||
41=Environmental Sciences, 42=Health Sciences, 43=History/Heritage/
|
||||
Archaeology, 44=Human Society, 46=Information and Computing Sciences,
|
||||
47=Language/Communication/Culture, 48=Law and Legal Studies,
|
||||
49=Mathematical Sciences, 50=Philosophy and Religious Studies,
|
||||
51=Physical Sciences, 52=Psychology). `"n."` = unknown/not classified.
|
||||
|
||||
Institution and research-area handling aside, **h-index and i10-index are
|
||||
natively provided by OpenAlex** (`summary_stats.h_index` /
|
||||
`summary_stats.i10_index` on the Author object) — you do not need to compute
|
||||
them yourself, despite them being "calculable."
|
||||
|
||||
## 4. Input schema
|
||||
|
||||
Pass a plain dict (or list of dicts for batch) with any subset of these keys —
|
||||
missing numeric keys default to 0, missing categorical keys default to
|
||||
"unknown". **Fields with no natural zero (the year fields, and any field where
|
||||
"0" would be misleading) should always be supplied from real data** — see §7
|
||||
caveats.
|
||||
|
||||
| field | type | description | source |
|
||||
|---|---|---|---|
|
||||
| `h-index` | int | author h-index | OpenAlex `summary_stats.h_index` (native) |
|
||||
| `i10-index` | int | author i10-index | OpenAlex `summary_stats.i10_index` (native) |
|
||||
| `publications` | int | total publication count | OpenAlex `works_count`, or count of that author's works |
|
||||
| `pub_citation_mean` | float | mean citations per publication | mean of `cited_by_count` across the author's works |
|
||||
| `pub_citation_sum` | float | total citations across publications | OpenAlex Author `cited_by_count` (native), or sum of works' `cited_by_count` |
|
||||
| `first_publication_year` | int | year of first publication | min `publication_year` across works |
|
||||
| `last_publication_year` | int | year of most recent publication | max `publication_year` across works |
|
||||
| `patents` | int | total patent count | your patent-matching pipeline |
|
||||
| `first_patent_year` | int | year of first patent | your patent-matching pipeline |
|
||||
| `last_patent_year` | int | year of most recent patent | your patent-matching pipeline |
|
||||
| `grants` | int | total grants/awards count | your grant-matching pipeline (or OpenAlex `awards` on works) |
|
||||
| `first_grant_year` | int | year of first grant | your grant-matching pipeline |
|
||||
| `last_grant_year` | int | year of most recent grant | your grant-matching pipeline |
|
||||
| `affiliations` | int | count of distinct institutional affiliations | OpenAlex Author `affiliations` (native) |
|
||||
| `activities_total` | int | publications + patents + grants | computed (sum) |
|
||||
| `g-index` | int | g-index (largest g s.t. top-g works have ≥ g² combined citations) | computed from per-work `cited_by_count` — see §5 |
|
||||
| `industry_collab_papers` | int | count of publications co-authored with a company-type institution | OpenAlex works' `authorships.institutions.type == "company"` |
|
||||
| `grant_research_impact` | int | count of publications linked to a grant the person received | OpenAlex works' `awards` field, or your grant-to-publication matching |
|
||||
| `publication_research_area` | str | broad research-area code of publications | see §3.3 |
|
||||
| `patent_research_area` | str | broad research-area code of patents | see §3.3 |
|
||||
| `grant_research_area` | str | broad research-area code of grants | see §3.3 |
|
||||
|
||||
Do **not** pass `institution` — it is not used by this model (see §3.1).
|
||||
|
||||
### 5. Computing g-index from OpenAlex
|
||||
|
||||
OpenAlex has no native g-index field. Compute it directly from a list of the
|
||||
person's per-work citation counts (`cited_by_count`), sorted descending:
|
||||
|
||||
```python
|
||||
def g_index(citation_counts: list[int]) -> int:
|
||||
counts = sorted(citation_counts, reverse=True)
|
||||
g = 0
|
||||
cumulative = 0
|
||||
for i, c in enumerate(counts, start=1):
|
||||
cumulative += c
|
||||
if cumulative >= i * i:
|
||||
g = i
|
||||
else:
|
||||
break
|
||||
return g
|
||||
```
|
||||
|
||||
## 6. Output format
|
||||
|
||||
```python
|
||||
clf.predict_one({...})
|
||||
# {'prediction': 1, 'probability_founder': 0.87, 'label': 'founder', 'model': 'lightgbm'}
|
||||
```
|
||||
|
||||
- `prediction`: 0 (non-founder) or 1 (founder), thresholded at `probability_founder >= 0.5`
|
||||
- `probability_founder`: calibrated-ish probability in [0, 1] from `predict_proba`
|
||||
- `label`: human-readable string version of `prediction`
|
||||
|
||||
`clf.predict([...])` (batch) returns a `pandas.DataFrame` with `prediction` and
|
||||
`probability_founder` columns, one row per input record, in input order.
|
||||
|
||||
## 7. Usage example
|
||||
|
||||
```python
|
||||
from founder_classifier import FounderClassifier
|
||||
|
||||
clf = FounderClassifier.load("models/lightgbm.joblib")
|
||||
|
||||
result = clf.predict_one({
|
||||
"h-index": 12, "i10-index": 15, "publications": 40,
|
||||
"pub_citation_mean": 22.5, "pub_citation_sum": 900,
|
||||
"first_publication_year": 2005, "last_publication_year": 2021,
|
||||
"patents": 2, "first_patent_year": 2015, "last_patent_year": 2018,
|
||||
"grants": 3, "first_grant_year": 2010, "last_grant_year": 2019,
|
||||
"affiliations": 2, "activities_total": 45, "g-index": 10,
|
||||
"industry_collab_papers": 4, "grant_research_impact": 5,
|
||||
"publication_research_area": "32", "patent_research_area": "32",
|
||||
"grant_research_area": "32",
|
||||
})
|
||||
print(result)
|
||||
# {'prediction': 1, 'probability_founder': 0.957, 'label': 'founder', 'model': 'lightgbm'}
|
||||
```
|
||||
|
||||
For a second opinion, load `stacking_ensemble.joblib` the same way and compare.
|
||||
|
||||
## 8. Features that affect the classification most
|
||||
|
||||
Permutation importance (mean drop in PR-AUC when a feature is shuffled) on the
|
||||
held-out test split, for both shipped models:
|
||||
|
||||
| feature | lightgbm | stacking_ensemble | OpenAlex availability |
|
||||
|---|---|---|---|
|
||||
| `publications` | **0.494** (dominant) | **0.323** (dominant) | native |
|
||||
| `pub_citation_sum` | 0.100 | 0.069 | computed from works |
|
||||
| `last_patent_year` | 0.089 | 0.081 | your patent pipeline |
|
||||
| `pub_citation_mean` | 0.058 | 0.042 | computed from works |
|
||||
| `i10-index` | 0.058 | 0.035 | native |
|
||||
| `g-index` | 0.039 | 0.035 | computed (§5) |
|
||||
| `activities_total` | 0.023 | 0.021 | computed |
|
||||
| `grants` | 0.023 | 0.019 | your grant pipeline |
|
||||
| `first_publication_year` | 0.016 | 0.015 | native |
|
||||
| `last_publication_year` | 0.010 | — | native |
|
||||
|
||||
**`publications` alone dwarfs every other feature** — by a wide margin, the
|
||||
single most important signal is simply how many papers someone has published.
|
||||
Citation-based signals (`pub_citation_sum`/`mean`, `i10-index`, `g-index`) are
|
||||
a clear second tier. Patent/grant *counts* matter far less than publication
|
||||
volume, and the timing feature `last_patent_year` is surprisingly informative
|
||||
(likely a proxy for "still recently active in applied/patentable work" close
|
||||
to the founding decision). Research-area and institution-adjacent signals are
|
||||
minor (each individual one-hot column contributes < 0.5% importance). Full
|
||||
per-model tables: `feature_importance_lightgbm.csv`,
|
||||
`feature_importance_stacking_ensemble.csv`.
|
||||
|
||||
## 9. Caveats
|
||||
|
||||
- **This is a full-career-profile model** (RQ1): it answers "does this
|
||||
person's overall profile look like a founder's?", not "will they found a
|
||||
company in the next N years?" — for the latter, see the sequence models
|
||||
(`../sequence/README.md`).
|
||||
- **Out-of-distribution inputs are not guarded against.** A record with almost
|
||||
all fields missing/zero is nonsensical (every real researcher has *some*
|
||||
publications) and can produce an unreliable, overconfident prediction —
|
||||
this was observed directly (an all-empty dict predicts "founder" at 99.7%
|
||||
confidence, an artifact of the model extrapolating into a region with no
|
||||
real training examples, not a meaningful result). Only call this model with
|
||||
real profile data for someone who has at least some publication history.
|
||||
- **Retraining on your own labeled data** (once you have enough founder/
|
||||
non-founder examples from your own institution) will likely outperform this
|
||||
model, especially for the research-area categorical signal (§3.3). This
|
||||
model is a strong starting point / cold-start solution before you have your
|
||||
own labels.
|
||||
- Reproduce or retrain via `export_classifier.py` (depends on the full
|
||||
`experiments/src` research package + `evaluation/datasets_complete`).
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
"""Export the two best RQ1 classifiers as standalone production artifacts,
|
||||
adapted for an OpenAlex + patents + grants data pipeline.
|
||||
|
||||
Two adaptations vs `src/data.py::build_rq1_matrix`: the `institution` one-hot is
|
||||
dropped (a model trained on 8 one-hots cannot be applied to a 9th, unseen
|
||||
institution), and four Dimensions-specific columns are dropped as unavailable
|
||||
when patents are matched to OpenAlex authors. Measured cost of each: README.md
|
||||
in this directory, "OpenAlex / production data compatibility".
|
||||
|
||||
Run: conda run -n potential python production/classifier/export_classifier.py
|
||||
(from the experiments/ directory)
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import joblib
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.inspection import permutation_importance
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
from src import config, data, evaluate, models, splits # noqa: E402
|
||||
|
||||
OUT_DIR = Path(__file__).resolve().parent
|
||||
MODELS_DIR = OUT_DIR / "models"
|
||||
MODELS_DIR.mkdir(exist_ok=True)
|
||||
|
||||
# Columns dropped for OpenAlex/production compatibility -- see module docstring.
|
||||
UNAVAILABLE_COLUMNS = [
|
||||
"pat_citation_mean",
|
||||
"pat_citation_sum",
|
||||
"linked_patents_to_publications",
|
||||
"grant_innovation_impact",
|
||||
]
|
||||
|
||||
RESEARCH_AREA_COLUMNS = ["publication_research_area", "patent_research_area", "grant_research_area"]
|
||||
|
||||
# The two models to ship, chosen empirically (see rank_production_models below).
|
||||
SHIP_MODELS = ["lightgbm", "stacking_ensemble"]
|
||||
|
||||
|
||||
def build_production_matrix(df):
|
||||
"""Same as data.build_rq1_matrix(include_institution=False) minus the four
|
||||
OpenAlex/production-unavailable columns."""
|
||||
X, y, groups = data.build_rq1_matrix(df, include_institution=False)
|
||||
X = X.drop(columns=UNAVAILABLE_COLUMNS)
|
||||
return X, y, groups
|
||||
|
||||
|
||||
def rank_and_validate(X, y):
|
||||
"""Fit every candidate on a held-out split so we get honest metrics + a
|
||||
permutation importance ranking for the *actual shipped* feature set."""
|
||||
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()
|
||||
candidates = {
|
||||
**models.advanced_models(scale_pos_weight=spw),
|
||||
"stacking_ensemble": models.stacking_model(scale_pos_weight=spw),
|
||||
}
|
||||
rows, fitted = [], {}
|
||||
for name, model in candidates.items():
|
||||
model, metrics, pred, proba = evaluate.fit_and_evaluate(model, X_train, y_train, X_test, y_test)
|
||||
rows.append({"model": name, **metrics})
|
||||
fitted[name] = model
|
||||
table = evaluate.results_table(rows, sort_by="pr_auc")
|
||||
print("Validated performance (held-out 20% split, production feature set):")
|
||||
print(table[["accuracy", "precision", "recall", "f1", "roc_auc", "pr_auc", "mcc"]])
|
||||
table.to_csv(OUT_DIR / "validated_holdout_metrics.csv")
|
||||
|
||||
# Permutation importance for each shipped model on the held-out split.
|
||||
importances = {}
|
||||
for name in SHIP_MODELS:
|
||||
result = permutation_importance(
|
||||
fitted[name], X_test, y_test, n_repeats=20, random_state=config.RANDOM_STATE, scoring="average_precision"
|
||||
)
|
||||
imp_df = pd.DataFrame(
|
||||
{"feature": X.columns, "importance_mean": result.importances_mean, "importance_std": result.importances_std}
|
||||
).sort_values("importance_mean", ascending=False)
|
||||
imp_df.to_csv(OUT_DIR / f"feature_importance_{name}.csv", index=False)
|
||||
importances[name] = imp_df
|
||||
print(f"\nTop 10 features for {name} (permutation importance, PR-AUC drop):")
|
||||
print(imp_df.head(10).to_string(index=False))
|
||||
return table, importances
|
||||
|
||||
|
||||
def fit_final_bundles(X, y):
|
||||
"""Refit each shipped model on ALL available labeled data (standard practice
|
||||
for a deployed artifact -- validated metrics above already establish that
|
||||
generalization performance holds up on unseen individuals/institutions)."""
|
||||
spw = (y == 0).sum() / (y == 1).sum()
|
||||
candidates = {
|
||||
**models.advanced_models(scale_pos_weight=spw),
|
||||
"stacking_ensemble": models.stacking_model(scale_pos_weight=spw),
|
||||
}
|
||||
numeric_columns = [c for c in config.RQ1_NUMERIC_COLUMNS if c not in UNAVAILABLE_COLUMNS]
|
||||
# Persist the *actual* categories seen at training time for each research-area
|
||||
# column (needed to reindex one-hot columns identically at inference time).
|
||||
raw_df = data.load_rq1_raw()
|
||||
broad_categories = {
|
||||
col: sorted(data._broad_research_area(raw_df[col]).unique().tolist()) for col in RESEARCH_AREA_COLUMNS
|
||||
}
|
||||
|
||||
for name in SHIP_MODELS:
|
||||
model = candidates[name]
|
||||
model.fit(X, y)
|
||||
bundle = {
|
||||
"model": model,
|
||||
"model_name": name,
|
||||
"feature_columns": X.columns.tolist(),
|
||||
"numeric_columns": numeric_columns,
|
||||
"log_columns": [c for c in config.RQ1_LOG_COLUMNS if c not in UNAVAILABLE_COLUMNS],
|
||||
"research_area_columns": RESEARCH_AREA_COLUMNS,
|
||||
"research_area_categories": broad_categories,
|
||||
"label_meaning": {0: "non-founder", 1: "founder"},
|
||||
}
|
||||
out_path = MODELS_DIR / f"{name}.joblib"
|
||||
joblib.dump(bundle, out_path)
|
||||
print(f"Saved {out_path} ({out_path.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
def main():
|
||||
raw_df = data.load_rq1_raw()
|
||||
X, y, _ = build_production_matrix(raw_df)
|
||||
print(f"Production feature matrix: {X.shape[0]} rows x {X.shape[1]} columns\n")
|
||||
|
||||
table, importances = rank_and_validate(X, y)
|
||||
top2 = table.index[:2].tolist()
|
||||
print(f"\nTop-2 by PR-AUC on production feature set: {top2}")
|
||||
|
||||
fit_final_bundles(X, y)
|
||||
|
||||
manifest = {
|
||||
"shipped_models": SHIP_MODELS,
|
||||
"feature_count": X.shape[1],
|
||||
"unavailable_columns_dropped": UNAVAILABLE_COLUMNS,
|
||||
"institution_onehot_dropped": True,
|
||||
}
|
||||
with open(OUT_DIR / "manifest.json", "w") as f:
|
||||
json.dump(manifest, f, indent=2)
|
||||
print("\nDone.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
feature,importance_mean,importance_std
|
||||
publications,0.49372270392208406,0.009435105555281502
|
||||
pub_citation_sum,0.10041155476971034,0.003075116147541558
|
||||
last_patent_year,0.08897556673923894,0.00369039716968687
|
||||
pub_citation_mean,0.05843840173995631,0.0035635258840383387
|
||||
i10-index,0.058276972447521766,0.0028493921400149316
|
||||
g-index,0.03926107174812248,0.002908392365462608
|
||||
activities_total,0.02269603064081724,0.0014262023325240447
|
||||
grants,0.022629143919601975,0.0018617301145260297
|
||||
first_publication_year,0.016383482397344773,0.0014781488366511484
|
||||
last_publication_year,0.01044333199563966,0.0012914478475198282
|
||||
last_grant_year,0.008814204773467744,0.0006485422255609053
|
||||
patents,0.007948968544722036,0.00072369450238458
|
||||
publication_research_area_32,0.004622593405503084,0.0005567329882739705
|
||||
industry_collab_papers,0.004127688678751134,0.0005178389595278936
|
||||
affiliations,0.0038678024032746117,0.0006972880130649415
|
||||
first_patent_year,0.003812250467041056,0.000739110083304315
|
||||
first_grant_year,0.0030673049491659722,0.0005750427084734693
|
||||
h-index,0.0026992385419333962,0.00038040011240434297
|
||||
grant_research_area_32,0.0024383846686938824,0.0006597174523401329
|
||||
grant_research_impact,0.002092380085101797,0.0009209829823855754
|
||||
patent_research_area_46,0.0015450646662926114,0.0003408238801588627
|
||||
publication_research_area_46,0.0011186842180353428,0.0003636648316547925
|
||||
publication_research_area_31,0.0007689503487253891,0.0003229045550739315
|
||||
publication_research_area_35,0.000357006395234688,0.000184261296332344
|
||||
patent_research_area_35,0.0003289822271172027,0.0002457177044892662
|
||||
grant_research_area_46,0.0003235675420170059,0.00012528589983147148
|
||||
patent_research_area_32,0.000284992232621617,9.07382535848989e-05
|
||||
publication_research_area_42,0.00017982554980572885,0.00010724763462688804
|
||||
publication_research_area_51,0.00015147606865889007,0.00017482583322384033
|
||||
publication_research_area_33,0.00014482998247801194,0.00014293663951790765
|
||||
publication_research_area_44,0.0001390054811560959,5.095898280286692e-05
|
||||
grant_research_area_42,0.00010679798913335037,0.00011517614876712806
|
||||
publication_research_area_52,7.58659457399391e-05,8.67872358194002e-05
|
||||
publication_research_area_n.,3.733479496259573e-05,8.266304276802761e-05
|
||||
publication_research_area_47,3.577968510939944e-05,3.644548262290321e-05
|
||||
grant_research_area_33,2.7053741977389746e-05,1.3158619878764252e-05
|
||||
publication_research_area_39,2.6107088659182988e-05,5.314752896673858e-05
|
||||
patent_research_area_40,2.293468269031207e-05,5.522677589407406e-05
|
||||
publication_research_area_30,2.1227363888909333e-05,4.0118754214761545e-05
|
||||
grant_research_area_52,1.86106929250307e-05,4.737938770158699e-05
|
||||
grant_research_area_31,1.7230231395626296e-05,3.303598252316633e-05
|
||||
grant_research_area_36,1.5591805886239208e-05,1.4155029297892755e-05
|
||||
grant_research_area_34,1.5538090563826935e-05,6.936899814614872e-05
|
||||
grant_research_area_51,1.516446191183185e-05,5.6983277869360076e-05
|
||||
publication_research_area_36,1.4576087392986769e-05,2.765828911048998e-05
|
||||
patent_research_area_34,1.2943329198150666e-05,3.9589156048043156e-05
|
||||
publication_research_area_40,1.0268854792233605e-05,0.00010816661742277235
|
||||
patent_research_area_31,7.878647505654702e-06,2.0077897722361337e-05
|
||||
grant_research_area_30,2.291815734967173e-06,4.65029322854696e-06
|
||||
publication_research_area_38,1.9069228478219014e-06,8.771931389052964e-05
|
||||
patent_research_area_41,6.061759097786279e-07,9.166702390722687e-06
|
||||
publication_research_area_43,2.6636266048374323e-08,1.1610479193812715e-07
|
||||
grant_research_area_37,0.0,0.0
|
||||
grant_research_area_49,0.0,0.0
|
||||
grant_research_area_50,0.0,0.0
|
||||
grant_research_area_43,0.0,0.0
|
||||
grant_research_area_44,0.0,0.0
|
||||
patent_research_area_52,0.0,0.0
|
||||
grant_research_area_47,0.0,0.0
|
||||
grant_research_area_48,0.0,0.0
|
||||
grant_research_area_38,0.0,0.0
|
||||
patent_research_area_47,0.0,0.0
|
||||
patent_research_area_39,0.0,0.0
|
||||
patent_research_area_38,0.0,0.0
|
||||
patent_research_area_50,0.0,0.0
|
||||
patent_research_area_49,0.0,0.0
|
||||
patent_research_area_48,0.0,0.0
|
||||
patent_research_area_33,0.0,0.0
|
||||
patent_research_area_44,0.0,0.0
|
||||
patent_research_area_43,0.0,0.0
|
||||
patent_research_area_42,0.0,0.0
|
||||
publication_research_area_50,0.0,0.0
|
||||
patent_research_area_36,0.0,0.0
|
||||
patent_research_area_37,0.0,0.0
|
||||
publication_research_area_48,0.0,0.0
|
||||
grant_research_area_35,-1.417609221954219e-07,6.811830057220157e-06
|
||||
patent_research_area_30,-2.1125354582318678e-07,5.786182703937211e-06
|
||||
publication_research_area_41,-3.4822477430085376e-06,5.216332045233262e-05
|
||||
grant_research_area_40,-3.6317530620000316e-06,1.3350040147139044e-05
|
||||
publication_research_area_34,-3.646016761565951e-06,7.33822378850038e-05
|
||||
grant_research_area_39,-7.1453723731962345e-06,7.890200374144198e-06
|
||||
publication_research_area_49,-1.1344775302907229e-05,8.151635605591815e-06
|
||||
patent_research_area_51,-1.6526341596556638e-05,1.1059230863873912e-05
|
||||
patent_research_area_n.,-2.1720602983060776e-05,7.506139221086442e-05
|
||||
publication_research_area_37,-2.9818072529441686e-05,1.7457265886226128e-05
|
||||
grant_research_area_n.,-4.7040468339543115e-05,0.00011100424284573038
|
||||
grant_research_area_41,-0.0001130957822619516,2.660738658933989e-05
|
||||
|
+88
@@ -0,0 +1,88 @@
|
||||
feature,importance_mean,importance_std
|
||||
publications,0.3230278846487044,0.008800711081034392
|
||||
last_patent_year,0.08101404353937798,0.003480354323912183
|
||||
pub_citation_sum,0.06944573429242025,0.0023742502139718533
|
||||
pub_citation_mean,0.04195885153037786,0.002746357604547681
|
||||
i10-index,0.03509514754261644,0.002072326739488329
|
||||
g-index,0.03475697537302609,0.0027920726906895555
|
||||
activities_total,0.020832913783627394,0.0014390050076316802
|
||||
grants,0.019315451629353792,0.001705491344778238
|
||||
first_publication_year,0.01533644702358411,0.001435861122416683
|
||||
patents,0.008735459919303962,0.0008664045277148187
|
||||
last_grant_year,0.00852538114821349,0.0008305351559872533
|
||||
last_publication_year,0.008331716857098981,0.0011919353376131424
|
||||
first_patent_year,0.004574821675796192,0.0008880825668646626
|
||||
publication_research_area_32,0.004441482221912802,0.0005572418844014392
|
||||
industry_collab_papers,0.003930523472063801,0.0005518946751113055
|
||||
affiliations,0.0030599567623114943,0.0010611086743104593
|
||||
h-index,0.0022261144135681645,0.0005336009903611933
|
||||
first_grant_year,0.001877805851533959,0.0005896264410466552
|
||||
grant_research_impact,0.0016329087316583224,0.0008953253954886791
|
||||
patent_research_area_46,0.0014940981662886431,0.00037841991074793763
|
||||
publication_research_area_46,0.0011952487055542527,0.00034735364248049394
|
||||
grant_research_area_32,0.0010669398974483101,0.0005455308275487198
|
||||
publication_research_area_31,0.0007084035131517119,0.00039455107739638177
|
||||
patent_research_area_32,0.0004949758173996676,0.00013130610768396822
|
||||
publication_research_area_35,0.0003405892771618013,0.00018230752010422918
|
||||
patent_research_area_35,0.00024248321741005552,0.00020196690479766595
|
||||
grant_research_area_46,0.00023508021158918924,9.949654281666699e-05
|
||||
patent_research_area_31,0.00018850830793534779,1.8256292436730253e-05
|
||||
publication_research_area_42,0.0001534410024302102,0.00011124851671888089
|
||||
publication_research_area_51,0.00014695613247396323,0.0001875329044078893
|
||||
publication_research_area_33,0.00013417272910902777,0.00013187331917677777
|
||||
publication_research_area_44,0.00012981751828511912,5.6292634597364995e-05
|
||||
grant_research_area_42,5.536599990074165e-05,9.314538927088949e-05
|
||||
publication_research_area_52,4.569653237913584e-05,7.131642881143011e-05
|
||||
grant_research_area_31,4.1136563865012964e-05,2.3807980697386147e-05
|
||||
patent_research_area_n.,3.185352984812484e-05,0.00011635744728257203
|
||||
publication_research_area_39,2.6622233316087042e-05,5.5811212973079166e-05
|
||||
grant_research_area_51,2.4725683306386914e-05,6.600893864529117e-05
|
||||
publication_research_area_47,2.433370482673447e-05,3.423391460291853e-05
|
||||
patent_research_area_40,1.8682066021558085e-05,8.373831667931168e-05
|
||||
grant_research_area_52,1.736850855706962e-05,4.3586661490832724e-05
|
||||
grant_research_area_33,1.5434425911642348e-05,7.2096436009871756e-06
|
||||
publication_research_area_36,1.4747622070127031e-05,2.0277087228790355e-05
|
||||
grant_research_area_36,1.142451025916702e-05,6.434576027802877e-06
|
||||
patent_research_area_34,8.701666157134858e-06,5.019098976931235e-05
|
||||
grant_research_area_44,4.732059862427862e-06,7.2140691084721474e-06
|
||||
grant_research_area_37,4.64755563436281e-06,5.030937947155093e-07
|
||||
patent_research_area_41,2.4010968401655396e-06,5.567934448611626e-06
|
||||
patent_research_area_30,1.6321848824496498e-06,5.780242227170541e-06
|
||||
publication_research_area_38,9.905339116711431e-07,8.061592993393422e-05
|
||||
grant_research_area_30,9.659275313156358e-07,2.7523076304409766e-06
|
||||
publication_research_area_43,5.303685287838533e-07,1.367136262691942e-07
|
||||
patent_research_area_49,4.579606428523064e-07,0.0
|
||||
patent_research_area_37,3.063681887460756e-07,1.7298092956127215e-06
|
||||
grant_research_area_43,2.3512457243968222e-07,8.230462484551701e-07
|
||||
grant_research_area_38,2.3508913500336347e-07,8.200887763327234e-07
|
||||
grant_research_area_48,5.8234010574809145e-08,9.530097523591368e-07
|
||||
patent_research_area_33,3.072036073303863e-08,2.2691555351810873e-07
|
||||
publication_research_area_48,1.7983012212674508e-08,2.2325824775832636e-07
|
||||
patent_research_area_36,1.7241796396172405e-08,7.515524809601928e-08
|
||||
publication_research_area_50,6.931049512104437e-10,3.8784698331014374e-07
|
||||
grant_research_area_47,0.0,0.0
|
||||
patent_research_area_44,0.0,0.0
|
||||
patent_research_area_52,0.0,0.0
|
||||
patent_research_area_50,0.0,0.0
|
||||
patent_research_area_38,0.0,0.0
|
||||
patent_research_area_39,0.0,0.0
|
||||
patent_research_area_43,0.0,0.0
|
||||
patent_research_area_47,-1.1949865169613717e-08,3.48654680192657e-07
|
||||
grant_research_area_50,-2.1918295900480445e-08,3.3714424966572567e-07
|
||||
grant_research_area_49,-8.055305700249704e-08,1.891835873709255e-07
|
||||
patent_research_area_48,-4.387378193082547e-07,1.0065335879337318e-07
|
||||
grant_research_area_35,-1.4239535029381135e-06,8.577025403596155e-06
|
||||
grant_research_area_40,-2.8211226388352716e-06,5.5951614108796825e-06
|
||||
patent_research_area_42,-3.3309781069246203e-06,1.8056260442298824e-06
|
||||
patent_research_area_51,-6.034520616637895e-06,9.657390477461269e-06
|
||||
grant_research_area_34,-6.555808500358085e-06,5.834666117024457e-05
|
||||
publication_research_area_30,-6.9231426525317994e-06,2.3604223992407287e-05
|
||||
grant_research_area_39,-7.033697191549671e-06,4.692880133162641e-06
|
||||
publication_research_area_41,-1.6315314521198056e-05,3.6394138064735864e-05
|
||||
publication_research_area_49,-2.0970323580088435e-05,1.491599600665608e-05
|
||||
publication_research_area_37,-2.4155344697468494e-05,1.268437871622249e-05
|
||||
publication_research_area_40,-2.4661278046128608e-05,9.362093188879351e-05
|
||||
publication_research_area_34,-4.671501475140283e-05,6.79190773369875e-05
|
||||
grant_research_area_n.,-6.528496794626637e-05,0.00033896991853285866
|
||||
grant_research_area_41,-8.826418872341368e-05,2.1901303480798616e-05
|
||||
publication_research_area_n.,-8.850450506823205e-05,0.00012674501058303883
|
||||
|
+109
@@ -0,0 +1,109 @@
|
||||
"""Self-contained inference wrapper for the founder-potential classifier.
|
||||
|
||||
Depends only on pandas, numpy and joblib -- no dependency on the `experiments/src`
|
||||
research package, so this file + a `models/*.joblib` bundle can be copied into any
|
||||
other codebase.
|
||||
|
||||
Usage:
|
||||
from founder_classifier import FounderClassifier
|
||||
|
||||
clf = FounderClassifier.load("models/lightgbm.joblib")
|
||||
result = clf.predict_one({
|
||||
"h-index": 12, "i10-index": 15, "publications": 40,
|
||||
"pub_citation_mean": 22.5, "pub_citation_sum": 900,
|
||||
"first_publication_year": 2005, "last_publication_year": 2021,
|
||||
"patents": 2, "first_patent_year": 2015, "last_patent_year": 2018,
|
||||
"grants": 3, "first_grant_year": 2010, "last_grant_year": 2019,
|
||||
"affiliations": 2, "activities_total": 45, "g-index": 10,
|
||||
"industry_collab_papers": 4, "grant_research_impact": 5,
|
||||
"publication_research_area": "32", "patent_research_area": "32",
|
||||
"grant_research_area": "32",
|
||||
})
|
||||
print(result) # {'prediction': 1, 'probability_founder': 0.87, ...}
|
||||
|
||||
See README.md in this directory for the full input schema and output format.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import joblib
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
|
||||
class FounderClassifier:
|
||||
"""Wraps a fitted sklearn/LightGBM classifier bundle produced by
|
||||
`export_classifier.py`, handling feature preprocessing (log1p transforms +
|
||||
research-area one-hot encoding) so callers can pass plain feature dicts."""
|
||||
|
||||
def __init__(self, bundle: dict[str, Any]):
|
||||
self._model = bundle["model"]
|
||||
self.model_name: str = bundle["model_name"]
|
||||
self.feature_columns: list[str] = bundle["feature_columns"]
|
||||
self.numeric_columns: list[str] = bundle["numeric_columns"]
|
||||
self.log_columns: list[str] = bundle["log_columns"]
|
||||
self.research_area_columns: list[str] = bundle["research_area_columns"]
|
||||
self.research_area_categories: dict[str, list[str]] = bundle["research_area_categories"]
|
||||
|
||||
@classmethod
|
||||
def load(cls, path: str | Path) -> "FounderClassifier":
|
||||
return cls(joblib.load(path))
|
||||
|
||||
# -- preprocessing -----------------------------------------------------
|
||||
@staticmethod
|
||||
def _broad_research_area(value: Any) -> str:
|
||||
"""Collapse a research-area code to its 2-character broad category,
|
||||
matching the training-time `data._broad_research_area` transform."""
|
||||
if value is None or (isinstance(value, float) and np.isnan(value)):
|
||||
return "n."
|
||||
return str(value).strip()[:2]
|
||||
|
||||
def _to_frame(self, records: list[dict[str, Any]]) -> pd.DataFrame:
|
||||
df = pd.DataFrame.from_records(records, index=range(len(records)))
|
||||
|
||||
# Missing numeric/categorical columns default to 0 / "n." (matches
|
||||
# training-time fillna(0) for any column that couldn't be parsed as
|
||||
# numeric, and the "n.a." fallback in data._broad_research_area).
|
||||
for col in self.numeric_columns:
|
||||
if col not in df.columns:
|
||||
df[col] = 0
|
||||
numeric = df[self.numeric_columns].apply(pd.to_numeric, errors="coerce").fillna(0)
|
||||
for col in self.log_columns:
|
||||
numeric[col] = np.log1p(numeric[col].clip(lower=0))
|
||||
|
||||
for col in self.research_area_columns:
|
||||
if col not in df.columns:
|
||||
df[col] = None
|
||||
cat_df = pd.DataFrame(
|
||||
{col: df[col].apply(self._broad_research_area) for col in self.research_area_columns}
|
||||
)
|
||||
categorical = pd.get_dummies(cat_df, prefix=cat_df.columns.tolist())
|
||||
|
||||
X = pd.concat([numeric, categorical], axis=1)
|
||||
# Reindex to the exact training-time column order; any research-area
|
||||
# category not seen during training (or missing here) becomes all-zero
|
||||
# for that one-hot block, which tree models handle gracefully.
|
||||
X = X.reindex(columns=self.feature_columns, fill_value=0)
|
||||
return X
|
||||
|
||||
# -- public API ----------------------------------------------------------
|
||||
def predict(self, records: list[dict[str, Any]]) -> pd.DataFrame:
|
||||
"""Batch prediction. `records` is a list of raw feature dicts (see
|
||||
README for the input schema). Returns a DataFrame with one row per
|
||||
input record: `prediction` (0/1) and `probability_founder` (0-1)."""
|
||||
X = self._to_frame(records)
|
||||
proba = self._model.predict_proba(X)[:, 1]
|
||||
pred = (proba >= 0.5).astype(int)
|
||||
return pd.DataFrame({"prediction": pred, "probability_founder": proba})
|
||||
|
||||
def predict_one(self, record: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Single-record convenience wrapper around `predict`."""
|
||||
row = self.predict([record]).iloc[0]
|
||||
return {
|
||||
"prediction": int(row["prediction"]),
|
||||
"probability_founder": float(row["probability_founder"]),
|
||||
"label": "founder" if row["prediction"] == 1 else "non-founder",
|
||||
"model": self.model_name,
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"shipped_models": [
|
||||
"lightgbm",
|
||||
"stacking_ensemble"
|
||||
],
|
||||
"feature_count": 87,
|
||||
"unavailable_columns_dropped": [
|
||||
"pat_citation_mean",
|
||||
"pat_citation_sum",
|
||||
"linked_patents_to_publications",
|
||||
"grant_innovation_impact"
|
||||
],
|
||||
"institution_onehot_dropped": true
|
||||
}
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
+7
@@ -0,0 +1,7 @@
|
||||
model,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier
|
||||
lightgbm,0.9293725371324644,0.9161016949152543,0.8897119341563786,0.902713987473904,0.9763933319115661,0.9680867355662728,0.8475189762274824,0.05343925129722402
|
||||
stacking_ensemble,0.9284631706577751,0.9009009009009009,0.9053497942386831,0.90311986863711,0.9748029272608074,0.9657412183896399,0.8464233584967953,0.05796028500367217
|
||||
xgboost,0.927250682024856,0.9079497907949791,0.8930041152263375,0.9004149377593361,0.9728476023474957,0.9640546196916957,0.8431866284933476,0.05821008235216141
|
||||
catboost,0.9227038496514095,0.8993344425956739,0.8897119341563786,0.8944973107157633,0.9709767935988879,0.9616152397971783,0.833539926599779,0.061886894004821225
|
||||
random_forest,0.8911791451955138,0.8639455782312925,0.8362139917695474,0.849853617733166,0.9489078062921099,0.9295025250699936,0.764805465144283,0.09198073526810191
|
||||
svm_rbf,0.8742043043346469,0.8424657534246576,0.8098765432098766,0.8258497691984893,0.9312032495280522,0.8989506133295394,0.7277986141772655,0.09551038087976692
|
||||
|
+97
@@ -0,0 +1,97 @@
|
||||
# Founder classifier v2 (symmetric landmark design)
|
||||
|
||||
Replaces `../classifier` (v1). **v1 must not be used for ranking or coaching:**
|
||||
it was trained with asymmetric observation windows (founders truncated at
|
||||
founding, non-founders full-career) and behaves as an inverse-productivity
|
||||
score in production — 1 publication → P(founder)=0.996, 800 → 0.0002. Its
|
||||
0.976 ROC-AUC was inflated by window-length leakage, and the companion
|
||||
`p_within_3y`/`p_within_5y` outputs were degenerate (exactly 1.0 for every
|
||||
author).
|
||||
|
||||
## What changed
|
||||
|
||||
| | v1 (asymmetric) | v2 (symmetric) |
|
||||
|---|---|---|
|
||||
| Observation window | founders truncated at founding; non-founders full career | every person truncated at an index year (real founding / cohort-matched pseudo-founding), identical construction for both classes |
|
||||
| Citation features (h-index, i10, g-index, citation sums) | included, window-contaminated | excluded — not historicizable to an index date |
|
||||
| `grants` | raw (consortium lists inflate ~100×, up to 409 grants/paper) | de-inflated via per-paper cap mapping (cap 10), applied inside the wrapper |
|
||||
| Institution one-hots | included | excluded — production scores people from arbitrary institutions |
|
||||
| Population | anyone matched | academics only: ≥4 publications at index (both classes), plausibility-filtered (see below) |
|
||||
| Headline holdout | ROC-AUC 0.976 / PR-AUC 0.969 (artifact) | ROC-AUC 0.874 / PR-AUC 0.726 (honest); temporal-split PR-AUC ≈0.73; 5-fold OOF 0.866/0.726 |
|
||||
| P(founder) vs output | strictly decreasing, incl. absurd tail (1 pub → 0.996) | plateau ~0.39–0.42 for 5–17 pubs at index, ~0.10–0.18 for 100+ (matches empirical label rates) |
|
||||
| p_within_{1,3,5}y | 3y/5y ≡ 1.0 for everyone | all horizons discriminate (ROC-AUC 0.86–0.89; ≤0.1% of scores above 0.99) |
|
||||
| Coach-facing number | raw probability | **percentile** vs the ~9k-academic reference cohort, with an out-of-population guard |
|
||||
|
||||
Two dataset artifacts beyond the window asymmetry were found and filtered
|
||||
during the rebuild, both class-asymmetric (rules applied to BOTH classes):
|
||||
|
||||
- **Sampling-frame clash on thin profiles.** Founders come from company
|
||||
databases (people with 1–3 lifetime papers included); non-founders from
|
||||
institutional researcher lists (thin profiles underrepresented). Left in,
|
||||
"long career + tiny record" reads as 65–72% founder. Hence the ≥4
|
||||
publications population rule, enforced at inference by `in_population`.
|
||||
- **Name-collision aggregates.** Non-founders matched by name alone merge
|
||||
multiple researchers (e.g. an "M Nakamura" spanning 1919–2023 with 28,050
|
||||
papers); 4.2% of non-founders vs 2.2% of founders had physically impossible
|
||||
profiles (>60-year span or >25 papers/year sustained). These rows are
|
||||
dropped.
|
||||
|
||||
Training details: `experiments/docs/DESIGN_NOTES.md` (design rationale), `experiments/src/symmetric.py`,
|
||||
`experiments/run_rq1_symmetric.py`, `experiments/run_rq2_symmetric.py`;
|
||||
results in `experiments/results/rq1_symmetric` and `rq2_symmetric`.
|
||||
|
||||
## Interpreting the outputs
|
||||
|
||||
- `percentile` (0–100): rank of the person's score against out-of-fold scores
|
||||
of the reference cohort (founders + non-founders from the 8 training
|
||||
institutions). This is the number to surface to coaches ("higher founding
|
||||
propensity than X% of comparable academics").
|
||||
- `probability_founder` (0–1): raw case-control model output. The training
|
||||
cohort is ~26% founders — far above any real-world base rate — so this is
|
||||
NOT a population founding probability. Do not display it as one.
|
||||
- `p_within_{k}y` bundles: same construction at index−k; conditional-timing
|
||||
evidence, same percentile caveat.
|
||||
|
||||
## Input contract (per record)
|
||||
|
||||
Lifetime totals **as of `scoring_year`** (for live profiles: the current year):
|
||||
`publications`, `patents`, `grants` (raw — the wrapper de-inflates),
|
||||
`first_publication_year`, `first_patent_year`, `first_grant_year`,
|
||||
`industry_collab_papers`, `linked_patents_to_publications`,
|
||||
`publication_research_area`, `patent_research_area`, `grant_research_area`.
|
||||
Missing fields default to 0 / "n.a.". Citation fields are accepted but ignored.
|
||||
|
||||
```python
|
||||
from founder_classifier_v2 import FounderClassifierV2
|
||||
clf = FounderClassifierV2.load("models/founder_classifier_v2.joblib")
|
||||
clf.predict_one({...}, scoring_year=2026)
|
||||
```
|
||||
|
||||
## Migrating smart-guide `profiling/multipliers/founding.py`
|
||||
|
||||
1. Copy this directory (wrapper + `models/*.joblib`) next to the v1 classifier.
|
||||
2. Point the classifier loader at `founder_classifier_v2.joblib` and pass
|
||||
`scoring_year` (extraction snapshot year).
|
||||
3. Surface `percentile` as `founding.percentile`; keep `probability_founder`
|
||||
internal. Replace the degenerate `p_within_3y/5y` fields with the v2
|
||||
bundles' outputs.
|
||||
4. Remove the README stop-block once v1 is no longer referenced.
|
||||
|
||||
## Known limitations (documented, not hidden)
|
||||
|
||||
- Non-founder historical snapshots are curve-estimates (empirical career
|
||||
curves fitted on founders' raw per-year records; log-space R² 0.89–0.94 vs
|
||||
ground truth), because non-founders' per-record data was never saved and the
|
||||
Dimensions API key is dead. Founders' snapshots use the same construction so
|
||||
fidelity is class-symmetric.
|
||||
- Pseudo-founding years for non-founders are sampled (seeded) from the
|
||||
founders' career-age-at-founding distribution, cohort-matched by decade of
|
||||
first publication.
|
||||
- Reference cohort is 8 research universities, index years ≈1950–2023; scoring
|
||||
profiles far outside that population extrapolates.
|
||||
- Conditional on career age, the score declines with publication volume beyond
|
||||
~20–40 papers at index (hyper-prolific researchers found less in this
|
||||
cohort). The empirical label rates support it after cleaning, but residual
|
||||
moderate name-collisions in the non-founder class could still contribute.
|
||||
Communicate to coaches as "the model favours focused mid-volume researchers",
|
||||
and treat very-high-output percentiles as conservative.
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
"""Export the symmetric founder classifier as a self-contained v2 bundle.
|
||||
|
||||
Produces models/founder_classifier_v2.joblib (and p_within_{k}y bundles) with:
|
||||
- the final model refit on the full symmetric dataset;
|
||||
- preprocessing metadata (feature order, log columns, research-area columns);
|
||||
- the grants de-inflation mapping fitted on raw founder records;
|
||||
- reference score quantiles for percentile ranking, computed from 5-fold
|
||||
OUT-OF-FOLD predictions (in-sample scores would shift live percentiles).
|
||||
|
||||
Run with: conda run -n potential python experiments/production/classifier_symmetric/export_classifier_v2.py
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import joblib
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.model_selection import StratifiedKFold, cross_val_predict
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(HERE.parents[1]))
|
||||
|
||||
from src import career_curves as cc
|
||||
from src import config, models, symmetric
|
||||
|
||||
MODELS_DIR = HERE / "models"
|
||||
PRIMARY = "lightgbm"
|
||||
|
||||
|
||||
def _grants_cap_table():
|
||||
"""The binned r -> capped_share mapping as plain arrays for the bundle."""
|
||||
yearly = cc.load_yearly()
|
||||
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.unique(np.quantile(r, np.linspace(0, 1, 21)))
|
||||
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
|
||||
return centers[binned.index.to_numpy()], binned.to_numpy()
|
||||
|
||||
|
||||
def _export(feats, X, y, label, model_name):
|
||||
spw = (y == 0).sum() / (y == 1).sum()
|
||||
model = models.advanced_models(scale_pos_weight=spw)[model_name]
|
||||
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=config.RANDOM_STATE)
|
||||
oof = cross_val_predict(model, X, y, cv=cv, method="predict_proba", n_jobs=-1)[:, 1]
|
||||
model.fit(X, y)
|
||||
|
||||
cap_r, cap_share = _grants_cap_table()
|
||||
bundle = {
|
||||
"model": model,
|
||||
"model_name": f"{model_name}_symmetric_{label}",
|
||||
"feature_columns": X.columns.tolist(),
|
||||
"numeric_columns": symmetric.SYMMETRIC_NUMERIC_COLUMNS,
|
||||
"log_columns": symmetric.SYMMETRIC_LOG_COLUMNS,
|
||||
"research_area_columns": [
|
||||
"publication_research_area", "patent_research_area", "grant_research_area"],
|
||||
"grants_cap_r": cap_r,
|
||||
"grants_cap_share": cap_share,
|
||||
"reference_score_quantiles": np.quantile(oof, np.linspace(0, 1, 1001)),
|
||||
}
|
||||
out = MODELS_DIR / f"{label}.joblib"
|
||||
joblib.dump(bundle, out)
|
||||
from sklearn.metrics import average_precision_score, roc_auc_score
|
||||
stats = {
|
||||
"rows": int(len(X)), "founders": int(y.sum()),
|
||||
"oof_roc_auc": round(float(roc_auc_score(y, oof)), 4),
|
||||
"oof_pr_auc": round(float(average_precision_score(y, oof)), 4),
|
||||
}
|
||||
print(f"{label}: {stats}")
|
||||
return {"file": out.name, "model": bundle["model_name"], **stats}
|
||||
|
||||
|
||||
def main():
|
||||
MODELS_DIR.mkdir(exist_ok=True)
|
||||
manifest = {"design": "symmetric landmark (see experiments/src/symmetric.py)", "bundles": []}
|
||||
|
||||
feats, attrition = symmetric.build_symmetric_dataset()
|
||||
X, y, _ = symmetric.build_matrix(feats, include_institution=False)
|
||||
manifest["attrition"] = {k: int(v) for k, v in attrition.items()}
|
||||
manifest["bundles"].append(_export(feats, X, y, "founder_classifier_v2", PRIMARY))
|
||||
|
||||
for k in [1, 3, 5]:
|
||||
feats_k, _ = symmetric.build_symmetric_dataset(offset=k)
|
||||
feats_k = feats_k[feats_k["pubs_at_index"] > 0].reset_index(drop=True)
|
||||
Xk, yk, _ = symmetric.build_matrix(feats_k, include_institution=False)
|
||||
manifest["bundles"].append(_export(feats_k, Xk, yk, f"p_within_{k}y_v2", PRIMARY))
|
||||
|
||||
(HERE / "manifest.json").write_text(json.dumps(manifest, indent=2))
|
||||
print(f"Manifest written to {HERE / 'manifest.json'}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
"""Self-contained inference wrapper for the SYMMETRIC founder-potential classifier.
|
||||
|
||||
Depends only on pandas, numpy and joblib. Replaces v1 (../classifier), which
|
||||
must not be used for ranking — see README.md in this directory for what changed,
|
||||
the input contract and how to read the outputs.
|
||||
|
||||
Three contract points the caller must get right:
|
||||
- `predict` requires `scoring_year`, the year the profile snapshot was taken.
|
||||
- `percentile` is the coach-facing output; `probability_founder` is a raw
|
||||
case-control score (~26% training base rate) and is NOT a population
|
||||
founding probability.
|
||||
- Pass `grants` RAW — the wrapper applies the training per-paper cap itself.
|
||||
|
||||
Usage:
|
||||
from founder_classifier_v2 import FounderClassifierV2
|
||||
|
||||
clf = FounderClassifierV2.load("models/founder_classifier_v2.joblib")
|
||||
result = clf.predict_one({
|
||||
"publications": 40, "patents": 2, "grants": 3,
|
||||
"first_publication_year": 2005,
|
||||
"first_patent_year": 2015, "first_grant_year": 2010,
|
||||
"industry_collab_papers": 4, "linked_patents_to_publications": 1,
|
||||
"publication_research_area": "32 Biomedical and Clinical Sciences",
|
||||
"patent_research_area": "32", "grant_research_area": "32",
|
||||
}, scoring_year=2026)
|
||||
# {'percentile': 71.4, 'probability_founder': 0.38, ...}
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import joblib
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
|
||||
class FounderClassifierV2:
|
||||
def __init__(self, bundle: dict[str, Any]):
|
||||
self._model = bundle["model"]
|
||||
self.model_name: str = bundle["model_name"]
|
||||
self.feature_columns: list[str] = bundle["feature_columns"]
|
||||
self.numeric_columns: list[str] = bundle["numeric_columns"]
|
||||
self.log_columns: list[str] = bundle["log_columns"]
|
||||
self.research_area_columns: list[str] = bundle["research_area_columns"]
|
||||
# Grants de-inflation: interpolation table r -> capped_share, r = grants/pubs.
|
||||
self.grants_cap_r: np.ndarray = np.asarray(bundle["grants_cap_r"])
|
||||
self.grants_cap_share: np.ndarray = np.asarray(bundle["grants_cap_share"])
|
||||
# Reference score quantiles for percentile ranking (1001 points on [0,1]).
|
||||
self.reference_scores: np.ndarray = np.asarray(bundle["reference_score_quantiles"])
|
||||
|
||||
@classmethod
|
||||
def load(cls, path: str | Path) -> "FounderClassifierV2":
|
||||
return cls(joblib.load(path))
|
||||
|
||||
# -- preprocessing -------------------------------------------------------
|
||||
@staticmethod
|
||||
def _broad_research_area(value: Any) -> str:
|
||||
if value is None or (isinstance(value, float) and np.isnan(value)):
|
||||
return "n."
|
||||
return str(value).strip()[:2]
|
||||
|
||||
def _capped_grants(self, grants: np.ndarray, pubs: np.ndarray) -> np.ndarray:
|
||||
r = grants / np.clip(pubs, 1, None)
|
||||
share = np.interp(r, self.grants_cap_r, self.grants_cap_share)
|
||||
return grants * np.clip(share, 0.0, 1.0)
|
||||
|
||||
def _to_frame(self, records: list[dict[str, Any]], scoring_year: int) -> pd.DataFrame:
|
||||
df = pd.DataFrame.from_records(records, index=range(len(records)))
|
||||
for col in ["publications", "patents", "grants", "first_publication_year",
|
||||
"first_patent_year", "first_grant_year",
|
||||
"industry_collab_papers", "linked_patents_to_publications"]:
|
||||
if col not in df.columns:
|
||||
df[col] = np.nan
|
||||
df[col] = pd.to_numeric(df[col], errors="coerce")
|
||||
|
||||
pubs = df["publications"].fillna(0).to_numpy(dtype=float)
|
||||
pats = df["patents"].fillna(0).to_numpy(dtype=float)
|
||||
grants = self._capped_grants(df["grants"].fillna(0).to_numpy(dtype=float), pubs)
|
||||
first_pub = df["first_publication_year"].to_numpy(dtype=float)
|
||||
career_age = np.clip(scoring_year - first_pub, 1, None)
|
||||
has_pat = (df["first_patent_year"].notna() & (df["first_patent_year"] <= scoring_year)
|
||||
& (pats > 0)).to_numpy()
|
||||
has_grant = (df["first_grant_year"].notna() & (df["first_grant_year"] <= scoring_year)
|
||||
& (grants > 0)).to_numpy()
|
||||
|
||||
numeric = pd.DataFrame({
|
||||
"pubs_at_index": pubs,
|
||||
"patents_at_index": pats,
|
||||
"grants_at_index": grants,
|
||||
"activities_at_index": pubs + pats + grants,
|
||||
"industry_collab_at_index": df["industry_collab_papers"].fillna(0),
|
||||
"linked_pat_pub_at_index": df["linked_patents_to_publications"].fillna(0),
|
||||
"career_age_at_index": career_age,
|
||||
"first_publication_year": first_pub,
|
||||
"pub_rate": pubs / career_age,
|
||||
"patent_rate": pats / career_age,
|
||||
"grant_rate": grants / career_age,
|
||||
"has_patents_at_index": has_pat.astype(int),
|
||||
"has_grants_at_index": has_grant.astype(int),
|
||||
"years_since_first_patent": np.where(
|
||||
has_pat, np.clip(scoring_year - df["first_patent_year"].fillna(scoring_year), 0, None), 0),
|
||||
"years_since_first_grant": np.where(
|
||||
has_grant, np.clip(scoring_year - df["first_grant_year"].fillna(scoring_year), 0, None), 0),
|
||||
})
|
||||
numeric = numeric[self.numeric_columns].fillna(0)
|
||||
for col in self.log_columns:
|
||||
numeric[col] = np.log1p(numeric[col].clip(lower=0))
|
||||
|
||||
cat_df = pd.DataFrame({
|
||||
col: df.get(col, pd.Series([None] * len(df))).apply(self._broad_research_area)
|
||||
for col in self.research_area_columns
|
||||
})
|
||||
categorical = pd.get_dummies(cat_df, prefix=cat_df.columns.tolist())
|
||||
X = pd.concat([numeric, categorical], axis=1)
|
||||
return X.reindex(columns=self.feature_columns, fill_value=0)
|
||||
|
||||
# -- public API ----------------------------------------------------------
|
||||
# The model's population is academics with a minimal record (see
|
||||
# experiments/src/symmetric.py::MIN_PUBS_AT_INDEX): below this, the training
|
||||
# classes come from clashing sampling frames (company databases vs
|
||||
# institutional researcher lists) and scores are not evidence.
|
||||
MIN_PUBLICATIONS = 4
|
||||
|
||||
def predict(self, records: list[dict[str, Any]], scoring_year: int) -> pd.DataFrame:
|
||||
"""`records`: raw profile dicts (lifetime totals as of `scoring_year`).
|
||||
Returns probability_founder (raw case-control score), percentile (rank
|
||||
vs the reference cohort, 0-100; the coach-facing number), and
|
||||
in_population. When in_population is False (fewer than
|
||||
MIN_PUBLICATIONS publications) percentile is NaN: the person is outside
|
||||
the modelled population and must not be ranked."""
|
||||
X = self._to_frame(records, scoring_year)
|
||||
proba = self._model.predict_proba(X)[:, 1]
|
||||
pct = np.interp(proba, self.reference_scores, np.linspace(0, 100, len(self.reference_scores)))
|
||||
pubs = pd.DataFrame.from_records(records).get("publications", pd.Series([0] * len(records)))
|
||||
in_pop = pd.to_numeric(pubs, errors="coerce").fillna(0).to_numpy() >= self.MIN_PUBLICATIONS
|
||||
return pd.DataFrame({
|
||||
"probability_founder": proba,
|
||||
"percentile": np.where(in_pop, np.round(pct, 1), np.nan),
|
||||
"in_population": in_pop,
|
||||
})
|
||||
|
||||
def predict_one(self, record: dict[str, Any], scoring_year: int) -> dict[str, Any]:
|
||||
row = self.predict([record], scoring_year).iloc[0]
|
||||
return {
|
||||
"percentile": None if not row["in_population"] else float(row["percentile"]),
|
||||
"probability_founder": float(row["probability_founder"]),
|
||||
"in_population": bool(row["in_population"]),
|
||||
"model": self.model_name,
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"design": "symmetric landmark (see experiments/src/symmetric.py)",
|
||||
"bundles": [
|
||||
{
|
||||
"file": "founder_classifier_v2.joblib",
|
||||
"model": "lightgbm_symmetric_founder_classifier_v2",
|
||||
"rows": 9017,
|
||||
"founders": 2349,
|
||||
"oof_roc_auc": 0.8659,
|
||||
"oof_pr_auc": 0.7257
|
||||
},
|
||||
{
|
||||
"file": "p_within_1y_v2.joblib",
|
||||
"model": "lightgbm_symmetric_p_within_1y_v2",
|
||||
"rows": 8515,
|
||||
"founders": 2238,
|
||||
"oof_roc_auc": 0.8614,
|
||||
"oof_pr_auc": 0.7154
|
||||
},
|
||||
{
|
||||
"file": "p_within_3y_v2.joblib",
|
||||
"model": "lightgbm_symmetric_p_within_3y_v2",
|
||||
"rows": 7706,
|
||||
"founders": 2010,
|
||||
"oof_roc_auc": 0.861,
|
||||
"oof_pr_auc": 0.7176
|
||||
},
|
||||
{
|
||||
"file": "p_within_5y_v2.joblib",
|
||||
"model": "lightgbm_symmetric_p_within_5y_v2",
|
||||
"rows": 6995,
|
||||
"founders": 1833,
|
||||
"oof_roc_auc": 0.8535,
|
||||
"oof_pr_auc": 0.7038
|
||||
}
|
||||
],
|
||||
"attrition": {
|
||||
"initial": 16822,
|
||||
"no_publication_anchor": 1430,
|
||||
"implausible_profile_founders": 425,
|
||||
"implausible_profile_nonfounders": 770,
|
||||
"founder_bad_founding_year": 340,
|
||||
"founder_bad_career_age": 723,
|
||||
"duplicates": 0,
|
||||
"below_min_pubs_at_index_founders": 1112,
|
||||
"below_min_pubs_at_index_nonfounders": 3005
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,188 @@
|
||||
# Founder-Timing Sequence Model — Production Guide
|
||||
|
||||
Given a researcher's **year-by-year publication/patent/grant activity**,
|
||||
predicts how many years into their career a "founding-like" moment falls, and
|
||||
derives a probability of founding within the next 1/2/3/5 years. This is the
|
||||
RQ-sequence model from the research pipeline (LSTM + Transformer), re-packaged
|
||||
for a production app.
|
||||
|
||||
## 1. Which two models, and why
|
||||
|
||||
The two model architectures evaluated (`experiments/results/sequence_founders/sequence_founders_comparison.csv`),
|
||||
ranked by held-out MAE, both far ahead of the naive heuristic (MAE=0.554) and
|
||||
an aggregate-feature Random Forest (MAE=2.571) baseline:
|
||||
|
||||
| rank | model | MAE | RMSE | R2 |
|
||||
|---|---|---|---|---|
|
||||
| 1 | **transformer** | 0.180 | 0.269 | 0.998 |
|
||||
| 2 | **lstm** | 0.208 | 0.258 | 0.998 |
|
||||
|
||||
Both are shipped (`models/transformer.pt`, `models/lstm.pt`) — they are close
|
||||
enough (Δmae=0.028 years, i.e. ~10 days) that using both as a cross-check is
|
||||
worthwhile. `transformer` is marginally better on MAE, `lstm` marginally better
|
||||
on RMSE (fewer large errors); either is a reasonable default.
|
||||
|
||||
**Important scope note:** these predict `founding_age` only for the regime the
|
||||
models were trained and validated on: founders whose company started **within
|
||||
20 years of their first publication**. Founders/candidates outside that range
|
||||
were excluded from training (see `experiments/README.md` "Sequence modeling"
|
||||
section) — treat predictions for very long, established careers (> 20 years
|
||||
of activity with no founding yet) with more caution; the model has not seen
|
||||
that regime.
|
||||
|
||||
## 2. Files
|
||||
|
||||
```
|
||||
production/sequence/
|
||||
founder_timing_model.py <- self-contained wrapper (torch/numpy only)
|
||||
models/
|
||||
transformer.pt <- recommended default
|
||||
lstm.pt <- alternative / second opinion
|
||||
export_sequence_models.py <- reproducible export/training script
|
||||
```
|
||||
|
||||
Each `.pt` is a single bundle: `{model_key, net_kwargs, state_dict, scaler_mean,
|
||||
scaler_std, window, channels, held_out_metrics, held_out_residuals,
|
||||
channel_ablation_mae_delta}`. You only need `founder_timing_model.py` + one
|
||||
`.pt` file to run predictions.
|
||||
|
||||
## 3. Input schema
|
||||
|
||||
The model consumes a **20-year rolling window** (`WINDOW = 20`) of yearly
|
||||
activity counts, ending at a reference year of your choice (typically "now").
|
||||
You provide plain `{year: count}` dictionaries — the wrapper handles
|
||||
alignment, left-zero-padding (for researchers with < 20 years of history) and
|
||||
the log1p transform used at training time:
|
||||
|
||||
```python
|
||||
model.build_sequence(
|
||||
pub_counts_by_year={2015: 2, 2016: 3, 2018: 1, 2020: 4, 2022: 2},
|
||||
pat_counts_by_year={2021: 1},
|
||||
grant_counts_by_year={2019: 1},
|
||||
as_of_year=2023,
|
||||
)
|
||||
```
|
||||
|
||||
| argument | type | description | source |
|
||||
|---|---|---|---|
|
||||
| `pub_counts_by_year` | dict[int, int] | publications per calendar year | OpenAlex works' `publication_year`, grouped/counted per author |
|
||||
| `pat_counts_by_year` | dict[int, int] | patents per calendar year | your patent-matching pipeline |
|
||||
| `grant_counts_by_year` | dict[int, int] | grants/awards per calendar year | your grant-matching pipeline |
|
||||
| `as_of_year` | int | the "reference now" the 20-year window ends at (defaults to the latest year with any activity) | e.g. current year |
|
||||
| `first_publication_year` | int | year of the researcher's first publication (needed only for `years_to_founding` / probability output, not for the raw point estimate) | OpenAlex, min `publication_year` |
|
||||
|
||||
Years outside `[as_of_year - 19, as_of_year]` are ignored; years inside that
|
||||
range with no entry default to a count of 0.
|
||||
|
||||
## 4. Output format
|
||||
|
||||
```python
|
||||
model.predict(
|
||||
pub_counts_by_year=..., pat_counts_by_year=..., grant_counts_by_year=...,
|
||||
first_publication_year=2015, as_of_year=2023,
|
||||
)
|
||||
# {
|
||||
# 'model': 'transformer',
|
||||
# 'predicted_founding_age': 8.4,
|
||||
# 'current_career_age': 8,
|
||||
# 'years_to_founding': 0.4,
|
||||
# 'probability_founds_within': {1: 0.62, 2: 0.87, 3: 0.95, 5: 0.99}
|
||||
# }
|
||||
```
|
||||
|
||||
- `predicted_founding_age`: point estimate — "how many years into a career
|
||||
does this activity pattern, taken as of `as_of_year`, look like a founding
|
||||
moment."
|
||||
- `current_career_age` = `as_of_year - first_publication_year` (only returned
|
||||
if `first_publication_year` is given).
|
||||
- `years_to_founding` = `predicted_founding_age - current_career_age`. Positive
|
||||
means the model expects founding is still that many years away (given the
|
||||
current trajectory); **zero or negative means the current profile already
|
||||
looks like a typical founding-moment profile** — founding could plausibly
|
||||
happen any time now (the model can't distinguish "already overdue" from
|
||||
"right now" — see §6 caveats).
|
||||
- `probability_founds_within`: `{k: P(founds within k years)}` for k in
|
||||
(1, 2, 3, 5) by default (pass `horizons=(...)` to customize) — see §5.
|
||||
|
||||
If you omit `first_publication_year`, you get only `predicted_founding_age`
|
||||
(no probability/timing-to-now fields, since those require knowing the current
|
||||
career age).
|
||||
|
||||
## 5. Probability design (why a residual-based approach, not a retrained model)
|
||||
|
||||
The underlying LSTM/Transformer are **point-estimate regressors** (trained
|
||||
with MSE loss) — they were not retrained with a probabilistic loss for this
|
||||
deliverable, since the existing point predictions are already extremely
|
||||
accurate (R²=0.998, MAE ≈ 2-2.5 months) and retraining risks losing that
|
||||
accuracy for a marginal gain in "native" probability calibration.
|
||||
|
||||
Instead, probability is derived **post-hoc** from the held-out test set's
|
||||
residual distribution (`held_out_residuals` in the bundle, ~460 examples per
|
||||
model): `P(founds within k years) = P(residual <= k - years_to_founding)`,
|
||||
i.e. the empirical fraction of held-out errors small enough that the true
|
||||
founding time would fall within `k` years given the current point estimate.
|
||||
This is non-parametric (no Gaussian assumption) and directly reflects the
|
||||
model's actual observed error spread, at the cost of being a global (not
|
||||
per-input) uncertainty estimate — every prediction uses the same residual
|
||||
pool, it doesn't widen for "harder" inputs specifically.
|
||||
|
||||
## 6. Features that affect the prediction most
|
||||
|
||||
Channel ablation (zero out one channel, re-predict on the held-out test set,
|
||||
measure the MAE increase) — `channel_ablation_mae_delta` in each bundle:
|
||||
|
||||
| channel | lstm MAE increase | transformer MAE increase |
|
||||
|---|---|---|
|
||||
| **pub** (publications) | **+8.29** | **+8.92** |
|
||||
| pat (patents) | -0.003 (noise) | -0.020 (noise) |
|
||||
| grant (grants) | -0.004 (noise) | -0.020 (noise) |
|
||||
|
||||
**The publication timeline completely dominates.** Removing it destroys the
|
||||
model (MAE jumps from ~0.2 to ~8.5 years — essentially random). Removing
|
||||
patents or grants changes nothing (the tiny negative deltas are noise, not a
|
||||
real effect) — for *this specific task* (predicting how far into a career a
|
||||
founding-like moment falls), patent/grant timing carries no additional signal
|
||||
beyond what publication timing already provides. Practically: if your
|
||||
production pipeline is missing patent/grant year-by-year data for some
|
||||
researchers, this model will still work essentially as well using publication
|
||||
history alone — you do not need to block on having complete patent/grant
|
||||
histories for this specific model (unlike the classifier, where patent/grant
|
||||
*counts* do matter — see `../classifier/README.md` §8).
|
||||
|
||||
## 7. Usage example
|
||||
|
||||
```python
|
||||
from founder_timing_model import FounderTimingModel
|
||||
|
||||
model = FounderTimingModel.load("models/transformer.pt")
|
||||
|
||||
result = model.predict(
|
||||
pub_counts_by_year={2016: 1, 2017: 2, 2018: 3, 2019: 2, 2020: 4, 2021: 3, 2022: 5},
|
||||
pat_counts_by_year={2021: 1},
|
||||
grant_counts_by_year={2020: 1},
|
||||
first_publication_year=2016,
|
||||
as_of_year=2022,
|
||||
)
|
||||
print(result)
|
||||
```
|
||||
|
||||
## 8. Caveats
|
||||
|
||||
- **Founders-only training data.** These models were trained exclusively on
|
||||
people who eventually founded a company, predicting *when in their career*
|
||||
that happened. There is no matched non-founder sequence in the source data
|
||||
(see `experiments/README.md` "Sequence modeling" for why), so this model
|
||||
cannot tell you whether someone will found at all — only, conditional on a
|
||||
founding-like pattern existing, how far into the career it falls. Combine
|
||||
with the classifier (`../classifier/README.md`) for the "will they found at
|
||||
all" question, and this model for "when."
|
||||
- **Retrospective training, prospective use.** Training examples anchor the
|
||||
20-year window at a *real, already-known* founding event. Using the window
|
||||
ending at "now" for someone who hasn't founded yet is a reasonable,
|
||||
intended extrapolation but was not directly validated against real
|
||||
future-unknown outcomes (no ground truth exists yet for currently-active
|
||||
non-founders). Treat `years_to_founding` as a useful signal/ranking tool
|
||||
more than a precise calendar forecast.
|
||||
- **Fixed 20-year window, [1, 20] founding-age range.** See §1.
|
||||
- Reproduce or retrain via `export_sequence_models.py` (depends on the full
|
||||
`experiments/src` research package + `evaluation/datasets_complete`).
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
"""Export the two best founder-timing sequence models (LSTM + Transformer) as
|
||||
standalone production artifacts, with a post-hoc probability layer derived from
|
||||
held-out residuals (see README.md "Probability design" section for rationale).
|
||||
|
||||
Run: conda run -n potential python production/sequence/export_sequence_models.py
|
||||
(from the experiments/ directory)
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
from src import config, evaluate, sequence_data, sequence_models # noqa: E402
|
||||
|
||||
OUT_DIR = Path(__file__).resolve().parent
|
||||
MODELS_DIR = OUT_DIR / "models"
|
||||
MODELS_DIR.mkdir(exist_ok=True)
|
||||
|
||||
LSTM_KWARGS = {"hidden_size": 64, "num_layers": 1, "dropout": 0.2}
|
||||
TRANSFORMER_KWARGS = {"d_model": 32, "n_heads": 4, "n_layers": 2, "dropout": 0.2}
|
||||
|
||||
|
||||
def channel_ablation(model, X_test, y_test, base_mae):
|
||||
"""Zero out one channel at a time (post-hoc, on the already-fitted model)
|
||||
and measure the MAE increase -- a cheap proxy for channel importance."""
|
||||
rows = {}
|
||||
for c, name in enumerate(sequence_data.CHANNELS):
|
||||
X_ablated = X_test.copy()
|
||||
X_ablated[:, :, c] = 0.0
|
||||
pred = model.predict(X_ablated)
|
||||
metrics = evaluate.regression_metrics(y_test, pred)
|
||||
rows[name] = metrics["mae"] - base_mae
|
||||
return rows
|
||||
|
||||
|
||||
def build_and_export(model_key, model_cls, net_kwargs, X_train, y_train, X_test, y_test, X_all, y_all):
|
||||
print(f"\n=== {model_key} ===")
|
||||
# 1) Fit on train only -> honest held-out metrics + residuals + channel ablation.
|
||||
model = model_cls(**net_kwargs)
|
||||
model.fit(X_train, y_train)
|
||||
pred_test = model.predict(X_test)
|
||||
metrics = evaluate.regression_metrics(y_test, pred_test)
|
||||
residuals = (y_test - pred_test).astype(np.float32)
|
||||
print(f" held-out: MAE={metrics['mae']:.3f} RMSE={metrics['rmse']:.3f} R2={metrics['r2']:.3f}")
|
||||
|
||||
ablation = channel_ablation(model, X_test, y_test, metrics["mae"])
|
||||
print(" channel ablation (MAE increase when channel is zeroed out):")
|
||||
for ch, delta in sorted(ablation.items(), key=lambda kv: -kv[1]):
|
||||
print(f" {ch:6s} +{delta:.4f} MAE")
|
||||
|
||||
# 2) Refit on ALL data for the final shipped artifact (standard practice;
|
||||
# generalization already validated above).
|
||||
final_model = model_cls(**net_kwargs)
|
||||
final_model.fit(X_all, y_all)
|
||||
|
||||
bundle = {
|
||||
"model_key": model_key,
|
||||
"net_kwargs": net_kwargs,
|
||||
"state_dict": final_model.model_.state_dict(),
|
||||
"scaler_mean": final_model.scaler_.mean_,
|
||||
"scaler_std": final_model.scaler_.std_,
|
||||
"window": sequence_data.WINDOW,
|
||||
"channels": sequence_data.CHANNELS,
|
||||
"held_out_metrics": metrics,
|
||||
"held_out_residuals": residuals,
|
||||
"channel_ablation_mae_delta": ablation,
|
||||
}
|
||||
out_path = MODELS_DIR / f"{model_key}.pt"
|
||||
torch.save(bundle, out_path)
|
||||
print(f" saved {out_path} ({out_path.stat().st_size / 1024:.0f} KB)")
|
||||
return metrics, residuals, ablation
|
||||
|
||||
|
||||
def main():
|
||||
print("Building founder-only sequence dataset...")
|
||||
sequences, founding_age, meta = sequence_data.build_founder_sequence_dataset()
|
||||
|
||||
idx = np.arange(len(sequences))
|
||||
idx_train, idx_test = train_test_split(idx, test_size=0.2, random_state=config.RANDOM_STATE)
|
||||
X_train, X_test = sequences[idx_train], sequences[idx_test]
|
||||
y_train, y_test = founding_age[idx_train], founding_age[idx_test]
|
||||
|
||||
results = {}
|
||||
results["lstm"] = build_and_export(
|
||||
"lstm", sequence_models.LSTMRegressor, LSTM_KWARGS,
|
||||
X_train, y_train, X_test, y_test, sequences, founding_age,
|
||||
)
|
||||
results["transformer"] = build_and_export(
|
||||
"transformer", sequence_models.TransformerRegressor, TRANSFORMER_KWARGS,
|
||||
X_train, y_train, X_test, y_test, sequences, founding_age,
|
||||
)
|
||||
|
||||
print("\nDone. Shipped: lstm.pt, transformer.pt")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
"""Self-contained inference wrapper for the founder-timing sequence models
|
||||
(LSTM / Transformer). Depends only on torch/numpy -- no dependency on the
|
||||
`experiments/src` research package.
|
||||
|
||||
These models predict `founding_age`: how many years into a researcher's
|
||||
publishing career a founding event falls, given their chronological
|
||||
publication/patent/grant activity in the WINDOW (20) years up to and including
|
||||
the reference point of interest ("now", if you're asking "how founding-ready
|
||||
does this person look today").
|
||||
|
||||
Usage:
|
||||
from founder_timing_model import FounderTimingModel
|
||||
|
||||
model = FounderTimingModel.load("models/transformer.pt")
|
||||
result = model.predict(
|
||||
pub_counts_by_year={2015: 2, 2016: 3, 2017: 1, 2020: 4, 2022: 2},
|
||||
pat_counts_by_year={2021: 1},
|
||||
grant_counts_by_year={2019: 1},
|
||||
first_publication_year=2015,
|
||||
as_of_year=2023,
|
||||
)
|
||||
print(result)
|
||||
|
||||
See README.md in this directory for the full input schema, output format and
|
||||
the "probability" design rationale.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
CHANNELS = ["pub", "pat", "grant"]
|
||||
WINDOW = 20
|
||||
DEFAULT_HORIZONS = (1, 2, 3, 5)
|
||||
|
||||
|
||||
class _LSTMNet(nn.Module):
|
||||
"""Must stay structurally identical to src/sequence_models.py::_LSTMNet --
|
||||
state_dict keys are loaded directly from the exported bundle."""
|
||||
|
||||
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):
|
||||
"""Must stay structurally identical to src/sequence_models.py::_TransformerNet."""
|
||||
|
||||
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)
|
||||
return self.head(pooled).squeeze(-1)
|
||||
|
||||
|
||||
class FounderTimingModel:
|
||||
def __init__(self, bundle: dict[str, Any]):
|
||||
self.model_key: str = bundle["model_key"]
|
||||
self.window: int = bundle["window"]
|
||||
self.channels: list[str] = bundle["channels"]
|
||||
self.scaler_mean = bundle["scaler_mean"]
|
||||
self.scaler_std = bundle["scaler_std"]
|
||||
self.held_out_metrics: dict = bundle["held_out_metrics"]
|
||||
self.held_out_residuals: np.ndarray = bundle["held_out_residuals"]
|
||||
self.channel_ablation_mae_delta: dict = bundle["channel_ablation_mae_delta"]
|
||||
|
||||
n_channels = len(self.channels)
|
||||
if self.model_key == "lstm":
|
||||
self._net = _LSTMNet(n_channels, **bundle["net_kwargs"])
|
||||
elif self.model_key == "transformer":
|
||||
self._net = _TransformerNet(n_channels, self.window, **bundle["net_kwargs"])
|
||||
else:
|
||||
raise ValueError(f"unknown model_key {self.model_key!r}")
|
||||
self._net.load_state_dict(bundle["state_dict"])
|
||||
self._net.eval()
|
||||
|
||||
@classmethod
|
||||
def load(cls, path: str | Path) -> "FounderTimingModel":
|
||||
return cls(torch.load(path, map_location="cpu", weights_only=False))
|
||||
|
||||
# -- building the input sequence ----------------------------------------
|
||||
def build_sequence(
|
||||
self,
|
||||
pub_counts_by_year: dict[int, int] | None = None,
|
||||
pat_counts_by_year: dict[int, int] | None = None,
|
||||
grant_counts_by_year: dict[int, int] | None = None,
|
||||
as_of_year: int | None = None,
|
||||
) -> np.ndarray:
|
||||
"""Turn per-year activity counts into the (WINDOW, 3) chronological,
|
||||
log1p-transformed array the model expects (oldest year first, ending
|
||||
at `as_of_year`). Years with no recorded activity default to 0; years
|
||||
before the start of the available history are zero-padded on the left
|
||||
(identical in spirit to how a founder with < WINDOW years of real
|
||||
pre-founding history looks in the training data)."""
|
||||
pub_counts_by_year = pub_counts_by_year or {}
|
||||
pat_counts_by_year = pat_counts_by_year or {}
|
||||
grant_counts_by_year = grant_counts_by_year or {}
|
||||
if as_of_year is None:
|
||||
all_years = list(pub_counts_by_year) + list(pat_counts_by_year) + list(grant_counts_by_year)
|
||||
if not all_years:
|
||||
raise ValueError("as_of_year must be given if no activity years are provided")
|
||||
as_of_year = max(all_years)
|
||||
|
||||
years = range(as_of_year - self.window + 1, as_of_year + 1) # oldest -> newest, length WINDOW
|
||||
channel_dicts = [pub_counts_by_year, pat_counts_by_year, grant_counts_by_year]
|
||||
seq = np.zeros((self.window, len(self.channels)), dtype=np.float32)
|
||||
for c, counts in enumerate(channel_dicts):
|
||||
for t, year in enumerate(years):
|
||||
seq[t, c] = max(0.0, float(counts.get(year, 0)))
|
||||
return np.log1p(seq)
|
||||
|
||||
# -- prediction -----------------------------------------------------------
|
||||
def _predict_point(self, sequence: np.ndarray) -> np.ndarray:
|
||||
"""`sequence`: (WINDOW, 3) or (n, WINDOW, 3) raw (log1p'd) array."""
|
||||
X = np.asarray(sequence, dtype=np.float32)
|
||||
if X.ndim == 2:
|
||||
X = X[None, ...]
|
||||
X = (X - self.scaler_mean) / self.scaler_std
|
||||
with torch.no_grad():
|
||||
pred = self._net(torch.tensor(X, dtype=torch.float32)).numpy()
|
||||
return pred
|
||||
|
||||
def residual_cdf(self, x: float) -> float:
|
||||
"""Empirical P(residual <= x) from the held-out test set -- the
|
||||
nonparametric basis for every probability this class reports."""
|
||||
return float(np.mean(self.held_out_residuals <= x))
|
||||
|
||||
def predict(
|
||||
self,
|
||||
pub_counts_by_year: dict[int, int] | None = None,
|
||||
pat_counts_by_year: dict[int, int] | None = None,
|
||||
grant_counts_by_year: dict[int, int] | None = None,
|
||||
first_publication_year: int | None = None,
|
||||
as_of_year: int | None = None,
|
||||
horizons: tuple[int, ...] = DEFAULT_HORIZONS,
|
||||
) -> dict[str, Any]:
|
||||
"""Full prediction for one researcher's history ending at `as_of_year`
|
||||
(defaults to the latest year with any recorded activity).
|
||||
|
||||
Returns:
|
||||
predicted_founding_age: point estimate of "years into career at the
|
||||
hypothetical founding moment defined by `as_of_year`".
|
||||
current_career_age: as_of_year - first_publication_year (if given).
|
||||
years_to_founding: predicted_founding_age - current_career_age; <=0
|
||||
means the current activity profile already looks like a typical
|
||||
founding-moment profile (founding could happen any time now).
|
||||
probability_founds_within: {k: P(founds within k years)} for each
|
||||
horizon in `horizons`, derived from held-out residuals (see README).
|
||||
"""
|
||||
seq = self.build_sequence(pub_counts_by_year, pat_counts_by_year, grant_counts_by_year, as_of_year)
|
||||
founding_age_hat = float(self._predict_point(seq)[0])
|
||||
|
||||
result: dict[str, Any] = {
|
||||
"model": self.model_key,
|
||||
"predicted_founding_age": founding_age_hat,
|
||||
}
|
||||
|
||||
if first_publication_year is not None:
|
||||
if as_of_year is None:
|
||||
all_years = list((pub_counts_by_year or {})) + list((pat_counts_by_year or {})) + list((grant_counts_by_year or {}))
|
||||
as_of_year = max(all_years) if all_years else first_publication_year
|
||||
current_career_age = as_of_year - first_publication_year
|
||||
years_to_founding = founding_age_hat - current_career_age
|
||||
result["current_career_age"] = current_career_age
|
||||
result["years_to_founding"] = years_to_founding
|
||||
result["probability_founds_within"] = {
|
||||
k: round(self.residual_cdf(k - years_to_founding), 4) for k in horizons
|
||||
}
|
||||
return result
|
||||
Binary file not shown.
BIN
Binary file not shown.
Reference in New Issue
Block a user