File size: 3,921 Bytes
ec1317f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
"""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")