genformer 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.
- genformer-0.1.0/LICENSE +21 -0
- genformer-0.1.0/PKG-INFO +159 -0
- genformer-0.1.0/README.md +119 -0
- genformer-0.1.0/genformer/__init__.py +9 -0
- genformer-0.1.0/genformer/data.py +193 -0
- genformer-0.1.0/genformer/metrics.py +144 -0
- genformer-0.1.0/genformer/models.py +514 -0
- genformer-0.1.0/genformer/noise.py +149 -0
- genformer-0.1.0/genformer/utils.py +288 -0
- genformer-0.1.0/genformer.egg-info/PKG-INFO +159 -0
- genformer-0.1.0/genformer.egg-info/SOURCES.txt +14 -0
- genformer-0.1.0/genformer.egg-info/dependency_links.txt +1 -0
- genformer-0.1.0/genformer.egg-info/requires.txt +15 -0
- genformer-0.1.0/genformer.egg-info/top_level.txt +1 -0
- genformer-0.1.0/pyproject.toml +69 -0
- genformer-0.1.0/setup.cfg +4 -0
genformer-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tanujit Chakraborty and Authors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
genformer-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: genformer
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Deep Generative Transformers for Probabilistic Time Series and Spatiotemporal Forecasting
|
|
5
|
+
Author: Rahul Goswami, Donia Besher, Rajdeep Pathak, Madhurima Panja, Tanujit Chakraborty
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/yuvrajiro/Genformer
|
|
8
|
+
Project-URL: Documentation, https://github.com/yuvrajiro/Genformer#readme
|
|
9
|
+
Project-URL: Repository, https://github.com/yuvrajiro/Genformer
|
|
10
|
+
Project-URL: Issues, https://github.com/yuvrajiro/Genformer/issues
|
|
11
|
+
Keywords: time series,forecasting,probabilistic forecasting,spatiotemporal,transformer,engression,deep learning,pytorch,uncertainty quantification
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: torch>=2.0.0
|
|
26
|
+
Requires-Dist: darts>=0.26.0
|
|
27
|
+
Requires-Dist: numpy>=1.24.0
|
|
28
|
+
Requires-Dist: pandas>=2.0.0
|
|
29
|
+
Requires-Dist: lightning>=2.0.0
|
|
30
|
+
Requires-Dist: gluonts>=0.14.0
|
|
31
|
+
Provides-Extra: docs
|
|
32
|
+
Requires-Dist: sphinx>=7.0.0; extra == "docs"
|
|
33
|
+
Requires-Dist: pydata-sphinx-theme>=0.15; extra == "docs"
|
|
34
|
+
Requires-Dist: sphinx-design>=0.5; extra == "docs"
|
|
35
|
+
Requires-Dist: sphinx-copybutton>=0.5; extra == "docs"
|
|
36
|
+
Requires-Dist: nbsphinx; extra == "docs"
|
|
37
|
+
Requires-Dist: ipython; extra == "docs"
|
|
38
|
+
Requires-Dist: ipykernel; extra == "docs"
|
|
39
|
+
Dynamic: license-file
|
|
40
|
+
|
|
41
|
+
<div align="center">
|
|
42
|
+
<img src="image.png" alt="Enformer Logo" width="600" />
|
|
43
|
+
|
|
44
|
+
# 🚀 Genformer: Deep Generative Transformers
|
|
45
|
+
**For Probabilistic Time Series and Spatiotemporal Forecasting** 📈✨
|
|
46
|
+
|
|
47
|
+
[](https://pypi.org/project/genformer/)
|
|
48
|
+
[](https://python.org)
|
|
49
|
+
[](https://pytorch.org)
|
|
50
|
+
[](https://yuvrajiro.github.io/Genformer/)
|
|
51
|
+
[](LICENSE)
|
|
52
|
+
</div>
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## 🌟 Introduction
|
|
57
|
+
|
|
58
|
+
Welcome to **Genformer**! 🎉 This is the official Python package for the paper:
|
|
59
|
+
> *"Deep Generative Transformers for Probabilistic Time Series and Spatiotemporal Forecasting"* 📝
|
|
60
|
+
|
|
61
|
+
Time series forecasting is hard, especially when dealing with uncertainty. **Genformer** brings the power of **Transformers** 🤖 together with the **Engression Paradigm** 🎲 (distributional regression) to give you:
|
|
62
|
+
* ✨ **Robust multivariate trajectories** instead of boring point predictions!
|
|
63
|
+
* ⚡ **Extremely lightweight** probabilistic capabilities with constant-factor overhead.
|
|
64
|
+
* 🌍 **Spatiotemporal support** via Graph-Enformer (GEnformer) for when your data has geographical/spatial relationships.
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## 🛠️ Installation
|
|
69
|
+
|
|
70
|
+
Get up and running in seconds! 🏃♂️💨
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
pip install genformer
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Or install the latest development version from source:
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
git clone https://github.com/yuvrajiro/Genformer.git
|
|
80
|
+
cd Enformer
|
|
81
|
+
pip install -e .
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## 💡 Quick Start
|
|
87
|
+
|
|
88
|
+
Generating probabilistic forecasts is as easy as pie 🥧:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
import pandas as pd
|
|
92
|
+
from darts import TimeSeries
|
|
93
|
+
from genformer.models import Enformer
|
|
94
|
+
|
|
95
|
+
# 1. Load your TimeSeries data 📊
|
|
96
|
+
series = TimeSeries.from_dataframe(pd.read_csv("your_data.csv"))
|
|
97
|
+
|
|
98
|
+
# 2. Initialize the awesome Enformer! 🚀
|
|
99
|
+
model = Enformer(
|
|
100
|
+
input_chunk_length=24,
|
|
101
|
+
output_chunk_length=12,
|
|
102
|
+
num_samples_engression=10, # Number of ensemble samples
|
|
103
|
+
n_epochs=30
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
# 3. Train & Predict 🔥
|
|
107
|
+
model.fit(series)
|
|
108
|
+
prediction = model.predict(n=12, num_samples=50)
|
|
109
|
+
|
|
110
|
+
# 4. Plot a beautiful probabilistic forecast 🌈
|
|
111
|
+
prediction.plot(low_quantile=0.05, high_quantile=0.95)
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## 🏗️ Architecture
|
|
117
|
+
|
|
118
|
+
### 🔮 Enformer (Temporal)
|
|
119
|
+
Injects pre-additive stochastic noise $\epsilon \sim \mathcal{N}(0, \sigma^2 \mathbf{I})$ into the batch-expanded inputs, optimizing the strictly proper **Energy Score Loss**.
|
|
120
|
+
|
|
121
|
+
### 🌐 Graph-Enformer (Spatiotemporal)
|
|
122
|
+
Extends Enformer by passing the spatial inputs through a Graph Convolutional Network (GCN) to capture intricate geographical topologies before processing temporal dependencies! 📍🗺️
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## 📚 Documentation & Examples
|
|
127
|
+
|
|
128
|
+
📖 **Read the full documentation online: [yuvrajiro.github.io/Genformer](https://yuvrajiro.github.io/Genformer/)**
|
|
129
|
+
|
|
130
|
+
Extensive documentation is built using Sphinx and `pydata-sphinx-theme`! To build the docs locally:
|
|
131
|
+
```bash
|
|
132
|
+
cd docs
|
|
133
|
+
make html
|
|
134
|
+
# Then open _build/html/index.html in your browser! 🌐
|
|
135
|
+
```
|
|
136
|
+
Check out the `docs/examples/` directory for fully runnable Jupyter Notebooks demonstrating both temporal and spatiotemporal forecasting! 🚀
|
|
137
|
+
|
|
138
|
+
---
|
|
139
|
+
|
|
140
|
+
## 📜 Citation & Special Thanks
|
|
141
|
+
|
|
142
|
+
If you find this work useful in your research, please cite our paper:
|
|
143
|
+
|
|
144
|
+
```bibtex
|
|
145
|
+
@article{pathak2026deep,
|
|
146
|
+
title={Deep Generative Transformers for Probabilistic Time Series and Spatiotemporal Forecasting},
|
|
147
|
+
author={Pathak, Rajdeep and Goswami, Rahul and Panja, Madhurima and Ghosh, Palash and Chakraborty, Tanujit},
|
|
148
|
+
journal={arXiv preprint arXiv:260307108},
|
|
149
|
+
year={2026}
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
💖 **Special Thanks:** We would like to extend a very special thanks to **Donia Besher** for her invaluable contributions and support! 🙌
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
<div align="center">
|
|
158
|
+
<i>Made with ❤️ by the Genformer Team</i>
|
|
159
|
+
</div>
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
<img src="image.png" alt="Enformer Logo" width="600" />
|
|
3
|
+
|
|
4
|
+
# 🚀 Genformer: Deep Generative Transformers
|
|
5
|
+
**For Probabilistic Time Series and Spatiotemporal Forecasting** 📈✨
|
|
6
|
+
|
|
7
|
+
[](https://pypi.org/project/genformer/)
|
|
8
|
+
[](https://python.org)
|
|
9
|
+
[](https://pytorch.org)
|
|
10
|
+
[](https://yuvrajiro.github.io/Genformer/)
|
|
11
|
+
[](LICENSE)
|
|
12
|
+
</div>
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## 🌟 Introduction
|
|
17
|
+
|
|
18
|
+
Welcome to **Genformer**! 🎉 This is the official Python package for the paper:
|
|
19
|
+
> *"Deep Generative Transformers for Probabilistic Time Series and Spatiotemporal Forecasting"* 📝
|
|
20
|
+
|
|
21
|
+
Time series forecasting is hard, especially when dealing with uncertainty. **Genformer** brings the power of **Transformers** 🤖 together with the **Engression Paradigm** 🎲 (distributional regression) to give you:
|
|
22
|
+
* ✨ **Robust multivariate trajectories** instead of boring point predictions!
|
|
23
|
+
* ⚡ **Extremely lightweight** probabilistic capabilities with constant-factor overhead.
|
|
24
|
+
* 🌍 **Spatiotemporal support** via Graph-Enformer (GEnformer) for when your data has geographical/spatial relationships.
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## 🛠️ Installation
|
|
29
|
+
|
|
30
|
+
Get up and running in seconds! 🏃♂️💨
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install genformer
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Or install the latest development version from source:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
git clone https://github.com/yuvrajiro/Genformer.git
|
|
40
|
+
cd Enformer
|
|
41
|
+
pip install -e .
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## 💡 Quick Start
|
|
47
|
+
|
|
48
|
+
Generating probabilistic forecasts is as easy as pie 🥧:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
import pandas as pd
|
|
52
|
+
from darts import TimeSeries
|
|
53
|
+
from genformer.models import Enformer
|
|
54
|
+
|
|
55
|
+
# 1. Load your TimeSeries data 📊
|
|
56
|
+
series = TimeSeries.from_dataframe(pd.read_csv("your_data.csv"))
|
|
57
|
+
|
|
58
|
+
# 2. Initialize the awesome Enformer! 🚀
|
|
59
|
+
model = Enformer(
|
|
60
|
+
input_chunk_length=24,
|
|
61
|
+
output_chunk_length=12,
|
|
62
|
+
num_samples_engression=10, # Number of ensemble samples
|
|
63
|
+
n_epochs=30
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
# 3. Train & Predict 🔥
|
|
67
|
+
model.fit(series)
|
|
68
|
+
prediction = model.predict(n=12, num_samples=50)
|
|
69
|
+
|
|
70
|
+
# 4. Plot a beautiful probabilistic forecast 🌈
|
|
71
|
+
prediction.plot(low_quantile=0.05, high_quantile=0.95)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## 🏗️ Architecture
|
|
77
|
+
|
|
78
|
+
### 🔮 Enformer (Temporal)
|
|
79
|
+
Injects pre-additive stochastic noise $\epsilon \sim \mathcal{N}(0, \sigma^2 \mathbf{I})$ into the batch-expanded inputs, optimizing the strictly proper **Energy Score Loss**.
|
|
80
|
+
|
|
81
|
+
### 🌐 Graph-Enformer (Spatiotemporal)
|
|
82
|
+
Extends Enformer by passing the spatial inputs through a Graph Convolutional Network (GCN) to capture intricate geographical topologies before processing temporal dependencies! 📍🗺️
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## 📚 Documentation & Examples
|
|
87
|
+
|
|
88
|
+
📖 **Read the full documentation online: [yuvrajiro.github.io/Genformer](https://yuvrajiro.github.io/Genformer/)**
|
|
89
|
+
|
|
90
|
+
Extensive documentation is built using Sphinx and `pydata-sphinx-theme`! To build the docs locally:
|
|
91
|
+
```bash
|
|
92
|
+
cd docs
|
|
93
|
+
make html
|
|
94
|
+
# Then open _build/html/index.html in your browser! 🌐
|
|
95
|
+
```
|
|
96
|
+
Check out the `docs/examples/` directory for fully runnable Jupyter Notebooks demonstrating both temporal and spatiotemporal forecasting! 🚀
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
## 📜 Citation & Special Thanks
|
|
101
|
+
|
|
102
|
+
If you find this work useful in your research, please cite our paper:
|
|
103
|
+
|
|
104
|
+
```bibtex
|
|
105
|
+
@article{pathak2026deep,
|
|
106
|
+
title={Deep Generative Transformers for Probabilistic Time Series and Spatiotemporal Forecasting},
|
|
107
|
+
author={Pathak, Rajdeep and Goswami, Rahul and Panja, Madhurima and Ghosh, Palash and Chakraborty, Tanujit},
|
|
108
|
+
journal={arXiv preprint arXiv:260307108},
|
|
109
|
+
year={2026}
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
💖 **Special Thanks:** We would like to extend a very special thanks to **Donia Besher** for her invaluable contributions and support! 🙌
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
<div align="center">
|
|
118
|
+
<i>Made with ❤️ by the Genformer Team</i>
|
|
119
|
+
</div>
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from typing import Tuple, Optional, List
|
|
4
|
+
from darts import TimeSeries, concatenate
|
|
5
|
+
from gluonts.dataset.repository.datasets import get_dataset
|
|
6
|
+
from gluonts.dataset.multivariate_grouper import MultivariateGrouper
|
|
7
|
+
from darts.dataprocessing.transformers import Scaler
|
|
8
|
+
from pandas.tseries.frequencies import to_offset
|
|
9
|
+
from gluonts.time_feature import norm_freq_str
|
|
10
|
+
|
|
11
|
+
def gluonts_item_to_darts_mv(item, freq: str) -> TimeSeries:
|
|
12
|
+
start = item["start"].to_timestamp() if hasattr(item["start"], "to_timestamp") else pd.Timestamp(item["start"])
|
|
13
|
+
target = np.asarray(item["target"])
|
|
14
|
+
if target.ndim != 2:
|
|
15
|
+
raise ValueError(f"Expected multivariate target with ndim=2, got shape {target.shape}")
|
|
16
|
+
|
|
17
|
+
values = target.T
|
|
18
|
+
times = pd.date_range(start=start, periods=values.shape[0], freq=freq)
|
|
19
|
+
cols = [f"dim_{i}" for i in range(values.shape[1])]
|
|
20
|
+
|
|
21
|
+
return TimeSeries.from_times_and_values(times, values, columns=cols)
|
|
22
|
+
|
|
23
|
+
def lag_covs_from_scaled_target(ts_sc: TimeSeries, lags=(1,24,168)) -> TimeSeries:
|
|
24
|
+
shifted = []
|
|
25
|
+
for L in lags:
|
|
26
|
+
s = ts_sc.shift(L).with_columns_renamed(
|
|
27
|
+
ts_sc.components, [f"{c}_lag{L}" for c in ts_sc.components]
|
|
28
|
+
)
|
|
29
|
+
shifted.append(s)
|
|
30
|
+
|
|
31
|
+
common = shifted[0]
|
|
32
|
+
for s in shifted[1:]:
|
|
33
|
+
common = common.slice_intersect(s)
|
|
34
|
+
shifted = [s.slice_intersect(common) for s in shifted]
|
|
35
|
+
return concatenate(shifted, axis=1)
|
|
36
|
+
|
|
37
|
+
def fourier_from_index_min(idx) -> TimeSeries:
|
|
38
|
+
minute = idx.minute.to_numpy()
|
|
39
|
+
hour = idx.hour.to_numpy()
|
|
40
|
+
dow = idx.dayofweek.to_numpy()
|
|
41
|
+
|
|
42
|
+
X = np.vstack([
|
|
43
|
+
np.sin(2 * np.pi * minute / 60.0),
|
|
44
|
+
np.cos(2 * np.pi * minute / 60.0),
|
|
45
|
+
np.sin(2 * np.pi * hour / 24.0),
|
|
46
|
+
np.cos(2 * np.pi * hour / 24.0),
|
|
47
|
+
np.sin(2 * np.pi * dow / 7.0),
|
|
48
|
+
np.cos(2 * np.pi * dow / 7.0),
|
|
49
|
+
]).T
|
|
50
|
+
|
|
51
|
+
return TimeSeries.from_times_and_values(
|
|
52
|
+
idx,
|
|
53
|
+
X,
|
|
54
|
+
columns=["min_sin", "min_cos", "h_sin", "h_cos", "dow_sin", "dow_cos"]
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
def fourier_from_index_day(idx) -> TimeSeries:
|
|
58
|
+
dow = idx.dayofweek.to_numpy()
|
|
59
|
+
X = np.vstack([
|
|
60
|
+
np.sin(2*np.pi*dow/7.0),
|
|
61
|
+
np.cos(2*np.pi*dow/7.0),
|
|
62
|
+
]).T
|
|
63
|
+
return TimeSeries.from_times_and_values(idx, X, columns=["dow_sin","dow_cos"])
|
|
64
|
+
|
|
65
|
+
def fourier_from_index(idx) -> TimeSeries:
|
|
66
|
+
hour = idx.hour.to_numpy()
|
|
67
|
+
dow = idx.dayofweek.to_numpy()
|
|
68
|
+
X = np.vstack([
|
|
69
|
+
np.sin(2*np.pi*hour/24.0),
|
|
70
|
+
np.cos(2*np.pi*hour/24.0),
|
|
71
|
+
np.sin(2*np.pi*dow/7.0),
|
|
72
|
+
np.cos(2*np.pi*dow/7.0),
|
|
73
|
+
]).T
|
|
74
|
+
return TimeSeries.from_times_and_values(idx, X, columns=["h_sin","h_cos","dow_sin","dow_cos"])
|
|
75
|
+
|
|
76
|
+
def dim_indicator_norm(idx, D: int) -> TimeSeries:
|
|
77
|
+
v = (np.arange(D, dtype=np.float32) / (D-1)).astype(np.float32) # 0..1
|
|
78
|
+
X = np.tile(v, (len(idx), 1))
|
|
79
|
+
cols = [f"dim_id_{i}" for i in range(D)]
|
|
80
|
+
return TimeSeries.from_times_and_values(idx, X, columns=cols)
|
|
81
|
+
|
|
82
|
+
def build_past_covs_552(ts_sc: TimeSeries, lags=(1,24,168), fourier_func=fourier_from_index_min) -> TimeSeries:
|
|
83
|
+
lag_covs = lag_covs_from_scaled_target(ts_sc, lags)
|
|
84
|
+
idx = lag_covs.time_index
|
|
85
|
+
time_covs = fourier_func(idx)
|
|
86
|
+
dim_covs = dim_indicator_norm(idx, ts_sc.width)
|
|
87
|
+
return concatenate([lag_covs, dim_covs, time_covs], axis=1)
|
|
88
|
+
|
|
89
|
+
def ts_upto(ts, end_time):
|
|
90
|
+
if hasattr(ts, "slice_end"):
|
|
91
|
+
return ts.slice_end(end_time)
|
|
92
|
+
if hasattr(ts, "drop_after"):
|
|
93
|
+
return ts.drop_after(end_time)
|
|
94
|
+
if hasattr(ts, "split_after"):
|
|
95
|
+
return ts.split_after(end_time)[0]
|
|
96
|
+
return ts.slice(ts.start_time(), end_time)
|
|
97
|
+
|
|
98
|
+
def gluon_to_wide_df(dataset):
|
|
99
|
+
series_list = []
|
|
100
|
+
|
|
101
|
+
for i, entry in enumerate(dataset):
|
|
102
|
+
idx = pd.date_range(
|
|
103
|
+
start=entry["start"].to_timestamp(),
|
|
104
|
+
periods=len(entry["target"]),
|
|
105
|
+
freq=entry["start"].freqstr
|
|
106
|
+
)
|
|
107
|
+
series = pd.Series(entry["target"], index=idx, name=f"node_{i}")
|
|
108
|
+
series_list.append(series)
|
|
109
|
+
|
|
110
|
+
return pd.concat(series_list, axis=1)
|
|
111
|
+
|
|
112
|
+
def get_7_test_windows(dataset, num_nodes=137):
|
|
113
|
+
all_series = []
|
|
114
|
+
|
|
115
|
+
for entry in dataset:
|
|
116
|
+
idx = pd.date_range(
|
|
117
|
+
start=entry["start"].to_timestamp(),
|
|
118
|
+
periods=len(entry["target"]),
|
|
119
|
+
freq=entry["start"].freqstr
|
|
120
|
+
)
|
|
121
|
+
all_series.append(pd.Series(entry["target"], index=idx))
|
|
122
|
+
|
|
123
|
+
num_windows = len(all_series) // num_nodes
|
|
124
|
+
windows = []
|
|
125
|
+
|
|
126
|
+
for w in range(num_windows):
|
|
127
|
+
start_idx = w * num_nodes
|
|
128
|
+
end_idx = (w + 1) * num_nodes
|
|
129
|
+
window_df = pd.concat(all_series[start_idx:end_idx], axis=1)
|
|
130
|
+
window_df.columns = [f"node_{i}" for i in range(num_nodes)]
|
|
131
|
+
windows.append(window_df)
|
|
132
|
+
|
|
133
|
+
return windows, all_series
|
|
134
|
+
|
|
135
|
+
def load_and_prepare_data(dataset_name: str,
|
|
136
|
+
lags: Tuple,
|
|
137
|
+
fourier_func_dict: dict):
|
|
138
|
+
|
|
139
|
+
ds = get_dataset(dataset_name, regenerate=False)
|
|
140
|
+
freq = ds.metadata.freq
|
|
141
|
+
offset = to_offset(freq)
|
|
142
|
+
granularity = norm_freq_str(offset.name)
|
|
143
|
+
|
|
144
|
+
train_list = list(ds.train)
|
|
145
|
+
test_list = list(ds.test)
|
|
146
|
+
num_test_dates = len(test_list) // len(train_list)
|
|
147
|
+
|
|
148
|
+
target_dim = int(ds.metadata.feat_static_cat[0].cardinality)
|
|
149
|
+
train_grouper = MultivariateGrouper(max_target_dim=target_dim)
|
|
150
|
+
test_grouper = MultivariateGrouper(num_test_dates=num_test_dates, max_target_dim=target_dim)
|
|
151
|
+
|
|
152
|
+
train_mv_items = list(train_grouper(train_list))
|
|
153
|
+
|
|
154
|
+
if dataset_name == 'kdd_cup_2018_without_missing':
|
|
155
|
+
for i in range(len(test_list)):
|
|
156
|
+
if len(test_list[i]['target']) == 10898:
|
|
157
|
+
test_list[i]['target'] = np.concatenate(
|
|
158
|
+
(test_list[i]['target'], np.zeros(8)), axis=0)
|
|
159
|
+
dataset_test = test_grouper(test_list)
|
|
160
|
+
else:
|
|
161
|
+
dataset_test = test_grouper(test_list)
|
|
162
|
+
|
|
163
|
+
test_mv_items = list(dataset_test)
|
|
164
|
+
|
|
165
|
+
train_ts = gluonts_item_to_darts_mv(train_mv_items[0], freq)
|
|
166
|
+
test_ts_list = [gluonts_item_to_darts_mv(it, freq) for it in test_mv_items]
|
|
167
|
+
|
|
168
|
+
y_scaler = Scaler()
|
|
169
|
+
train_y_sc = y_scaler.fit_transform(train_ts)
|
|
170
|
+
|
|
171
|
+
test_windows, all_series = get_7_test_windows(test_list, num_nodes=target_dim)
|
|
172
|
+
|
|
173
|
+
fourier_func = fourier_func_dict.get(dataset_name, fourier_from_index)
|
|
174
|
+
train_pc = build_past_covs_552(train_y_sc, lags=lags, fourier_func=fourier_func)
|
|
175
|
+
|
|
176
|
+
train_y_sc = train_y_sc.slice_intersect(train_pc)
|
|
177
|
+
train_pc = train_pc.slice_intersect(train_y_sc)
|
|
178
|
+
|
|
179
|
+
return {
|
|
180
|
+
'scaler': y_scaler, 'train_ts': train_ts, 'train_y_sc': train_y_sc,
|
|
181
|
+
'test_ts_list': test_ts_list, 'test_windows': test_windows,
|
|
182
|
+
'all_series': all_series, 'train_pc': train_pc, 'freq': granularity,
|
|
183
|
+
'fourier_func': fourier_func
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
FOURIER_DICT = {
|
|
187
|
+
'solar_nips': fourier_from_index,
|
|
188
|
+
'wiki2000_nips': fourier_from_index_day,
|
|
189
|
+
'electricity_nips': fourier_from_index,
|
|
190
|
+
'taxi_30min': fourier_from_index_min,
|
|
191
|
+
'kdd_cup_2018_without_missing': fourier_from_index,
|
|
192
|
+
'traffic_nips': fourier_from_index
|
|
193
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import torch
|
|
4
|
+
from gluonts.model.forecast import SampleForecast
|
|
5
|
+
from gluonts.evaluation import MultivariateEvaluator
|
|
6
|
+
from darts import TimeSeries
|
|
7
|
+
|
|
8
|
+
from genformer.data import ts_upto, build_past_covs_552
|
|
9
|
+
|
|
10
|
+
def to_gluonts_multivariate_inputs(
|
|
11
|
+
preds: np.ndarray,
|
|
12
|
+
targets: np.ndarray,
|
|
13
|
+
start_dates,
|
|
14
|
+
freq: str = "H",
|
|
15
|
+
item_ids=None,
|
|
16
|
+
past_targets: np.ndarray | None = None,
|
|
17
|
+
dtype=np.float32,
|
|
18
|
+
):
|
|
19
|
+
preds = np.asarray(preds, dtype=dtype)
|
|
20
|
+
targets = np.asarray(targets, dtype=dtype)
|
|
21
|
+
|
|
22
|
+
B, N, T, D = preds.shape
|
|
23
|
+
|
|
24
|
+
if isinstance(start_dates, (str, pd.Timestamp, pd.Period)) or not hasattr(start_dates, "__len__"):
|
|
25
|
+
start_dates = [start_dates] * B
|
|
26
|
+
|
|
27
|
+
if item_ids is None:
|
|
28
|
+
item_ids = [f"item_{i}" for i in range(B)]
|
|
29
|
+
|
|
30
|
+
targets_list = []
|
|
31
|
+
forecasts_list = []
|
|
32
|
+
|
|
33
|
+
columns = list(range(D))
|
|
34
|
+
|
|
35
|
+
for i in range(B):
|
|
36
|
+
start_period = pd.Period(start_dates[i], freq=freq)
|
|
37
|
+
forecast = SampleForecast(
|
|
38
|
+
samples=preds[i],
|
|
39
|
+
start_date=start_period,
|
|
40
|
+
item_id=item_ids[i],
|
|
41
|
+
)
|
|
42
|
+
forecasts_list.append(forecast)
|
|
43
|
+
|
|
44
|
+
if past_targets is None:
|
|
45
|
+
target_index = pd.period_range(start=start_period, periods=T, freq=freq)
|
|
46
|
+
target_values = targets[i]
|
|
47
|
+
else:
|
|
48
|
+
H = past_targets.shape[1]
|
|
49
|
+
target_index = pd.period_range(start=start_period - H, periods=H + T, freq=freq)
|
|
50
|
+
target_values = np.concatenate([past_targets[i], targets[i]], axis=0)
|
|
51
|
+
|
|
52
|
+
target_df = pd.DataFrame(target_values, index=target_index, columns=columns)
|
|
53
|
+
targets_list.append(target_df)
|
|
54
|
+
|
|
55
|
+
return targets_list, forecasts_list
|
|
56
|
+
|
|
57
|
+
def crps(preds, targets, quantiles=(np.arange(20) / 20.0)[1:]):
|
|
58
|
+
x = np.quantile(preds, quantiles, axis=1, method="nearest")
|
|
59
|
+
quantiles = np.expand_dims(quantiles, axis=list(range(1, len(preds.shape))))
|
|
60
|
+
loss = 2 * np.sum(np.abs((x - targets) * ((targets <= x) - quantiles)), axis=2)
|
|
61
|
+
return loss.mean() / np.abs(targets).sum(axis=1).mean()
|
|
62
|
+
|
|
63
|
+
def crps_sum(preds, targets, quantiles=(np.arange(20) / 20.0)[1:], frequency='D'):
|
|
64
|
+
preds_sum = preds.sum(axis=-1)
|
|
65
|
+
targets_sum = targets.sum(axis=-1)
|
|
66
|
+
return crps(preds_sum, targets_sum, quantiles=quantiles)
|
|
67
|
+
|
|
68
|
+
def get_metric_and_prediction(model, test_windows, y_scaler, pred_len=24, lags=(1, 24, 168), num_samples=100, seed=42, std=None, fourier_func=None, is_clip=False, frequency='D'):
|
|
69
|
+
all_forecasts = []
|
|
70
|
+
all_targets = []
|
|
71
|
+
to_save_forecast = []
|
|
72
|
+
to_save_targets = []
|
|
73
|
+
|
|
74
|
+
for i, window_df in enumerate(test_windows):
|
|
75
|
+
full_ts = TimeSeries.from_dataframe(window_df).astype(np.float32)
|
|
76
|
+
full_sc = y_scaler.transform(full_ts).astype(np.float32)
|
|
77
|
+
full_pc = build_past_covs_552(full_sc, lags=lags, fourier_func=fourier_func).astype(np.float32)
|
|
78
|
+
|
|
79
|
+
full_sc = full_sc.slice_intersect(full_pc)
|
|
80
|
+
full_ts = full_ts.slice_intersect(full_sc)
|
|
81
|
+
full_pc = full_pc.slice_intersect(full_sc)
|
|
82
|
+
|
|
83
|
+
past_true_sc = full_sc[:-pred_len]
|
|
84
|
+
gt_future = full_ts[-pred_len:]
|
|
85
|
+
|
|
86
|
+
forecast_start = gt_future.start_time()
|
|
87
|
+
pc_past = ts_upto(full_pc, forecast_start)
|
|
88
|
+
|
|
89
|
+
model.model.encoder[0].reset_seed(seed)
|
|
90
|
+
if std is not None:
|
|
91
|
+
model.model.encoder[0].reset_std(std)
|
|
92
|
+
|
|
93
|
+
fc_sc = model.predict(
|
|
94
|
+
n=pred_len,
|
|
95
|
+
series=past_true_sc,
|
|
96
|
+
past_covariates=pc_past,
|
|
97
|
+
num_samples=num_samples,
|
|
98
|
+
verbose=False,
|
|
99
|
+
random_state=1456445
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
fc = y_scaler.inverse_transform(fc_sc)
|
|
103
|
+
if is_clip:
|
|
104
|
+
fc = fc.with_values(np.clip(fc.all_values(), a_min=0, a_max=None))
|
|
105
|
+
|
|
106
|
+
to_save_forecast.append(fc)
|
|
107
|
+
to_save_targets.append(gt_future)
|
|
108
|
+
|
|
109
|
+
all_forecasts.append(fc.all_values(copy=False))
|
|
110
|
+
all_targets.append(gt_future.all_values(copy=False))
|
|
111
|
+
|
|
112
|
+
stacked_forecasts = np.stack(all_forecasts, axis=0)
|
|
113
|
+
preds_reshaped = np.transpose(stacked_forecasts, (0, 3, 1, 2))
|
|
114
|
+
|
|
115
|
+
stacked_targets = np.stack(all_targets, axis=0)
|
|
116
|
+
targets_reshaped = np.squeeze(stacked_targets, axis=-1)
|
|
117
|
+
|
|
118
|
+
target_list , forecast_list = to_gluonts_multivariate_inputs(preds_reshaped, targets_reshaped, pd.Timestamp(gt_future.start_time()), freq=frequency)
|
|
119
|
+
|
|
120
|
+
evaluator = MultivariateEvaluator(quantiles=(np.arange(20) / 20.0)[1:], target_agg_funcs={'sum': np.sum})
|
|
121
|
+
agg_metric, item_metrics = evaluator(target_list, forecast_list)
|
|
122
|
+
|
|
123
|
+
print(f"======= Evaluation metrics for models =======")
|
|
124
|
+
print("CRPS:", agg_metric["mean_wQuantileLoss"])
|
|
125
|
+
print("ND:", agg_metric["ND"])
|
|
126
|
+
print("NRMSE:", agg_metric["NRMSE"])
|
|
127
|
+
print("")
|
|
128
|
+
print("CRPS-Sum:", agg_metric["m_sum_mean_wQuantileLoss"])
|
|
129
|
+
print("ND-Sum:", agg_metric["m_sum_ND"])
|
|
130
|
+
print("NRMSE-Sum:", agg_metric["m_sum_NRMSE"])
|
|
131
|
+
crps_ours = crps_sum(preds_reshaped, targets_reshaped)
|
|
132
|
+
print("CRPS Ours:", crps_ours)
|
|
133
|
+
|
|
134
|
+
return agg_metric["m_sum_mean_wQuantileLoss"], agg_metric["m_sum_ND"], agg_metric["m_sum_NRMSE"], crps_ours, to_save_forecast, to_save_targets
|
|
135
|
+
|
|
136
|
+
def energy_score_loss(samples: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
|
137
|
+
M = samples.size(0)
|
|
138
|
+
dist_to_target = torch.linalg.norm(samples - target.unsqueeze(0), dim=-1).mean(0)
|
|
139
|
+
s = samples.reshape(M, -1, samples.size(-1))
|
|
140
|
+
diff = s.unsqueeze(1) - s.unsqueeze(0)
|
|
141
|
+
pairwise_dist = torch.linalg.norm(diff, dim=-1).mean(dim=(0, 1))
|
|
142
|
+
dist_samples = pairwise_dist.view(target.size(0), target.size(1))
|
|
143
|
+
loss = dist_to_target - 0.5 * dist_samples
|
|
144
|
+
return loss.mean()
|