Download scripts/best_tables.py from eduzrh/training-model-material: direct link, hf CLI and curl.
- Browser
- Download file 3.92 kB
-
https://huggingface.co/datasets/eduzrh/training-model-material/resolve/main/scripts/best_tables.py
- Command line
-
hf download hf://datasets/eduzrh/training-model-material/scripts/best_tables.py
-
curl -L -o best_tables.py https://huggingface.co/datasets/eduzrh/training-model-material/resolve/main/scripts/best_tables.py
3.92 kB
| """Summarise the performance-first (``best_*``) runs. | |
| Produces ``results/tables/tab_best.csv`` with, per architecture: | |
| * per-fold stress R2 averaged over seeds (mean +- sd over folds/seeds) | |
| * pooled out-of-fold stress / shape / primary R2 for seed 0 and for the | |
| seed-averaged predictions (all seeds share one fold split by construction) | |
| and prints the markdown table used in the report. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| ROOT = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(ROOT / "code")) | |
| from pimamba.data import TARGETS, TARGET_KEYS # noqa: E402 | |
| from pimamba.metrics import PRIMARY, _r2, regression_metrics # noqa: E402 | |
| RUNS = ROOT / "results" / "runs" | |
| TABLES = ROOT / "results" / "tables" | |
| def runs_of(prefix: str): | |
| out = {} | |
| for d in RUNS.glob(f"{prefix}_*_f*_s*"): | |
| try: | |
| m, f, s = d.name[len(prefix) + 1:].rsplit("_", 2) | |
| f = int(f[1:]); s = int(s[1:]) | |
| except ValueError: | |
| continue | |
| if (d / "metrics.json").exists(): | |
| out.setdefault(m, {}).setdefault(s, {})[f] = d | |
| return out | |
| def pooled(tags: dict, seeds: list[int]): | |
| """Pool the predictions of one model over the given seeds.""" | |
| P, Y, M = [], [], [] | |
| for f in sorted(tags[seeds[0]]): | |
| arrs = [np.load(tags[s][f] / "predictions.npz", allow_pickle=True) | |
| for s in seeds if f in tags.get(s, {})] | |
| if not arrs: | |
| continue | |
| P.append(np.mean([a["pred"] for a in arrs], 0)) | |
| Y.append(arrs[0]["true"]); M.append(arrs[0]["mask"]) | |
| if not P: | |
| return None | |
| return (np.concatenate(P), np.concatenate(Y), np.concatenate(M)) | |
| def score(P, Y, M): | |
| pt = regression_metrics(Y.reshape(-1, len(TARGETS)), P.reshape(-1, len(TARGETS)), | |
| M.reshape(-1, len(TARGETS))) | |
| j = TARGET_KEYS.index("sigma") | |
| mm = M[:, :, j] > 0 | |
| sig = _r2(Y[:, :, j][mm], P[:, :, j][mm]) | |
| ys, ps = [], [] | |
| for i in range(P.shape[0]): | |
| k = M[i, :, j] > 0 | |
| if k.sum() < 4: | |
| continue | |
| ys.append(Y[i, k, j] - Y[i, k, j].mean()) | |
| ps.append(P[i, k, j] - P[i, k, j].mean()) | |
| shape = _r2(np.concatenate(ys), np.concatenate(ps)) | |
| prim = [pt[k]["r2"] for k in PRIMARY if np.isfinite(pt[k]["r2"])] | |
| return dict(sigma=sig, shape=shape, primary=float(np.mean(prim))) | |
| def main(prefix="best"): | |
| found = runs_of(prefix) | |
| rows = [] | |
| for m, per_seed in sorted(found.items()): | |
| seeds = sorted(per_seed) | |
| folds = sorted(per_seed[seeds[0]]) | |
| nparams = json.loads((per_seed[seeds[0]][folds[0]] / "metrics.json").read_text())["n_params"] | |
| fold_r2 = [] | |
| for s in seeds: | |
| for f, d in per_seed[s].items(): | |
| r = json.loads((d / "metrics.json").read_text()) | |
| fold_r2.append(r["per_target"]["sigma"]["r2"]) | |
| row = {"model": m, "seeds": len(seeds), "folds": len(folds), | |
| "params": nparams, | |
| "fold_r2_mean": float(np.mean(fold_r2)), | |
| "fold_r2_sd": float(np.std(fold_r2)), | |
| "n_runs": sum(len(v) for v in per_seed.values())} | |
| full = all(len(per_seed[s]) == 5 for s in seeds) | |
| if full: | |
| for tag, ss in (("seed0", [seeds[0]]), ("seedavg", seeds)): | |
| g = pooled(per_seed, ss) | |
| sc = score(*g) | |
| row[f"{tag}_sigma"] = round(sc["sigma"], 3) | |
| row[f"{tag}_shape"] = round(sc["shape"], 3) | |
| row[f"{tag}_primary"] = round(sc["primary"], 3) | |
| rows.append(row) | |
| df = pd.DataFrame(rows) | |
| TABLES.mkdir(parents=True, exist_ok=True) | |
| df.to_csv(TABLES / f"tab_{prefix}.csv", index=False) | |
| print(df.to_string(index=False)) | |
| return df | |
| if __name__ == "__main__": | |
| main(sys.argv[1] if len(sys.argv) > 1 else "best") |