Download sort_export.py from jantheman/heating-grid-forecast-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 3.11 kB
-
https://huggingface.co/jantheman/heating-grid-forecast-benchmark/resolve/main/sort_export.py
- Command line
-
hf download hf://jantheman/heating-grid-forecast-benchmark/sort_export.py
-
curl -L -o sort_export.py https://huggingface.co/jantheman/heating-grid-forecast-benchmark/resolve/main/sort_export.py
3.11 kB
| """Sorted-quantile variants of the neural March predictions (quantile | |
| rearrangement, Chernozhukov et al.): np.sort along the quantile axis per row. | |
| Writes results/predictions_{lstm,gnn}_sorted.csv.""" | |
| import sys | |
| import time | |
| from pathlib import Path | |
| from types import SimpleNamespace | |
| import numpy as np | |
| import pandas as pd | |
| import torch | |
| sys.path.insert(0, str(Path.cwd())) | |
| import run_baselines as rb | |
| from train_seq import build_model, daily_origins, download_all, make_batches, prepare, HORIZON | |
| from huggingface_hub import hf_hub_download, HfApi | |
| files = download_all(Path.cwd()) | |
| D = prepare(files) | |
| consumers = pd.read_csv(files["graph/consumer_mapping.csv"]).consumer.sort_values().tolist() | |
| index = pd.date_range("2024-12-31 23:00", periods=len(D["Y"]), freq="15min", tz="UTC") | |
| origins_test = daily_origins(index, D["test"]) | |
| slots = np.concatenate([np.arange(o + HORIZON, o + 2 * HORIZON) for o in origins_test]) | |
| ts_index = index[slots] | |
| n_c = D["Y"].shape[1] | |
| base = pd.DataFrame({ | |
| "time_utc": np.repeat(ts_index.strftime("%Y-%m-%d %H:%M:%S+0000").values, n_c), | |
| "consumer": np.tile(consumers, len(slots)), | |
| "y_true_kwh": D["Y"][slots].reshape(-1), | |
| "observed": D["M"][slots].reshape(-1).astype(int), | |
| }) | |
| QCOLS = ["q05", "q15", "q25", "q35", "q45", "q50", "q55", "q65", "q75", "q85", "q95"] | |
| REORDER = lambda q: np.concatenate([q, (q[..., 4:5] + q[..., 5:6]) / 2], axis=2)[ | |
| ..., [0, 1, 2, 3, 4, 10, 5, 6, 7, 8, 9]] | |
| api = HfApi() | |
| def save_sorted(name, q_sorted10): | |
| qc = REORDER(q_sorted10) | |
| df = base.copy() | |
| for i, col in enumerate(QCOLS): | |
| df[col] = qc[:, :, i].reshape(-1) | |
| out = Path("results") / f"predictions_{name}_sorted.csv" | |
| out.parent.mkdir(exist_ok=True) | |
| df.to_csv(out, index=False) | |
| api.upload_file(path_or_fileobj=out, path_in_repo=f"results/{out.name}", | |
| repo_id=rb.REPO_CODE, repo_type="model", | |
| commit_message=f"March predictions: {name} (rearranged quantiles)") | |
| print(f"pushed {out.name}", flush=True) | |
| def neural_q(model_name): | |
| ckpt = torch.load(hf_hub_download(rb.REPO_CODE, f"models/{model_name}.pt", | |
| repo_type="model", local_dir=Path.cwd()), | |
| map_location="cpu", weights_only=False) | |
| model = build_model(SimpleNamespace(model=model_name), ckpt["n_features"], 27, | |
| ckpt["A"].shape[0]) | |
| model.A = torch.tensor(ckpt["A"]) | |
| model.load_state_dict(ckpt["state_dict"]) | |
| model.eval() | |
| qs = [] | |
| with torch.no_grad(): | |
| for hist, hmask, xhist, xfut, y, m in make_batches(origins_test, D): | |
| q, _ = model(torch.tensor(hist), torch.tensor(hmask), | |
| torch.tensor(xhist), torch.tensor(xfut)) | |
| qs.append(q.numpy()) | |
| q = np.concatenate(qs, axis=0).transpose(0, 3, 2, 1).reshape(-1, n_c, 10) | |
| return np.sort(q, axis=2) * D["sd"][None, :, None] + D["mu"][None, :, None] | |
| for name in ["lstm", "gnn"]: | |
| t0 = time.time() | |
| save_sorted(name, neural_q(name)) | |
| print(f"{name} sorted in {time.time()-t0:.0f}s", flush=True) | |
| print("DONE", flush=True) | |