Download analyze_table2.py from Ki-Asif/obsnode-table2-reproduction: direct link, hf CLI and curl.
- Browser
- Download file 11.8 kB
-
https://huggingface.co/datasets/Ki-Asif/obsnode-table2-reproduction/resolve/main/analyze_table2.py
- Command line
-
hf download hf://datasets/Ki-Asif/obsnode-table2-reproduction/analyze_table2.py
-
curl -L -o analyze_table2.py https://huggingface.co/datasets/Ki-Asif/obsnode-table2-reproduction/resolve/main/analyze_table2.py
11.8 kB
| """Table 2 / Section 5.1 reproduction analysis for arXiv 2604.26070 (ObsNODE). | |
| Reads the author-pipeline metric pickles produced by the patched | |
| Pred_{ObsNODE,NODE}_CF_cancer_*.py scripts, aggregates over seeds 1-5, | |
| computes the paper's Table 2 quantities on the first-6-prediction-point | |
| window (paper: "averaged over six prediction time points") and the full | |
| 19-point horizon, and independently recomputes CB/ATE from the raw | |
| prediction and CF pickles with independently computed train mean/std. | |
| Variable order in x tensors: 0 = tumor volume, 1 = body weight (toxicity). | |
| Shapes: per-series tensors are (time_points, 2); per-variable (2,). | |
| Raw x_pred pickles: (time_points, patients, 2), unstandardized. | |
| """ | |
| import os | |
| import pickle | |
| import numpy as np | |
| import torch | |
| OBS = "/work/eval_out/obsNODE" | |
| NOD = "/work/eval_out/NODE" | |
| CFDIR = "/work/ObsNODE/Code/Counterfactual/CF_data_cancer/dataset_cancer_cf" | |
| TRAINPKL = "/work/data/data_train_cancer_DoseAI.pkl" | |
| OUT = "/work/eval_out/analysis" | |
| os.makedirs(OUT, exist_ok=True) | |
| # Paper Table 2 reference numbers. | |
| PAPER = { | |
| "obsNODE": { | |
| "cb_tumor": [0.1738, 0.1739, 0.1724, 0.1708, 0.1708], | |
| "cb_weight": [0.0952, 0.0941, 0.0924, 0.0924, 0.0926], | |
| "ate_tumor": [0.1633, 0.1770, 0.1831, 0.1771, 0.1771], | |
| "ate_weight": [0.0937, 0.0968, 0.0992, 0.0995, 0.0995], | |
| }, | |
| "NODE": { | |
| "cb_tumor": [-0.5152, -0.5288, -0.5364, -0.5321, -0.5321], | |
| "cb_weight": [-2.0229, -2.0272, -2.0313, -2.0315, -2.0315], | |
| "ate_tumor": [-0.5257] * 5, | |
| "ate_weight": [-2.0245] * 5, | |
| }, | |
| "true_ate_tumor": [-0.0105, 0.0031, 0.0107, 0.0063, 0.0063], | |
| "true_ate_weight": [-0.0016, 0.0227, 0.0068, 0.0070, 0.0070], | |
| } | |
| PAPER_MAE = {"obsNODE": {"tumor": 0.1723, "weight": 0.0933}, | |
| "NODE": {"tumor": 0.5289, "weight": 2.0289}} | |
| def load_metric_pickles(model_dir, tag): | |
| """Per-seed per-CF metric tensors from the author pipeline.""" | |
| per_seed = {} # (cf, seed) -> dict of tensors | |
| for cf in range(1, 7): | |
| for seed in range(1, 6): | |
| p = os.path.join( | |
| model_dir, | |
| f"data_pred_cb_ate_cancer_CF_{cf}_seed_{seed}_{tag}.pkl") | |
| (cb_ps, cb_pv, ate_ps, ate_pv, | |
| ate_ps_def, ate_pv_def) = pickle.load(open(p, "rb")) | |
| per_seed[(cf, seed)] = { | |
| "cb_ps": cb_ps, "cb_pv": cb_pv, | |
| "ate_ps": ate_ps, "ate_pv": ate_pv, | |
| "ate_ps_def": ate_ps_def, "ate_pv_def": ate_pv_def, | |
| } | |
| return per_seed | |
| def stack_mean(ds, key): | |
| return torch.stack([d[key] for d in ds]).mean(dim=0) | |
| def stack_std(ds, key): | |
| return torch.stack([d[key] for d in ds]).std(dim=0) | |
| def table2_rows(per_seed): | |
| """CB / predATE / trueATE / |predATE-trueATE| per variable per CF, | |
| averaged over seeds, on the 6-point window and full horizon.""" | |
| rows = {} | |
| for cf in range(1, 6): | |
| ds = [per_seed[(cf, s)] for s in range(1, 6)] | |
| # Six-point window (paper Table 2): first 6 prediction points after tc. | |
| cb_ps6 = torch.stack([d["cb_ps"][:6] for d in ds]).mean(0) # (6, 2) | |
| ate_ps6 = torch.stack([d["ate_ps"][:6] for d in ds]).mean(0) | |
| ate_ps_def6 = torch.stack([d["ate_ps_def"][:6] for d in ds]).mean(0) | |
| # Full 19-point horizon for reference. | |
| cb_full = torch.stack([d["cb_pv"] for d in ds]).mean(0) # (2,) | |
| ate_full = torch.stack([d["ate_pv"] for d in ds]).mean(0) | |
| ate_def_full = torch.stack([d["ate_pv_def"] for d in ds]).mean(0) | |
| rows[cf] = { | |
| "cb6": cb_ps6.mean(0), "ate6": ate_ps6.mean(0), | |
| "true_ate6": ate_ps_def6.mean(0), | |
| "abs_ate_err6": (ate_ps6.mean(0) - ate_ps_def6.mean(0)).abs(), | |
| "cb_full": cb_full, "ate_full": ate_full, | |
| "true_ate_full": ate_def_full, | |
| "abs_ate_err_full": (ate_full - ate_def_full).abs(), | |
| "seed_std_cb6": torch.stack( | |
| [d["cb_ps"][:6].mean(0) for d in ds]).std(0), | |
| } | |
| return rows | |
| def independent_check(model_dir, tag, cf): | |
| """Recompute CB over the 6-point window directly from the raw | |
| unstandardized prediction pickle and the raw CF pickles, using train | |
| mean/std recomputed here from the raw training data.""" | |
| data_train = pickle.load(open(TRAINPKL, "rb")) | |
| t_train, x_train, _ = data_train | |
| mean = x_train.mean(dim=(0, 1), keepdim=True) | |
| std = x_train.std(dim=(0, 1), keepdim=True) | |
| x_pred = pickle.load(open(os.path.join( | |
| model_dir, f"data_pred_cancer_CF_{cf}_seed_1_{tag}.pkl"), "rb")) | |
| data_cf = pickle.load(open(os.path.join( | |
| CFDIR, f"data_test_cancer_gamma_4_CF_{cf}.pkl"), "rb")) | |
| data_cf6 = pickle.load(open(os.path.join( | |
| CFDIR, f"data_test_cancer_gamma_4_CF_6.pkl"), "rb")) | |
| t_cf, x_cf, _ = data_cf | |
| t_cf6, x_cf6, _ = data_cf6 | |
| num_time = 24 | |
| x_cf, x_cf6 = x_cf[:num_time], x_cf6[:num_time] | |
| idx = 5 | |
| x_true_cf = x_cf[idx:] | |
| x_true_cf6 = x_cf6[idx:] | |
| assert x_pred.shape == x_true_cf.shape, (x_pred.shape, x_true_cf.shape) | |
| cb = ((x_pred - mean) / std - (x_true_cf - mean) / std) | |
| ate = ((x_pred - mean) / std - (x_true_cf6 - mean) / std) | |
| true_ate = ((x_true_cf - mean) / std - (x_true_cf6 - mean) / std) | |
| return { | |
| "cb6": cb[:6].mean(dim=(0, 1)), | |
| "cb_full": cb.mean(dim=(0, 1)), | |
| "ate6": ate[:6].mean(dim=(0, 1)), | |
| "true_ate6": true_ate[:6].mean(dim=(0, 1)), | |
| } | |
| def treatment_path_check(model_dir, tag): | |
| """Does the prediction actually depend on the future treatment path? | |
| Compare x_pred across regimes and against CF6's own prediction.""" | |
| preds = {} | |
| for cf in range(1, 7): | |
| vals = [] | |
| for seed in range(1, 6): | |
| p = pickle.load(open(os.path.join( | |
| model_dir, | |
| f"data_pred_cancer_CF_{cf}_seed_{seed}_{tag}.pkl"), "rb")) | |
| vals.append(p[:6].mean(dim=1)) # (6, 2) mean over patients | |
| preds[cf] = torch.stack(vals).mean(0) | |
| sens = {} | |
| for cf in range(1, 6): | |
| d = (preds[cf] - preds[6]).abs().mean().item() | |
| sens[cf] = d | |
| spread = max( | |
| (preds[a] - preds[b]).abs().mean().item() | |
| for a in range(1, 6) for b in range(1, 6) if a < b) | |
| return sens, spread | |
| def fmt(vals, n=4): | |
| return "/".join(f"{v:.{n}f}" for v in vals.tolist()) | |
| def main(): | |
| report = [] | |
| rep = report.append | |
| summary = {} | |
| for model_dir, tag, label in [(OBS, "obsNODE", "ObsNODE"), | |
| (NOD, "NODE", "NODE")]: | |
| per_seed = load_metric_pickles(model_dir, tag) | |
| rows = table2_rows(per_seed) | |
| summary[label] = rows | |
| rep(f"## {label}") | |
| rep(f"{'CF':>3} | {'CB6 tumor':>10} {'CB6 weight':>10} | " | |
| f"{'predATE6 t':>10} {'predATE6 w':>10} | " | |
| f"{'trueATE6 t':>10} {'trueATE6 w':>10} | " | |
| f"{'|ATEerr|6 t':>11} {'|ATEerr|6 w':>11} | " | |
| f"{'seedstd CB t':>12}") | |
| mae = {"tumor": [], "weight": []} | |
| for cf in range(1, 6): | |
| r = rows[cf] | |
| rep(f"{cf:>3} | {fmt(r['cb6'])[:10+5]} | " | |
| f"{r['ate6'][0]:.4f} {r['ate6'][1]:.4f} | " | |
| f"{r['true_ate6'][0]:.4f} {r['true_ate6'][1]:.4f} | " | |
| f"{r['abs_ate_err6'][0]:.4f} {r['abs_ate_err6'][1]:.4f} | " | |
| f"{r['seed_std_cb6'][0]:.4f}") | |
| mae["tumor"].append(r["abs_ate_err6"][0].item()) | |
| mae["weight"].append(r["abs_ate_err6"][1].item()) | |
| rep(f"mean |ATE err| tumor = {np.mean(mae['tumor']):.4f} " | |
| f"(paper {PAPER_MAE[tag]['tumor']}), " | |
| f"weight = {np.mean(mae['weight']):.4f} " | |
| f"(paper {PAPER_MAE[tag]['weight']})") | |
| rep("full-horizon CB tumor: " + | |
| fmt(torch.stack([rows[c]["cb_full"][0] for c in range(1, 6)]))) | |
| rep("full-horizon CB weight: " + | |
| fmt(torch.stack([rows[c]["cb_full"][1] for c in range(1, 6)]))) | |
| rep("full-horizon predATE tumor: " + | |
| fmt(torch.stack([rows[c]["ate_full"][0] for c in range(1, 6)]))) | |
| rep("full-horizon trueATE tumor: " + | |
| fmt(torch.stack([rows[c]["true_ate_full"][0] for c in range(1, 6)]))) | |
| rep("full-horizon predATE weight: " + | |
| fmt(torch.stack([rows[c]["ate_full"][1] for c in range(1, 6)]))) | |
| rep("full-horizon trueATE weight: " + | |
| fmt(torch.stack([rows[c]["true_ate_full"][1] for c in range(1, 6)]))) | |
| rep("") | |
| # Paper reference table alongside. | |
| rep("## Paper Table 2 reference") | |
| rep(f"ObsNODE CB tumor : {PAPER['obsNODE']['cb_tumor']}") | |
| rep(f"ours CB tumor : " + fmt(torch.stack( | |
| [summary['ObsNODE'][c]['cb6'][0] for c in range(1, 6)]))) | |
| rep(f"ObsNODE CB weight : {PAPER['obsNODE']['cb_weight']}") | |
| rep(f"ours CB weight : " + fmt(torch.stack( | |
| [summary['ObsNODE'][c]['cb6'][1] for c in range(1, 6)]))) | |
| rep(f"NODE CB tumor : {PAPER['NODE']['cb_tumor']}") | |
| rep(f"ours CB tumor : " + fmt(torch.stack( | |
| [summary['NODE'][c]['cb6'][0] for c in range(1, 6)]))) | |
| rep(f"NODE CB weight : {PAPER['NODE']['cb_weight']}") | |
| rep(f"ours CB weight : " + fmt(torch.stack( | |
| [summary['NODE'][c]['cb6'][1] for c in range(1, 6)]))) | |
| rep(f"true ATE tumor : {PAPER['true_ate_tumor']}") | |
| rep(f"ours true tumor : " + fmt(torch.stack( | |
| [summary['ObsNODE'][c]['true_ate6'][0] for c in range(1, 6)]))) | |
| rep(f"true ATE weight : {PAPER['true_ate_weight']}") | |
| rep(f"ours true weight: " + fmt(torch.stack( | |
| [summary['ObsNODE'][c]['true_ate6'][1] for c in range(1, 6)]))) | |
| rep(f"ObsNODE ATE tumor : {PAPER['obsNODE']['ate_tumor']}") | |
| rep(f"ours ATE tumor : " + fmt(torch.stack( | |
| [summary['ObsNODE'][c]['ate6'][0] for c in range(1, 6)]))) | |
| rep(f"ObsNODE ATE weight : {PAPER['obsNODE']['ate_weight']}") | |
| rep(f"ours ATE weight : " + fmt(torch.stack( | |
| [summary['ObsNODE'][c]['ate6'][1] for c in range(1, 6)]))) | |
| rep(f"NODE ATE tumor : {PAPER['NODE']['ate_tumor']}") | |
| rep(f"ours ATE tumor : " + fmt(torch.stack( | |
| [summary['NODE'][c]['ate6'][0] for c in range(1, 6)]))) | |
| rep(f"NODE ATE weight : {PAPER['NODE']['ate_weight']}") | |
| rep(f"ours ATE weight : " + fmt(torch.stack( | |
| [summary['NODE'][c]['ate6'][1] for c in range(1, 6)]))) | |
| rep("") | |
| # Independent recomputation (seed 1) vs author pipeline. | |
| rep("## Independent recomputation from raw pickles (seed 1)") | |
| for model_dir, tag, label in [(OBS, "obsNODE", "ObsNODE"), | |
| (NOD, "NODE", "NODE")]: | |
| per_seed = load_metric_pickles(model_dir, tag) | |
| for cf in [1, 5]: | |
| ind = independent_check(model_dir, tag, cf) | |
| pipe = per_seed[(cf, 1)] | |
| dcb = (ind["cb6"] - pipe["cb_ps"][:6].mean(0)).abs().max().item() | |
| date = (ind["ate6"] - pipe["ate_ps"][:6].mean(0)).abs().max().item() | |
| rep(f"{label} CF{cf}: max|independent-pipeline| " | |
| f"CB={dcb:.2e} predATE={date:.2e} " | |
| f"(indep CB6 t/w = {ind['cb6'][0]:.4f}/{ind['cb6'][1]:.4f})") | |
| rep("") | |
| # Treatment-path sensitivity. | |
| rep("## Treatment-path sensitivity (mean |x_pred_CFk - x_pred_CF6|, 6 pts)") | |
| for model_dir, tag, label in [(OBS, "obsNODE", "ObsNODE"), | |
| (NOD, "NODE", "NODE")]: | |
| sens, spread = treatment_path_check(model_dir, tag) | |
| rep(f"{label}: CF1..CF5 vs CF6 = " + | |
| "/".join(f"{sens[c]:.4f}" for c in range(1, 6)) + | |
| f" | max pairwise spread = {spread:.4f}") | |
| text = "\n".join(report) | |
| print(text) | |
| with open(os.path.join(OUT, "table2_report.txt"), "w") as f: | |
| f.write(text) | |
| if __name__ == "__main__": | |
| main() | |