Datasets:
File size: 13,197 Bytes
d79a78d | 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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | """Experiments behind "tried and not shipped" (the optional step 5) and the headroom estimate.
None of this feeds the submission; it documents why the shipped models stop where they do.
Every experiment uses the same folds, scoring and selected models as the backtest.
1. headroom: how much skill a forecast with perfect knowledge of each city's level could reach
2. station shift: correct documented station changes with shifts estimated against neighbors
3. shrinkage: shrink the per-city cdd ~ temperature coefficient toward the nearest cities
Writes reports/experiments/{headroom.csv, station_shift.csv, cdd_coefficient_shrinkage.csv, EXPERIMENTS.md}.
Run: PYTHONPATH=code python -m protostar.experiments
"""
import json
import warnings
import numpy as np
import pandas as pd
from .backtest import N_BOOT, SE_MULT, Fold, md_table
from .common import (BASELINE_WINDOW, CONFIRMATION_FOLDS, METRICS, MIN_VALID_YEARS, REPORTS, SEED,
SELECTION_FOLDS)
from .data import Panel, cities, load_annual, load_coverage, long_table, panels
from .models import BASELINES, fallback, neighbor_order, pooled_slope, predict
OUT = REPORTS / "experiments"
REF = BASELINES["30-year average"]
FOLDS = [("selection", f) for f in SELECTION_FOLDS] + [("confirmation", f) for f in CONFIRMATION_FOLDS]
def mae_on(fold: Fold, metric: str, pred: np.ndarray) -> float:
mask = fold.scored[metric]
return float(np.abs(np.where(mask, pred - fold.truth[metric], 0.0)).sum() / mask.sum())
# ── 1. Headroom ──────────────────────────────────────────────────────────────
def headroom(P, order, selected) -> pd.DataFrame:
"""Skill of an 'oracle level' forecast: each city's own mean over its scored test years.
No flat forecast can beat it, and it is optimistic: a mean fitted to the same 7 values it
is scored on absorbs about 1/7 of the variance (roughly 7 % of the MAE) even for pure noise.
"""
rows = []
for kind, f in FOLDS:
fold = Fold(P, *f)
for metric in METRICS:
truth = np.where(fold.scored[metric], fold.truth[metric], np.nan)
n = np.isfinite(truth).sum(axis=1, keepdims=True)
level = np.nansum(truth, axis=1, keepdims=True) / np.maximum(n, 1)
oracle = float(np.nansum(np.abs(truth - level)) / fold.scored[metric].sum())
ref = fold.mae(REF, metric, order)
rows.append({"fold_kind": kind, "fold": fold.name, "metric": metric, "mae_30y_average": ref,
"skill_selected": 1 - fold.mae(selected[metric], metric, order) / ref,
"skill_oracle_level": 1 - oracle / ref})
return pd.DataFrame(rows)
# ── 2. Station-shift correction ──────────────────────────────────────────────
def homogenize(p: Panel, changes: np.ndarray, order: np.ndarray, min_t: float = 2.0,
k: int = 8, side: int = 15) -> tuple[Panel, int]:
"""Move the years before each documented station change (within the last 30 years of the
panel) to the level of the current station.
shift = mean(d after) - mean(d before), d = city value - mean of its k nearest cities that
year, over up to `side` valid years on each side (the 'before' side stops at an earlier
change); applied when its Welch |t| >= min_t. Only years up to the panel's last year are used.
"""
y = p.y.copy()
n_years = y.shape[1]
ch = changes[:, :n_years]
adjusted = 0
for i in np.flatnonzero(ch[:, -BASELINE_WINDOW:].sum(axis=1) > 0):
neighbors = order[i][:k]
for b in sorted(np.flatnonzero(ch[i, -BASELINE_WINDOW:]) + n_years - BASELINE_WINDOW, reverse=True):
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning) # years where no neighbor is valid
d = y[i] - np.nanmean(y[neighbors], axis=0)
after = d[b + 1:]
after = after[np.isfinite(after)][:side]
earlier = np.flatnonzero(ch[i, :b])
start = earlier[-1] + 1 if earlier.size else 0
before = d[start:b]
before = before[np.isfinite(before)][-side:]
if after.size < 3 or before.size < 3:
continue
delta = after.mean() - before.mean()
se = np.sqrt(after.var(ddof=1) / after.size + before.var(ddof=1) / before.size)
if se > 0 and abs(delta / se) >= min_t:
y[i, :b] += delta
y[i, b] = np.nan # the change year mixes both stations
adjusted += 1
return Panel(p.metric, p.city_ids, p.years, y), adjusted
def station_shift(P, order, selected) -> tuple[pd.DataFrame, pd.DataFrame]:
"""(per fold x metric detail, verdict per metric by the backtest's acceptance rule)."""
cov = load_coverage()
ids = {c: i for i, c in enumerate(P["cdd"].city_ids)}
years = P["cdd"].years
changes = np.zeros((len(ids), len(years)), int)
for row in cov[cov["Station Changes"] > 0].itertuples():
changes[ids[row.ID], row.Year - years[0]] = 1
rng = np.random.default_rng(SEED)
boot_w = rng.multinomial(len(ids), np.full(len(ids), 1.0 / len(ids)), size=N_BOOT).astype(float)
rows, verdicts = [], []
for min_t in (2.0, 3.0):
errors = {m: [] for m in METRICS} # selection folds: (corrected, selected, reference) per city
for kind, f in FOLDS:
fold = Fold(P, *f)
adj, n_adj = {}, {}
for metric in METRICS:
adj[metric], n_adj[metric] = homogenize(fold.train[metric], changes, order, min_t=min_t)
for metric in METRICS:
mask = fold.scored[metric]
pred = predict(selected[metric], adj, metric, order, fold.years)
e_new = np.abs(np.where(mask, pred - fold.truth[metric], 0.0)).sum(axis=1)
e_sel, _ = fold.errors(selected[metric], metric, order)
e_ref, _ = fold.errors(REF, metric, order)
if kind == "selection":
errors[metric].append((e_new, e_sel, e_ref))
rows.append({"min_abs_t": min_t, "fold_kind": kind, "fold": fold.name, "metric": metric,
"shifts_applied": n_adj[metric], "skill_selected": 1 - e_sel.sum() / e_ref.sum(),
"skill_corrected": 1 - e_new.sum() / e_ref.sum(),
"change_points": 100 * (e_sel.sum() - e_new.sum()) / e_ref.sum()})
for metric in METRICS:
gains = [100 * (e_sel.sum() - e_new.sum()) / e_ref.sum() for e_new, e_sel, e_ref in errors[metric]]
boot = sum(100 * (boot_w @ (e_sel - e_new)) / (boot_w @ e_ref)
for e_new, e_sel, e_ref in errors[metric]) / len(errors[metric])
se = float(boot.std(ddof=1))
verdicts.append({"min_abs_t": min_t, "metric": metric, "gain_points_mean_selection": float(np.mean(gains)),
"se_points": se, "gain_fold_1": gains[0], "gain_fold_2": gains[1],
"passes_rule": bool(min(gains) > 0 and np.mean(gains) > SE_MULT * se)})
return pd.DataFrame(rows), pd.DataFrame(verdicts)
# ── 3. Shrinking the cdd ~ temperature coefficient ───────────────────────────
def cdd_via_temp_pooled(train, order, years, temp_spec, k: int, lam: float) -> np.ndarray:
"""The shipped cdd model, with the regression coefficient pooled like the trend slopes."""
x, y = train["annual_avg_temp"].y[:, -BASELINE_WINDOW:], train["cdd"].y[:, -BASELINE_WINDOW:]
ok = np.isfinite(x) & np.isfinite(y)
count = ok.sum(axis=1)
safe = np.maximum(count, 1)
xbar = np.where(ok, x, 0.0).sum(axis=1) / safe
ybar = np.where(ok, y, 0.0).sum(axis=1) / safe
dx = np.where(ok, x - xbar[:, None], 0.0)
sxx = (dx ** 2).sum(axis=1)
beta = np.where((sxx > 0) & (count >= MIN_VALID_YEARS),
(dx * np.where(ok, y, 0.0)).sum(axis=1) / np.where(sxx > 0, sxx, 1.0), np.nan)
beta = pooled_slope(beta, order, k, lam)
t_hat = predict(temp_spec, train, "annual_avg_temp", order, years)
out = ybar[:, None] + beta[:, None] * (t_hat - xbar[:, None])
out = np.where((count >= MIN_VALID_YEARS)[:, None], out, np.nan)
return np.maximum(fallback(train["cdd"], out, order), 0.0)
def shrinkage(P, order, selected) -> pd.DataFrame:
spec = selected["cdd"]
assert spec["type"] == "cdd_via_temp", "this experiment refines the shipped cdd model"
rows = []
for k in (8, 16, 32):
for lam in (1.0, 0.75, 0.5, 0.25, 0.0):
row = {"k": k, "own_coefficient_weight": lam}
for kind, f in FOLDS:
fold = Fold(P, *f)
pred = cdd_via_temp_pooled(fold.train, order, fold.years, spec["temp"], k, lam)
row[fold.name] = 1 - mae_on(fold, "cdd", pred) / fold.mae(REF, "cdd", order)
rows.append(row)
out = pd.DataFrame(rows)
sel = [Fold(P, *f).name for f in SELECTION_FOLDS]
out["mean selection"] = out[sel].mean(axis=1)
return out
def main():
OUT.mkdir(parents=True, exist_ok=True)
annual = load_annual()
P = panels(long_table(annual))
geo = cities(annual)
order = neighbor_order(geo["lat"].to_numpy(), geo["lon"].to_numpy())
selected = json.loads((REPORTS / "backtest" / "selected.json").read_text())["selected"]
head = headroom(P, order, selected)
shift, shift_verdict = station_shift(P, order, selected)
shr = shrinkage(P, order, selected)
# with full weight on the own coefficient the experiment must reproduce the shipped model
base = shr[shr["own_coefficient_weight"] == 1.0].iloc[0]
for kind, f in FOLDS:
fold = Fold(P, *f)
assert abs(base[fold.name] - fold.skill(selected["cdd"], "cdd", order)) < 1e-12
head.to_csv(OUT / "headroom.csv", index=False)
shift.to_csv(OUT / "station_shift.csv", index=False)
shift_verdict.to_csv(OUT / "station_shift_verdict.csv", index=False)
assert not shift_verdict["passes_rule"].any(), "a station-shift correction passes the rule: revisit the selection"
sel_names = [Fold(P, *f).name for f in SELECTION_FOLDS]
alt = shr[shr["own_coefficient_weight"] < 1.0]
base_sel = shr.loc[shr["own_coefficient_weight"] == 1.0, sel_names].iloc[0]
assert not (alt[sel_names] > base_sel.to_numpy()).all(axis=1).any(), "a shrinkage weight gains on both folds"
shr.to_csv(OUT / "cdd_coefficient_shrinkage.csv", index=False)
pct = "{:+.1%}"
wide = shift.pivot_table(index=["min_abs_t", "metric"], columns="fold", values="change_points", sort=False)
wide = wide[[Fold(P, *f).name for _, f in FOLDS]].reset_index()
text = f"""# Experiments behind "tried and not shipped"
Generated by `python -m protostar.experiments` (do not edit). Same folds, scoring and selected
models as the backtest; nothing here feeds the submission.
## 1. Headroom: skill of a forecast that knows each city's true level
`skill_oracle_level` uses each city's own mean over its scored test years: no flat forecast can
beat it, and it is optimistic by construction (a mean fitted to the 7 values it is scored on
gains roughly 7 % of the MAE even on pure noise).
{md_table(head, {"mae_30y_average": "{:.3f}", "skill_selected": pct, "skill_oracle_level": pct})}
## 2. Correcting documented station changes
Years before a documented station change (inside the 30-year window) are moved by the shift
estimated against the 8 nearest cities when its Welch |t| reaches `min_abs_t`. Change in skill of
the selected models, in points (1 point = 1 % of the 30-year-average MAE):
{md_table(wide, {c: "{:+.2f}" for c in wide.columns if c not in ("min_abs_t", "metric")})}
By the backtest's rule (gain on both selection folds and larger than {SE_MULT:g} bootstrap standard errors):
{md_table(shift_verdict, {c: "{:+.2f}" for c in ("gain_points_mean_selection", "gain_fold_1", "gain_fold_2")} | {"se_points": "{:.2f}"})}
Shifts applied per fold and metric, and the skills: `station_shift.csv`.
## 3. Shrinking the cdd ~ temperature coefficient toward the k nearest cities
Skill of the cdd model by weight on the city's own coefficient (1.0 = the shipped model):
{md_table(shr, {c: pct for c in shr.columns if c not in ("k", "own_coefficient_weight")})}
## Reading
No station-shift correction passes the backtest's rule (the best case, cdd, gains about 0.3 points
on both selection folds, within two standard errors), and no shrinkage weight gains on both
selection folds. Both are within noise, so neither ships. (The run fails if this ever changes.)
"""
(OUT / "EXPERIMENTS.md").write_text(text)
pd.set_option("display.width", 250, "display.max_columns", 30)
print(head.round(3).to_string(index=False), "\n")
print(wide.round(2).to_string(index=False), "\n")
print(shr.round(4).to_string(index=False))
if __name__ == "__main__":
main()
|