release-slip-baseline / eval_transfer.py
myeongjinji's picture
Transfer to unseen organisations: leave-one-collection-out results
52fc6bc verified
Raw History Blame Contribute Delete
5.77 kB
"""Does the issue slip model carry over to an organisation it has never seen?
python eval_transfer.py hf/jira-release-slip --out hf/release-slip-baseline
For each collection C in the test split (later releases) and offset k, the same test rows of C
are scored three ways:
| scorer | trained on | C's track record at T |
|---|---|---|
| `in_domain` | every collection's training releases, C included (the published v2 model) | as recorded |
| `transfer` | the training releases of every collection **except C** | as recorded |
| `transfer_no_history` | the same | removed (`project_prior_*` = no earlier release), as for a tracker with no history yet |
Same features, hyper-parameters and calibration as v2 (`train_model_v2.py`). Paired bootstrap
over C's test releases gives 95% intervals of transfer − in-domain. Pooling every collection's
transfer predictions gives the overall cost of meeting a new organisation. Collections under
1,000 test rows or 20 test releases are flagged small. Writes `metrics_transfer.json`; the
transfer models are not kept (`python eval_transfer.py` rebuilds them). A collection with no
training rows of its own (`train_rows_of_it` = 0) was never seen by the published model either:
its in-domain and transfer scores are the same, and it is a natural "new organisation" case.
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.calibration import CalibratedClassifierCV
from sklearn.ensemble import HistGradientBoostingClassifier
from common import load_skops
from train_model import scores
from train_model_v2 import FEATURES, SMALL, paired_delta
KS = (14, 28)
def fit(train: pd.DataFrame, params: dict):
model = CalibratedClassifierCV(
HistGradientBoostingClassifier(max_iter=400, early_stopping=False, random_state=0,
**params), method="isotonic", cv=3)
return model.fit(train[list(FEATURES)], train.slipped)
def without_history(df: pd.DataFrame) -> pd.DataFrame:
return df.assign(project_prior_releases=0.0, project_prior_slip_rate=-1.0)
def evaluate(data: Path, models: Path, k: int, only: list[str] | None = None) -> dict:
train = pd.read_parquet(data / f"k{k}" / "train.parquet")
test = pd.read_parquet(data / f"k{k}" / "test.parquet")
params = json.loads((models / "metrics_v2.json").read_text())["params"][f"k{k}"]
in_domain = load_skops(models / f"model_v2_k{k}.skops").predict_proba(
test[list(FEATURES)])[:, 1]
collections = only or sorted(test.collection.unique(),
key=lambda c: -int((test.collection == c).sum()))
out: dict = {"per_collection": {}}
pooled = {"transfer": np.full(len(test), np.nan), "transfer_no_history": np.full(len(test), np.nan)}
for c in collections:
rows = (test.collection == c).to_numpy()
part = test[rows]
model = fit(train[train.collection != c], params)
p = {"in_domain": in_domain[rows],
"transfer": model.predict_proba(part[list(FEATURES)])[:, 1],
"transfer_no_history": model.predict_proba(without_history(part)[list(FEATURES)])[:, 1]}
pooled["transfer"][rows] = p["transfer"]
pooled["transfer_no_history"][rows] = p["transfer_no_history"]
releases = int(part.release_id.nunique())
entry = {"rows": len(part), "releases": releases,
"slipped": round(float(part.slipped.mean()), 3),
"train_rows_without_it": int((train.collection != c).sum()),
# 0 means the published model never saw this collection either
"train_rows_of_it": int((train.collection == c).sum()),
"small": len(part) < SMALL["rows"] or releases < SMALL["releases"]}
if part.slipped.nunique() == 2:
entry |= {name: scores(part, v) for name, v in p.items()}
entry["transfer_minus_in_domain"] = paired_delta(part, p["transfer"], p["in_domain"])
entry["no_history_minus_in_domain"] = paired_delta(part, p["transfer_no_history"],
p["in_domain"])
out["per_collection"][c] = entry
print(f"k={k} {c:12} rows {len(part):6} "
+ (f"PR-AUC in {entry['in_domain']['pr_auc']} transfer {entry['transfer']['pr_auc']} "
f"no-history {entry['transfer_no_history']['pr_auc']}" if "in_domain" in entry
else "one class only"), flush=True)
if only is None: # every test row scored by a model that never saw its collection
out["pooled"] = {"in_domain": scores(test, in_domain),
"transfer": scores(test, pooled["transfer"]),
"transfer_no_history": scores(test, pooled["transfer_no_history"]),
"transfer_minus_in_domain": paired_delta(test, pooled["transfer"], in_domain),
"no_history_minus_in_domain": paired_delta(
test, pooled["transfer_no_history"], in_domain)}
return out
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("data", help="the jira-release-slip folder")
ap.add_argument("--out", default="hf/release-slip-baseline")
ns = ap.parse_args()
out = Path(ns.out)
results = {f"k{k}": evaluate(Path(ns.data), out, k) for k in KS}
(out / "metrics_transfer.json").write_text(json.dumps(
{"features": list(FEATURES), "protocol": "leave one collection out; train on the train "
"split of the other collections, score the held-out collection's test split",
"small": SMALL, "results": results}, indent=1))
if __name__ == "__main__":
main()