sl-protostar-climate-ceviche / code /extra_backtest.py
sleonca's picture
Upload folder using huggingface_hub
b47743b verified
Raw History Blame Contribute Delete
7.08 kB
"""PROMPT_SIGUIENTE Step A: pre-2019 backtest of the new candidates (code/models_extra.py) and the
per-metric weighted ensemble.
* New models are scored with the unchanged backtest.run() (origins 1990..2011, 7-year horizon). Their
predictions are cached in results/extra_backtest/preds/<model>.parquet.
* Weighted ensemble, per metric, of four components: the current model ("ours"), the ARIMA ensemble B, the
best ETS variant for that metric (highest mean S_m) and the hierarchical model. Weights are non-negative,
sum to 1, on a 0.1 grid (286 combinations), chosen by the mean S_m over the 6 origins.
Overfitting check: weights chosen on origins 1990-2006 only, then evaluated on the 2011 origin.
Outputs: results/extra_backtest/{summary.csv, metrics_by_origin.csv, ensemble_weights.csv, holdout_check.csv}
Run: python code/extra_backtest.py [--force]
"""
import argparse
import itertools
import time
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import pandas as pd
import backtest
import models_extra as mx
from arima_backtest import PREDS as ARIMA_PREDS
from backtest import COORDS, H, LV, ORIGINS
from common import METRICS, ROOT
OUT = ROOT / "results" / "extra_backtest"
PREDS = OUT / "preds"
ALL = list(METRICS)
TEMP = ["annual_avg_temp"]
NEW = {
"ets_holt": (mx.ets_holt, {}, ALL),
"ets_damped": (mx.ets_damped, {}, ALL),
"ets_pooled": (mx.ets_pooled, {}, ALL),
"hierarchical": (mx.hierarchical, {}, ALL),
"tmax_tmin": (mx.tmax_tmin, dict(slope_scale=1.25), TEMP),
"tmax_tmin_s1": (mx.tmax_tmin, dict(slope_scale=1.0), TEMP),
}
ETS = ["ets_holt", "ets_damped", "ets_pooled"]
GRID = [w for w in itertools.product(range(11), repeat=4) if sum(w) == 10] # tenths, 286 combos
COMPONENTS = ["ours", "arima_ensemble_B", "best_ets", "hierarchical"]
def years_for(o):
return list(range(o + 1, min(o + H, 2018) + 1))
def compute(name, force=False):
f = PREDS / f"{name}.parquet"
if f.exists() and not force:
return pd.read_parquet(f)
fn, kw, mets = NEW[name]
parts = []
for m in mets:
for o in ORIGINS:
p = fn(LV, o, years_for(o), COORDS, m, **kw)[["ID", "metric", "Year", "pred"]].assign(origin=o)
p.attrs = {}
parts.append(p)
df = pd.concat(parts, ignore_index=True)
df.to_parquet(f)
return df
def as_series(df):
return df.set_index(["ID", "metric", "Year", "origin"]).pred
def run_cached(pred: pd.Series, metric, origins=ORIGINS):
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, origins=origins).set_index("origin").S
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--force", action="store_true")
args = ap.parse_args()
PREDS.mkdir(parents=True, exist_ok=True)
P = {}
for name in NEW:
t0 = time.time()
P[name] = as_series(compute(name, args.force))
print(f"{name:14s} {time.time() - t0:6.1f}s", flush=True)
ours = as_series(pd.read_parquet(ARIMA_PREDS / "ours.parquet"))
pa49 = as_series(pd.read_parquet(ARIMA_PREDS / "pooled_auto_at_1949.parquet"))
ensB = ours.copy()
tm = ensB.index.get_level_values("metric") == "annual_avg_temp"
ensB[tm] = (0.75 * ours + 0.25 * pa49).reindex(ensB.index)[tm]
P["ours"], P["arima_ensemble_B"] = ours, ensB
rows = []
S = {}
for name, pred in P.items():
for m in ALL:
if m not in pred.index.get_level_values("metric"):
continue
s = run_cached(pred, m)
S[(name, m)] = s
rows += [dict(model=name, metric=m, origin=o, S=v) for o, v in s.items()]
mo = pd.DataFrame(rows)
mo.to_csv(OUT / "metrics_by_origin.csv", index=False)
# weighted ensemble per metric
wrows, hold, ens_parts = [], [], []
for m in ALL:
best_ets = max(ETS, key=lambda n: S[(n, m)].mean())
comps = {"ours": P["ours"], "arima_ensemble_B": P["arima_ensemble_B"], "best_ets": P[best_ets], "hierarchical": P["hierarchical"]}
X = pd.concat([c.xs(m, level="metric", drop_level=False) for c in comps.values()], axis=1, keys=COMPONENTS).dropna()
def evaluate(w, origins):
return run_cached(pd.Series(X.to_numpy() @ (np.array(w) / 10), index=X.index), m, origins)
# S per origin for every grid point, computed once on all origins
res = {w: evaluate(w, ORIGINS) for w in GRID}
full = max(GRID, key=lambda w: (res[w].mean(), -sum(1 for x in w if x)))
early = max(GRID, key=lambda w: (res[w].loc[ORIGINS[:-1]].mean(), -sum(1 for x in w if x)))
wrows.append(dict(metric=m, best_ets=best_ets, **{f"w_{c}": full[i] / 10 for i, c in enumerate(COMPONENTS)},
S_mean=res[full].mean(), S_2011=res[full].loc[2011],
S_mean_ours=S[("ours", m)].mean(), S_2011_ours=S[("ours", m)].loc[2011]))
hold.append(dict(metric=m, **{f"w_{c}": early[i] / 10 for i, c in enumerate(COMPONENTS)},
S_1990_2006_fit=res[early].loc[ORIGINS[:-1]].mean(), S_2011_holdout=res[early].loc[2011],
S_2011_ours=S[("ours", m)].loc[2011], S_2011_fullweights=res[full].loc[2011]))
ens_parts.append(pd.Series(X.to_numpy() @ (np.array(full) / 10), index=X.index))
for o, v in res[full].items():
mo.loc[len(mo)] = dict(model="weighted_ensemble", metric=m, origin=o, S=v)
W = pd.DataFrame(wrows)
W.to_csv(OUT / "ensemble_weights.csv", index=False)
Hd = pd.DataFrame(hold)
Hd.to_csv(OUT / "holdout_check.csv", index=False)
pd.concat(ens_parts).rename("pred").reset_index().to_parquet(PREDS / "weighted_ensemble.parquet")
mo.to_csv(OUT / "metrics_by_origin.csv", index=False)
summ = mo.groupby(["model", "metric"]).S.agg(S_mean="mean").reset_index()
summ = summ.merge(mo[mo.origin == 2011].rename(columns={"S": "S_2011"})[["model", "metric", "S_2011"]], on=["model", "metric"])
summ.to_csv(OUT / "summary.csv", index=False)
full_models = [n for n in summ.model.unique() if (summ.model == n).sum() == 4]
sc = mo[mo.model.isin(full_models)].groupby(["model", "origin"]).S.mean().clip(lower=0).mul(100).unstack()
sc["mean"] = sc[ORIGINS].mean(1)
sc.sort_values("mean", ascending=False).to_csv(OUT / "score_by_origin.csv")
pd.set_option("display.width", 220)
print("\nMean S_m (6 origins):\n", summ.pivot(index="model", columns="metric", values="S_mean")[ALL].round(4).to_string())
print("\nS_m at 2011:\n", summ.pivot(index="model", columns="metric", values="S_2011")[ALL].round(4).to_string())
print("\nComposite Score:\n", sc.sort_values("mean", ascending=False).round(2).to_string())
print("\nEnsemble weights (all 6 origins):\n", W.round(4).to_string(index=False))
print("\nHoldout check (weights from 1990-2006, scored on 2011):\n", Hd.round(4).to_string(index=False))
if __name__ == "__main__":
main()