futureish 0.1.0__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.
- futureish/__init__.py +13 -0
- futureish/_internal/__init__.py +1 -0
- futureish/_internal/constants.py +7 -0
- futureish/_internal/dummy.py +30 -0
- futureish/_internal/repr.py +257 -0
- futureish/catboost/__init__.py +12 -0
- futureish/catboost/model.py +141 -0
- futureish/datapoints/__init__.py +5 -0
- futureish/datapoints/base.py +24 -0
- futureish/datapoints/recorded.py +23 -0
- futureish/datapoints/time.py +12 -0
- futureish/datasets/__init__.py +19 -0
- futureish/datasets/base.py +322 -0
- futureish/datasets/config.py +394 -0
- futureish/datasets/dataset.py +69 -0
- futureish/datasets/forecast.py +109 -0
- futureish/datasets/online.py +73 -0
- futureish/datasets/online_training.py +69 -0
- futureish/datasets/predict.py +118 -0
- futureish/datasets/test.py +21 -0
- futureish/datasets/train.py +32 -0
- futureish/features/__init__.py +19 -0
- futureish/features/base.py +95 -0
- futureish/features/bucket.py +154 -0
- futureish/features/businessday.py +56 -0
- futureish/features/input_base.py +130 -0
- futureish/features/modular.py +91 -0
- futureish/features/recorded.py +86 -0
- futureish/features/recorded_base.py +68 -0
- futureish/features/sincos_time.py +93 -0
- futureish/features/sparse.py +95 -0
- futureish/features/target.py +78 -0
- futureish/forecasting/__init__.py +6 -0
- futureish/forecasting/forecaster.py +126 -0
- futureish/forecasting/inference.py +389 -0
- futureish/gpr/__init__.py +22 -0
- futureish/gpr/gpytorch/__init__.py +15 -0
- futureish/gpr/gpytorch/backends/__init__.py +4 -0
- futureish/gpr/gpytorch/backends/gpytorch_model.py +136 -0
- futureish/gpr/gpytorch/backends/gpytorch_sgp.py +52 -0
- futureish/gpr/gpytorch/backends/gpytorch_vgp.py +46 -0
- futureish/gpr/gpytorch/backends/online_pep/__init__.py +5 -0
- futureish/gpr/gpytorch/backends/online_pep/gpytorch_online_pep.py +113 -0
- futureish/gpr/gpytorch/backends/online_pep/osgpr_pep.py +276 -0
- futureish/gpr/gpytorch/backends/online_pep/pep_compute_base.py +171 -0
- futureish/gpr/gpytorch/backends/online_pep/sgpr_pep.py +107 -0
- futureish/gpr/gpytorch/gpytorch_model_trainer.py +242 -0
- futureish/modeling/__init__.py +7 -0
- futureish/modeling/base.py +153 -0
- futureish/modeling/config.py +21 -0
- futureish/scaling/__init__.py +13 -0
- futureish/scaling/base.py +38 -0
- futureish/scaling/chained.py +142 -0
- futureish/scaling/data.py +54 -0
- futureish/scaling/difference.py +37 -0
- futureish/scaling/noop.py +35 -0
- futureish/scaling/z_score.py +35 -0
- futureish/utils/__init__.py +8 -0
- futureish/utils/polars.py +246 -0
- futureish/utils/timedelta.py +285 -0
- futureish-0.1.0.dist-info/METADATA +225 -0
- futureish-0.1.0.dist-info/RECORD +63 -0
- futureish-0.1.0.dist-info/WHEEL +4 -0
futureish/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
2
|
+
from pkgutil import extend_path
|
|
3
|
+
|
|
4
|
+
__path__ = extend_path(__path__, __name__)
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
__version__ = version("futureish")
|
|
8
|
+
except PackageNotFoundError:
|
|
9
|
+
__version__ = "0.0.0+unknown"
|
|
10
|
+
|
|
11
|
+
import polars as pl
|
|
12
|
+
|
|
13
|
+
pl.Config.set_engine_affinity("streaming")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Private implementation details for the timeseries package."""
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from ..modeling.base import ABCModel
|
|
2
|
+
from ..modeling.config import FitConfig
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from numpy.typing import NDArray
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
from typing import Any, Callable, Optional
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class DummyModel(ABCModel):
|
|
13
|
+
def __init__(self):
|
|
14
|
+
super().__init__()
|
|
15
|
+
|
|
16
|
+
@property
|
|
17
|
+
def _repr_fields(self) -> dict[str, Any]:
|
|
18
|
+
return super()._repr_fields
|
|
19
|
+
|
|
20
|
+
def _fit(self, X: NDArray[np.float64], features: dict[str, NDArray[np.float64]], config: Optional[FitConfig] = None) -> None:
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
def _predict(self, X: NDArray[np.float64]) -> dict[str, tuple[NDArray[np.float64], NDArray[np.float64]]]:
|
|
24
|
+
return {name: (np.repeat(np.array([1.0]), X.shape[0]), np.repeat(np.array([0.0]), X.shape[0])) for name in self.feature_names}
|
|
25
|
+
|
|
26
|
+
def _predict_mean(self, X: NDArray[np.float64]) -> dict[str, NDArray[np.float64]]:
|
|
27
|
+
return {name: mean for name, (mean, _) in self._predict(X).items()}
|
|
28
|
+
|
|
29
|
+
def _predict_sample(self, X: NDArray[np.float64]) -> dict[str, NDArray[np.float64]]:
|
|
30
|
+
return {name: mean for name, (mean, _) in self._predict(X).items()}
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
#type: ignore
|
|
2
|
+
"""Shared __repr__/_repr_html_ machinery for every gpr_ts class that declares
|
|
3
|
+
a `_repr_fields` property (dict[str, Any] of the fields worth showing).
|
|
4
|
+
|
|
5
|
+
ReprMixin walks that dict and recurses into any value that itself has
|
|
6
|
+
`_repr_fields` (or a list of such values) - so e.g. Forecaster's repr walks
|
|
7
|
+
down through its DataConfig into every InputFeature/TargetFeature/Scaler
|
|
8
|
+
without each of those needing its own __repr__/_repr_html_ implementation.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import html
|
|
12
|
+
from typing import Any, Optional
|
|
13
|
+
|
|
14
|
+
_MAX_LIST_ITEMS = 10
|
|
15
|
+
_MAX_DEPTH = 8
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _repr_fields_of(value: Any) -> Optional[dict[str, Any]]:
|
|
19
|
+
"""`value._repr_fields` if it's a dict (i.e. a proper `@property`), else
|
|
20
|
+
None - guards against a class that (by bug) defines `_repr_fields` as a
|
|
21
|
+
plain method, where accessing it without calling would hand back a bound
|
|
22
|
+
method instead of a dict.
|
|
23
|
+
"""
|
|
24
|
+
fields: Optional[dict[str, Any]] = getattr(value, "_repr_fields", None)
|
|
25
|
+
return fields if isinstance(fields, dict) else None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _is_array_like(value: Any) -> bool:
|
|
29
|
+
# duck-typed rather than isinstance-checked against numpy/torch/polars
|
|
30
|
+
# directly - all three happen to be available here (gpytorch pulls in
|
|
31
|
+
# numpy/torch, polars is a direct dependency), but this stays correct for
|
|
32
|
+
# any other array-ish type (e.g. pandas) a future _repr_fields might hold.
|
|
33
|
+
return hasattr(value, "shape") and not _repr_fields_of(value)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _array_summary(value: Any) -> str:
|
|
37
|
+
dtype = getattr(value, "dtype", None)
|
|
38
|
+
shape = tuple(getattr(value, "shape", ()))
|
|
39
|
+
dtype_str = f", dtype={dtype}" if dtype is not None else ""
|
|
40
|
+
return f"{type(value).__name__}(shape={shape}{dtype_str})"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _callable_summary(value: Any) -> str:
|
|
44
|
+
name = getattr(value, "__qualname__", None) or getattr(value, "__name__", None) or repr(value)
|
|
45
|
+
return f"<{name}>"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _leaf_repr(value: Any) -> str:
|
|
49
|
+
if _is_array_like(value):
|
|
50
|
+
return _array_summary(value)
|
|
51
|
+
if callable(value) and not isinstance(value, type):
|
|
52
|
+
return _callable_summary(value)
|
|
53
|
+
if isinstance(value, type):
|
|
54
|
+
return value.__name__
|
|
55
|
+
return repr(value)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _indent(text: str, prefix: str = "\t") -> str:
|
|
59
|
+
return "\n".join(prefix + line for line in text.splitlines())
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _attach_key(key: str, formatted: str) -> str:
|
|
63
|
+
"""Render `key=formatted`, keeping a multi-line `formatted`'s opening
|
|
64
|
+
bracket on the key's own line (`key=[` / `key=ClassName(`) instead of
|
|
65
|
+
dropping it to its own line - matches how e.g. `black` formats nested
|
|
66
|
+
literals, rather than one extra level of indentation for no reason.
|
|
67
|
+
"""
|
|
68
|
+
if "\n" not in formatted:
|
|
69
|
+
return f"{key}={formatted}"
|
|
70
|
+
first, *rest = formatted.splitlines()
|
|
71
|
+
return "\n".join([f"{key}={first}", *rest])
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _format_value(value: Any, seen: set[int], depth: int) -> str:
|
|
75
|
+
if depth >= _MAX_DEPTH:
|
|
76
|
+
return _leaf_repr(value)
|
|
77
|
+
|
|
78
|
+
fields = _repr_fields_of(value)
|
|
79
|
+
if fields is not None:
|
|
80
|
+
return _format_object(value, fields, seen, depth)
|
|
81
|
+
|
|
82
|
+
if isinstance(value, (list, tuple)):
|
|
83
|
+
items = list(value)
|
|
84
|
+
if not items:
|
|
85
|
+
return "[]"
|
|
86
|
+
if not any(_repr_fields_of(item) is not None for item in items):
|
|
87
|
+
return repr(value)
|
|
88
|
+
return _format_list(items, seen, depth)
|
|
89
|
+
|
|
90
|
+
return _leaf_repr(value)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _format_object(value: Any, fields: dict[str, Any], seen: set[int], depth: int) -> str:
|
|
94
|
+
class_name = value.__class__.__name__
|
|
95
|
+
obj_id = id(value)
|
|
96
|
+
if obj_id in seen:
|
|
97
|
+
return f"{class_name}(...)"
|
|
98
|
+
seen = seen | {obj_id}
|
|
99
|
+
|
|
100
|
+
if not fields:
|
|
101
|
+
return f"{class_name}()"
|
|
102
|
+
|
|
103
|
+
lines: list[str] = []
|
|
104
|
+
for key, field_value in fields.items():
|
|
105
|
+
formatted = _format_value(field_value, seen, depth + 1)
|
|
106
|
+
lines.append(_attach_key(key, formatted))
|
|
107
|
+
|
|
108
|
+
body = ",\n".join(lines)
|
|
109
|
+
return f"{class_name}(\n{_indent(body)}\n)"
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _format_list(items: list[Any], seen: set[int], depth: int) -> str:
|
|
113
|
+
shown = items[:_MAX_LIST_ITEMS]
|
|
114
|
+
lines = [_format_value(item, seen, depth + 1) for item in shown]
|
|
115
|
+
if len(items) > _MAX_LIST_ITEMS:
|
|
116
|
+
lines.append(f"... ({len(items) - _MAX_LIST_ITEMS} more)")
|
|
117
|
+
body = ",\n".join(_indent(line) for line in lines)
|
|
118
|
+
return f"[\n{body}\n]"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class ReprMixin:
|
|
122
|
+
@property
|
|
123
|
+
def _repr_fields(self) -> dict[str, Any]:
|
|
124
|
+
return {}
|
|
125
|
+
|
|
126
|
+
def __repr__(self) -> str:
|
|
127
|
+
fields = _repr_fields_of(self)
|
|
128
|
+
return _format_object(self, fields or {}, set(), 0)
|
|
129
|
+
|
|
130
|
+
def _repr_html_(self) -> str:
|
|
131
|
+
fields = _repr_fields_of(self)
|
|
132
|
+
return _html_root(self, fields or {})
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# --------------------------------------------------------------------------
|
|
136
|
+
# HTML rendering
|
|
137
|
+
# --------------------------------------------------------------------------
|
|
138
|
+
|
|
139
|
+
_CSS = """
|
|
140
|
+
<style>
|
|
141
|
+
.gpr-ts-repr { font-family: -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; font-size: 13px; color: inherit; }
|
|
142
|
+
.gpr-ts-repr details { margin: 2px 0; }
|
|
143
|
+
.gpr-ts-repr summary { cursor: pointer; font-weight: 600; padding: 2px 0; }
|
|
144
|
+
.gpr-ts-repr summary:hover { color: #2563eb; }
|
|
145
|
+
.gpr-ts-repr table { border-collapse: collapse; margin: 4px 0 4px 1.2em; }
|
|
146
|
+
.gpr-ts-repr td, .gpr-ts-repr th { border: 1px solid rgba(128, 128, 128, 0.35); padding: 3px 8px; text-align: left; vertical-align: top; }
|
|
147
|
+
.gpr-ts-repr th { background: rgba(128, 128, 128, 0.12); font-weight: 600; }
|
|
148
|
+
.gpr-ts-repr .gpr-ts-field { font-weight: 600; white-space: nowrap; }
|
|
149
|
+
.gpr-ts-repr .gpr-ts-scalar { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
150
|
+
.gpr-ts-repr .gpr-ts-empty { color: rgba(128, 128, 128, 0.8); font-style: italic; }
|
|
151
|
+
</style>
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _esc(text: Any) -> str:
|
|
156
|
+
return html.escape(str(text))
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _html_root(value: Any, fields: dict[str, Any]) -> str:
|
|
160
|
+
body = _html_object(value, fields, set(), depth=0, open_=True)
|
|
161
|
+
return f'{_CSS}<div class="gpr-ts-repr">{body}</div>'
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _html_value(value: Any, seen: set[int], depth: int) -> str:
|
|
165
|
+
if depth >= _MAX_DEPTH:
|
|
166
|
+
return f'<span class="gpr-ts-scalar">{_esc(_leaf_repr(value))}</span>'
|
|
167
|
+
|
|
168
|
+
fields = _repr_fields_of(value)
|
|
169
|
+
if fields is not None:
|
|
170
|
+
return _html_object(value, fields, seen, depth)
|
|
171
|
+
|
|
172
|
+
if isinstance(value, (list, tuple)):
|
|
173
|
+
items = list(value)
|
|
174
|
+
if items and any(_repr_fields_of(item) is not None for item in items):
|
|
175
|
+
return _html_list(items, seen, depth)
|
|
176
|
+
|
|
177
|
+
return f'<span class="gpr-ts-scalar">{_esc(_leaf_repr(value))}</span>'
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _html_object(value: Any, fields: dict[str, Any], seen: set[int], depth: int, open_: bool = False) -> str:
|
|
181
|
+
"""One object as a small horizontal table: field names as column
|
|
182
|
+
headers, its own values as the single row underneath - reads like a
|
|
183
|
+
single-row dataframe rather than a vertical key/value list.
|
|
184
|
+
"""
|
|
185
|
+
class_name = value.__class__.__name__
|
|
186
|
+
obj_id = id(value)
|
|
187
|
+
if obj_id in seen:
|
|
188
|
+
return f'<span class="gpr-ts-scalar">{_esc(class_name)}(...)</span>'
|
|
189
|
+
seen = seen | {obj_id}
|
|
190
|
+
|
|
191
|
+
if not fields:
|
|
192
|
+
return f'<span class="gpr-ts-scalar">{_esc(class_name)}()</span>'
|
|
193
|
+
|
|
194
|
+
header = "".join(f"<th>{_esc(key)}</th>" for key in fields)
|
|
195
|
+
values = "".join(f"<td>{_html_value(field_value, seen, depth + 1)}</td>" for field_value in fields.values())
|
|
196
|
+
table = f"<table><tr>{header}</tr><tr>{values}</tr></table>"
|
|
197
|
+
|
|
198
|
+
open_attr = " open" if open_ else ""
|
|
199
|
+
return f"<details{open_attr}><summary>{_esc(class_name)}</summary>{table}</details>"
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
_MISSING = object()
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _html_list(items: list[Any], seen: set[int], depth: int) -> str:
|
|
206
|
+
shown = items[:_MAX_LIST_ITEMS]
|
|
207
|
+
remaining = len(items) - len(shown)
|
|
208
|
+
summary = f"{len(items)} item{'s' if len(items) != 1 else ''}"
|
|
209
|
+
|
|
210
|
+
field_dicts = [_repr_fields_of(item) for item in shown]
|
|
211
|
+
if all(f is not None for f in field_dicts):
|
|
212
|
+
table = _html_uniform_list_table(shown, field_dicts, seen, depth, remaining)
|
|
213
|
+
else:
|
|
214
|
+
table = _html_mixed_list_table(shown, seen, depth, remaining)
|
|
215
|
+
|
|
216
|
+
return f"<details><summary>{summary}</summary>{table}</details>"
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _html_uniform_list_table(shown: list[Any], field_dicts: list[dict[str, Any]], seen: set[int], depth: int, remaining: int) -> str:
|
|
220
|
+
"""Every item has its own `_repr_fields` - render as one dataframe-like
|
|
221
|
+
table, columns as the (unioned, order-preserving) field names and one
|
|
222
|
+
row per item, rather than a nested `<details>` per item.
|
|
223
|
+
"""
|
|
224
|
+
keys: list[str] = []
|
|
225
|
+
for fields in field_dicts:
|
|
226
|
+
for key in fields:
|
|
227
|
+
if key not in keys:
|
|
228
|
+
keys.append(key)
|
|
229
|
+
|
|
230
|
+
header = "".join(f"<th>{_esc(key)}</th>" for key in ["#", *keys])
|
|
231
|
+
rows: list[str] = []
|
|
232
|
+
for i, fields in enumerate(field_dicts):
|
|
233
|
+
cells = [f"<td>{i}</td>"]
|
|
234
|
+
for key in keys:
|
|
235
|
+
field_value = fields.get(key, _MISSING)
|
|
236
|
+
cell = "" if field_value is _MISSING else _html_value(field_value, seen, depth + 1)
|
|
237
|
+
cells.append(f"<td>{cell}</td>")
|
|
238
|
+
rows.append("<tr>" + "".join(cells) + "</tr>")
|
|
239
|
+
|
|
240
|
+
if remaining > 0:
|
|
241
|
+
rows.append(f'<tr><td colspan="{len(keys) + 1}" class="gpr-ts-empty">... ({remaining} more)</td></tr>')
|
|
242
|
+
|
|
243
|
+
return f"<table><tr>{header}</tr>{''.join(rows)}</table>"
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _html_mixed_list_table(shown: list[Any], seen: set[int], depth: int, remaining: int) -> str:
|
|
247
|
+
rows: list[str] = []
|
|
248
|
+
for i, item in enumerate(shown):
|
|
249
|
+
rows.append(
|
|
250
|
+
"<tr>"
|
|
251
|
+
f'<td class="gpr-ts-field">[{i}]</td>'
|
|
252
|
+
f"<td>{_html_value(item, seen, depth + 1)}</td>"
|
|
253
|
+
"</tr>"
|
|
254
|
+
)
|
|
255
|
+
if remaining > 0:
|
|
256
|
+
rows.append(f'<tr><td colspan="2" class="gpr-ts-empty">... ({remaining} more)</td></tr>')
|
|
257
|
+
return f"<table>{''.join(rows)}</table>"
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
2
|
+
from pkgutil import extend_path
|
|
3
|
+
from .model import CatBoostTimeseriesModel, CatboostFitConfig
|
|
4
|
+
|
|
5
|
+
__path__ = extend_path(__path__, __name__)
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
__version__ = version("timeseries-catboost")
|
|
9
|
+
except PackageNotFoundError:
|
|
10
|
+
__version__ = "0.0.0+unknown"
|
|
11
|
+
|
|
12
|
+
__all__ = ["CatBoostTimeseriesModel", "CatboostFitConfig"]
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
from dataclasses import asdict, dataclass
|
|
2
|
+
from types import SimpleNamespace
|
|
3
|
+
from typing import Any, Optional, Callable, Union
|
|
4
|
+
import numpy as np
|
|
5
|
+
from numpy.typing import NDArray
|
|
6
|
+
import catboost
|
|
7
|
+
from ..modeling.base import ABCModel
|
|
8
|
+
from ..modeling.config import FitConfig
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class CatboostFitConfig(FitConfig):
|
|
12
|
+
"""
|
|
13
|
+
Configuration for fitting a CatBoost model.
|
|
14
|
+
Besides `enable_tqdm`, all other parameters are passed directly to the CatBoost `fit` method.
|
|
15
|
+
"""
|
|
16
|
+
use_best_model: Optional[bool] = None
|
|
17
|
+
eval_set: Optional[Union[catboost.Pool, list[catboost.Pool], tuple[NDArray, NDArray], list[tuple[NDArray, NDArray]]]] = None
|
|
18
|
+
verbose: Optional[bool] = False
|
|
19
|
+
silent: Optional[bool] = None
|
|
20
|
+
logging_level: Optional[str] = None
|
|
21
|
+
early_stopping_rounds: Optional[int] = None
|
|
22
|
+
enable_tqdm: Optional[bool] = False
|
|
23
|
+
|
|
24
|
+
class Callback:
|
|
25
|
+
def __init__(self, feature_name: str, iterations: Optional[int] = None):
|
|
26
|
+
self.feature_name = feature_name
|
|
27
|
+
self.iterations = iterations
|
|
28
|
+
from tqdm.auto import tqdm
|
|
29
|
+
self.tqdm = tqdm(total=iterations, desc=f"Training progress {self.feature_name}", leave=False)
|
|
30
|
+
def after_iteration(self, info: SimpleNamespace) -> bool:
|
|
31
|
+
self.tqdm.update(1)
|
|
32
|
+
loss = info.metrics.get("learn", {})
|
|
33
|
+
loss = loss.get("MultiRMSE", loss.get("RMSE", None))
|
|
34
|
+
if loss is not None:
|
|
35
|
+
self.tqdm.set_postfix({"loss": f"{loss[-1]:.6f}"})
|
|
36
|
+
if self.iterations is not None and info.iteration >= self.iterations:
|
|
37
|
+
self.tqdm.close()
|
|
38
|
+
return True # Continue training
|
|
39
|
+
|
|
40
|
+
class CatBoostTimeseriesModel(ABCModel):
|
|
41
|
+
"""
|
|
42
|
+
A wrapper around CatBoost for time series forecasting.
|
|
43
|
+
Supports both single-output and multi-output regression.
|
|
44
|
+
"""
|
|
45
|
+
def __init__(self, use_multioutput: bool = False, uncertainty_prediction = False, **catboost_kwargs):
|
|
46
|
+
"""
|
|
47
|
+
:param use_multioutput: If True, uses a single CatBoost model for multi-output regression. If False, uses one model per output.
|
|
48
|
+
:param uncertainty_prediction: If True, enables uncertainty prediction using virtual ensembles. Not compatible with multi-output mode.
|
|
49
|
+
:param catboost_kwargs: Keyword arguments to pass to the CatBoostRegressor
|
|
50
|
+
"""
|
|
51
|
+
super().__init__()
|
|
52
|
+
self._catboost_kwargs = catboost_kwargs
|
|
53
|
+
self.use_multioutput = use_multioutput
|
|
54
|
+
self.uncertainty_prediction = uncertainty_prediction
|
|
55
|
+
self.models: dict[str, catboost.CatBoostRegressor] = {}
|
|
56
|
+
|
|
57
|
+
if "allow_writing_files" not in catboost_kwargs:
|
|
58
|
+
catboost_kwargs["allow_writing_files"] = False
|
|
59
|
+
|
|
60
|
+
if self.use_multioutput and self.uncertainty_prediction:
|
|
61
|
+
raise ValueError("Uncertainty prediction is not supported with multioutput models.")
|
|
62
|
+
|
|
63
|
+
if not self.use_multioutput and self._catboost_kwargs.get("loss_function", "RMSE") == "MultiRMSE":
|
|
64
|
+
raise ValueError("When use_multioutput is False, loss_function cannot be 'MultiRMSE'.")
|
|
65
|
+
|
|
66
|
+
if self.use_multioutput:
|
|
67
|
+
if self._catboost_kwargs.get("loss_function", "MultiRMSE") != "MultiRMSE":
|
|
68
|
+
raise ValueError("When use_multioutput is True, loss_function must be 'MultiRMSE'.")
|
|
69
|
+
self._catboost_kwargs["loss_function"] = "MultiRMSE"
|
|
70
|
+
|
|
71
|
+
if self.uncertainty_prediction:
|
|
72
|
+
if self._catboost_kwargs.get("loss_function", "RMSEWithUncertainty") != "RMSEWithUncertainty":
|
|
73
|
+
raise ValueError("When uncertainty_prediction is True, loss_function must be 'RMSEWithUncertainty'.")
|
|
74
|
+
self._catboost_kwargs["loss_function"] = "RMSEWithUncertainty"
|
|
75
|
+
|
|
76
|
+
def _fit(self, X: NDArray[np.float64], features: dict[str, NDArray[np.float64]], config: Optional[FitConfig] = None) -> None:
|
|
77
|
+
enable_tqdm = False
|
|
78
|
+
if config is not None:
|
|
79
|
+
if not isinstance(config, CatboostFitConfig):
|
|
80
|
+
raise TypeError(f"Expected config to be of type CatboostFitConfig, got {type(config)}")
|
|
81
|
+
kwargs = config.as_dict()
|
|
82
|
+
enable_tqdm = kwargs.pop("enable_tqdm", False)
|
|
83
|
+
else:
|
|
84
|
+
kwargs = {}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
if not self.use_multioutput:
|
|
88
|
+
if enable_tqdm:
|
|
89
|
+
from tqdm.auto import tqdm
|
|
90
|
+
iterator = tqdm(self.feature_names, desc="Fitting models")
|
|
91
|
+
else:
|
|
92
|
+
iterator = self.feature_names
|
|
93
|
+
for f in iterator:
|
|
94
|
+
try:
|
|
95
|
+
m = catboost.CatBoostRegressor(**self._catboost_kwargs)
|
|
96
|
+
callbacks = []
|
|
97
|
+
if enable_tqdm:
|
|
98
|
+
callbacks = [Callback(f, iterations=kwargs.get("iterations", None))]
|
|
99
|
+
m.fit(X, features[f], **kwargs, callbacks=callbacks)
|
|
100
|
+
self.models[f] = m
|
|
101
|
+
except Exception as e:
|
|
102
|
+
raise RuntimeError(f"Failed to fit model for feature '{f}': {e}")
|
|
103
|
+
else:
|
|
104
|
+
m = catboost.CatBoostRegressor(**self._catboost_kwargs)
|
|
105
|
+
callbacks = None
|
|
106
|
+
if enable_tqdm:
|
|
107
|
+
callbacks = [Callback("multioutput", iterations=kwargs.get("iterations", None))]
|
|
108
|
+
# features[feature] is a 2d array with shape (n_samples, 1)
|
|
109
|
+
stacked_features = np.concatenate([features[feature] for feature in self.feature_names], axis=1)
|
|
110
|
+
m.fit(X, stacked_features, **kwargs, callbacks=callbacks)
|
|
111
|
+
self.models["multioutput"] = m
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _predict(self, X: NDArray[np.float64]) -> dict[str, tuple[NDArray[np.float64], NDArray[np.float64]]]:
|
|
115
|
+
if not self.uncertainty_prediction:
|
|
116
|
+
raise ValueError("Uncertainty prediction is not enabled for this model.")
|
|
117
|
+
pred = {}
|
|
118
|
+
for f in self.feature_names:
|
|
119
|
+
pred_all = self.models[f].virtual_ensembles_predict(X, prediction_type="TotalUncertainty", virtual_ensembles_count=10)
|
|
120
|
+
mean = pred_all[:, 0]
|
|
121
|
+
std = np.sqrt(pred_all[:, 1] + pred_all[:, 2]) # Total uncertainty = aleatoric + epistemic
|
|
122
|
+
pred[f] = (mean, std)
|
|
123
|
+
return pred
|
|
124
|
+
|
|
125
|
+
def _predict_mean(self, X: NDArray[np.float64]) -> dict[str, NDArray[np.float64]]:
|
|
126
|
+
pred = {}
|
|
127
|
+
if not self.use_multioutput:
|
|
128
|
+
for f in self.feature_names:
|
|
129
|
+
pred_all = self.models[f].predict(X)
|
|
130
|
+
if self.uncertainty_prediction:
|
|
131
|
+
pred[f] = pred_all[:, 0]
|
|
132
|
+
else:
|
|
133
|
+
pred[f] = pred_all
|
|
134
|
+
else:
|
|
135
|
+
stacked_pred = self.models["multioutput"].predict(X)
|
|
136
|
+
if len(self.feature_names) == 1:
|
|
137
|
+
pred[self.feature_names[0]] = stacked_pred.flatten()
|
|
138
|
+
else:
|
|
139
|
+
for i, f in enumerate(self.feature_names):
|
|
140
|
+
pred[f] = stacked_pred[:, i].flatten()
|
|
141
|
+
return pred
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
from typing import Any
|
|
3
|
+
import polars as pl
|
|
4
|
+
|
|
5
|
+
from .._internal.repr import ReprMixin
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True)
|
|
8
|
+
class DataPoint(ReprMixin):
|
|
9
|
+
"""
|
|
10
|
+
Base class for a data point in the raw data. Defines the name and if the data point is known in the future.
|
|
11
|
+
"""
|
|
12
|
+
name: str
|
|
13
|
+
known_future: bool = field(default=False, kw_only=True)
|
|
14
|
+
|
|
15
|
+
@property
|
|
16
|
+
def column(self) -> pl.Expr:
|
|
17
|
+
return pl.col(self.name)
|
|
18
|
+
|
|
19
|
+
@property
|
|
20
|
+
def _repr_fields(self) -> dict[str, Any]:
|
|
21
|
+
return {
|
|
22
|
+
"name": self.name,
|
|
23
|
+
"known_future": self.known_future,
|
|
24
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from ..utils.timedelta import TimeDeltaOperator
|
|
5
|
+
|
|
6
|
+
from .base import DataPoint
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class RecordedDataPoint(DataPoint):
|
|
10
|
+
"""
|
|
11
|
+
Data point for a recorded value in the raw data.
|
|
12
|
+
"""
|
|
13
|
+
step_size: TimeDeltaOperator
|
|
14
|
+
def __init__(self, name: str, step_size: str, known_future: bool = False):
|
|
15
|
+
super().__init__(name=name, known_future=known_future)
|
|
16
|
+
object.__setattr__(self, "step_size", TimeDeltaOperator(step_size))
|
|
17
|
+
|
|
18
|
+
@property
|
|
19
|
+
def _repr_fields(self) -> dict[str, Any]:
|
|
20
|
+
new_fields = {
|
|
21
|
+
"step_size": self.step_size,
|
|
22
|
+
}
|
|
23
|
+
return super()._repr_fields | new_fields
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
from .base import DataPoint
|
|
4
|
+
from .._internal.constants import TIME
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True)
|
|
7
|
+
class TimeDataPoint(DataPoint):
|
|
8
|
+
"""
|
|
9
|
+
Data point that is based on the time column in the raw data. This data point is always known in the future.
|
|
10
|
+
"""
|
|
11
|
+
def __init__(self):
|
|
12
|
+
super().__init__(name=TIME, known_future=True)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from .config import DataConfig
|
|
2
|
+
from .online import OnlineDataset
|
|
3
|
+
from .online_training import OnlineTrainingDataset
|
|
4
|
+
from .predict import PredictDatasetBase
|
|
5
|
+
from .train import TrainDataset
|
|
6
|
+
from .test import TestDataset
|
|
7
|
+
from .forecast import ForecastingDataset
|
|
8
|
+
from .dataset import Dataset
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"DataConfig",
|
|
12
|
+
"OnlineDataset",
|
|
13
|
+
"TrainDataset",
|
|
14
|
+
"OnlineTrainingDataset",
|
|
15
|
+
"PredictDatasetBase",
|
|
16
|
+
"TestDataset",
|
|
17
|
+
"ForecastingDataset",
|
|
18
|
+
"Dataset",
|
|
19
|
+
]
|