File size: 2,814 Bytes
49f3de8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | """Generate submission.csv: fit chosen methods on data <= 2018, predict 2019-2025.
Reads outputs/decision.json (from backtest.py) if present; otherwise uses the
documented default (shared_slope for temp/cdd, mean30 for precip/hottest).
Every value comes from this code's model on <=2018-12-31 data.
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
import pandas as pd
sys.path.insert(0, str(Path(__file__).parent))
from dataset import (METRICS, add_validity, download, load_annual, load_cities,
load_coverage, long_valid)
from leakage import assert_no_forbidden_artifacts
from models import forecast_all
DEFAULT_METHODS = {
"annual_avg_temp": "shared_slope",
"cdd": "shared_slope",
"total_precip_in": "mean30",
"hottest_day_temp": "mean30",
}
TARGET_YEARS = list(range(2019, 2026))
ORIGIN = 2018
def main() -> None:
root = Path(__file__).resolve().parent.parent
assert_no_forbidden_artifacts(Path(__file__).parent)
data_root = download(root / "data" / "_source")
annual = add_validity(load_annual(data_root), load_coverage(data_root))
cities = load_cities(data_root)
long_df = long_valid(annual)
assert long_df["Year"].max() <= ORIGIN, "training data beyond 2018!"
decision_path = root / "outputs" / "decision.json"
if decision_path.exists():
methods = json.loads(decision_path.read_text())["methods"]
print(f"methods from backtest decision: {methods}")
else:
methods = DEFAULT_METHODS
print(f"methods (default, no decision.json): {methods}")
pred = forecast_all(long_df, ORIGIN, TARGET_YEARS, methods)
all_cities = sorted(cities["ID"].astype(str).unique())
out = pred.rename(columns={"city_id": "city_id", "Year": "year",
"metric": "metric", "value": "predicted_value"})
out["city_id"] = out["city_id"].astype(str)
# Guarantee the full 210 x 7 x 4 grid (forecast_all covers every city in the
# training long table; assert instead of silently filling).
expected = {(c, y, m) for c in all_cities for y in TARGET_YEARS for m in METRICS}
got = set(zip(out["city_id"], out["year"], out["metric"]))
missing = expected - got
if missing:
raise RuntimeError(f"missing {len(missing)} forecast rows, e.g. {sorted(missing)[:5]}")
out = out[["city_id", "year", "metric", "predicted_value"]]\
.sort_values(["city_id", "year", "metric"]).reset_index(drop=True)
out_path = root / "submission.csv"
out.to_csv(out_path, index=False)
print(f"wrote {out_path}: {len(out)} rows")
print(out.groupby("metric")["predicted_value"].describe().round(2).to_string())
if __name__ == "__main__":
main()
|