-
Notifications
You must be signed in to change notification settings - Fork 882
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature/multivariate wrapper #1917
Open
JanFidor
wants to merge
27
commits into
unit8co:master
Choose a base branch
from
JanFidor:feature/multivariate-wrapper
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
83bba23
add global_forecasting_model_wrapper.py
JanFidor 08999fc
add tests
JanFidor a079c8e
add comments
JanFidor ef4d305
Merge branch 'master' into feature/multivariate-wrapper
JanFidor d652e3a
Switch to being a multivariate model wrapper instead of a global mode…
JanFidor ddc3fd3
Merge branch 'unit8co:master' into feature/multivariate-wrapper
JanFidor c2e7037
Merge branch 'master' into feature/multivariate-wrapper
JanFidor ba39d55
refactor
JanFidor 48cb156
add missing property decorator
JanFidor fb1c06b
update tests
JanFidor 450e081
Merge branch 'master' into feature/multivariate-wrapper
madtoinou 36d3f13
Merge branch 'master' into feature/multivariate-wrapper
madtoinou 5a0e32a
Improve testing code for MultivariateForecastingModelWrapper
felixdivo 8c1b573
Merge pull request #1 from felixdivo/feature/multivariate-wrapper
JanFidor 908cfd4
Merge remote-tracking branch 'upstream/master' into feature/multivari…
JanFidor bf64cff
Expand description
JanFidor aea93b1
Refactor fit loop to make it more intuitive
JanFidor 05af0ca
delete function and rewrite docstring
JanFidor 37226d3
fix future_covariates error
JanFidor 2b4138a
Merge branch 'master' into feature/multivariate-wrapper
madtoinou 90303d6
Merge remote-tracking branch 'upstream/master' into feature/multivari…
JanFidor 908b1ef
parametrize test
JanFidor f7ca592
lint
JanFidor 7386d9e
add to __all__ init.py
JanFidor 219b933
update import
JanFidor 40e87d3
parametrize encoder support
JanFidor e0eb50b
Merge branch 'master' into feature/multivariate-wrapper
madtoinou File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
145 changes: 145 additions & 0 deletions
145
darts/models/forecasting/multivariate_forecasting_model_wrapper.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,145 @@ | ||
""" | ||
Multivariate forecasting model wrapper | ||
------------------------- | ||
|
||
A wrapper around local forecasting models to enable multivariate series training and forecasting. One model is trained | ||
for each component of the target series, independently of the others hence ignoring the potential interactions between | ||
its components. | ||
""" | ||
|
||
from typing import List, Optional, Tuple | ||
|
||
from darts.logging import get_logger, raise_if_not | ||
from darts.models.forecasting.forecasting_model import ( | ||
FutureCovariatesLocalForecastingModel, | ||
LocalForecastingModel, | ||
TransferableFutureCovariatesLocalForecastingModel, | ||
) | ||
from darts.timeseries import TimeSeries, concatenate | ||
from darts.utils.ts_utils import seq2series | ||
|
||
logger = get_logger(__name__) | ||
|
||
|
||
class MultivariateForecastingModelWrapper(FutureCovariatesLocalForecastingModel): | ||
def __init__(self, model: LocalForecastingModel): | ||
""" | ||
Wrapper for univariate LocalForecastingModel to enable multivariate series training and forecasting. | ||
|
||
A copy of the provided model will be trained independently on each component of the target series, ignoring the | ||
potential interactions. | ||
---------- | ||
model | ||
Model used to predict individual components | ||
""" | ||
super().__init__() | ||
|
||
self.model: LocalForecastingModel = model | ||
self._trained_models: List[LocalForecastingModel] = [] | ||
|
||
def _fit(self, series: TimeSeries, future_covariates: Optional[TimeSeries] = None): | ||
super()._fit(series, future_covariates) | ||
self._trained_models = [] | ||
|
||
series = seq2series(series) | ||
for comp in series.components: | ||
comp = series.univariate_component(comp) | ||
component_model = ( | ||
self.model.untrained_model().fit( | ||
series=comp, future_covariates=future_covariates | ||
) | ||
if self.supports_future_covariates | ||
else self.model.untrained_model().fit(series=comp) | ||
) | ||
self._trained_models.append(component_model) | ||
|
||
return self | ||
|
||
def predict( | ||
self, | ||
n: int, | ||
series: Optional[TimeSeries] = None, | ||
future_covariates: Optional[TimeSeries] = None, | ||
num_samples: int = 1, | ||
**kwargs, | ||
) -> TimeSeries: | ||
return self._predict(n, future_covariates, num_samples, **kwargs) | ||
|
||
def _predict( | ||
self, | ||
n: int, | ||
future_covariates: Optional[TimeSeries] = None, | ||
num_samples: int = 1, | ||
verbose: bool = False, | ||
**kwargs, | ||
) -> TimeSeries: | ||
predictions = [ | ||
model.predict(n=n, future_covariates=future_covariates) | ||
if self.supports_future_covariates | ||
else model.predict(n=n) | ||
for model in self._trained_models | ||
] | ||
|
||
raise_if_not( | ||
len(predictions) == len(self._trained_models), | ||
f"Prediction contains {len(predictions)} components but {len(self._trained_models)} models were fitted", | ||
) | ||
|
||
return concatenate(predictions, axis=1) | ||
|
||
@property | ||
def extreme_lags( | ||
self, | ||
) -> Tuple[ | ||
Optional[int], | ||
Optional[int], | ||
Optional[int], | ||
Optional[int], | ||
Optional[int], | ||
Optional[int], | ||
]: | ||
return self.model.extreme_lags | ||
|
||
@property | ||
def _model_encoder_settings( | ||
self, | ||
) -> Tuple[ | ||
Optional[int], | ||
Optional[int], | ||
bool, | ||
bool, | ||
Optional[List[int]], | ||
Optional[List[int]], | ||
]: | ||
return None, None, False, self.supports_future_covariates, None, None | ||
|
||
@property | ||
def supports_multivariate(self) -> bool: | ||
return True | ||
|
||
@property | ||
def supports_past_covariates(self) -> bool: | ||
return self.model.supports_past_covariates | ||
|
||
@property | ||
def supports_future_covariates(self) -> bool: | ||
return self.model.supports_future_covariates | ||
|
||
@property | ||
def supports_static_covariates(self) -> bool: | ||
return self.model.supports_static_covariates | ||
|
||
@property | ||
def _is_probabilistic(self) -> bool: | ||
""" | ||
A MultivariateForecastingModelWrapper is probabilistic if the base_model | ||
is probabilistic | ||
""" | ||
return self.model._is_probabilistic | ||
|
||
def _supports_non_retrainable_historical_forecasts(self) -> bool: | ||
return isinstance(self.model, TransferableFutureCovariatesLocalForecastingModel) | ||
|
||
@property | ||
def _supress_generate_predict_encoding(self) -> bool: | ||
return isinstance(self.model, TransferableFutureCovariatesLocalForecastingModel) |
130 changes: 130 additions & 0 deletions
130
darts/tests/models/forecasting/test_multivariate_forecasting_model_wrapper.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
import copy | ||
|
||
import pytest | ||
|
||
from darts import TimeSeries | ||
from darts.logging import get_logger | ||
from darts.models import ( | ||
ARIMA, | ||
BATS, | ||
FFT, | ||
TBATS, | ||
AutoARIMA, | ||
Croston, | ||
ExponentialSmoothing, | ||
FourTheta, | ||
KalmanForecaster, | ||
MultivariateForecastingModelWrapper, | ||
NaiveMean, | ||
NaiveMovingAverage, | ||
NaiveSeasonal, | ||
Prophet, | ||
StatsForecastAutoCES, | ||
StatsForecastAutoTheta, | ||
Theta, | ||
) | ||
from darts.utils import timeseries_generation as tg | ||
|
||
logger = get_logger(__name__) | ||
|
||
local_models = [ | ||
NaiveMean(), | ||
NaiveMovingAverage(5), | ||
NaiveSeasonal(), | ||
ExponentialSmoothing(), | ||
StatsForecastAutoTheta(season_length=12), | ||
StatsForecastAutoCES(season_length=12, model="Z"), | ||
Theta(1), | ||
FourTheta(1), | ||
FFT(trend="poly"), | ||
TBATS(use_trend=True, use_arma_errors=True, use_box_cox=True), | ||
BATS(use_trend=True, use_arma_errors=True, use_box_cox=True), | ||
] | ||
|
||
future_covariates_models = [ | ||
Prophet(), | ||
Croston(), | ||
AutoARIMA(), | ||
ARIMA(12, 1, 1), | ||
KalmanForecaster(), | ||
] | ||
|
||
|
||
class TestMultivariateForecastingModelWrapper: | ||
RANDOM_SEED = 42 | ||
|
||
ts_length = 50 | ||
n_pred = 5 | ||
|
||
univariate = tg.gaussian_timeseries(length=ts_length, mean=50) | ||
multivariate = univariate.stack(tg.gaussian_timeseries(length=ts_length, mean=20)) | ||
|
||
future_covariates = tg.gaussian_timeseries(length=ts_length + n_pred, mean=50) | ||
|
||
@pytest.mark.parametrize("model", local_models) | ||
@pytest.mark.parametrize("series", [univariate, multivariate]) | ||
def test_fit_predict_local_models(self, model, series): | ||
self._test_predict_with_base_model(model, series) | ||
|
||
@pytest.mark.parametrize("model", future_covariates_models) | ||
@pytest.mark.parametrize("series", [univariate, multivariate]) | ||
def test_fit_predict_local_future_covariates_models(self, model, series): | ||
self._test_predict_with_base_model(model, series, self.future_covariates) | ||
|
||
@pytest.mark.parametrize("model_object", future_covariates_models) | ||
@pytest.mark.parametrize("series", [univariate, multivariate]) | ||
@pytest.mark.parametrize("future_covariates", [future_covariates, None]) | ||
def test_encoders_support(self, model_object, series, future_covariates): | ||
add_encoders = { | ||
"position": {"future": ["relative"]}, | ||
} | ||
|
||
model_params = { | ||
k: vals for k, vals in copy.deepcopy(model_object.model_params).items() | ||
} | ||
model_params["add_encoders"] = add_encoders | ||
model = model_object.__class__(**model_params) | ||
|
||
self._test_predict_with_base_model(model, series, future_covariates) | ||
|
||
def _test_predict_with_base_model( | ||
self, model, series: TimeSeries, future_covariates=None | ||
): | ||
print(type(series), isinstance(series, TimeSeries)) | ||
preds = self.trained_model_predictions( | ||
model, self.n_pred, series, future_covariates | ||
) | ||
assert isinstance(preds, TimeSeries) | ||
assert preds.n_components == series.n_components | ||
|
||
# Make sure that the compound prediction is the same as the individual predictions | ||
individual_preds = self.trained_individual_model_predictions( | ||
model, self.n_pred, series, future_covariates | ||
) | ||
for component in range(series.n_components): | ||
assert preds.univariate_component(component) == individual_preds[component] | ||
|
||
def trained_model_predictions(self, base_model, n, series, future_covariates): | ||
model = MultivariateForecastingModelWrapper(base_model) | ||
print(series) | ||
model.fit(series, future_covariates=future_covariates) | ||
return model.predict(n=n, series=series, future_covariates=future_covariates) | ||
|
||
def trained_individual_model_predictions( | ||
self, base_model, n, series, future_covariates | ||
): | ||
predictions = [] | ||
for component in range(series.n_components): | ||
single_series = series.univariate_component(component) | ||
|
||
model = base_model.untrained_model() | ||
if model.supports_future_covariates: | ||
model.fit(single_series, future_covariates=future_covariates) | ||
predictions.append( | ||
model.predict(n=n, future_covariates=future_covariates) | ||
) | ||
else: | ||
model.fit(single_series) | ||
predictions.append(model.predict(n=n)) | ||
|
||
return predictions |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Your tests are not matching the style of the others tests, please look how they are defined in test_local_forecasting_models.py (especially the parametrize decorator and the helper functions)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should be fixed now (8c1b573)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of loops in the
test_fit_predict_local_models()
andtest_fit_predict_local_future_covariates_models()
what will make the test fail if one of the model fails, without indicating which one, it would be great to leveragepytest.mark.parametrize
and replace the list of instantiated models with a list of kwargs (one for local, one for local that supports future covariates), that would then be used to create the model before fit/predict (as done here).Also, testing models that support future covariates without actually passing future covariates in
fit()
would be great.