Download forecast.py from helmo/tabum: direct link, hf CLI and curl.
- Browser
- Download file 6.72 kB
-
https://huggingface.co/spaces/helmo/tabum/resolve/main/forecast.py
- Command line
-
hf download hf://spaces/helmo/tabum/forecast.py
-
curl -L -o forecast.py https://huggingface.co/spaces/helmo/tabum/resolve/main/forecast.py
6.72 kB
| """tabUM as a forecaster: time becomes columns, one forward pass predicts the whole horizon. | |
| Each past time step is a training row and each future step a test row. A row's columns: | |
| - where it sits in time (a running step index, daily data only) and the calendar (hour, weekday, day of year, as numbers and as | |
| sine/cosine pairs so 23:00 sits next to 00:00); | |
| - seasonal lags: the value one, two, three and four seasons earlier (a season is a day for hourly data used with a | |
| short horizon, a week otherwise). Only lags at least as long as the horizon are used, so every lag of every future | |
| row is a value already observed: no recursion, no leakage; | |
| - the mean of those lags. | |
| tabUM never trains: fit() stores the rows and predict() reads them in context. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| import numpy as np | |
| import pandas as pd | |
| FEATURE_NAMES = { | |
| "step": "time step (trend)", "hour": "hour of day", "hour_sin": "hour of day", "hour_cos": "hour of day", | |
| "dow": "day of week", "dow_sin": "day of week", "dow_cos": "day of week", "weekend": "weekend", | |
| "doy_sin": "time of year", "doy_cos": "time of year", "month": "time of year", "dom": "day of month", | |
| } | |
| class Plan: | |
| step: pd.Timedelta | |
| season: int # steps per season used for the lags and the seasonal-naive baseline | |
| lags: list[int] | |
| hourly: bool | |
| def plan(index: pd.DatetimeIndex, horizon: int) -> Plan: | |
| step = index[1] - index[0] | |
| hourly = step < pd.Timedelta("1D") | |
| per_day = max(1, int(round(pd.Timedelta("1D") / step))) | |
| week = 7 * per_day | |
| season = week if hourly else 7 | |
| k0 = int(np.ceil(horizon / season)) | |
| lags = [season * k for k in range(k0, k0 + 4)] | |
| return Plan(step, season, lags, hourly) | |
| # Hourly series do better without the running time index (backtest over 46 series x 3 dates: electricity 0.91 -> 0.87, | |
| # pedestrians 1.31 -> 1.17, traffic 0.88 -> 0.89 of the seasonal-naive error), so it is used for daily data only. | |
| DROP: set[str] = {"hourly:step"} | |
| def features(index: pd.DatetimeIndex, values: np.ndarray, positions: np.ndarray, p: Plan, origin: pd.Timestamp, | |
| known_until: int) -> tuple[np.ndarray, list[str]]: | |
| """Rows for the given positions of the series. values[known_until:] are treated as unknown.""" | |
| idx = index[positions] | |
| cols: dict[str, np.ndarray] = {"step": ((idx - origin) / p.step).to_numpy(float)} | |
| dow, doy = idx.dayofweek.to_numpy(), idx.dayofyear.to_numpy() | |
| if p.hourly: | |
| h = idx.hour.to_numpy() + idx.minute.to_numpy() / 60 | |
| cols.update(hour=h, hour_sin=np.sin(2 * np.pi * h / 24), hour_cos=np.cos(2 * np.pi * h / 24)) | |
| cols.update(dow=dow.astype(float), dow_sin=np.sin(2 * np.pi * dow / 7), dow_cos=np.cos(2 * np.pi * dow / 7), | |
| weekend=(dow >= 5).astype(float), doy_sin=np.sin(2 * np.pi * doy / 365.25), | |
| doy_cos=np.cos(2 * np.pi * doy / 365.25)) | |
| if not p.hourly: | |
| cols.update(dom=idx.day.to_numpy(float), month=idx.month.to_numpy(float)) | |
| known = values.astype(float).copy() | |
| known[known_until:] = np.nan | |
| lagged = [] | |
| for L in p.lags: | |
| src = positions - L | |
| v = np.where(src >= 0, known[np.clip(src, 0, None)], np.nan) | |
| cols[f"lag{L}"] = v | |
| lagged.append(v) | |
| with np.errstate(all="ignore"): | |
| cols["lag_mean"] = np.nanmean(np.stack(lagged, 1), 1) | |
| names = [n for n in cols if n not in DROP and not (p.hourly and f"hourly:{n}" in DROP)] | |
| return np.stack([cols[n] for n in names], 1), names | |
| def lag_label(name: str, p: Plan) -> str: | |
| if name == "lag_mean": | |
| return "same time, recent seasons (mean)" | |
| L = int(name[3:]) | |
| k = L // p.season | |
| unit = "week" if (p.season % 7 == 0 and (p.hourly or p.season == 7)) else "season" | |
| return f"same time, {k} {unit}{'s' if k > 1 else ''} earlier" | |
| def seasonal_naive(values: np.ndarray, end: int, horizon: int, season: int) -> np.ndarray: | |
| last = values[end - season:end] | |
| return last[np.arange(horizon) % season] | |
| def run(reg_factory, series: pd.Series, horizon: int, context: int, backtest: bool, | |
| quantiles=(0.1, 0.5, 0.9), importances: bool = True) -> dict: | |
| """Forecast `horizon` steps. backtest=True hides the last `horizon` known points and forecasts them.""" | |
| s = series.copy() | |
| values = s.to_numpy(float) | |
| n = len(values) | |
| if backtest: | |
| end = n - horizon | |
| future_index = s.index[end:end + horizon] | |
| else: | |
| end = n | |
| future_index = pd.date_range(s.index[-1] + (s.index[1] - s.index[0]), periods=horizon, freq=s.index[1] - s.index[0]) | |
| s = pd.concat([s, pd.Series(np.nan, index=future_index)]) | |
| values = s.to_numpy(float) | |
| p = plan(s.index, horizon) | |
| start = max(0, end - context) | |
| train_pos = np.arange(start, end) | |
| train_pos = train_pos[~np.isnan(values[train_pos])] | |
| test_pos = np.arange(end, end + horizon) | |
| origin = s.index[start] | |
| Xtr, names = features(s.index, values, train_pos, p, origin, end) | |
| Xte, _ = features(s.index, values, test_pos, p, origin, end) | |
| import time | |
| t0 = time.time() | |
| reg = reg_factory().fit(Xtr, values[train_pos]) | |
| o = reg._out(Xte) # one forward pass; every quantile reads the same distribution | |
| q_ = lambda q: reg.model.predict_quantile(o, q)[0].float().cpu().numpy() | |
| out = {"index": future_index, "names": names, "plan": p, "end": end, "start": start, "median": q_(0.5), | |
| "mean": reg.model.predict_mean(o)[0].float().cpu().numpy()} | |
| for q in quantiles: | |
| out[q] = out["median"] if q == 0.5 else q_(q) | |
| out["seconds"] = time.time() - t0 | |
| out["naive"] = seasonal_naive(np.nan_to_num(values, nan=np.nanmean(values[start:end])), end, horizon, p.season) | |
| if backtest: | |
| out["actual"] = values[end:end + horizon] | |
| if importances: | |
| imp = reg.feature_importances(Xte) | |
| groups: dict[str, float] = {} | |
| for nm, v in zip(names, imp): | |
| label = lag_label(nm, p) if nm.startswith("lag") else FEATURE_NAMES[nm] | |
| groups[label] = groups.get(label, 0.0) + float(v) | |
| out["importances"] = dict(sorted(groups.items(), key=lambda kv: -kv[1])) | |
| return out | |
| def scores(out: dict) -> dict | None: | |
| if "actual" not in out: | |
| return None | |
| a = out["actual"] | |
| ok = ~np.isnan(a) | |
| if not ok.any(): | |
| return None | |
| mae = lambda f: float(np.mean(np.abs(f[ok] - a[ok]))) | |
| cover = float(np.mean((a[ok] >= out[0.1][ok]) & (a[ok] <= out[0.9][ok]))) | |
| return {"tabum": mae(out["median"]), "naive": mae(out["naive"]), "coverage": cover, | |
| "wape": mae(out["median"]) / max(float(np.mean(np.abs(a[ok]))), 1e-9)} | |