Datasets:
Download code/arima_select.py from sleonca/sl-protostar-climate-ceviche: direct link, hf CLI and curl.
- Browser
- Download file 4.84 kB
-
https://huggingface.co/datasets/sleonca/sl-protostar-climate-ceviche/resolve/main/code/arima_select.py
- Command line
-
hf download hf://datasets/sleonca/sl-protostar-climate-ceviche/code/arima_select.py
-
curl -L -o arima_select.py https://huggingface.co/datasets/sleonca/sl-protostar-climate-ceviche/resolve/main/code/arima_select.py
4.84 kB
| """Step 10 of the ARIMA experiments: choose one ARIMA-based configuration per metric from the | |
| pre-2019 backtest only (cached predictions of arima_backtest.py; no data after 2018 is involved). | |
| Selection rule, fixed before looking at the results: | |
| A. best pure ARIMA per metric = ARIMA-family model with the highest mean S_m over the 6 origins; | |
| B. ensemble per metric = w * ARIMA + (1 - w) * current model, w in {0.25, 0.5}, for the ARIMA models | |
| listed in CANDIDATES. An ensemble is accepted for a metric only if it beats the current model on | |
| BOTH the mean S_m and S_m at origin 2011; among accepted ones, the highest mean S_m wins. | |
| Otherwise the metric keeps the current model. | |
| The resulting configurations are scored with the unchanged backtest.run() and compared with the | |
| current model on the mean composite Score and at origin 2011. | |
| Outputs: results/arima_select/{ensembles.csv, configs.csv, score_by_origin.csv} | |
| Run: python code/arima_select.py | |
| """ | |
| import warnings | |
| warnings.filterwarnings("ignore") | |
| import pandas as pd | |
| import backtest | |
| from arima_backtest import MODELS, PREDS, REFERENCE | |
| from backtest import ORIGINS | |
| from common import METRICS, ROOT | |
| OUT = ROOT / "results" / "arima_select" | |
| WEIGHTS = (0.25, 0.5) | |
| CANDIDATES = { | |
| "annual_avg_temp": ["arima_100_ct", "arima_101_ct", "arima_111_drift", "auto_d0_ct", "pooled_auto", "pooled_auto@1949"], | |
| "cdd": ["arima_100_ct", "arima_101_ct", "arima_111_drift", "auto_d0_ct", "pooled_auto", "cdd_hybrid_N10"], | |
| "total_precip_in": ["arima_100_c", "auto_d0_c", "pooled_auto", "pooled_auto@1949"], | |
| "hottest_day_temp": ["arima_100_c", "auto_d0_c", "pooled_auto", "arima_100_ct"], | |
| } | |
| def load(name): | |
| return pd.read_parquet(PREDS / f"{name.replace('@', '_at_')}.parquet").set_index(["ID", "metric", "Year", "origin"]).pred | |
| def run_cached(pred: pd.Series, metric): | |
| p = pred.rename("pred").reset_index() | |
| def fn(lv, o, yrs, coords, m): | |
| return p[(p.origin == o) & (p.metric == m) & p.Year.isin(yrs)][["ID", "metric", "Year", "pred"]] | |
| return backtest.run(fn, metric) | |
| def main(): | |
| OUT.mkdir(parents=True, exist_ok=True) | |
| ours = load("ours") | |
| arima_names = [n for n in MODELS if n not in REFERENCE] | |
| rows = [] | |
| for m in METRICS: | |
| r = run_cached(ours, m) | |
| rows.append(dict(metric=m, model="ours", w=0.0, S_mean=r.S.mean(), S_2011=r.S.iloc[-1])) | |
| for name in arima_names: | |
| if m not in MODELS[name]["metrics"]: | |
| continue | |
| a = load(name) | |
| r = run_cached(a, m) | |
| rows.append(dict(metric=m, model=name, w=1.0, S_mean=r.S.mean(), S_2011=r.S.iloc[-1])) | |
| if name in CANDIDATES[m]: | |
| for w in WEIGHTS: | |
| e = (w * a + (1 - w) * ours).dropna() | |
| r = run_cached(e, m) | |
| rows.append(dict(metric=m, model=name, w=w, S_mean=r.S.mean(), S_2011=r.S.iloc[-1])) | |
| T = pd.DataFrame(rows) | |
| T.to_csv(OUT / "ensembles.csv", index=False) | |
| configs = {"ours": {}, "A_best_arima": {}, "B_ensemble_rule": {}} | |
| for m in METRICS: | |
| t = T[T.metric == m] | |
| base = t[t.model == "ours"].iloc[0] | |
| configs["ours"][m] = ("ours", 0.0) | |
| a = t[t.w == 1.0].sort_values("S_mean", ascending=False).iloc[0] | |
| configs["A_best_arima"][m] = (a.model, 1.0) | |
| ens = t[(t.w > 0) & (t.w < 1) & (t.S_mean > base.S_mean) & (t.S_2011 > base.S_2011)] | |
| if len(ens): | |
| b = ens.sort_values("S_mean", ascending=False).iloc[0] | |
| configs["B_ensemble_rule"][m] = (b.model, b.w) | |
| else: | |
| configs["B_ensemble_rule"][m] = ("ours", 0.0) | |
| score_rows, cfg_rows = [], [] | |
| for cname, cfg in configs.items(): | |
| Ss = [] | |
| for m, (name, w) in cfg.items(): | |
| pred = ours if w == 0 else (w * load(name) + (1 - w) * ours).dropna() | |
| r = run_cached(pred, m) | |
| Ss.append(r.set_index("origin").S.rename(m)) | |
| cfg_rows.append(dict(config=cname, metric=m, model=name, w=w, S_mean=r.S.mean(), S_2011=r.S.iloc[-1])) | |
| S = pd.concat(Ss, axis=1) | |
| sc = S.mean(1).clip(lower=0) * 100 | |
| score_rows.append(dict(config=cname, **{str(o): sc[o] for o in ORIGINS}, mean=sc.mean())) | |
| C = pd.DataFrame(cfg_rows) | |
| C.to_csv(OUT / "configs.csv", index=False) | |
| SC = pd.DataFrame(score_rows).set_index("config") | |
| SC.to_csv(OUT / "score_by_origin.csv") | |
| pd.set_option("display.width", 220); pd.set_option("display.max_rows", 200) | |
| for m in METRICS: | |
| t = T[T.metric == m].sort_values("S_mean", ascending=False) | |
| print(f"\n{m} (top 12)\n", t.head(12).round(4).to_string(index=False)) | |
| print("\nConfigurations:\n", C.round(4).to_string(index=False)) | |
| print("\nComposite Score by origin:\n", SC.round(2).to_string()) | |
| if __name__ == "__main__": | |
| main() | |