genformer 0.1.0__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.
genformer/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ from genformer.models import Enformer, GEnformer
2
+ from genformer.noise import GaussianNoise, UniformNoise
3
+
4
+ __all__ = [
5
+ "Enformer",
6
+ "GEnformer",
7
+ "GaussianNoise",
8
+ "UniformNoise",
9
+ ]
genformer/data.py ADDED
@@ -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
+ }
genformer/metrics.py ADDED
@@ -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()