autogluon.timeseries 1.4.1b20250906__py3-none-any.whl → 1.4.1b20251210__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.
Potentially problematic release.
This version of autogluon.timeseries might be problematic. Click here for more details.
- autogluon/timeseries/configs/hyperparameter_presets.py +2 -2
- autogluon/timeseries/dataset/ts_dataframe.py +97 -86
- autogluon/timeseries/learner.py +68 -35
- autogluon/timeseries/metrics/__init__.py +4 -4
- autogluon/timeseries/metrics/abstract.py +8 -8
- autogluon/timeseries/metrics/point.py +9 -9
- autogluon/timeseries/metrics/quantile.py +5 -5
- autogluon/timeseries/metrics/utils.py +4 -4
- autogluon/timeseries/models/__init__.py +4 -1
- autogluon/timeseries/models/abstract/abstract_timeseries_model.py +52 -39
- autogluon/timeseries/models/abstract/model_trial.py +2 -1
- autogluon/timeseries/models/abstract/tunable.py +8 -8
- autogluon/timeseries/models/autogluon_tabular/mlforecast.py +58 -62
- autogluon/timeseries/models/autogluon_tabular/per_step.py +26 -15
- autogluon/timeseries/models/autogluon_tabular/transforms.py +11 -9
- autogluon/timeseries/models/chronos/__init__.py +2 -1
- autogluon/timeseries/models/chronos/chronos2.py +361 -0
- autogluon/timeseries/models/chronos/model.py +125 -87
- autogluon/timeseries/models/chronos/{pipeline/utils.py → utils.py} +68 -36
- autogluon/timeseries/models/ensemble/__init__.py +34 -2
- autogluon/timeseries/models/ensemble/abstract.py +5 -42
- autogluon/timeseries/models/ensemble/array_based/__init__.py +3 -0
- autogluon/timeseries/models/ensemble/array_based/abstract.py +236 -0
- autogluon/timeseries/models/ensemble/array_based/models.py +73 -0
- autogluon/timeseries/models/ensemble/array_based/regressor/__init__.py +12 -0
- autogluon/timeseries/models/ensemble/array_based/regressor/abstract.py +88 -0
- autogluon/timeseries/models/ensemble/array_based/regressor/linear_stacker.py +167 -0
- autogluon/timeseries/models/ensemble/array_based/regressor/per_quantile_tabular.py +94 -0
- autogluon/timeseries/models/ensemble/array_based/regressor/tabular.py +107 -0
- autogluon/timeseries/models/ensemble/{greedy.py → ensemble_selection.py} +41 -61
- autogluon/timeseries/models/ensemble/per_item_greedy.py +162 -0
- autogluon/timeseries/models/ensemble/weighted/__init__.py +8 -0
- autogluon/timeseries/models/ensemble/weighted/abstract.py +40 -0
- autogluon/timeseries/models/ensemble/{basic.py → weighted/basic.py} +6 -16
- autogluon/timeseries/models/ensemble/weighted/greedy.py +57 -0
- autogluon/timeseries/models/gluonts/abstract.py +25 -25
- autogluon/timeseries/models/gluonts/dataset.py +11 -11
- autogluon/timeseries/models/local/__init__.py +0 -7
- autogluon/timeseries/models/local/abstract_local_model.py +15 -18
- autogluon/timeseries/models/local/naive.py +2 -2
- autogluon/timeseries/models/local/npts.py +1 -1
- autogluon/timeseries/models/local/statsforecast.py +12 -12
- autogluon/timeseries/models/multi_window/multi_window_model.py +39 -24
- autogluon/timeseries/models/registry.py +3 -4
- autogluon/timeseries/models/toto/__init__.py +3 -0
- autogluon/timeseries/models/toto/_internal/__init__.py +9 -0
- autogluon/timeseries/models/toto/_internal/backbone/__init__.py +3 -0
- autogluon/timeseries/models/toto/_internal/backbone/attention.py +196 -0
- autogluon/timeseries/models/toto/_internal/backbone/backbone.py +262 -0
- autogluon/timeseries/models/toto/_internal/backbone/distribution.py +70 -0
- autogluon/timeseries/models/toto/_internal/backbone/kvcache.py +136 -0
- autogluon/timeseries/models/toto/_internal/backbone/rope.py +89 -0
- autogluon/timeseries/models/toto/_internal/backbone/rotary_embedding_torch.py +342 -0
- autogluon/timeseries/models/toto/_internal/backbone/scaler.py +305 -0
- autogluon/timeseries/models/toto/_internal/backbone/transformer.py +333 -0
- autogluon/timeseries/models/toto/_internal/dataset.py +165 -0
- autogluon/timeseries/models/toto/_internal/forecaster.py +423 -0
- autogluon/timeseries/models/toto/dataloader.py +108 -0
- autogluon/timeseries/models/toto/hf_pretrained_model.py +118 -0
- autogluon/timeseries/models/toto/model.py +236 -0
- autogluon/timeseries/predictor.py +301 -103
- autogluon/timeseries/regressor.py +27 -30
- autogluon/timeseries/splitter.py +3 -27
- autogluon/timeseries/trainer/ensemble_composer.py +439 -0
- autogluon/timeseries/trainer/model_set_builder.py +9 -9
- autogluon/timeseries/trainer/prediction_cache.py +16 -16
- autogluon/timeseries/trainer/trainer.py +300 -275
- autogluon/timeseries/trainer/utils.py +17 -0
- autogluon/timeseries/transforms/covariate_scaler.py +8 -8
- autogluon/timeseries/transforms/target_scaler.py +15 -15
- autogluon/timeseries/utils/constants.py +10 -0
- autogluon/timeseries/utils/datetime/lags.py +1 -3
- autogluon/timeseries/utils/datetime/seasonality.py +1 -3
- autogluon/timeseries/utils/features.py +18 -14
- autogluon/timeseries/utils/forecast.py +6 -7
- autogluon/timeseries/utils/timer.py +173 -0
- autogluon/timeseries/version.py +1 -1
- autogluon.timeseries-1.4.1b20251210-py3.11-nspkg.pth +1 -0
- {autogluon.timeseries-1.4.1b20250906.dist-info → autogluon_timeseries-1.4.1b20251210.dist-info}/METADATA +39 -22
- autogluon_timeseries-1.4.1b20251210.dist-info/RECORD +103 -0
- {autogluon.timeseries-1.4.1b20250906.dist-info → autogluon_timeseries-1.4.1b20251210.dist-info}/WHEEL +1 -1
- autogluon/timeseries/evaluator.py +0 -6
- autogluon/timeseries/models/chronos/pipeline/__init__.py +0 -10
- autogluon/timeseries/models/chronos/pipeline/base.py +0 -160
- autogluon/timeseries/models/chronos/pipeline/chronos.py +0 -544
- autogluon/timeseries/models/chronos/pipeline/chronos_bolt.py +0 -580
- autogluon.timeseries-1.4.1b20250906-py3.9-nspkg.pth +0 -1
- autogluon.timeseries-1.4.1b20250906.dist-info/RECORD +0 -75
- {autogluon.timeseries-1.4.1b20250906.dist-info → autogluon_timeseries-1.4.1b20251210.dist-info/licenses}/LICENSE +0 -0
- {autogluon.timeseries-1.4.1b20250906.dist-info → autogluon_timeseries-1.4.1b20251210.dist-info/licenses}/NOTICE +0 -0
- {autogluon.timeseries-1.4.1b20250906.dist-info → autogluon_timeseries-1.4.1b20251210.dist-info}/namespace_packages.txt +0 -0
- {autogluon.timeseries-1.4.1b20250906.dist-info → autogluon_timeseries-1.4.1b20251210.dist-info}/top_level.txt +0 -0
- {autogluon.timeseries-1.4.1b20250906.dist-info → autogluon_timeseries-1.4.1b20251210.dist-info}/zip-safe +0 -0
|
@@ -1,3 +1,35 @@
|
|
|
1
1
|
from .abstract import AbstractTimeSeriesEnsembleModel
|
|
2
|
-
from .
|
|
3
|
-
from .
|
|
2
|
+
from .array_based import LinearStackerEnsemble, MedianEnsemble, PerQuantileTabularEnsemble, TabularEnsemble
|
|
3
|
+
from .per_item_greedy import PerItemGreedyEnsemble
|
|
4
|
+
from .weighted import GreedyEnsemble, PerformanceWeightedEnsemble, SimpleAverageEnsemble
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def get_ensemble_class(name: str):
|
|
8
|
+
mapping = {
|
|
9
|
+
"GreedyEnsemble": GreedyEnsemble,
|
|
10
|
+
"PerItemGreedyEnsemble": PerItemGreedyEnsemble,
|
|
11
|
+
"PerformanceWeightedEnsemble": PerformanceWeightedEnsemble,
|
|
12
|
+
"SimpleAverageEnsemble": SimpleAverageEnsemble,
|
|
13
|
+
"WeightedEnsemble": GreedyEnsemble, # old alias for this model
|
|
14
|
+
"MedianEnsemble": MedianEnsemble,
|
|
15
|
+
"TabularEnsemble": TabularEnsemble,
|
|
16
|
+
"PerQuantileTabularEnsemble": PerQuantileTabularEnsemble,
|
|
17
|
+
"LinearStackerEnsemble": LinearStackerEnsemble,
|
|
18
|
+
}
|
|
19
|
+
if name not in mapping:
|
|
20
|
+
raise ValueError(f"Unknown ensemble type: {name}. Available: {list(mapping.keys())}")
|
|
21
|
+
return mapping[name]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"AbstractTimeSeriesEnsembleModel",
|
|
26
|
+
"GreedyEnsemble",
|
|
27
|
+
"LinearStackerEnsemble",
|
|
28
|
+
"MedianEnsemble",
|
|
29
|
+
"PerformanceWeightedEnsemble",
|
|
30
|
+
"PerItemGreedyEnsemble",
|
|
31
|
+
"PerQuantileTabularEnsemble",
|
|
32
|
+
"SimpleAverageEnsemble",
|
|
33
|
+
"TabularEnsemble",
|
|
34
|
+
"get_ensemble_class",
|
|
35
|
+
]
|
|
@@ -1,9 +1,6 @@
|
|
|
1
|
-
import functools
|
|
2
1
|
import logging
|
|
3
2
|
from abc import ABC, abstractmethod
|
|
4
|
-
from typing import Optional
|
|
5
3
|
|
|
6
|
-
import numpy as np
|
|
7
4
|
from typing_extensions import final
|
|
8
5
|
|
|
9
6
|
from autogluon.core.utils.exceptions import TimeLimitExceeded
|
|
@@ -27,8 +24,8 @@ class AbstractTimeSeriesEnsembleModel(TimeSeriesModelBase, ABC):
|
|
|
27
24
|
self,
|
|
28
25
|
predictions_per_window: dict[str, list[TimeSeriesDataFrame]],
|
|
29
26
|
data_per_window: list[TimeSeriesDataFrame],
|
|
30
|
-
model_scores:
|
|
31
|
-
time_limit:
|
|
27
|
+
model_scores: dict[str, float] | None = None,
|
|
28
|
+
time_limit: float | None = None,
|
|
32
29
|
):
|
|
33
30
|
"""Fit ensemble model given predictions of candidate base models and the true data.
|
|
34
31
|
|
|
@@ -69,9 +66,9 @@ class AbstractTimeSeriesEnsembleModel(TimeSeriesModelBase, ABC):
|
|
|
69
66
|
self,
|
|
70
67
|
predictions_per_window: dict[str, list[TimeSeriesDataFrame]],
|
|
71
68
|
data_per_window: list[TimeSeriesDataFrame],
|
|
72
|
-
model_scores:
|
|
73
|
-
time_limit:
|
|
74
|
-
):
|
|
69
|
+
model_scores: dict[str, float] | None = None,
|
|
70
|
+
time_limit: float | None = None,
|
|
71
|
+
) -> None:
|
|
75
72
|
"""Private method for `fit`. See `fit` for documentation of arguments. Apart from the model
|
|
76
73
|
training logic, `fit` additionally implements other logic such as keeping track of the time limit.
|
|
77
74
|
"""
|
|
@@ -103,37 +100,3 @@ class AbstractTimeSeriesEnsembleModel(TimeSeriesModelBase, ABC):
|
|
|
103
100
|
This method should be called after performing refit_full to point to the refitted base models, if necessary.
|
|
104
101
|
"""
|
|
105
102
|
pass
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
class AbstractWeightedTimeSeriesEnsembleModel(AbstractTimeSeriesEnsembleModel, ABC):
|
|
109
|
-
"""Abstract class for weighted ensembles which assign one (global) weight per model."""
|
|
110
|
-
|
|
111
|
-
def __init__(self, name: Optional[str] = None, **kwargs):
|
|
112
|
-
if name is None:
|
|
113
|
-
name = "WeightedEnsemble"
|
|
114
|
-
super().__init__(name=name, **kwargs)
|
|
115
|
-
self.model_to_weight: dict[str, float] = {}
|
|
116
|
-
|
|
117
|
-
@property
|
|
118
|
-
def model_names(self) -> list[str]:
|
|
119
|
-
return list(self.model_to_weight.keys())
|
|
120
|
-
|
|
121
|
-
@property
|
|
122
|
-
def model_weights(self) -> np.ndarray:
|
|
123
|
-
return np.array(list(self.model_to_weight.values()), dtype=np.float64)
|
|
124
|
-
|
|
125
|
-
def _predict(self, data: dict[str, TimeSeriesDataFrame], **kwargs) -> TimeSeriesDataFrame:
|
|
126
|
-
weighted_predictions = [data[model_name] * weight for model_name, weight in self.model_to_weight.items()]
|
|
127
|
-
return functools.reduce(lambda x, y: x + y, weighted_predictions)
|
|
128
|
-
|
|
129
|
-
def get_info(self) -> dict:
|
|
130
|
-
info = super().get_info()
|
|
131
|
-
info["model_weights"] = self.model_to_weight.copy()
|
|
132
|
-
return info
|
|
133
|
-
|
|
134
|
-
def remap_base_models(self, model_refit_map: dict[str, str]) -> None:
|
|
135
|
-
updated_weights = {}
|
|
136
|
-
for model, weight in self.model_to_weight.items():
|
|
137
|
-
model_full_name = model_refit_map.get(model, model)
|
|
138
|
-
updated_weights[model_full_name] = weight
|
|
139
|
-
self.model_to_weight = updated_weights
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import Any, Sequence
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from autogluon.timeseries.dataset import TimeSeriesDataFrame
|
|
7
|
+
from autogluon.timeseries.metrics.abstract import TimeSeriesScorer
|
|
8
|
+
from autogluon.timeseries.utils.features import CovariateMetadata
|
|
9
|
+
|
|
10
|
+
from ..abstract import AbstractTimeSeriesEnsembleModel
|
|
11
|
+
from .regressor import EnsembleRegressor
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ArrayBasedTimeSeriesEnsembleModel(AbstractTimeSeriesEnsembleModel, ABC):
|
|
15
|
+
"""Abstract base class for time series ensemble models which operate on arrays of base model
|
|
16
|
+
predictions for training and inference.
|
|
17
|
+
|
|
18
|
+
Other Parameters
|
|
19
|
+
----------------
|
|
20
|
+
isotonization: str, default = "sort"
|
|
21
|
+
The isotonization method to use (i.e. the algorithm to prevent quantile non-crossing).
|
|
22
|
+
Currently only "sort" is supported.
|
|
23
|
+
detect_and_ignore_failures: bool, default = True
|
|
24
|
+
Whether to detect and ignore "failed models", defined as models which have a loss that is larger
|
|
25
|
+
than 10x the median loss of all the models. This can be very important for the regression-based
|
|
26
|
+
ensembles, as moving the weight from such a "failed model" to zero can require a long training
|
|
27
|
+
time.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
path: str | None = None,
|
|
33
|
+
name: str | None = None,
|
|
34
|
+
hyperparameters: dict[str, Any] | None = None,
|
|
35
|
+
freq: str | None = None,
|
|
36
|
+
prediction_length: int = 1,
|
|
37
|
+
covariate_metadata: CovariateMetadata | None = None,
|
|
38
|
+
target: str = "target",
|
|
39
|
+
quantile_levels: Sequence[float] = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9),
|
|
40
|
+
eval_metric: str | TimeSeriesScorer | None = None,
|
|
41
|
+
):
|
|
42
|
+
super().__init__(
|
|
43
|
+
path=path,
|
|
44
|
+
name=name,
|
|
45
|
+
hyperparameters=hyperparameters,
|
|
46
|
+
freq=freq,
|
|
47
|
+
prediction_length=prediction_length,
|
|
48
|
+
covariate_metadata=covariate_metadata,
|
|
49
|
+
target=target,
|
|
50
|
+
quantile_levels=quantile_levels,
|
|
51
|
+
eval_metric=eval_metric,
|
|
52
|
+
)
|
|
53
|
+
self.ensemble_regressor: EnsembleRegressor | None = None
|
|
54
|
+
self._model_names: list[str] = []
|
|
55
|
+
|
|
56
|
+
def _get_default_hyperparameters(self) -> dict[str, Any]:
|
|
57
|
+
return {
|
|
58
|
+
"isotonization": "sort",
|
|
59
|
+
"detect_and_ignore_failures": True,
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
@staticmethod
|
|
63
|
+
def to_array(df: TimeSeriesDataFrame) -> np.ndarray:
|
|
64
|
+
"""Given a TimeSeriesDataFrame object, return a single array composing the values contained
|
|
65
|
+
in the data frame.
|
|
66
|
+
|
|
67
|
+
Parameters
|
|
68
|
+
----------
|
|
69
|
+
df
|
|
70
|
+
TimeSeriesDataFrame to convert to an array. Must contain exactly `prediction_length`
|
|
71
|
+
values for each item. The columns of `df` can correspond to ground truth values
|
|
72
|
+
or predictions (in which case, these will be the mean or quantile forecasts).
|
|
73
|
+
|
|
74
|
+
Returns
|
|
75
|
+
-------
|
|
76
|
+
array
|
|
77
|
+
of shape (num_items, prediction_length, num_outputs).
|
|
78
|
+
"""
|
|
79
|
+
assert df.index.is_monotonic_increasing
|
|
80
|
+
array = df.to_numpy()
|
|
81
|
+
num_items = df.num_items
|
|
82
|
+
shape = (
|
|
83
|
+
num_items,
|
|
84
|
+
df.shape[0] // num_items, # timesteps per item
|
|
85
|
+
df.shape[1], # num_outputs
|
|
86
|
+
)
|
|
87
|
+
return array.reshape(shape)
|
|
88
|
+
|
|
89
|
+
def _get_base_model_predictions(
|
|
90
|
+
self,
|
|
91
|
+
predictions_per_window: dict[str, list[TimeSeriesDataFrame]] | dict[str, TimeSeriesDataFrame],
|
|
92
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
93
|
+
"""Given a mapping from model names to a list of data frames representing
|
|
94
|
+
their predictions per window, return a multidimensional array representation.
|
|
95
|
+
|
|
96
|
+
Parameters
|
|
97
|
+
----------
|
|
98
|
+
predictions_per_window
|
|
99
|
+
A dictionary with list[TimeSeriesDataFrame] values, where each TimeSeriesDataFrame
|
|
100
|
+
contains predictions for the window in question. If the dictionary values are
|
|
101
|
+
TimeSeriesDataFrame, they will be treated like a single window.
|
|
102
|
+
|
|
103
|
+
Returns
|
|
104
|
+
-------
|
|
105
|
+
base_model_mean_predictions
|
|
106
|
+
Array of shape (num_windows, num_items, prediction_length, 1, num_models)
|
|
107
|
+
base_model_quantile_predictions
|
|
108
|
+
Array of shape (num_windows, num_items, prediction_length, num_quantiles, num_models)
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
if not predictions_per_window:
|
|
112
|
+
raise ValueError("No base model predictions are provided.")
|
|
113
|
+
|
|
114
|
+
first_prediction = list(predictions_per_window.values())[0]
|
|
115
|
+
if isinstance(first_prediction, TimeSeriesDataFrame):
|
|
116
|
+
predictions_per_window = {k: [v] for k, v in predictions_per_window.items()} # type: ignore
|
|
117
|
+
|
|
118
|
+
predictions = {
|
|
119
|
+
model_name: [self.to_array(window) for window in windows] # type: ignore
|
|
120
|
+
for model_name, windows in predictions_per_window.items()
|
|
121
|
+
}
|
|
122
|
+
base_model_predictions = np.stack([x for x in predictions.values()], axis=-1)
|
|
123
|
+
|
|
124
|
+
return base_model_predictions[:, :, :, :1, :], base_model_predictions[:, :, :, 1:, :]
|
|
125
|
+
|
|
126
|
+
def _isotonize(self, prediction_array: np.ndarray) -> np.ndarray:
|
|
127
|
+
"""Apply isotonization to ensure quantile non-crossing.
|
|
128
|
+
|
|
129
|
+
Parameters
|
|
130
|
+
----------
|
|
131
|
+
prediction_array
|
|
132
|
+
Array of shape (num_windows, num_items, prediction_length, num_quantiles)
|
|
133
|
+
|
|
134
|
+
Returns
|
|
135
|
+
-------
|
|
136
|
+
isotonized_array
|
|
137
|
+
Array with same shape but quantiles sorted along last dimension
|
|
138
|
+
"""
|
|
139
|
+
isotonization = self.get_hyperparameter("isotonization")
|
|
140
|
+
if isotonization == "sort":
|
|
141
|
+
return np.sort(prediction_array, axis=-1)
|
|
142
|
+
return prediction_array
|
|
143
|
+
|
|
144
|
+
def _fit(
|
|
145
|
+
self,
|
|
146
|
+
predictions_per_window: dict[str, list[TimeSeriesDataFrame]],
|
|
147
|
+
data_per_window: list[TimeSeriesDataFrame],
|
|
148
|
+
model_scores: dict[str, float] | None = None,
|
|
149
|
+
time_limit: float | None = None,
|
|
150
|
+
) -> None:
|
|
151
|
+
# process inputs
|
|
152
|
+
filtered_predictions = self._filter_failed_models(predictions_per_window, model_scores)
|
|
153
|
+
base_model_mean_predictions, base_model_quantile_predictions = self._get_base_model_predictions(
|
|
154
|
+
filtered_predictions
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
# process labels
|
|
158
|
+
ground_truth_per_window = [y.slice_by_timestep(-self.prediction_length, None) for y in data_per_window]
|
|
159
|
+
labels = np.stack(
|
|
160
|
+
[self.to_array(gt) for gt in ground_truth_per_window], axis=0
|
|
161
|
+
) # (num_windows, num_items, prediction_length, 1)
|
|
162
|
+
|
|
163
|
+
self._model_names = list(filtered_predictions.keys())
|
|
164
|
+
self.ensemble_regressor = self._get_ensemble_regressor()
|
|
165
|
+
self.ensemble_regressor.fit(
|
|
166
|
+
base_model_mean_predictions=base_model_mean_predictions,
|
|
167
|
+
base_model_quantile_predictions=base_model_quantile_predictions,
|
|
168
|
+
labels=labels,
|
|
169
|
+
time_limit=time_limit,
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
@abstractmethod
|
|
173
|
+
def _get_ensemble_regressor(self) -> EnsembleRegressor:
|
|
174
|
+
pass
|
|
175
|
+
|
|
176
|
+
def _predict(self, data: dict[str, TimeSeriesDataFrame], **kwargs) -> TimeSeriesDataFrame:
|
|
177
|
+
if self.ensemble_regressor is None:
|
|
178
|
+
if not self._model_names:
|
|
179
|
+
raise ValueError("Ensemble model has not been fitted yet.")
|
|
180
|
+
# Try to recreate the regressor (for loaded models)
|
|
181
|
+
self.ensemble_regressor = self._get_ensemble_regressor()
|
|
182
|
+
|
|
183
|
+
input_data = {}
|
|
184
|
+
for m in self.model_names:
|
|
185
|
+
assert m in data, f"Predictions for model {m} not provided during ensemble prediction."
|
|
186
|
+
input_data[m] = data[m]
|
|
187
|
+
|
|
188
|
+
base_model_mean_predictions, base_model_quantile_predictions = self._get_base_model_predictions(input_data)
|
|
189
|
+
|
|
190
|
+
mean_predictions, quantile_predictions = self.ensemble_regressor.predict(
|
|
191
|
+
base_model_mean_predictions=base_model_mean_predictions,
|
|
192
|
+
base_model_quantile_predictions=base_model_quantile_predictions,
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
quantile_predictions = self._isotonize(quantile_predictions)
|
|
196
|
+
prediction_array = np.concatenate([mean_predictions, quantile_predictions], axis=-1)
|
|
197
|
+
|
|
198
|
+
output = list(input_data.values())[0].copy()
|
|
199
|
+
num_folds, num_items, num_timesteps, num_outputs = prediction_array.shape
|
|
200
|
+
assert (num_folds, num_timesteps) == (1, self.prediction_length)
|
|
201
|
+
assert len(output.columns) == num_outputs
|
|
202
|
+
|
|
203
|
+
output[output.columns] = prediction_array.reshape((num_items * num_timesteps, num_outputs))
|
|
204
|
+
|
|
205
|
+
return output
|
|
206
|
+
|
|
207
|
+
@property
|
|
208
|
+
def model_names(self) -> list[str]:
|
|
209
|
+
return self._model_names
|
|
210
|
+
|
|
211
|
+
def remap_base_models(self, model_refit_map: dict[str, str]) -> None:
|
|
212
|
+
"""Update names of the base models based on the mapping in model_refit_map."""
|
|
213
|
+
self._model_names = [model_refit_map.get(name, name) for name in self._model_names]
|
|
214
|
+
|
|
215
|
+
def _filter_failed_models(
|
|
216
|
+
self,
|
|
217
|
+
predictions_per_window: dict[str, list[TimeSeriesDataFrame]],
|
|
218
|
+
model_scores: dict[str, float] | None,
|
|
219
|
+
) -> dict[str, list[TimeSeriesDataFrame]]:
|
|
220
|
+
"""Filter out failed models based on detect_and_ignore_failures setting."""
|
|
221
|
+
if not self.get_hyperparameter("detect_and_ignore_failures"):
|
|
222
|
+
return predictions_per_window
|
|
223
|
+
|
|
224
|
+
if model_scores is None or len(model_scores) == 0:
|
|
225
|
+
return predictions_per_window
|
|
226
|
+
|
|
227
|
+
valid_scores = {k: v for k, v in model_scores.items() if np.isfinite(v)}
|
|
228
|
+
if len(valid_scores) == 0:
|
|
229
|
+
raise ValueError("All models have NaN scores. At least one model must run successfully to fit an ensemble")
|
|
230
|
+
|
|
231
|
+
losses = {k: -v for k, v in valid_scores.items()}
|
|
232
|
+
median_loss = np.nanmedian(list(losses.values()))
|
|
233
|
+
threshold = 10 * median_loss
|
|
234
|
+
good_models = {k for k, loss in losses.items() if loss <= threshold}
|
|
235
|
+
|
|
236
|
+
return {k: v for k, v in predictions_per_window.items() if k in good_models}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from abc import ABC
|
|
2
|
+
from typing import Any, Type
|
|
3
|
+
|
|
4
|
+
from .abstract import ArrayBasedTimeSeriesEnsembleModel
|
|
5
|
+
from .regressor import (
|
|
6
|
+
EnsembleRegressor,
|
|
7
|
+
LinearStackerEnsembleRegressor,
|
|
8
|
+
MedianEnsembleRegressor,
|
|
9
|
+
PerQuantileTabularEnsembleRegressor,
|
|
10
|
+
TabularEnsembleRegressor,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class MedianEnsemble(ArrayBasedTimeSeriesEnsembleModel):
|
|
15
|
+
def _get_ensemble_regressor(self) -> MedianEnsembleRegressor:
|
|
16
|
+
return MedianEnsembleRegressor()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class BaseTabularEnsemble(ArrayBasedTimeSeriesEnsembleModel, ABC):
|
|
20
|
+
ensemble_regressor_type: Type[EnsembleRegressor]
|
|
21
|
+
|
|
22
|
+
def _get_default_hyperparameters(self) -> dict[str, Any]:
|
|
23
|
+
default_hps = super()._get_default_hyperparameters()
|
|
24
|
+
default_hps.update({"model_name": "GBM", "model_hyperparameters": {}})
|
|
25
|
+
return default_hps
|
|
26
|
+
|
|
27
|
+
def _get_ensemble_regressor(self):
|
|
28
|
+
hyperparameters = self.get_hyperparameters()
|
|
29
|
+
return self.ensemble_regressor_type(
|
|
30
|
+
quantile_levels=list(self.quantile_levels),
|
|
31
|
+
model_name=hyperparameters["model_name"],
|
|
32
|
+
model_hyperparameters=hyperparameters["model_hyperparameters"],
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class TabularEnsemble(BaseTabularEnsemble):
|
|
37
|
+
"""Time series ensemble model using a single AutoGluon-Tabular model for all quantiles."""
|
|
38
|
+
|
|
39
|
+
ensemble_regressor_type = TabularEnsembleRegressor
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class PerQuantileTabularEnsemble(BaseTabularEnsemble):
|
|
43
|
+
"""Time series ensemble model using separate AutoGluon-Tabular models for each quantile in
|
|
44
|
+
addition to a dedicated model for the mean (point) forecast.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
ensemble_regressor_type = PerQuantileTabularEnsembleRegressor
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class LinearStackerEnsemble(ArrayBasedTimeSeriesEnsembleModel):
|
|
51
|
+
"""Time series ensemble model using linear stacker with PyTorch optimization."""
|
|
52
|
+
|
|
53
|
+
def _get_default_hyperparameters(self) -> dict[str, Any]:
|
|
54
|
+
default_hps = super()._get_default_hyperparameters()
|
|
55
|
+
default_hps.update(
|
|
56
|
+
{
|
|
57
|
+
"weights_per": "m",
|
|
58
|
+
"lr": 0.1,
|
|
59
|
+
"max_epochs": 10000,
|
|
60
|
+
"relative_tolerance": 1e-7,
|
|
61
|
+
}
|
|
62
|
+
)
|
|
63
|
+
return default_hps
|
|
64
|
+
|
|
65
|
+
def _get_ensemble_regressor(self) -> LinearStackerEnsembleRegressor:
|
|
66
|
+
hps = self.get_hyperparameters()
|
|
67
|
+
return LinearStackerEnsembleRegressor(
|
|
68
|
+
quantile_levels=list(self.quantile_levels),
|
|
69
|
+
weights_per=hps["weights_per"],
|
|
70
|
+
lr=hps["lr"],
|
|
71
|
+
max_epochs=hps["max_epochs"],
|
|
72
|
+
relative_tolerance=hps["relative_tolerance"],
|
|
73
|
+
)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from .abstract import EnsembleRegressor, MedianEnsembleRegressor
|
|
2
|
+
from .linear_stacker import LinearStackerEnsembleRegressor
|
|
3
|
+
from .per_quantile_tabular import PerQuantileTabularEnsembleRegressor
|
|
4
|
+
from .tabular import TabularEnsembleRegressor
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"EnsembleRegressor",
|
|
8
|
+
"LinearStackerEnsembleRegressor",
|
|
9
|
+
"MedianEnsembleRegressor",
|
|
10
|
+
"PerQuantileTabularEnsembleRegressor",
|
|
11
|
+
"TabularEnsembleRegressor",
|
|
12
|
+
]
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from typing_extensions import Self
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class EnsembleRegressor(ABC):
|
|
8
|
+
def __init__(self, *args, **kwargs):
|
|
9
|
+
pass
|
|
10
|
+
|
|
11
|
+
@abstractmethod
|
|
12
|
+
def fit(
|
|
13
|
+
self,
|
|
14
|
+
base_model_mean_predictions: np.ndarray,
|
|
15
|
+
base_model_quantile_predictions: np.ndarray,
|
|
16
|
+
labels: np.ndarray,
|
|
17
|
+
time_limit: float | None = None,
|
|
18
|
+
) -> Self:
|
|
19
|
+
"""
|
|
20
|
+
Parameters
|
|
21
|
+
----------
|
|
22
|
+
base_model_mean_predictions
|
|
23
|
+
Mean (point) predictions of base models. Array of shape
|
|
24
|
+
(num_windows, num_items, prediction_length, 1, num_models)
|
|
25
|
+
|
|
26
|
+
base_model_quantile_predictions
|
|
27
|
+
Quantile predictions of base models. Array of shape
|
|
28
|
+
(num_windows, num_items, prediction_length, num_quantiles, num_models)
|
|
29
|
+
|
|
30
|
+
labels
|
|
31
|
+
Ground truth array of shape
|
|
32
|
+
(num_windows, num_items, prediction_length, 1)
|
|
33
|
+
|
|
34
|
+
time_limit
|
|
35
|
+
Approximately how long `fit` will run (wall-clock time in seconds). If
|
|
36
|
+
not specified, training time will not be limited.
|
|
37
|
+
"""
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
@abstractmethod
|
|
41
|
+
def predict(
|
|
42
|
+
self,
|
|
43
|
+
base_model_mean_predictions: np.ndarray,
|
|
44
|
+
base_model_quantile_predictions: np.ndarray,
|
|
45
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
46
|
+
"""Predict with the fitted ensemble regressor for a single window.
|
|
47
|
+
The items do not have to refer to the same item indices used when fitting
|
|
48
|
+
the model.
|
|
49
|
+
|
|
50
|
+
Parameters
|
|
51
|
+
----------
|
|
52
|
+
base_model_mean_predictions
|
|
53
|
+
Mean (point) predictions of base models. Array of shape
|
|
54
|
+
(1, num_items, prediction_length, 1, num_models)
|
|
55
|
+
|
|
56
|
+
base_model_quantile_predictions
|
|
57
|
+
Quantile predictions of base models. Array of shape
|
|
58
|
+
(1, num_items, prediction_length, num_quantiles, num_models)
|
|
59
|
+
|
|
60
|
+
Returns
|
|
61
|
+
-------
|
|
62
|
+
ensemble_mean_predictions
|
|
63
|
+
Array of shape (1, num_items, prediction_length, 1)
|
|
64
|
+
ensemble_quantile_predictions
|
|
65
|
+
Array of shape (1, num_items, prediction_length, num_quantiles)
|
|
66
|
+
"""
|
|
67
|
+
pass
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class MedianEnsembleRegressor(EnsembleRegressor):
|
|
71
|
+
def fit(
|
|
72
|
+
self,
|
|
73
|
+
base_model_mean_predictions: np.ndarray,
|
|
74
|
+
base_model_quantile_predictions: np.ndarray,
|
|
75
|
+
labels: np.ndarray,
|
|
76
|
+
time_limit: float | None = None,
|
|
77
|
+
) -> Self:
|
|
78
|
+
return self
|
|
79
|
+
|
|
80
|
+
def predict(
|
|
81
|
+
self,
|
|
82
|
+
base_model_mean_predictions: np.ndarray,
|
|
83
|
+
base_model_quantile_predictions: np.ndarray,
|
|
84
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
85
|
+
return (
|
|
86
|
+
np.nanmedian(base_model_mean_predictions, axis=-1),
|
|
87
|
+
np.nanmedian(base_model_quantile_predictions, axis=-1),
|
|
88
|
+
)
|