Datasets:
File size: 19,158 Bytes
029e02e | 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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 | """Post-hoc analyses + paper artifacts for MacroLens (NeurIPS 2026 E&D track).
One pass over the reeval JSON + saved pkls produces every table + figure
referenced by §6 and the appendix.
Outputs (in --output-dir):
Main-text artifacts:
tab_t1_leaderboard.tex -- T1 leaderboard
tab_t2_t5_gap.tex -- T2 vs T5 valuation gap
fig_ablation_4panel.pdf -- 4-panel ablation figure (4 tasks x 2 models x A-E)
fig_cross_task_corr.pdf -- cross-task ranking heatmap
tab_cross_task_corr.tex -- same as table
Evaluation-research tables:
tab_baseline_floor.tex -- saturation: methods failing to beat naive
tab_failure_modes.tex -- per-cell mode (ok/parser_fail/saturation/scale_blowup)
Appendix per-task tables:
tab_per_task_T1.tex .. tab_per_task_T7.tex
Stratifications:
stratify_T1_sector.csv -- §App.C
stratify_T2_quartile.csv
stratify_T5_quartile.csv
stratify_T4_event_type.csv
stratify_T7_state.csv
Raw CSVs (backing every table):
panel_metrics.csv, ablation_metrics.csv, failure_modes.csv
Usage:
python -m whatif_bench.experiments.analyses.post_hoc \\
--predictions-dir whatif_bench/experiments/predictions \\
--reeval whatif_bench/experiments/results/canon_reeval_<TS>.json \\
--output-dir whatif_bench/experiments/analyses_out
"""
from __future__ import annotations
import argparse
import json
import pickle
from pathlib import Path
import numpy as np
import pandas as pd
PANEL = [
"persistence", "historical_analogue", "sector_median", "metro_median",
"lightgbm", "random_forest",
"dlinear", "itransformer", "moderntcn",
"chronos2", "moirai2", "timesfm",
"chattime", "time_mqa",
"gpt_oss_120b", "gpt51", "gemini3_flash", "qwen35",
]
NAIVE = {"persistence", "historical_analogue", "sector_median", "metro_median"}
TASKS = ["T1", "T2", "T3", "T4", "T5", "T6", "T7"]
ABL_TASKS = ["T1", "T2", "T4", "T5"]
ABL_MODELS = ["gpt51", "gemini3_flash"]
PRIMARY = {
"T1": "mse", "T2": "median_ape", "T3": "overall_mape",
"T4": "return_mae_pct", "T5": "median_ape", "T6": "overall_mape",
"T7": "rent_MAPE",
}
LABEL = {
"mse": "MSE", "median_ape": "medAPE\\%", "overall_mape": "MAPE\\%",
"return_mae_pct": "MAE\\%", "rent_MAPE": "MAPE\\%",
}
SETTINGS = ["A", "B", "C", "D", "E"]
# ── data loading ──────────────────────────────────────────────────────────
def load_metrics(reeval_path: Path) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Return (panel_df, abl_df) with primary metric per row."""
recs = json.loads(reeval_path.read_text())
if isinstance(recs, dict):
recs = recs.get("records", recs)
rows = []
for r in recs:
if r.get("status") != "ok":
continue
m, t = r.get("method_id"), r.get("task")
if m not in PANEL or t not in TASKS:
continue
key = PRIMARY[t]
v = (r.get("metrics") or {}).get(key, {}).get("value")
if v is None:
continue
rows.append({
"method": m, "task": t,
"setting": r.get("ablation_setting") or "",
"metric_key": key, "value": float(v),
})
df = pd.DataFrame(rows)
panel = df[df["setting"] == ""].drop(columns=["setting"]).copy()
abl = df[df["setting"] != ""].copy()
return panel, abl
def load_pkls(pred_dir: Path) -> list[dict]:
out = []
for p in sorted(pred_dir.glob("*.pkl")):
try:
with p.open("rb") as f:
d = pickle.load(f)
out.append(d)
except Exception:
continue
return out
# ── analyses (each returns a DataFrame) ───────────────────────────────────
def cross_task_correlation(panel: pd.DataFrame) -> pd.DataFrame:
from scipy.stats import spearmanr
pv = panel.pivot(index="method", columns="task", values="value")
rho = pd.DataFrame(index=TASKS, columns=TASKS, dtype=float)
for ta in TASKS:
for tb in TASKS:
common = pv[[ta, tb]].dropna() if ta in pv.columns and tb in pv.columns else pd.DataFrame()
if len(common) >= 4 and ta != tb:
rho.loc[ta, tb] = spearmanr(common[ta], common[tb])[0]
elif ta == tb:
rho.loc[ta, tb] = 1.0
return rho
def baseline_floor(panel: pd.DataFrame) -> pd.DataFrame:
"""Per-task: naive floor + count of methods beating / failing it."""
rows = []
for t in TASKS:
sub = panel[panel["task"] == t]
floor = sub[sub["method"].isin(NAIVE)]["value"].min()
if pd.isna(floor):
continue
non_naive = sub[~sub["method"].isin(NAIVE)]
beat = (non_naive["value"] < floor * 0.99).sum()
fail = (~(non_naive["value"] < floor * 0.99)).sum()
rows.append({"task": t, "naive_floor": floor,
"n_beat": int(beat), "n_fail": int(fail)})
return pd.DataFrame(rows)
def t2_t5_gap(panel: pd.DataFrame) -> pd.DataFrame:
from scipy.stats import spearmanr
pv = panel.pivot(index="method", columns="task", values="value")
common = pv[["T2", "T5"]].dropna()
common = common.assign(
delta=common["T5"] - common["T2"],
T2_rank=common["T2"].rank().astype(int),
T5_rank=common["T5"].rank().astype(int),
).sort_values("T2").reset_index()
rho = spearmanr(common["T2"], common["T5"])[0] if len(common) >= 3 else float("nan")
common.attrs["spearman_rho"] = rho
common.attrs["mean_delta"] = common["delta"].mean()
return common
def classify_mode(d: dict) -> str:
yp = d.get("y_pred")
if yp is None:
return "no_pkl"
if hasattr(yp, "columns"):
col = next((c for c in ("pred", "value", "predicted_equity_value",
"predicted_return_pct", "pred_rent", "pred_price")
if c in yp.columns), None)
vals = pd.to_numeric(yp[col], errors="coerce").to_numpy() if col else np.array([])
else:
vals = np.asarray(yp, dtype=np.float64).ravel()
if vals.size == 0:
return "no_pkl"
finite = vals[np.isfinite(vals)]
if finite.size / vals.size < 0.5:
return "parser_fail"
if finite.size and np.max(np.abs(finite)) > 1e8:
return "scale_blowup"
if finite.size and np.std(finite) < 1e-3:
return "saturation"
return "ok"
def failure_modes(pkls: list[dict]) -> pd.DataFrame:
rows = []
for d in pkls:
m, t = d.get("method_id"), d.get("task")
s = d.get("ablation_setting") or ""
if m in PANEL and t in TASKS and not s:
rows.append({"method": m, "task": t, "mode": classify_mode(d)})
return pd.DataFrame(rows)
def stratify(pkls: list[dict], task: str, key_col: str, metric: str) -> pd.DataFrame:
"""Per-(method, stratum) primary metric for one task."""
rows = []
for d in pkls:
if d.get("task") != task or d.get("method_id") not in PANEL:
continue
if (d.get("ablation_setting") or ""):
continue
meta, yt, yp = d.get("meta_test"), d.get("y_test"), d.get("y_pred")
if meta is None or key_col not in meta.columns:
continue
m = d["method_id"]
if metric == "mse": # T1 trajectory
yt_a = np.asarray(yt, dtype=np.float64)
yp_a = np.asarray(yp, dtype=np.float64).copy()
if yt_a.ndim == 1: yt_a = yt_a.reshape(-1, 1)
if yp_a.ndim == 1: yp_a = yp_a.reshape(-1, 1)
yp_a[~np.isfinite(yp_a).all(axis=1)] = 0.0
n = min(len(meta), len(yp_a))
per_inst = ((yp_a[:n] - yt_a[:n]) ** 2).mean(axis=1)
df = pd.DataFrame({key_col: meta[key_col].astype(str).values[:n],
"v": per_inst})
agg = df.groupby(key_col)["v"].mean()
elif metric == "median_ape": # T2 / T5
yt_a = np.asarray(yt, dtype=np.float64).ravel()
yp_a = np.where(np.isfinite(np.asarray(yp, dtype=np.float64).ravel()),
np.asarray(yp, dtype=np.float64).ravel(), 0.0)
n = min(len(meta), len(yt_a), len(yp_a))
keep = np.isfinite(yt_a[:n]) & (np.abs(yt_a[:n]) >= 1.0)
ape = np.minimum(np.abs(yp_a[:n][keep] - yt_a[:n][keep]) / np.abs(yt_a[:n][keep]),
10.0) * 100.0
df = pd.DataFrame({key_col: meta[key_col].astype(str).values[:n][keep],
"v": ape})
agg = df.groupby(key_col)["v"].median()
elif metric == "return_mae_pct": # T4
if hasattr(yp, "columns"):
yp_a = pd.to_numeric(yp.iloc[:, -1], errors="coerce").to_numpy()
else:
yp_a = np.asarray(yp, dtype=np.float64).ravel()
yt_a = np.asarray(yt, dtype=np.float64).ravel()
yp_a = np.where(np.isfinite(yp_a), yp_a, 0.0)
n = min(len(meta), len(yt_a), len(yp_a))
df = pd.DataFrame({key_col: meta[key_col].astype(str).values[:n],
"v": np.abs(yt_a[:n] - yp_a[:n])})
agg = df.groupby(key_col)["v"].mean()
else:
continue
for k, v in agg.items():
rows.append({"method": m, key_col: k, "value": float(v)})
return pd.DataFrame(rows)
# ── renderers ─────────────────────────────────────────────────────────────
def fmt(v) -> str:
if pd.isna(v):
return "--"
if isinstance(v, str):
return v
if abs(v) >= 1e6: return f"{v:.2e}"
if abs(v) >= 100: return f"{v:.0f}"
if abs(v) >= 1: return f"{v:.2f}"
return f"{v:.4f}"
def tex_safe(s: str) -> str:
return str(s).replace("_", r"\_")
def latex_table(df: pd.DataFrame, caption: str, label: str,
escape: bool = False) -> str:
"""Wrap pd.to_latex with NeurIPS-friendly defaults."""
body = df.to_latex(
index=False, escape=escape, na_rep="--",
column_format="l" + "c" * (len(df.columns) - 1),
)
# Strip outer environment, wrap in table+caption.
return (
"\\begin{table}[h]\n\\centering\n"
f"\\caption{{{caption}}}\n\\label{{{label}}}\n\\small\n"
+ body.replace("\\begin{tabular}", "\\begin{tabular}").rstrip()
+ "\n\\end{table}\n"
)
def render_t1_leaderboard(panel: pd.DataFrame, out: Path) -> None:
family_map = {
"persistence": "Naive", "historical_analogue": "Naive",
"sector_median": "Naive", "metro_median": "Naive",
"lightgbm": "Classical", "random_forest": "Classical",
"dlinear": "Sequence", "itransformer": "Sequence", "moderntcn": "Sequence",
"chronos2": "TSFM", "moirai2": "TSFM", "timesfm": "TSFM",
"chattime": "TS-LLM", "time_mqa": "TS-LLM",
"gpt_oss_120b": "LLM-ZS", "gpt51": "LLM-ZS",
"gemini3_flash": "LLM-ZS", "qwen35": "LLM-ZS",
}
t1 = panel[panel["task"] == "T1"].copy()
t1["family"] = t1["method"].map(family_map)
t1["method"] = t1["method"].map(tex_safe)
t1["mse"] = t1["value"].map(fmt)
t1 = t1[["family", "method", "mse"]]
t1.columns = ["Family", "Method", "MSE"]
out.write_text(latex_table(
t1, caption="T1 contextual time-series forecasting (close-trajectory MSE, "
"single seed with cluster-bootstrap 95\\% CIs in App.~A).",
label="tab:t1",
))
def render_t2_t5_gap(gap: pd.DataFrame, out: Path) -> None:
df = gap[["method", "T2", "T5", "delta", "T2_rank", "T5_rank"]].copy()
df["method"] = df["method"].map(tex_safe)
for c in ("T2", "T5", "delta"):
df[c] = df[c].map(fmt)
df.columns = ["Method", "T2 medAPE", "T5 medAPE", "$\\Delta$(T5--T2)",
"rank T2", "rank T5"]
rho = gap.attrs.get("spearman_rho")
md = gap.attrs.get("mean_delta")
out.write_text(latex_table(
df,
caption=(
"T2 vs T5 valuation gap. $\\Delta$ is medAPE delta when "
"market-price features are removed (T5). "
f"Spearman $\\rho$(T2 ranking, T5 ranking) $= {rho:.3f}$; "
f"mean $\\Delta = {md:+.2f}$ medAPE pts."
),
label="tab:t2-t5-gap",
))
def render_correlation(rho: pd.DataFrame, out_tex: Path, out_pdf: Path) -> None:
df = rho.round(2).copy()
df.insert(0, "", df.index)
out_tex.write_text(latex_table(
df, caption="Cross-task ranking correlation (Spearman $\\rho$). "
"Negative cells (boxed) are the multi-task non-redundancy "
"evidence: methods that win T1 lose T3 and T6.",
label="tab:cross-task-corr",
))
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(5.5, 4.5))
arr = rho.to_numpy(dtype=float)
im = ax.imshow(arr, cmap="RdBu_r", vmin=-1.0, vmax=1.0, aspect="equal")
ax.set_xticks(range(len(TASKS))); ax.set_xticklabels(TASKS)
ax.set_yticks(range(len(TASKS))); ax.set_yticklabels(TASKS)
for i in range(len(TASKS)):
for j in range(len(TASKS)):
v = arr[i, j]
if not np.isnan(v):
ax.text(j, i, f"{v:.2f}", ha="center", va="center",
color="white" if abs(v) > 0.5 else "black", fontsize=9)
fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
fig.tight_layout()
fig.savefig(out_pdf, bbox_inches="tight")
plt.close(fig)
def render_baseline_floor(bf: pd.DataFrame, out: Path) -> None:
df = bf.copy()
df["naive_floor"] = df["naive_floor"].map(fmt)
df.columns = ["Task", "Naive floor", "\\# beating", "\\# failing"]
out.write_text(latex_table(
df, caption="Saturation analysis: per-task best-naive baseline value "
"and counts of non-naive methods beating / failing it.",
label="tab:baseline-floor",
))
def render_failure_modes(fm: pd.DataFrame, out: Path) -> None:
pv = fm.pivot(index="method", columns="task", values="mode")
pv = pv.reindex(index=PANEL, columns=TASKS)
pv = pv.reset_index()
pv["method"] = pv["method"].map(tex_safe)
pv.columns = ["Method"] + TASKS
out.write_text(latex_table(
pv,
caption="Per-cell failure-mode taxonomy. ok = reasonable predictions; "
"parser\\_fail = $>$50\\% NaN after parser; "
"saturation = constant predictions near zero; "
"scale\\_blowup = parser-induced extreme values.",
label="tab:failure-modes",
))
def render_per_task_table(panel: pd.DataFrame, task: str, out: Path) -> None:
df = panel[panel["task"] == task].sort_values("value")[["method", "value"]].copy()
df["method"] = df["method"].map(tex_safe)
df["value"] = df["value"].map(fmt)
metric_label = LABEL.get(PRIMARY[task], PRIMARY[task])
df.columns = ["Method", metric_label]
out.write_text(latex_table(
df, caption=f"{task} per-method primary metric ({metric_label}).",
label=f"tab:per-task-{task}",
))
def render_ablation_4panel(abl: pd.DataFrame, out: Path) -> None:
"""4 panels (T1, T2, T4, T5); two lines per panel (gpt51, gemini3_flash)."""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 4, figsize=(13, 3.0))
colors = {"gpt51": "#1f77b4", "gemini3_flash": "#d62728"}
nice = {"gpt51": "GPT-5.1", "gemini3_flash": "Gemini-3-Flash"}
for ax, t in zip(axes, ABL_TASKS):
for m in ABL_MODELS:
sub = abl[(abl["method"] == m) & (abl["task"] == t)]
sub = sub.set_index("setting").reindex(SETTINGS)["value"]
ax.plot(SETTINGS, sub.values, marker="o", color=colors[m],
label=nice[m], linewidth=1.6, markersize=5)
ax.set_title(f"{t} ({LABEL[PRIMARY[t]].replace(chr(92)+'%', '%')})", fontsize=10)
ax.set_xlabel("Context setting (A→E)", fontsize=9)
ax.tick_params(axis="both", labelsize=8)
ax.grid(True, alpha=0.3, linewidth=0.4)
if t == "T1":
ax.set_yscale("log")
ax.set_ylabel("MSE (log)", fontsize=9)
else:
ax.set_ylabel(LABEL[PRIMARY[t]].replace("\\%", "%"), fontsize=9)
axes[0].legend(loc="best", fontsize=8, frameon=True)
fig.tight_layout()
fig.savefig(out, bbox_inches="tight")
plt.close(fig)
# ── main ─────────────────────────────────────────────────────────────────
def main() -> int:
p = argparse.ArgumentParser()
p.add_argument("--predictions-dir", required=True, type=Path)
p.add_argument("--reeval", required=True, type=Path)
p.add_argument("--output-dir", required=True, type=Path)
args = p.parse_args()
args.output_dir.mkdir(parents=True, exist_ok=True)
O = args.output_dir
panel, abl = load_metrics(args.reeval)
pkls = load_pkls(args.predictions_dir)
panel.to_csv(O / "panel_metrics.csv", index=False)
abl.to_csv(O / "ablation_metrics.csv", index=False)
# Main-text artifacts
render_t1_leaderboard(panel, O / "tab_t1_leaderboard.tex")
gap = t2_t5_gap(panel); gap.to_csv(O / "t2_t5_gap.csv", index=False)
render_t2_t5_gap(gap, O / "tab_t2_t5_gap.tex")
rho = cross_task_correlation(panel); rho.to_csv(O / "cross_task_correlation.csv")
render_correlation(rho, O / "tab_cross_task_corr.tex", O / "fig_cross_task_corr.pdf")
render_ablation_4panel(abl, O / "fig_ablation_4panel.pdf")
# Evaluation-research tables
bf = baseline_floor(panel); bf.to_csv(O / "baseline_floor.csv", index=False)
render_baseline_floor(bf, O / "tab_baseline_floor.tex")
fm = failure_modes(pkls); fm.to_csv(O / "failure_modes.csv", index=False)
render_failure_modes(fm, O / "tab_failure_modes.tex")
# Per-task headline tables (appendix)
for t in TASKS:
render_per_task_table(panel, t, O / f"tab_per_task_{t}.tex")
# Stratifications (T7 omitted: two-output rent/price doesn't fit the
# single-metric stratify shape; appendix table is rendered direct from pkl).
# T2/T5 stratify by market-cap quartile (mcap_q) per the draft
# protocol; T1 by GICS sector; T4 by scenario event_type.
for task, key, metric, name in [
("T1", "sector", "mse", "T1_sector"),
("T2", "mcap_q", "median_ape", "T2_mcap_q"),
("T5", "mcap_q", "median_ape", "T5_mcap_q"),
("T4", "event_type", "return_mae_pct", "T4_event_type"),
]:
s = stratify(pkls, task, key, metric)
if not s.empty:
s.to_csv(O / f"stratify_{name}.csv", index=False)
print(f"\nOK — wrote {len(list(O.iterdir()))} artifacts to {O}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
|