Datasets:
Download code/arima_forecast.py from sleonca/sl-protostar-climate-ceviche: direct link, hf CLI and curl.
- Browser
- Download file 3.94 kB
-
https://huggingface.co/datasets/sleonca/sl-protostar-climate-ceviche/resolve/main/code/arima_forecast.py
- Command line
-
hf download hf://datasets/sleonca/sl-protostar-climate-ceviche/code/arima_forecast.py
-
curl -L -o arima_forecast.py https://huggingface.co/datasets/sleonca/sl-protostar-climate-ceviche/resolve/main/code/arima_forecast.py
3.94 kB
| """Step 10 of the ARIMA experiments: forecast 2019-2025 from data up to 2018-12-31 with the configuration | |
| chosen on the pre-2019 backtest (code/arima_select.py) and write results/submission_arima.csv. | |
| Chosen configuration ("B_ensemble_rule"): the current model for every metric, except annual_avg_temp, | |
| which is 0.75 x current model + 0.25 x pooled-trend ARIMA (70-year window, `pooled_auto@1949`). | |
| This file never overwrites submission.csv. | |
| python code/arima_forecast.py # writes results/submission_arima.csv | |
| python code/arima_forecast.py --config NAME --out PATH # any configuration in CONFIGS | |
| """ | |
| import argparse | |
| import warnings | |
| warnings.filterwarnings("ignore") | |
| import pandas as pd | |
| import final_model | |
| from arima_backtest import MODELS | |
| from common import CUTOFF_YEAR, METRICS, ROOT, load_annual, long_valid | |
| YEARS = list(range(2019, 2026)) | |
| OURS = "ours" | |
| # per metric: list of (model name in arima_backtest.MODELS or "ours", weight) | |
| CONFIGS = { | |
| "B_ensemble_rule": {"annual_avg_temp": [(OURS, 0.75), ("pooled_auto@1949", 0.25)], | |
| "total_precip_in": [(OURS, 1.0)], "hottest_day_temp": [(OURS, 1.0)], "cdd": [(OURS, 1.0)]}, | |
| "A_best_arima": {"annual_avg_temp": [("arima_111_drift", 1.0)], "total_precip_in": [("arima_100_c", 1.0)], | |
| "hottest_day_temp": [("pooled_auto@1979", 1.0)], "cdd": [("arima_101_ct", 1.0)]}, | |
| } | |
| def single(name, lv, coords, metric): | |
| if name == OURS: | |
| return final_model.forecast(lv, CUTOFF_YEAR, YEARS, coords, metric) | |
| if name in CONFIGS: | |
| raise ValueError(name) | |
| spec = MODELS[name] | |
| p = spec["fn"](lv, CUTOFF_YEAR, YEARS, coords, metric, **spec["kw"]) | |
| p.attrs = {} | |
| return p | |
| def forecast(parts, lv, coords): | |
| """parts: {metric: [(model, weight), ...]} -> DataFrame ID, metric, Year, pred.""" | |
| out = [] | |
| for m in METRICS: | |
| acc = None | |
| for name, w in parts[m]: | |
| p = single(name, lv, coords, m).set_index(["ID", "metric", "Year"]).pred * w | |
| acc = p if acc is None else acc + p | |
| out.append(acc.rename("pred").reset_index()) | |
| return pd.concat(out, ignore_index=True) | |
| def write(pred, lv, path): | |
| # fallback for any city-metric left empty: mean of all valid years (as 03_forecast.py) | |
| longrun = lv[lv.valid].groupby(["ID", "metric"]).value.mean().rename("lr").reset_index() | |
| pred = pred.merge(longrun, on=["ID", "metric"], how="left") | |
| n_fb = int(pred.pred.isna().sum()) | |
| pred["pred"] = pred.pred.fillna(pred.lr) | |
| tmpl = pd.read_csv(ROOT / "submission.csv", dtype={"city_id": str})[["city_id", "year", "metric"]] | |
| sub = tmpl.merge(pred.rename(columns={"ID": "city_id", "Year": "year", "pred": "predicted_value"}) | |
| [["city_id", "year", "metric", "predicted_value"]], on=["city_id", "year", "metric"], how="left") | |
| assert len(sub) == 5880 and sub.predicted_value.notna().all() | |
| sub["predicted_value"] = sub.predicted_value.round(3) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| sub.to_csv(path, index=False) | |
| return sub, n_fb | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--config", default="B_ensemble_rule") | |
| ap.add_argument("--out", default=str(ROOT / "results" / "submission_arima.csv")) | |
| args = ap.parse_args() | |
| out = ROOT / args.out if not args.out.startswith("/") else __import__("pathlib").Path(args.out) | |
| if out.resolve() == (ROOT / "submission.csv").resolve(): | |
| raise SystemExit("refusing to overwrite submission.csv") | |
| A = load_annual() | |
| lv = long_valid(A) | |
| assert lv.Year.max() == CUTOFF_YEAR | |
| coords = A.groupby("ID")[["Lat", "Lon"]].first() | |
| sub, n_fb = write(forecast(CONFIGS[args.config], lv, coords), lv, out) | |
| print(f"{args.config}: wrote {out} ({len(sub)} rows, {n_fb} fallback rows)") | |
| print(sub.groupby(["metric", "year"]).predicted_value.mean().unstack().round(2)) | |
| if __name__ == "__main__": | |
| main() | |