AtmosIQ commited on
Commit
5d0862f
·
verified ·
1 Parent(s): cfdbd23

Upload scripts/evaluate.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/evaluate.py +72 -0
scripts/evaluate.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ evaluate.py — M2 Go/No-Go. Loads atmosiq_best.pt, predicts on the TEST fold (spatial
3
+ held-out nodes, full-graph), reports per-pollutant spatial-held-out R²/RMSE/MAE at
4
+ horizon 0, and compares to the M1 XGBoost floor (refs.json). Blueprint §10 primary metric.
5
+ Run: python data\models\evaluate.py --tensors data\tensors --ckpt data\atmosiq_best.pt
6
+ """
7
+ from __future__ import annotations
8
+ import os, sys, json, argparse, pathlib
9
+ import numpy as np, torch
10
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
11
+ from model import AtmosIQNet
12
+ from dataset_v2 import AtmosData
13
+
14
+ POLL=["pm2_5","pm10","no2","so2","co","o3","nh3"]
15
+
16
+ def main():
17
+ ap=argparse.ArgumentParser()
18
+ ap.add_argument("--tensors",default="data/tensors"); ap.add_argument("--ckpt",default="data/atmosiq_best.pt")
19
+ ap.add_argument("--window",type=int,default=7); ap.add_argument("--refs",default="data/models/refs.json")
20
+ ap.add_argument("--test_days",type=int,default=0,help="0=all test days")
21
+ a=ap.parse_args()
22
+ dev="cuda" if torch.cuda.is_available() else "cpu"; print("device:",dev)
23
+ meta=json.load(open(pathlib.Path(a.tensors)/"meta.json"))
24
+ data=AtmosData(a.tensors, window=a.window, device=dev)
25
+ cfg={"calendar_num_dim":meta["dimsD_num"],"n_recon_channels":9+meta["dimsB"]+meta["dimsC_static"]+meta["dimsC_yearly"],
26
+ "categorical":{"land_use_class":4,"grap_stage":3,"n_landuse":meta["n_landuse"],"n_grap":meta["n_grap"]}}
27
+ net=AtmosIQNet(cfg).to(dev); net.load_state_dict(torch.load(a.ckpt,map_location=dev)); net.eval()
28
+ nz=np.load(pathlib.Path(a.tensors)/"norm.npz")
29
+ ylm=torch.tensor(nz["y_logmean"]).float().to(dev) if "y_logmean" in nz else None
30
+ yls=torch.tensor(nz["y_logstd"]).float().to(dev) if "y_logstd" in nz else None
31
+ print(f"loaded {a.ckpt} ({sum(p.numel() for p in net.parameters()):,} params)")
32
+
33
+ alln=torch.arange(data.N,device=data.store)
34
+ ei,eh,nh=data.ei.to(dev),data.e_hat.to(dev),data.n_hat.to(dev)
35
+ te_days=data.target_days(2)
36
+ if a.test_days: te_days=te_days[:a.test_days]
37
+ te_mask=(data.split==2).float().unsqueeze(-1).to(dev)
38
+ print(f"test days: {len(te_days)} | held-out test nodes: {int((data.split==2).sum())}")
39
+
40
+ # collect horizon-0 predictions (median = mu in log space -> expm1) vs truth on test nodes
41
+ Ys={p:[] for p in POLL}; Ps={p:[] for p in POLL}
42
+ with torch.no_grad():
43
+ for t in te_days:
44
+ b=data.window(t,alln,ei,eh,nh)
45
+ out=net(b["groups_t"],b["ei"],b["e_hat"],b["n_hat"],b["wu"],b["wv"],b["blh"],b["comp"])
46
+ mu=out["mu"][:,0,:] # horizon 0 [N,7] (standardized log space)
47
+ if ylm is not None: mu=mu*yls.view(1,-1)+ylm.view(1,-1) # de-standardize
48
+ pred=(torch.exp(mu.clamp(max=12))-1e-3).clamp_min(0) # log(y+eps) inverse; clamp>=0 (fixes co negatives)
49
+ y=b["y"][:,0,:]; m=(b["m"][:,0,:]*te_mask)
50
+ for j,p in enumerate(POLL):
51
+ mm=m[:,j]>0
52
+ if mm.any():
53
+ Ys[p].append(y[mm,j].cpu()); Ps[p].append(pred[mm,j].cpu())
54
+
55
+ refs=json.load(open(a.refs)) if os.path.exists(a.refs) else {}
56
+ print("\n===== M2 — SPATIAL-HELD-OUT R² (horizon 0, blueprint §10) =====")
57
+ print(f"{'pollutant':8} {'n':>6} {'R²':>8} {'RMSE':>8} {'MAE':>8} vs XGBoost")
58
+ r2s=[]
59
+ for p in POLL:
60
+ if not Ys[p]: print(f"{p:8} {'--':>6} no test labels"); continue
61
+ y=torch.cat(Ys[p]).numpy(); pr=torch.cat(Ps[p]).numpy()
62
+ pr=np.nan_to_num(pr,nan=np.nanmean(y))
63
+ ss_res=((y-pr)**2).sum(); ss_tot=((y-y.mean())**2).sum()+1e-9
64
+ r2=1-ss_res/ss_tot; rmse=np.sqrt(((y-pr)**2).mean()); mae=np.abs(y-pr).mean()
65
+ xg=refs.get(p,{}).get("xgboost")
66
+ cmp=f"xgb {xg:+.2f} {'BEAT' if (xg is not None and r2>xg) else 'below' if xg is not None else ''}"
67
+ print(f"{p:8} {len(y):>6} {r2:>+8.3f} {rmse:>8.2f} {mae:>8.2f} {cmp}")
68
+ if p not in ("nh3",): r2s.append(r2) # nh3 excluded from Go/No-Go (sparse-aux)
69
+ print(f"\nmean primary R² (excl nh3): {np.mean(r2s):+.3f}")
70
+ print("Go/No-Go: GNN should beat XGBoost floor on primary pollutants (esp pm2_5) on SPATIAL held-out.")
71
+
72
+ if __name__=="__main__": main()