event-forecast 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- event_forecast/__init__.py +37 -0
- event_forecast/_features.py +133 -0
- event_forecast/baselines.py +125 -0
- event_forecast/catboost_model.py +179 -0
- event_forecast/cli.py +52 -0
- event_forecast/comparison.py +70 -0
- event_forecast/coverage.py +98 -0
- event_forecast/errors.py +13 -0
- event_forecast/io.py +123 -0
- event_forecast/model.py +47 -0
- event_forecast/output.py +16 -0
- event_forecast/panel.py +106 -0
- event_forecast/py.typed +0 -0
- event_forecast/selection.py +202 -0
- event_forecast/validation.py +256 -0
- event_forecast-0.1.1.dist-info/METADATA +148 -0
- event_forecast-0.1.1.dist-info/RECORD +21 -0
- event_forecast-0.1.1.dist-info/WHEEL +5 -0
- event_forecast-0.1.1.dist-info/entry_points.txt +2 -0
- event_forecast-0.1.1.dist-info/licenses/LICENSE +21 -0
- event_forecast-0.1.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Daily event forecasting with explicit coverage and causal information delays."""
|
|
2
|
+
|
|
3
|
+
from .coverage import CoverageSpec
|
|
4
|
+
from .errors import ModelingError, OptionalDependencyError, ValidationError
|
|
5
|
+
from .panel import prepare_daily_panel
|
|
6
|
+
from .baselines import LastMatchingWeekday, MeanMatchingWeekdays, RollingLevelMean
|
|
7
|
+
from .model import Model, data_through_date
|
|
8
|
+
from .output import integer_counts, ROUNDING_POLICY
|
|
9
|
+
from .validation import Candidate, FoldPlan, EvaluationResult, chronological_folds, evaluate
|
|
10
|
+
from .selection import Selection, HoldoutReport, select, holdout_report
|
|
11
|
+
from .comparison import paired_mae_interval
|
|
12
|
+
from .catboost_model import CatBoostConfig, CatBoostCountModel
|
|
13
|
+
|
|
14
|
+
__version__ = "0.1.1"
|
|
15
|
+
__all__ = ["CoverageSpec", "prepare_daily_panel", "ValidationError", "ModelingError", "OptionalDependencyError"]
|
|
16
|
+
__all__ += [
|
|
17
|
+
"LastMatchingWeekday",
|
|
18
|
+
"MeanMatchingWeekdays",
|
|
19
|
+
"RollingLevelMean",
|
|
20
|
+
"Model",
|
|
21
|
+
"data_through_date",
|
|
22
|
+
"integer_counts",
|
|
23
|
+
"ROUNDING_POLICY",
|
|
24
|
+
]
|
|
25
|
+
__all__ += [
|
|
26
|
+
"Candidate",
|
|
27
|
+
"FoldPlan",
|
|
28
|
+
"EvaluationResult",
|
|
29
|
+
"chronological_folds",
|
|
30
|
+
"evaluate",
|
|
31
|
+
"Selection",
|
|
32
|
+
"HoldoutReport",
|
|
33
|
+
"select",
|
|
34
|
+
"holdout_report",
|
|
35
|
+
]
|
|
36
|
+
__all__ += ["paired_mae_interval"]
|
|
37
|
+
__all__ += ["CatBoostConfig", "CatBoostCountModel"]
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Causal feature calculations preserved from the v1.1.1 archive."""
|
|
2
|
+
|
|
3
|
+
from datetime import timedelta
|
|
4
|
+
from functools import lru_cache
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
from pandas.tseries.holiday import USFederalHolidayCalendar
|
|
9
|
+
|
|
10
|
+
from datetime import date
|
|
11
|
+
from .coverage import as_date
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def day(value):
|
|
15
|
+
return value if isinstance(value, date) else as_date(value)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
GROUP = ["area", "category"]
|
|
19
|
+
CATEGORICAL = GROUP + ["series_id", "weekday_category"]
|
|
20
|
+
LAGS = (7, 14, 21, 28)
|
|
21
|
+
WINDOWS = (7, 28)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@lru_cache(maxsize=32)
|
|
25
|
+
def holidays(year):
|
|
26
|
+
return set(USFederalHolidayCalendar().holidays(f"{year - 1}-01-01", f"{year + 1}-12-31").date)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def calendar(date_value, holiday_calendar="none"):
|
|
30
|
+
value = day(date_value)
|
|
31
|
+
if holiday_calendar not in ("us_federal", "none"):
|
|
32
|
+
raise ValueError("Unknown holiday calendar")
|
|
33
|
+
known = holidays(value.year) if holiday_calendar == "us_federal" else set()
|
|
34
|
+
phase = 2 * np.pi * (value.timetuple().tm_yday - 1) / 365.25
|
|
35
|
+
return {
|
|
36
|
+
"dow": value.weekday(),
|
|
37
|
+
"weekend": int(value.weekday() >= 5),
|
|
38
|
+
"month": value.month,
|
|
39
|
+
"year_sin": np.sin(phase),
|
|
40
|
+
"year_cos": np.cos(phase),
|
|
41
|
+
"federal_holiday": int(value in known),
|
|
42
|
+
"before_holiday": int(value + timedelta(days=1) in known),
|
|
43
|
+
"after_holiday": int(value - timedelta(days=1) in known),
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class FeatureEngineer:
|
|
48
|
+
def __init__(self, config, groups):
|
|
49
|
+
self.cfg, self.groups = config, groups
|
|
50
|
+
|
|
51
|
+
def for_date(self, panel, target_date, data_through_date):
|
|
52
|
+
target, through = day(target_date), day(data_through_date)
|
|
53
|
+
available = panel[(panel.date <= through.isoformat()) & (panel.date < target.isoformat())]
|
|
54
|
+
output = []
|
|
55
|
+
grouped = {key: value.sort_values("date") for key, value in available.groupby(GROUP, sort=False)}
|
|
56
|
+
for area, cat in self.groups:
|
|
57
|
+
series = grouped.get((area, cat), pd.DataFrame(columns=["date", "count"]))
|
|
58
|
+
values = {r.date: float(r.count) for r in series.itertuples() if pd.notna(r.count)}
|
|
59
|
+
row = {
|
|
60
|
+
"date": target.isoformat(),
|
|
61
|
+
"area": area,
|
|
62
|
+
"category": cat,
|
|
63
|
+
**calendar(target, self.cfg.holiday_calendar),
|
|
64
|
+
}
|
|
65
|
+
for lag in LAGS:
|
|
66
|
+
row[f"lag_{lag}"] = values.get((target - timedelta(days=lag)).isoformat(), np.nan)
|
|
67
|
+
for lag in (0, 1, 2, 6):
|
|
68
|
+
row[f"cutoff_lag_{lag}"] = values.get((through - timedelta(days=lag)).isoformat(), np.nan)
|
|
69
|
+
for window in WINDOWS:
|
|
70
|
+
recent = np.asarray(
|
|
71
|
+
[values.get((through - timedelta(days=i)).isoformat(), np.nan) for i in range(window)]
|
|
72
|
+
)
|
|
73
|
+
finite = recent[np.isfinite(recent)]
|
|
74
|
+
row[f"available_{window}"] = len(finite)
|
|
75
|
+
row[f"rolling_mean_{window}"] = float(np.mean(finite)) if len(finite) else np.nan
|
|
76
|
+
row[f"rolling_std_{window}"] = float(np.std(finite)) if len(finite) else np.nan
|
|
77
|
+
earlier = np.asarray([values.get((through - timedelta(days=i)).isoformat(), np.nan) for i in range(7, 14)])
|
|
78
|
+
earlier = earlier[np.isfinite(earlier)]
|
|
79
|
+
row["weekly_trend"] = row["rolling_mean_7"] - float(np.mean(earlier)) if len(earlier) else np.nan
|
|
80
|
+
same = [y for d, y in values.items() if day(d).weekday() == target.weekday()][-4:]
|
|
81
|
+
row["same_weekday_mean"] = float(np.mean(same)) if same else np.nan
|
|
82
|
+
row["history_days"] = len(values)
|
|
83
|
+
row["last_available_count"] = next(reversed(values.values())) if values else np.nan
|
|
84
|
+
row["effective_horizon"] = (target - through).days
|
|
85
|
+
row["data_staleness"] = (target - through).days - 1
|
|
86
|
+
if self.cfg.feature_schema == "v3":
|
|
87
|
+
same8 = [y for d, y in values.items() if day(d).weekday() == target.weekday()][-8:]
|
|
88
|
+
same4 = same8[-4:]
|
|
89
|
+
row.update(series_id=area + "|" + cat, weekday_category=str(target.weekday()))
|
|
90
|
+
for name, value in (
|
|
91
|
+
("same_weekday_median4", np.median(same4) if same4 else np.nan),
|
|
92
|
+
("same_weekday_mean8", np.mean(same8) if same8 else np.nan),
|
|
93
|
+
("same_weekday_std4", np.std(same4) if same4 else np.nan),
|
|
94
|
+
):
|
|
95
|
+
row[name] = float(value)
|
|
96
|
+
row["same_weekday_trend"] = (
|
|
97
|
+
(np.mean(same4[-2:]) - np.mean(same4[:2])) / (row["same_weekday_mean"] + 1)
|
|
98
|
+
if len(same4) == 4
|
|
99
|
+
else np.nan
|
|
100
|
+
)
|
|
101
|
+
row["level_ratio_7_28"] = (row["rolling_mean_7"] + 1) / (row["rolling_mean_28"] + 1)
|
|
102
|
+
|
|
103
|
+
ratios = []
|
|
104
|
+
for i in range(14):
|
|
105
|
+
recent_day = through - timedelta(days=i)
|
|
106
|
+
actual = values.get(recent_day.isoformat())
|
|
107
|
+
past = [values.get((recent_day - timedelta(days=7 * j)).isoformat()) for j in range(1, 5)]
|
|
108
|
+
past = [v for v in past if v is not None]
|
|
109
|
+
ratios.append(
|
|
110
|
+
(actual + 1) / (np.mean(past) + 1) if actual is not None and len(past) >= 2 else np.nan
|
|
111
|
+
)
|
|
112
|
+
for window in (7, 14):
|
|
113
|
+
valid = np.asarray(ratios[:window])
|
|
114
|
+
valid = valid[np.isfinite(valid)]
|
|
115
|
+
row[f"weekday_adjusted_ratio_{window}"] = float(np.mean(valid)) if len(valid) else np.nan
|
|
116
|
+
output.append(row)
|
|
117
|
+
return pd.DataFrame(output)
|
|
118
|
+
|
|
119
|
+
def training_frame(self, panel):
|
|
120
|
+
outputs = []
|
|
121
|
+
for target in sorted(panel.date.unique()):
|
|
122
|
+
through = day(target) - timedelta(days=self.cfg.lag_days + 1)
|
|
123
|
+
rows = self.for_date(panel, target, through)
|
|
124
|
+
labels = panel[panel.date == target][["date", *GROUP, "count"]]
|
|
125
|
+
outputs.append(rows.merge(labels, on=["date", *GROUP], validate="one_to_one"))
|
|
126
|
+
return pd.concat(outputs, ignore_index=True) if outputs else pd.DataFrame()
|
|
127
|
+
|
|
128
|
+
@staticmethod
|
|
129
|
+
def matrix(frame):
|
|
130
|
+
result = frame.drop(columns=["date", "count"], errors="ignore").copy()
|
|
131
|
+
for name in result:
|
|
132
|
+
result[name] = result[name].astype(str) if name in CATEGORICAL else result[name].astype("float32")
|
|
133
|
+
return result
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Causal seasonal and level baselines extracted from the archived implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import timedelta
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
from .coverage import as_date
|
|
12
|
+
from .errors import ModelingError
|
|
13
|
+
from .model import check_cutoff, nonnegative_int
|
|
14
|
+
from .panel import validate_panel
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MeanMatchingWeekdays:
|
|
18
|
+
"""Mean of up to n available matching weekdays through the declared cutoff."""
|
|
19
|
+
|
|
20
|
+
is_baseline = True
|
|
21
|
+
|
|
22
|
+
def __init__(self, n: int = 4, *, lag_days: int = 2) -> None:
|
|
23
|
+
self.n = nonnegative_int(n, "n", 1)
|
|
24
|
+
self.lag_days = nonnegative_int(lag_days, "lag_days")
|
|
25
|
+
self.groups: tuple[tuple[str, str], ...] = ()
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def name(self) -> str:
|
|
29
|
+
"""Stable candidate identifier."""
|
|
30
|
+
return f"weekday_mean{self.n}"
|
|
31
|
+
|
|
32
|
+
def parameters(self) -> dict[str, Any]:
|
|
33
|
+
"""Return the serializable forecast definition, excluding fitted state."""
|
|
34
|
+
return dict(n=self.n, lag_days=self.lag_days)
|
|
35
|
+
|
|
36
|
+
def fit(self, panel: pd.DataFrame) -> MeanMatchingWeekdays:
|
|
37
|
+
"""Validate the panel and retain its declared group order."""
|
|
38
|
+
self.groups = validate_panel(panel)
|
|
39
|
+
return self
|
|
40
|
+
|
|
41
|
+
def predict(self, panel: pd.DataFrame, target_date: str, data_through_date: str) -> np.ndarray:
|
|
42
|
+
"""Forecast without reading any counts after the declared cutoff."""
|
|
43
|
+
check_cutoff(target_date, data_through_date, self.lag_days)
|
|
44
|
+
if not self.groups:
|
|
45
|
+
raise ModelingError("Fit the model before prediction")
|
|
46
|
+
history = panel[(panel.date <= data_through_date) & (panel.date < target_date)]
|
|
47
|
+
if validate_panel(history) != self.groups:
|
|
48
|
+
raise ModelingError("Prediction group order differs from fitted group order")
|
|
49
|
+
result = []
|
|
50
|
+
for area, category in self.groups:
|
|
51
|
+
series = (
|
|
52
|
+
history[(history.area == area) & (history.category == category)]
|
|
53
|
+
.dropna(subset=["count"])
|
|
54
|
+
.sort_values("date")
|
|
55
|
+
)
|
|
56
|
+
same = series[series.date.map(lambda x: as_date(x).weekday() == as_date(target_date).weekday())]
|
|
57
|
+
if same.empty:
|
|
58
|
+
raise ModelingError(f"No available same-weekday history for {area}/{category}")
|
|
59
|
+
result.append(float(np.mean(same["count"].tail(self.n))))
|
|
60
|
+
return np.asarray(result)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class LastMatchingWeekday(MeanMatchingWeekdays):
|
|
64
|
+
"""Last available matching weekday through the declared cutoff."""
|
|
65
|
+
|
|
66
|
+
def __init__(self, *, lag_days: int = 2) -> None:
|
|
67
|
+
super().__init__(1, lag_days=lag_days)
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def name(self) -> str:
|
|
71
|
+
"""Stable archived candidate identifier."""
|
|
72
|
+
return "seasonal_naive"
|
|
73
|
+
|
|
74
|
+
def parameters(self) -> dict[str, Any]:
|
|
75
|
+
"""Return the serializable forecast definition."""
|
|
76
|
+
return dict(lag_days=self.lag_days)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class RollingLevelMean:
|
|
80
|
+
"""Mean of an exact consecutive complete window ending at the cutoff."""
|
|
81
|
+
|
|
82
|
+
is_baseline = True
|
|
83
|
+
|
|
84
|
+
def __init__(self, days: int = 28, *, lag_days: int = 2) -> None:
|
|
85
|
+
self.days = nonnegative_int(days, "days", 1)
|
|
86
|
+
self.lag_days = nonnegative_int(lag_days, "lag_days")
|
|
87
|
+
self.groups: tuple[tuple[str, str], ...] = ()
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def name(self) -> str:
|
|
91
|
+
"""Stable candidate identifier."""
|
|
92
|
+
return f"rolling_mean{self.days}"
|
|
93
|
+
|
|
94
|
+
def parameters(self) -> dict[str, Any]:
|
|
95
|
+
"""Return the serializable forecast definition."""
|
|
96
|
+
return dict(days=self.days, lag_days=self.lag_days)
|
|
97
|
+
|
|
98
|
+
def fit(self, panel: pd.DataFrame) -> RollingLevelMean:
|
|
99
|
+
"""Validate the panel and retain its group order."""
|
|
100
|
+
self.groups = validate_panel(panel)
|
|
101
|
+
return self
|
|
102
|
+
|
|
103
|
+
def predict(self, panel: pd.DataFrame, target_date: str, data_through_date: str) -> np.ndarray:
|
|
104
|
+
"""Require every date in the window; never skip missing labels."""
|
|
105
|
+
check_cutoff(target_date, data_through_date, self.lag_days)
|
|
106
|
+
if not self.groups:
|
|
107
|
+
raise ModelingError("Fit the model before prediction")
|
|
108
|
+
cutoff = as_date(data_through_date)
|
|
109
|
+
expected = {(cutoff - timedelta(days=i)).isoformat() for i in range(self.days)}
|
|
110
|
+
history = panel[panel.date.isin(expected)]
|
|
111
|
+
if validate_panel(history) != self.groups:
|
|
112
|
+
raise ModelingError("Prediction group order differs from fitted group order")
|
|
113
|
+
result = []
|
|
114
|
+
for area, category in self.groups:
|
|
115
|
+
series = history[(history.area == area) & (history.category == category)]
|
|
116
|
+
values = series["count"].to_numpy(dtype=float)
|
|
117
|
+
if (
|
|
118
|
+
len(series) != self.days
|
|
119
|
+
or set(series.date) != expected
|
|
120
|
+
or not np.isfinite(values).all()
|
|
121
|
+
or (values < 0).any()
|
|
122
|
+
):
|
|
123
|
+
raise ModelingError(f"A complete {self.days} day window is required for {area}/{category}")
|
|
124
|
+
result.append(float(np.mean(values)))
|
|
125
|
+
return np.asarray(result)
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Optional CatBoost count model; importing this module does not import CatBoost."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
from ._features import FeatureEngineer, GROUP, CATEGORICAL
|
|
12
|
+
from .errors import ModelingError, OptionalDependencyError, ValidationError
|
|
13
|
+
from .model import check_cutoff, nonnegative_int
|
|
14
|
+
from .panel import validate_panel
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _catboost():
|
|
18
|
+
try:
|
|
19
|
+
from catboost import CatBoostRegressor, Pool
|
|
20
|
+
except ImportError as exc:
|
|
21
|
+
raise OptionalDependencyError('This candidate requires CatBoost. Install "event-forecast[catboost]".') from exc
|
|
22
|
+
|
|
23
|
+
class CPUCountRegressor(CatBoostRegressor):
|
|
24
|
+
def get_feature_importance(self, *args, **kwargs):
|
|
25
|
+
kwargs.setdefault("thread_count", self.get_param("thread_count"))
|
|
26
|
+
return super().get_feature_importance(*args, **kwargs)
|
|
27
|
+
|
|
28
|
+
return CPUCountRegressor, Pool
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True, slots=True)
|
|
32
|
+
class CatBoostConfig:
|
|
33
|
+
"""Fixed CPU model settings; defaults match the archived GitHub experiment.
|
|
34
|
+
|
|
35
|
+
Holidays are disabled by default. Choose us_federal explicitly to enable
|
|
36
|
+
the original holiday indicators. lag_days must match the evaluation plan.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
lag_days: int = 2
|
|
40
|
+
iterations: int = 100
|
|
41
|
+
depth: int = 4
|
|
42
|
+
learning_rate: float = 0.05
|
|
43
|
+
l2_leaf_reg: float = 10.0
|
|
44
|
+
loss: str = "MAE"
|
|
45
|
+
feature_set: str = "seasonal"
|
|
46
|
+
offset: bool = True
|
|
47
|
+
min_feature_history_days: int = 28
|
|
48
|
+
feature_schema: str = "v3"
|
|
49
|
+
holiday_calendar: str = "none"
|
|
50
|
+
seed: int = 42
|
|
51
|
+
thread_count: int = 1
|
|
52
|
+
|
|
53
|
+
def __post_init__(self) -> None:
|
|
54
|
+
for name in ("iterations", "depth", "min_feature_history_days", "thread_count"):
|
|
55
|
+
nonnegative_int(getattr(self, name), name, 1)
|
|
56
|
+
nonnegative_int(self.lag_days, "lag_days")
|
|
57
|
+
nonnegative_int(self.seed, "seed")
|
|
58
|
+
if (
|
|
59
|
+
self.depth > 10
|
|
60
|
+
or not 0 < self.learning_rate <= 1
|
|
61
|
+
or not np.isfinite(self.l2_leaf_reg)
|
|
62
|
+
or self.l2_leaf_reg < 0
|
|
63
|
+
):
|
|
64
|
+
raise ValidationError("Invalid CatBoost depth, learning rate or regularization")
|
|
65
|
+
if (
|
|
66
|
+
self.loss not in ("MAE", "Poisson")
|
|
67
|
+
or self.feature_set not in ("legacy", "stationary", "seasonal")
|
|
68
|
+
or type(self.offset) is not bool
|
|
69
|
+
):
|
|
70
|
+
raise ValidationError("Invalid CatBoost loss, feature set or offset policy")
|
|
71
|
+
if self.feature_schema not in ("v2", "v3") or self.holiday_calendar not in ("none", "us_federal"):
|
|
72
|
+
raise ValidationError("Unknown feature schema or holiday calendar")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class CatBoostCountModel:
|
|
76
|
+
"""One shared causal count regressor across all declared area/category groups."""
|
|
77
|
+
|
|
78
|
+
is_baseline = False
|
|
79
|
+
|
|
80
|
+
def __init__(self, config: CatBoostConfig | None = None) -> None:
|
|
81
|
+
self.config = config or CatBoostConfig()
|
|
82
|
+
self.groups: tuple[tuple[str, str], ...] = ()
|
|
83
|
+
self.fitted_through: str | None = None
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def name(self) -> str:
|
|
87
|
+
"""Stable archived candidate identifier."""
|
|
88
|
+
return "catboost_" + self.config.loss.lower()
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def lag_days(self) -> int:
|
|
92
|
+
"""Availability delay used in historical feature construction and prediction."""
|
|
93
|
+
return self.config.lag_days
|
|
94
|
+
|
|
95
|
+
def parameters(self) -> dict[str, Any]:
|
|
96
|
+
"""Return the complete serializable model definition."""
|
|
97
|
+
return asdict(self.config)
|
|
98
|
+
|
|
99
|
+
def _matrix(self, frame: pd.DataFrame) -> pd.DataFrame:
|
|
100
|
+
matrix = self.fe.matrix(frame)
|
|
101
|
+
if self.config.feature_set != "legacy":
|
|
102
|
+
matrix = matrix.drop(columns=["month", "year_sin", "year_cos", "history_days"])
|
|
103
|
+
return matrix
|
|
104
|
+
|
|
105
|
+
def _offset(self, frame: pd.DataFrame) -> np.ndarray:
|
|
106
|
+
if not self.config.offset:
|
|
107
|
+
return np.zeros(len(frame))
|
|
108
|
+
level = frame.same_weekday_mean.to_numpy(dtype=float)
|
|
109
|
+
if not np.isfinite(level).all():
|
|
110
|
+
raise ModelingError("Count offset requires available weekday history")
|
|
111
|
+
return np.log(np.maximum(level, 0.1)) if self.config.loss == "Poisson" else level
|
|
112
|
+
|
|
113
|
+
def fit(self, panel: pd.DataFrame) -> CatBoostCountModel:
|
|
114
|
+
"""Fit admitted labels with causal features using the configured lag."""
|
|
115
|
+
Regressor, Pool = _catboost()
|
|
116
|
+
self.groups = validate_panel(panel)
|
|
117
|
+
self.fe = FeatureEngineer(self.config, self.groups)
|
|
118
|
+
frame = self.fe.training_frame(panel)
|
|
119
|
+
frame = frame[(frame.history_days >= self.config.min_feature_history_days) & frame["count"].notna()]
|
|
120
|
+
frame = frame.sort_values(["date", *GROUP]).reset_index(drop=True)
|
|
121
|
+
if frame.empty:
|
|
122
|
+
raise ModelingError("Insufficient count-model training labels")
|
|
123
|
+
self.training_rows = len(frame)
|
|
124
|
+
self.fitted_through = str(frame.date.max())
|
|
125
|
+
self.columns = list(self._matrix(frame).columns)
|
|
126
|
+
self.all_zero = bool((frame["count"] == 0).all())
|
|
127
|
+
if not self.all_zero:
|
|
128
|
+
cfg = self.config
|
|
129
|
+
self.model = Regressor(
|
|
130
|
+
loss_function=cfg.loss,
|
|
131
|
+
iterations=cfg.iterations,
|
|
132
|
+
depth=cfg.depth,
|
|
133
|
+
learning_rate=cfg.learning_rate,
|
|
134
|
+
l2_leaf_reg=cfg.l2_leaf_reg,
|
|
135
|
+
thread_count=cfg.thread_count,
|
|
136
|
+
random_seed=cfg.seed,
|
|
137
|
+
task_type="CPU",
|
|
138
|
+
has_time=True,
|
|
139
|
+
allow_writing_files=False,
|
|
140
|
+
verbose=False,
|
|
141
|
+
allow_const_label=True,
|
|
142
|
+
**({"boost_from_average": False} if cfg.offset else {}),
|
|
143
|
+
)
|
|
144
|
+
pool = Pool(
|
|
145
|
+
self._matrix(frame),
|
|
146
|
+
frame["count"].to_numpy(dtype=float),
|
|
147
|
+
cat_features=[c for c in CATEGORICAL if c in self.columns],
|
|
148
|
+
baseline=self._offset(frame) if cfg.offset else None,
|
|
149
|
+
thread_count=cfg.thread_count,
|
|
150
|
+
)
|
|
151
|
+
self.model.fit(pool)
|
|
152
|
+
self.feature_importance = dict(zip(self.columns, self.model.feature_importances_.tolist(), strict=True))
|
|
153
|
+
else:
|
|
154
|
+
self.feature_importance = {}
|
|
155
|
+
return self
|
|
156
|
+
|
|
157
|
+
def predict(self, panel: pd.DataFrame, target_date: str, data_through_date: str) -> np.ndarray:
|
|
158
|
+
"""Predict at the declared cutoff, rejecting weights trained beyond it."""
|
|
159
|
+
check_cutoff(target_date, data_through_date, self.lag_days)
|
|
160
|
+
if not self.fitted_through:
|
|
161
|
+
raise ModelingError("Fit or load a model before prediction")
|
|
162
|
+
if self.fitted_through > data_through_date:
|
|
163
|
+
raise ValidationError("Model was fitted on labels after the requested data_through_date")
|
|
164
|
+
available = panel[panel.date <= data_through_date]
|
|
165
|
+
if validate_panel(available) != self.groups:
|
|
166
|
+
raise ValidationError("Prediction group order differs from fitted group order")
|
|
167
|
+
frame = self.fe.for_date(available, target_date, data_through_date)
|
|
168
|
+
if self.all_zero:
|
|
169
|
+
return np.zeros(len(frame))
|
|
170
|
+
matrix = self._matrix(frame)[self.columns]
|
|
171
|
+
margin = np.asarray(
|
|
172
|
+
self.model.predict(matrix, prediction_type="RawFormulaVal", thread_count=self.config.thread_count),
|
|
173
|
+
dtype=float,
|
|
174
|
+
)
|
|
175
|
+
margin += self._offset(frame)
|
|
176
|
+
result = np.exp(margin) if self.config.loss == "Poisson" else np.maximum(margin, 0)
|
|
177
|
+
if not np.isfinite(result).all() or (result < 0).any():
|
|
178
|
+
raise ModelingError("Invalid count prediction scale")
|
|
179
|
+
return result
|
event_forecast/cli.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Optional local-file experiment command; no network or repository assumptions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Sequence
|
|
9
|
+
|
|
10
|
+
from . import (
|
|
11
|
+
CatBoostCountModel,
|
|
12
|
+
LastMatchingWeekday,
|
|
13
|
+
MeanMatchingWeekdays,
|
|
14
|
+
RollingLevelMean,
|
|
15
|
+
chronological_folds,
|
|
16
|
+
evaluate,
|
|
17
|
+
holdout_report,
|
|
18
|
+
prepare_daily_panel,
|
|
19
|
+
select,
|
|
20
|
+
)
|
|
21
|
+
from .io import read_coverage, read_events, save_model, write_json
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
25
|
+
"""Run the bundled experiment policy on caller-provided local input files."""
|
|
26
|
+
parser = argparse.ArgumentParser(prog="event-forecast")
|
|
27
|
+
subcommands = parser.add_subparsers(dest="command", required=True)
|
|
28
|
+
run = subcommands.add_parser("run", help="Validate, freeze selection, then score holdout")
|
|
29
|
+
run.add_argument("--events", type=Path, required=True)
|
|
30
|
+
run.add_argument("--coverage", type=Path, required=True)
|
|
31
|
+
run.add_argument("--output", type=Path, required=True)
|
|
32
|
+
run.add_argument("--catboost", action="store_true", help="Include the optional fixed MAE challenger")
|
|
33
|
+
args = parser.parse_args(argv)
|
|
34
|
+
panel = prepare_daily_panel(read_events(args.events), read_coverage(args.coverage))
|
|
35
|
+
plan = chronological_folds(panel)
|
|
36
|
+
candidates = [LastMatchingWeekday, MeanMatchingWeekdays, RollingLevelMean]
|
|
37
|
+
if args.catboost:
|
|
38
|
+
candidates.append(CatBoostCountModel)
|
|
39
|
+
results = [evaluate(candidate, panel, plan) for candidate in candidates]
|
|
40
|
+
selection = select(results)
|
|
41
|
+
args.output.mkdir(parents=True, exist_ok=False)
|
|
42
|
+
# Persist the decision before the first holdout score is computed.
|
|
43
|
+
write_json(args.output / "selection.json", json.loads(selection.to_json()))
|
|
44
|
+
write_json(args.output / "validation.json", [result.to_dict() for result in results])
|
|
45
|
+
report = holdout_report(selection, panel, candidates)
|
|
46
|
+
write_json(args.output / "holdout.json", report.to_dict())
|
|
47
|
+
for result in report.comparisons:
|
|
48
|
+
result.predictions.to_csv(args.output / f"{result.definition.name}_holdout.csv", index=False)
|
|
49
|
+
chosen = next(candidate for candidate in candidates if candidate().name == selection.selected_model)
|
|
50
|
+
save_model(chosen().fit(panel), args.output / "model")
|
|
51
|
+
print(f"Selected {selection.selected_model}; holdout MAE {report.selected.metrics.mae:.6f}")
|
|
52
|
+
return 0
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Paired circular date-block bootstrap of matched MAE differences."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
from .errors import ValidationError
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def paired_mae_interval(
|
|
11
|
+
candidate: pd.DataFrame, reference: pd.DataFrame, block_days: int = 7, repeats: int = 10000, seed: int = 42
|
|
12
|
+
) -> dict[str, Any]:
|
|
13
|
+
"""Resample complete date blocks jointly across groups, candidate minus reference.
|
|
14
|
+
|
|
15
|
+
The percentile interval is conditional on the fixed compared forecasts; it
|
|
16
|
+
does not correct retrospective candidate selection or nonstationarity.
|
|
17
|
+
"""
|
|
18
|
+
keys = ["date", "area", "category"]
|
|
19
|
+
frames = []
|
|
20
|
+
for frame in [candidate, reference]:
|
|
21
|
+
if not set([*keys, "y_true", "y_pred"]).issubset(frame.columns) or frame[keys].isna().any().any():
|
|
22
|
+
raise ValidationError("Matched prediction records are required")
|
|
23
|
+
if frame.duplicated(keys).any():
|
|
24
|
+
raise ValidationError("Duplicate group and date")
|
|
25
|
+
values = frame[["y_true", "y_pred"]].to_numpy(dtype=float)
|
|
26
|
+
if not np.isfinite(values).all() or (values < 0).any():
|
|
27
|
+
raise ValidationError("Finite nonnegative observations and predictions are required")
|
|
28
|
+
frames.append(frame.set_index(keys).sort_index())
|
|
29
|
+
left, right = frames
|
|
30
|
+
if not left.index.equals(right.index) or not np.array_equal(left.y_true, right.y_true):
|
|
31
|
+
raise ValidationError("Candidates must have identical observation keys and values")
|
|
32
|
+
# Python integer arithmetic avoids unsigned wrap and float precision loss.
|
|
33
|
+
left_error = (left.y_pred.astype(object) - left.y_true.astype(object)).abs()
|
|
34
|
+
right_error = (right.y_pred.astype(object) - right.y_true.astype(object)).abs()
|
|
35
|
+
error = (left_error - right_error).astype(float)
|
|
36
|
+
daily = error.groupby(level="date").mean()
|
|
37
|
+
counts = error.groupby(level="date").size()
|
|
38
|
+
groups = len(error.index.droplevel("date").unique())
|
|
39
|
+
dates = pd.to_datetime(daily.index)
|
|
40
|
+
n = len(daily)
|
|
41
|
+
if n < 2 or not (counts == groups).all() or not dates.equals(pd.date_range(dates.min(), dates.max())):
|
|
42
|
+
raise ValidationError("Consecutive dates and the same groups on every date are required")
|
|
43
|
+
if type(block_days) is not int or not 1 <= block_days <= n // 2 or type(repeats) is not int or repeats < 100:
|
|
44
|
+
raise ValidationError("Use at least two blocks and at least 100 bootstrap replicates")
|
|
45
|
+
rng = np.random.default_rng(seed)
|
|
46
|
+
starts = rng.integers(0, n, size=(repeats, (n + block_days - 1) // block_days))
|
|
47
|
+
indices = ((starts[:, :, None] + np.arange(block_days)) % n).reshape(repeats, -1)[:, :n]
|
|
48
|
+
draws = daily.to_numpy()[indices].mean(axis=1)
|
|
49
|
+
return {
|
|
50
|
+
"method": "paired_circular_date_block_percentile_bootstrap",
|
|
51
|
+
"difference_order": "candidate_minus_reference",
|
|
52
|
+
"difference_mae": float(daily.mean()),
|
|
53
|
+
"interval_95": np.quantile(draws, [0.025, 0.975]).tolist(),
|
|
54
|
+
"block_days": block_days,
|
|
55
|
+
"repeats": repeats,
|
|
56
|
+
"seed": seed,
|
|
57
|
+
"days": n,
|
|
58
|
+
"groups": groups,
|
|
59
|
+
"nonoverlapping_blocks": n // block_days,
|
|
60
|
+
"blocks_per_resample": starts.shape[1],
|
|
61
|
+
"unique_bootstrap_differences": int(np.unique(np.round(draws, 12)).size),
|
|
62
|
+
"unique_difference_decimal_places": 12,
|
|
63
|
+
"daily_differences": [{"date": str(date), "difference": float(value)} for date, value in daily.items()],
|
|
64
|
+
"limitations": [
|
|
65
|
+
"Conditional on the recorded forecasts and fixed comparison",
|
|
66
|
+
"Does not account for model search or repair retrospective selection bias",
|
|
67
|
+
"Short periods and nonstationarity limit interval reliability",
|
|
68
|
+
"All groups are resampled together within each date block",
|
|
69
|
+
],
|
|
70
|
+
}
|