-
Notifications
You must be signed in to change notification settings - Fork 82
Add SaveEnsembleMixin
#1046
Merged
Merged
Add SaveEnsembleMixin
#1046
Changes from 4 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
b515027
Add SaveEnsembleMixin and tests for it
53ab49c
Add SaveEnsembleMixin into ensembles, fix tests
d75ba1a
Fix test for SaveModelPipelineMixin
21d5407
Update changelog
d706004
Fix number of digits
68283a7
Fix tests, reformat code
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
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
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 |
---|---|---|
@@ -1,4 +1,4 @@ | ||
from etna.ensembles.base import EnsembleMixin | ||
from etna.ensembles.direct_ensemble import DirectEnsemble | ||
from etna.ensembles.mixins import EnsembleMixin | ||
from etna.ensembles.stacking_ensemble import StackingEnsemble | ||
from etna.ensembles.voting_ensemble import VotingEnsemble |
This file was deleted.
Oops, something went wrong.
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
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,148 @@ | ||
import pathlib | ||
import tempfile | ||
import zipfile | ||
from copy import deepcopy | ||
from typing import Any | ||
from typing import List | ||
from typing import Optional | ||
|
||
import pandas as pd | ||
|
||
from etna.core import SaveMixin | ||
from etna.core import load | ||
from etna.datasets import TSDataset | ||
from etna.loggers import tslogger | ||
from etna.pipeline.base import BasePipeline | ||
|
||
|
||
class EnsembleMixin: | ||
"""Base mixin for the ensembles.""" | ||
|
||
@staticmethod | ||
def _validate_pipeline_number(pipelines: List[BasePipeline]): | ||
"""Check that given valid number of pipelines.""" | ||
if len(pipelines) < 2: | ||
raise ValueError("At least two pipelines are expected.") | ||
|
||
@staticmethod | ||
def _get_horizon(pipelines: List[BasePipeline]) -> int: | ||
"""Get ensemble's horizon.""" | ||
horizons = {pipeline.horizon for pipeline in pipelines} | ||
if len(horizons) > 1: | ||
raise ValueError("All the pipelines should have the same horizon.") | ||
return horizons.pop() | ||
|
||
@staticmethod | ||
def _fit_pipeline(pipeline: BasePipeline, ts: TSDataset) -> BasePipeline: | ||
"""Fit given pipeline with ``ts``.""" | ||
tslogger.log(msg=f"Start fitting {pipeline}.") | ||
pipeline.fit(ts=ts) | ||
tslogger.log(msg=f"Pipeline {pipeline} is fitted.") | ||
return pipeline | ||
|
||
@staticmethod | ||
def _forecast_pipeline(pipeline: BasePipeline) -> TSDataset: | ||
"""Make forecast with given pipeline.""" | ||
tslogger.log(msg=f"Start forecasting with {pipeline}.") | ||
forecast = pipeline.forecast() | ||
tslogger.log(msg=f"Forecast is done with {pipeline}.") | ||
return forecast | ||
|
||
@staticmethod | ||
def _predict_pipeline( | ||
ts: TSDataset, | ||
pipeline: BasePipeline, | ||
start_timestamp: Optional[pd.Timestamp], | ||
end_timestamp: Optional[pd.Timestamp], | ||
) -> TSDataset: | ||
"""Make predict with given pipeline.""" | ||
tslogger.log(msg=f"Start prediction with {pipeline}.") | ||
prediction = pipeline.predict(ts=ts, start_timestamp=start_timestamp, end_timestamp=end_timestamp) | ||
tslogger.log(msg=f"Prediction is done with {pipeline}.") | ||
return prediction | ||
|
||
|
||
class SaveEnsembleMixin(SaveMixin): | ||
"""Implementation of ``AbstractSaveable`` abstract class for ensemble pipelines. | ||
|
||
It saves object to the zip archive with 3 entities: | ||
|
||
* metadata.json: contains library version and class name. | ||
|
||
* object.pkl: pickled without pipelines and ts. | ||
|
||
* pipelines: folder with saved pipelines. | ||
""" | ||
|
||
pipelines: List[BasePipeline] | ||
ts: Optional[TSDataset] | ||
|
||
def save(self, path: pathlib.Path): | ||
"""Save the object. | ||
|
||
Parameters | ||
---------- | ||
path: | ||
Path to save object to. | ||
""" | ||
pipelines = self.pipelines | ||
ts = self.ts | ||
try: | ||
# extract attributes we can't easily save | ||
delattr(self, "pipelines") | ||
delattr(self, "ts") | ||
|
||
# save the remaining part | ||
super().save(path=path) | ||
finally: | ||
self.pipelines = pipelines | ||
self.ts = ts | ||
|
||
with zipfile.ZipFile(path, "a") as archive: | ||
with tempfile.TemporaryDirectory() as _temp_dir: | ||
temp_dir = pathlib.Path(_temp_dir) | ||
|
||
# save transforms separately | ||
pipelines_dir = temp_dir / "pipelines" | ||
pipelines_dir.mkdir() | ||
num_digits = len(str(len(pipelines) - 1)) | ||
for i, pipeline in enumerate(pipelines): | ||
save_name = f"{i:0{num_digits}d}.zip" | ||
pipeline_save_path = pipelines_dir / save_name | ||
pipeline.save(pipeline_save_path) | ||
archive.write(pipeline_save_path, f"pipelines/{save_name}") | ||
|
||
@classmethod | ||
def load(cls, path: pathlib.Path, ts: Optional[TSDataset] = None) -> Any: | ||
"""Load an object. | ||
|
||
Parameters | ||
---------- | ||
path: | ||
Path to load object from. | ||
ts: | ||
TSDataset to set into loaded pipeline. | ||
|
||
Returns | ||
------- | ||
: | ||
Loaded object. | ||
""" | ||
obj = super().load(path=path) | ||
obj.ts = deepcopy(ts) | ||
|
||
with zipfile.ZipFile(path, "r") as archive: | ||
with tempfile.TemporaryDirectory() as _temp_dir: | ||
temp_dir = pathlib.Path(_temp_dir) | ||
|
||
archive.extractall(temp_dir) | ||
|
||
# load pipelines | ||
pipelines_dir = temp_dir / "pipelines" | ||
pipelines = [] | ||
for path in sorted(pipelines_dir.iterdir()): | ||
pipelines.append(load(path, ts=ts)) | ||
|
||
obj.pipelines = pipelines | ||
|
||
return obj |
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
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
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
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
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.
💣
What do you want to do?
We always can use fix len - for example 8 symbols - it will be enough
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.
Ok, I will also change that for transforms (we have the same logic where).