Download scripts/evaluate.py from AtmosIQ/atmosiq-processed: direct link, hf CLI and curl.
- Browser
- Download file 4.21 kB
-
https://huggingface.co/datasets/AtmosIQ/atmosiq-processed/resolve/main/scripts/evaluate.py
- Command line
-
hf download hf://datasets/AtmosIQ/atmosiq-processed/scripts/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/datasets/AtmosIQ/atmosiq-processed/resolve/main/scripts/evaluate.py
4.21 kB
| r""" | |
| evaluate.py — M2 Go/No-Go. Loads atmosiq_best.pt, predicts on the TEST fold (spatial | |
| held-out nodes, full-graph), reports per-pollutant spatial-held-out R²/RMSE/MAE at | |
| horizon 0, and compares to the M1 XGBoost floor (refs.json). Blueprint §10 primary metric. | |
| Run: python data\models\evaluate.py --tensors data\tensors --ckpt data\atmosiq_best.pt | |
| """ | |
| from __future__ import annotations | |
| import os, sys, json, argparse, pathlib | |
| import numpy as np, torch | |
| sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) | |
| from model import AtmosIQNet | |
| from dataset_v2 import AtmosData | |
| POLL=["pm2_5","pm10","no2","so2","co","o3","nh3"] | |
| def main(): | |
| ap=argparse.ArgumentParser() | |
| ap.add_argument("--tensors",default="data/tensors"); ap.add_argument("--ckpt",default="data/atmosiq_best.pt") | |
| ap.add_argument("--window",type=int,default=7); ap.add_argument("--refs",default="data/models/refs.json") | |
| ap.add_argument("--test_days",type=int,default=0,help="0=all test days") | |
| a=ap.parse_args() | |
| dev="cuda" if torch.cuda.is_available() else "cpu"; print("device:",dev) | |
| meta=json.load(open(pathlib.Path(a.tensors)/"meta.json")) | |
| data=AtmosData(a.tensors, window=a.window, device=dev) | |
| cfg={"calendar_num_dim":meta["dimsD_num"],"n_recon_channels":9+meta["dimsB"]+meta["dimsC_static"]+meta["dimsC_yearly"], | |
| "categorical":{"land_use_class":4,"grap_stage":3,"n_landuse":meta["n_landuse"],"n_grap":meta["n_grap"]}} | |
| net=AtmosIQNet(cfg).to(dev); net.load_state_dict(torch.load(a.ckpt,map_location=dev)); net.eval() | |
| nz=np.load(pathlib.Path(a.tensors)/"norm.npz") | |
| ylm=torch.tensor(nz["y_logmean"]).float().to(dev) if "y_logmean" in nz else None | |
| yls=torch.tensor(nz["y_logstd"]).float().to(dev) if "y_logstd" in nz else None | |
| print(f"loaded {a.ckpt} ({sum(p.numel() for p in net.parameters()):,} params)") | |
| alln=torch.arange(data.N,device=data.store) | |
| ei,eh,nh=data.ei.to(dev),data.e_hat.to(dev),data.n_hat.to(dev) | |
| te_days=data.target_days(2) | |
| if a.test_days: te_days=te_days[:a.test_days] | |
| te_mask=(data.split==2).float().unsqueeze(-1).to(dev) | |
| print(f"test days: {len(te_days)} | held-out test nodes: {int((data.split==2).sum())}") | |
| # collect horizon-0 predictions (median = mu in log space -> expm1) vs truth on test nodes | |
| Ys={p:[] for p in POLL}; Ps={p:[] for p in POLL} | |
| with torch.no_grad(): | |
| for t in te_days: | |
| b=data.window(t,alln,ei,eh,nh) | |
| out=net(b["groups_t"],b["ei"],b["e_hat"],b["n_hat"],b["wu"],b["wv"],b["blh"],b["comp"]) | |
| mu=out["mu"][:,0,:] # horizon 0 [N,7] (standardized log space) | |
| if ylm is not None: mu=mu*yls.view(1,-1)+ylm.view(1,-1) # de-standardize | |
| pred=(torch.exp(mu.clamp(max=12))-1e-3).clamp_min(0) # log(y+eps) inverse; clamp>=0 (fixes co negatives) | |
| y=b["y"][:,0,:]; m=(b["m"][:,0,:]*te_mask) | |
| for j,p in enumerate(POLL): | |
| mm=m[:,j]>0 | |
| if mm.any(): | |
| Ys[p].append(y[mm,j].cpu()); Ps[p].append(pred[mm,j].cpu()) | |
| refs=json.load(open(a.refs)) if os.path.exists(a.refs) else {} | |
| print("\n===== M2 — SPATIAL-HELD-OUT R² (horizon 0, blueprint §10) =====") | |
| print(f"{'pollutant':8} {'n':>6} {'R²':>8} {'RMSE':>8} {'MAE':>8} vs XGBoost") | |
| r2s=[] | |
| for p in POLL: | |
| if not Ys[p]: print(f"{p:8} {'--':>6} no test labels"); continue | |
| y=torch.cat(Ys[p]).numpy(); pr=torch.cat(Ps[p]).numpy() | |
| pr=np.nan_to_num(pr,nan=np.nanmean(y)) | |
| ss_res=((y-pr)**2).sum(); ss_tot=((y-y.mean())**2).sum()+1e-9 | |
| r2=1-ss_res/ss_tot; rmse=np.sqrt(((y-pr)**2).mean()); mae=np.abs(y-pr).mean() | |
| xg=refs.get(p,{}).get("xgboost") | |
| cmp=f"xgb {xg:+.2f} {'BEAT' if (xg is not None and r2>xg) else 'below' if xg is not None else ''}" | |
| print(f"{p:8} {len(y):>6} {r2:>+8.3f} {rmse:>8.2f} {mae:>8.2f} {cmp}") | |
| if p not in ("nh3",): r2s.append(r2) # nh3 excluded from Go/No-Go (sparse-aux) | |
| print(f"\nmean primary R² (excl nh3): {np.mean(r2s):+.3f}") | |
| print("Go/No-Go: GNN should beat XGBoost floor on primary pollutants (esp pm2_5) on SPATIAL held-out.") | |
| if __name__=="__main__": main() |