metaforecast 0.1.0__tar.gz

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.
Files changed (32) hide show
  1. metaforecast-0.1.0/.gitignore +169 -0
  2. metaforecast-0.1.0/PKG-INFO +15 -0
  3. metaforecast-0.1.0/README.md +1 -0
  4. metaforecast-0.1.0/metaforecast/__init__.py +0 -0
  5. metaforecast-0.1.0/metaforecast/ensembles/__init__.py +0 -0
  6. metaforecast-0.1.0/metaforecast/ensembles/ade.py +320 -0
  7. metaforecast-0.1.0/metaforecast/ensembles/base.py +351 -0
  8. metaforecast-0.1.0/metaforecast/ensembles/expert_loss.py +86 -0
  9. metaforecast-0.1.0/metaforecast/ensembles/mlewa.py +71 -0
  10. metaforecast-0.1.0/metaforecast/ensembles/mlpol.py +75 -0
  11. metaforecast-0.1.0/metaforecast/ensembles/static.py +58 -0
  12. metaforecast-0.1.0/metaforecast/ensembles/windowing.py +97 -0
  13. metaforecast-0.1.0/metaforecast/longhorizon/__init__.py +0 -0
  14. metaforecast-0.1.0/metaforecast/longhorizon/ftn.py +162 -0
  15. metaforecast-0.1.0/metaforecast/synth/__init__.py +0 -0
  16. metaforecast-0.1.0/metaforecast/synth/generators/__init__.py +0 -0
  17. metaforecast-0.1.0/metaforecast/synth/generators/_base.py +181 -0
  18. metaforecast-0.1.0/metaforecast/synth/generators/dba.py +56 -0
  19. metaforecast-0.1.0/metaforecast/synth/generators/jittering.py +24 -0
  20. metaforecast-0.1.0/metaforecast/synth/generators/kernelsynth.py +118 -0
  21. metaforecast-0.1.0/metaforecast/synth/generators/mbb.py +82 -0
  22. metaforecast-0.1.0/metaforecast/synth/generators/scaling.py +21 -0
  23. metaforecast-0.1.0/metaforecast/synth/generators/tsmixup.py +78 -0
  24. metaforecast-0.1.0/metaforecast/synth/generators/warping_mag.py +44 -0
  25. metaforecast-0.1.0/metaforecast/synth/generators/warping_time.py +43 -0
  26. metaforecast-0.1.0/metaforecast/utils/__init__.py +0 -0
  27. metaforecast-0.1.0/metaforecast/utils/barycenters.py +67 -0
  28. metaforecast-0.1.0/metaforecast/utils/data.py +23 -0
  29. metaforecast-0.1.0/metaforecast/utils/log.py +16 -0
  30. metaforecast-0.1.0/metaforecast/utils/normalization.py +25 -0
  31. metaforecast-0.1.0/metaforecast/utils/windows.py +78 -0
  32. metaforecast-0.1.0/pyproject.toml +32 -0
@@ -0,0 +1,169 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ .idea/
163
+ lightning_logs
164
+
165
+
166
+ # Custom
167
+ assets/
168
+ experiments_extra/
169
+ scripts/
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.3
2
+ Name: metaforecast
3
+ Version: 0.1.0
4
+ Summary: Meta-learning and Data-centric Forecasting
5
+ Project-URL: Homepage, https://github.com/vcerqueira/metaforecast
6
+ Project-URL: Bug Tracker, https://github.com/vcerqueira/metaforecast/issues
7
+ Author-email: Vitor Cerqueira <cerqueira.vitormanuel@gmail.com>
8
+ Keywords: Data Science,Forecasting,Machine Learning,Time Series
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+
15
+ meta-learning and data-centric AI for actionable forecasting
@@ -0,0 +1 @@
1
+ meta-learning and data-centric AI for actionable forecasting
File without changes
File without changes
@@ -0,0 +1,320 @@
1
+ from typing import Union, Tuple, List, Optional
2
+
3
+ import pandas as pd
4
+ import lightgbm as lgb
5
+ from mlforecast import MLForecast
6
+ from statsforecast import StatsForecast
7
+
8
+ from sklearn.multioutput import MultiOutputRegressor as MIMO
9
+
10
+ from metaforecast.utils.normalization import Normalizations
11
+ from metaforecast.ensembles.base import BaseADE
12
+
13
+ DForDFTuple = Union[pd.DataFrame, Tuple[pd.DataFrame, pd.DataFrame]]
14
+
15
+
16
+ class ADE(BaseADE):
17
+ LGB_PARS = {'verbosity': -1, 'n_jobs': 1, 'linear_tree': True}
18
+
19
+ def __init__(self,
20
+ freq: str,
21
+ trim_ratio: float,
22
+ meta_lags: List[int],
23
+ trim_by_uid: bool = True,
24
+ meta_model=MIMO(lgb.LGBMRegressor(**LGB_PARS))):
25
+ """
26
+ :param trim_ratio:
27
+ :param meta_model:
28
+ """
29
+ self.frequency = freq
30
+
31
+ super().__init__(window_size=self.WINDOW_SIZE_BY_FREQ[self.frequency],
32
+ trim_ratio=trim_ratio,
33
+ trim_by_uid=trim_by_uid,
34
+ meta_model=meta_model)
35
+
36
+ self.model_names = None
37
+
38
+ self.meta_lags = meta_lags
39
+ self.lag_names = [f'lag{i}' for i in self.meta_lags]
40
+
41
+ self.meta_mlf = MLForecast(
42
+ models=[],
43
+ freq=self.frequency,
44
+ lags=self.meta_lags
45
+ )
46
+
47
+ self.meta_df = None
48
+ self.raw_meta_data = None
49
+ self.insample_scores = None
50
+ self.use_window = False
51
+
52
+ def fit(self, insample_fcst: pd.DataFrame, **kwargs):
53
+ """
54
+
55
+ """
56
+
57
+ self._fit(insample_fcst)
58
+
59
+ def _fit(self, insample_fcst):
60
+ if self.model_names is None:
61
+ self.model_names = insample_fcst.columns.to_list()
62
+ self.model_names = [x for x in self.model_names if x not in self.METADATA + ['h']]
63
+
64
+ self._set_n_models()
65
+
66
+ in_sample_loss_df = self._get_insample_loss(insample_fcst)
67
+
68
+ self.insample_scores = self.evaluate_base_fcst(insample_fcst=insample_fcst,
69
+ use_window=self.use_window)
70
+
71
+ self.raw_meta_data = self.meta_mlf.preprocess(in_sample_loss_df)
72
+
73
+ self.meta_df = self._process_meta_data(self.raw_meta_data)
74
+
75
+ x, y = self.meta_df
76
+ # print(y.isna().mean())
77
+ if y.isna().any().any():
78
+ y = y.ffill().bfill()
79
+
80
+ self.meta_model.fit(x, y)
81
+
82
+ def predict(self, preds: pd.DataFrame, train: pd.DataFrame, h: int):
83
+
84
+ fcst = self._predict(preds=preds, train=train, h=h)
85
+ fcst.name = self.alias
86
+
87
+ return fcst
88
+
89
+ def update_weights(self, fcst: pd.DataFrame):
90
+ raise NotImplementedError
91
+
92
+ def _predict(self, preds: pd.DataFrame, train: pd.DataFrame, h: int):
93
+ # could use ade.mlf.make_future_dataframe(h=4)
94
+ df_ext = train.merge(preds, on=['unique_id', 'ds'], how='outer')
95
+ df_ext = df_ext[self.METADATA]
96
+ df_ext['y'] = df_ext['y'].fillna(value=-1)
97
+
98
+ meta_dataset = self.meta_mlf.preprocess(df_ext)
99
+
100
+ weights = self._weights_by_uid(meta_dataset, h=h)
101
+
102
+ fcst = preds.apply(lambda x: self._weighted_average(x, weights), axis=1)
103
+
104
+ return fcst
105
+
106
+ def _get_insample_loss(self, insample_fcst: pd.DataFrame):
107
+ in_sample_loss = []
108
+ in_sample_uid = insample_fcst.copy().groupby('unique_id')
109
+ for uid, uid_df in in_sample_uid:
110
+ for mod in self.model_names:
111
+ uid_df[mod] = uid_df[mod] - uid_df['y']
112
+
113
+ in_sample_loss.append(uid_df)
114
+
115
+ in_sample_loss_df = pd.concat(in_sample_loss)
116
+
117
+ # first h forward
118
+ # could average all horizons
119
+ if 'h' in in_sample_loss_df.columns:
120
+ in_sample_loss_df = in_sample_loss_df.query('h==1').drop(columns=['h'])
121
+
122
+ return in_sample_loss_df
123
+
124
+ def _process_meta_data(self,
125
+ meta_data: pd.DataFrame,
126
+ return_X_y: bool = True) -> DForDFTuple:
127
+
128
+ lag_locs = meta_data.columns.str.startswith('lag')
129
+ lag_cols = meta_data.columns[lag_locs].to_list()
130
+
131
+ if return_X_y:
132
+ X_meta, Y_meta = meta_data[lag_cols], meta_data[self.model_names]
133
+ return X_meta, Y_meta
134
+ else:
135
+ meta_df = meta_data[lag_cols + self.model_names]
136
+
137
+ return meta_df
138
+
139
+ def _weights_by_uid(self, df: pd.DataFrame, h: int):
140
+ top_overall = self._get_top_k(self.insample_scores.mean())
141
+ top_by_uid = self.insample_scores.apply(self._get_top_k, axis=1)
142
+
143
+ uid_weights = {}
144
+ for uid, meta_uid_df in df.groupby('unique_id'):
145
+ if h > 1:
146
+ lags = meta_uid_df.head(-(h - 1)).tail(1)[self.lag_names]
147
+ else:
148
+ lags = meta_uid_df.tail(1)[self.lag_names]
149
+
150
+ meta_pred = self.meta_model.predict(lags)
151
+ meta_pred = pd.DataFrame(meta_pred, columns=self.model_names)
152
+
153
+ weights = self._weights_from_errors(meta_pred)
154
+
155
+ if self.trim_by_uid:
156
+ poor_models = [x not in top_by_uid[uid] for x in weights.index]
157
+ else:
158
+ poor_models = [x not in top_overall for x in weights.index]
159
+
160
+ weights[poor_models] = 0
161
+ weights /= weights.sum()
162
+
163
+ uid_weights[uid] = weights
164
+
165
+ weights_df = pd.DataFrame(uid_weights).T
166
+ weights_df.index.name = 'unique_id'
167
+
168
+ return weights_df
169
+
170
+ def _reweight_by_redundancy(self):
171
+ raise NotImplementedError
172
+
173
+ @staticmethod
174
+ def _weights_from_errors(meta_predictions: pd.DataFrame) -> pd.Series:
175
+ e_hat = meta_predictions.abs()
176
+
177
+ W = e_hat.apply(
178
+ func=lambda x: Normalizations.normalize_and_proportion(-x),
179
+ axis=1)
180
+
181
+ weight_s = W.iloc[0]
182
+
183
+ return weight_s
184
+
185
+
186
+ class GlobalADE(ADE):
187
+ ## todo in inference lags are the same of all
188
+ # could include past errors...
189
+
190
+ def __init__(self,
191
+ freq: str,
192
+ trim_ratio: float,
193
+ meta_lags: List[int],
194
+ trim_by_uid: bool = True,
195
+ meta_model=lgb.LGBMRegressor(**ADE.LGB_PARS)):
196
+
197
+ super().__init__(freq=freq,
198
+ trim_ratio=trim_ratio,
199
+ meta_lags=meta_lags,
200
+ trim_by_uid=trim_by_uid,
201
+ meta_model=meta_model)
202
+
203
+ self.alias = 'GADE'
204
+
205
+ def _process_meta_data(self,
206
+ meta_data: pd.DataFrame,
207
+ return_X_y: bool = True) -> DForDFTuple:
208
+
209
+ lag_locs = meta_data.columns.str.startswith('lag')
210
+ lag_cols = meta_data.columns[lag_locs].to_list()
211
+
212
+ df_melt = meta_data.drop(columns='y').melt(['unique_id', 'ds'] + lag_cols)
213
+ df_melt['unique_id'] = df_melt.apply(lambda x: f'{x["unique_id"]}_{x["variable"]}', axis=1)
214
+ df_melt = df_melt.rename(columns={'value': 'error'})
215
+
216
+ if return_X_y:
217
+ X_meta, Y_meta = df_melt[lag_cols], df_melt['error']
218
+ return X_meta, Y_meta
219
+ else:
220
+ meta_df = df_melt[lag_cols + ['error']]
221
+
222
+ return meta_df
223
+
224
+ def _weights_by_uid(self, df: pd.DataFrame, h: int):
225
+ top_overall = self._get_top_k(self.insample_scores.mean())
226
+ top_by_uid = self.insample_scores.apply(self._get_top_k, axis=1)
227
+
228
+ uid_weights = {}
229
+ for uid, meta_uid_df in df.groupby('unique_id'):
230
+ lags = meta_uid_df.head(-(h - 1)).tail(1)[self.lag_names]
231
+
232
+ meta_pred = self.meta_model.predict(lags)
233
+ meta_pred = pd.DataFrame(meta_pred, columns=self.model_names)
234
+
235
+ weights = self._weights_from_errors(meta_pred)
236
+
237
+ if self.trim_by_uid:
238
+ poor_models = [x not in top_by_uid[uid] for x in weights.index]
239
+ else:
240
+ poor_models = [x not in top_overall for x in weights.index]
241
+
242
+ weights[poor_models] = 0
243
+ weights /= weights.sum()
244
+
245
+ uid_weights[uid] = weights
246
+
247
+ weights_df = pd.DataFrame(uid_weights).T
248
+ weights_df.index.name = 'unique_id'
249
+
250
+ return weights_df
251
+
252
+ def _reweight_by_redundancy(self):
253
+ raise NotImplementedError
254
+
255
+ def update_weights(self, fcst: pd.DataFrame):
256
+ raise NotImplementedError
257
+
258
+
259
+ class MLForecastADE(ADE):
260
+
261
+ def __init__(self,
262
+ mlf: MLForecast,
263
+ trim_ratio: float,
264
+ sf: Optional[StatsForecast] = None,
265
+ meta_model=MIMO(lgb.LGBMRegressor(**ADE.LGB_PARS))):
266
+ """
267
+ :param trim_ratio:
268
+ :param meta_model:
269
+ """
270
+ self.mlf = mlf
271
+ self.sf = sf
272
+ self.frequency = self.mlf.ts.freq
273
+
274
+ super().__init__(freq=self.frequency,
275
+ trim_ratio=trim_ratio,
276
+ meta_model=meta_model,
277
+ meta_lags=self.mlf.ts.lags)
278
+
279
+ def fit(self, **kwargs):
280
+ """
281
+
282
+ """
283
+
284
+ insample_fcst = self.mlf.fcst_fitted_values_
285
+
286
+ if self.sf is not None:
287
+ self.sf.forecast(fitted=True, h=1)
288
+ insample_fcst_sf = self.sf.forecast_fitted_values()
289
+
290
+ insample_fcst = insample_fcst.merge(insample_fcst_sf.drop(columns='y'),
291
+ on=self.METADATA_NO_T)
292
+
293
+ self._fit(insample_fcst)
294
+
295
+ def predict(self, train: pd.DataFrame, h: int, **kwargs):
296
+ base_fcst = self.mlf.predict(h=h)
297
+
298
+ if self.sf is not None:
299
+ base_fcst_sf = self.sf.predict(h=h)
300
+
301
+ base_fcst = base_fcst.merge(base_fcst_sf, on=self.METADATA_NO_T)
302
+
303
+ fcst = self._predict(preds=base_fcst, train=train, h=h)
304
+
305
+ return fcst
306
+
307
+ def update_weights(self, fcst: pd.DataFrame):
308
+ raise NotImplementedError
309
+
310
+ def _reweight_by_redundancy(self):
311
+ raise NotImplementedError
312
+
313
+ def update_estimates(self, df: pd.DataFrame):
314
+ """
315
+ Updating loss statistics for dynamic model selection
316
+
317
+ :param df: dataset with actual values and predictions, similar to insample predictions
318
+ """
319
+
320
+ raise NotImplementedError