tabpfn-time-series 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.
@@ -0,0 +1,11 @@
1
+ from .feature import DefaultFeatures, FeatureTransformer
2
+ from .predictor import TabPFNTimeSeriesPredictor, TabPFNMode
3
+
4
+ __version__ = "0.1.0"
5
+
6
+ __all__ = [
7
+ "DefaultFeatures",
8
+ "FeatureTransformer",
9
+ "TabPFNTimeSeriesPredictor",
10
+ "TabPFNMode",
11
+ ]
@@ -0,0 +1,226 @@
1
+ import pandas as pd
2
+ import numpy as np
3
+
4
+ import datasets
5
+ from autogluon.timeseries import TimeSeriesDataFrame
6
+
7
+
8
+ def generate_test_X(
9
+ train_tsdf: TimeSeriesDataFrame,
10
+ prediction_length: int,
11
+ ):
12
+ test_dfs = []
13
+ for item_id in train_tsdf.item_ids:
14
+ last_train_timestamp = train_tsdf.xs(item_id, level="item_id").index.max()
15
+ first_test_timestamp = pd.date_range(
16
+ start=last_train_timestamp, periods=2, freq=train_tsdf.freq
17
+ )[-1]
18
+ test_dfs.append(
19
+ pd.DataFrame(
20
+ {
21
+ "target": np.full(prediction_length, np.nan),
22
+ "timestamp": pd.date_range(
23
+ start=first_test_timestamp,
24
+ periods=prediction_length,
25
+ freq=train_tsdf.freq,
26
+ ),
27
+ "item_id": item_id,
28
+ }
29
+ )
30
+ )
31
+
32
+ test_tsdf = TimeSeriesDataFrame.from_data_frame(pd.concat(test_dfs))
33
+ assert test_tsdf.item_ids.equals(train_tsdf.item_ids)
34
+
35
+ return test_tsdf
36
+
37
+
38
+ # From pandas._libs.tslibs.dtypes.OFFSET_TO_PERIOD_FREQSTR
39
+ offset_alias_to_period_alias = {
40
+ "WEEKDAY": "D",
41
+ "EOM": "M",
42
+ "BME": "M",
43
+ "SME": "M",
44
+ "BQS": "Q",
45
+ "QS": "Q",
46
+ "BQE": "Q",
47
+ "BQE-DEC": "Q",
48
+ "BQE-JAN": "Q",
49
+ "BQE-FEB": "Q",
50
+ "BQE-MAR": "Q",
51
+ "BQE-APR": "Q",
52
+ "BQE-MAY": "Q",
53
+ "BQE-JUN": "Q",
54
+ "BQE-JUL": "Q",
55
+ "BQE-AUG": "Q",
56
+ "BQE-SEP": "Q",
57
+ "BQE-OCT": "Q",
58
+ "BQE-NOV": "Q",
59
+ "MS": "M",
60
+ "D": "D",
61
+ "B": "B",
62
+ "min": "min",
63
+ "s": "s",
64
+ "ms": "ms",
65
+ "us": "us",
66
+ "ns": "ns",
67
+ "h": "h",
68
+ "QE": "Q",
69
+ "QE-DEC": "Q-DEC",
70
+ "QE-JAN": "Q-JAN",
71
+ "QE-FEB": "Q-FEB",
72
+ "QE-MAR": "Q-MAR",
73
+ "QE-APR": "Q-APR",
74
+ "QE-MAY": "Q-MAY",
75
+ "QE-JUN": "Q-JUN",
76
+ "QE-JUL": "Q-JUL",
77
+ "QE-AUG": "Q-AUG",
78
+ "QE-SEP": "Q-SEP",
79
+ "QE-OCT": "Q-OCT",
80
+ "QE-NOV": "Q-NOV",
81
+ "YE": "Y",
82
+ "YE-DEC": "Y-DEC",
83
+ "YE-JAN": "Y-JAN",
84
+ "YE-FEB": "Y-FEB",
85
+ "YE-MAR": "Y-MAR",
86
+ "YE-APR": "Y-APR",
87
+ "YE-MAY": "Y-MAY",
88
+ "YE-JUN": "Y-JUN",
89
+ "YE-JUL": "Y-JUL",
90
+ "YE-AUG": "Y-AUG",
91
+ "YE-SEP": "Y-SEP",
92
+ "YE-OCT": "Y-OCT",
93
+ "YE-NOV": "Y-NOV",
94
+ "W": "W",
95
+ "ME": "M",
96
+ "Y": "Y",
97
+ "BYE": "Y",
98
+ "BYE-DEC": "Y",
99
+ "BYE-JAN": "Y",
100
+ "BYE-FEB": "Y",
101
+ "BYE-MAR": "Y",
102
+ "BYE-APR": "Y",
103
+ "BYE-MAY": "Y",
104
+ "BYE-JUN": "Y",
105
+ "BYE-JUL": "Y",
106
+ "BYE-AUG": "Y",
107
+ "BYE-SEP": "Y",
108
+ "BYE-OCT": "Y",
109
+ "BYE-NOV": "Y",
110
+ "YS": "Y",
111
+ "BYS": "Y",
112
+ "QS-JAN": "Q",
113
+ "QS-FEB": "Q",
114
+ "QS-MAR": "Q",
115
+ "QS-APR": "Q",
116
+ "QS-MAY": "Q",
117
+ "QS-JUN": "Q",
118
+ "QS-JUL": "Q",
119
+ "QS-AUG": "Q",
120
+ "QS-SEP": "Q",
121
+ "QS-OCT": "Q",
122
+ "QS-NOV": "Q",
123
+ "QS-DEC": "Q",
124
+ "BQS-JAN": "Q",
125
+ "BQS-FEB": "Q",
126
+ "BQS-MAR": "Q",
127
+ "BQS-APR": "Q",
128
+ "BQS-MAY": "Q",
129
+ "BQS-JUN": "Q",
130
+ "BQS-JUL": "Q",
131
+ "BQS-AUG": "Q",
132
+ "BQS-SEP": "Q",
133
+ "BQS-OCT": "Q",
134
+ "BQS-NOV": "Q",
135
+ "BQS-DEC": "Q",
136
+ "YS-JAN": "Y",
137
+ "YS-FEB": "Y",
138
+ "YS-MAR": "Y",
139
+ "YS-APR": "Y",
140
+ "YS-MAY": "Y",
141
+ "YS-JUN": "Y",
142
+ "YS-JUL": "Y",
143
+ "YS-AUG": "Y",
144
+ "YS-SEP": "Y",
145
+ "YS-OCT": "Y",
146
+ "YS-NOV": "Y",
147
+ "YS-DEC": "Y",
148
+ "BYS-JAN": "Y",
149
+ "BYS-FEB": "Y",
150
+ "BYS-MAR": "Y",
151
+ "BYS-APR": "Y",
152
+ "BYS-MAY": "Y",
153
+ "BYS-JUN": "Y",
154
+ "BYS-JUL": "Y",
155
+ "BYS-AUG": "Y",
156
+ "BYS-SEP": "Y",
157
+ "BYS-OCT": "Y",
158
+ "BYS-NOV": "Y",
159
+ "BYS-DEC": "Y",
160
+ "Y-JAN": "Y-JAN",
161
+ "Y-FEB": "Y-FEB",
162
+ "Y-MAR": "Y-MAR",
163
+ "Y-APR": "Y-APR",
164
+ "Y-MAY": "Y-MAY",
165
+ "Y-JUN": "Y-JUN",
166
+ "Y-JUL": "Y-JUL",
167
+ "Y-AUG": "Y-AUG",
168
+ "Y-SEP": "Y-SEP",
169
+ "Y-OCT": "Y-OCT",
170
+ "Y-NOV": "Y-NOV",
171
+ "Y-DEC": "Y-DEC",
172
+ "Q-JAN": "Q-JAN",
173
+ "Q-FEB": "Q-FEB",
174
+ "Q-MAR": "Q-MAR",
175
+ "Q-APR": "Q-APR",
176
+ "Q-MAY": "Q-MAY",
177
+ "Q-JUN": "Q-JUN",
178
+ "Q-JUL": "Q-JUL",
179
+ "Q-AUG": "Q-AUG",
180
+ "Q-SEP": "Q-SEP",
181
+ "Q-OCT": "Q-OCT",
182
+ "Q-NOV": "Q-NOV",
183
+ "Q-DEC": "Q-DEC",
184
+ "W-MON": "W-MON",
185
+ "W-TUE": "W-TUE",
186
+ "W-WED": "W-WED",
187
+ "W-THU": "W-THU",
188
+ "W-FRI": "W-FRI",
189
+ "W-SAT": "W-SAT",
190
+ "W-SUN": "W-SUN",
191
+ }
192
+
193
+
194
+ # From https://github.com/amazon-science/chronos-forecasting/blob/ad410c9c0ae0d499aeec9a7af09b0636844b6274/scripts/evaluation/evaluate.py#L28
195
+ def to_gluonts_univariate(hf_dataset: datasets.Dataset):
196
+ series_fields = [
197
+ col
198
+ for col in hf_dataset.features
199
+ if isinstance(hf_dataset.features[col], datasets.Sequence)
200
+ ]
201
+ series_fields.remove("timestamp")
202
+ dataset_length = hf_dataset.info.splits["train"].num_examples * len(series_fields)
203
+ dataset_freq = pd.infer_freq(hf_dataset[0]["timestamp"])
204
+ dataset_freq = offset_alias_to_period_alias.get(dataset_freq, dataset_freq)
205
+
206
+ gts_dataset = []
207
+ for hf_entry in hf_dataset:
208
+ for field in series_fields:
209
+ gts_dataset.append(
210
+ {
211
+ "start": pd.Period(
212
+ hf_entry["timestamp"][0],
213
+ freq=dataset_freq,
214
+ ),
215
+ "target": hf_entry[field],
216
+ }
217
+ )
218
+ assert len(gts_dataset) == dataset_length
219
+
220
+ return gts_dataset
221
+
222
+
223
+ def split_time_series_to_X_y(df: pd.DataFrame, target_col="target"):
224
+ X = pd.DataFrame(df.drop(columns=[target_col]))
225
+ y = pd.DataFrame(df[target_col])
226
+ return X, y
@@ -0,0 +1,5 @@
1
+ TABPFN_DEFAULT_QUANTILE_CONFIG = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
2
+ TABPFN_DEFAULT_CONFIG = {
3
+ "model": "2noar4o2",
4
+ "optimize_metric": "median",
5
+ }
@@ -0,0 +1,78 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+ from typing import Tuple, List, Callable
4
+
5
+ import gluonts.time_feature
6
+ from autogluon.timeseries import TimeSeriesDataFrame
7
+
8
+
9
+ class DefaultFeatures:
10
+ @staticmethod
11
+ def add_running_index(df: pd.DataFrame) -> pd.Series:
12
+ df["running_index"] = range(len(df))
13
+ return df
14
+
15
+ @staticmethod
16
+ def add_calendar_features(df: pd.DataFrame) -> pd.DataFrame:
17
+ CALENDAR_COMPONENT = [
18
+ "year",
19
+ # "month",
20
+ # "day",
21
+ ]
22
+
23
+ CALENDAR_FEATURES = [
24
+ # (feature, natural seasonality)
25
+ ("hour_of_day", 24),
26
+ ("day_of_week", 7),
27
+ ("day_of_month", 30.5),
28
+ ("day_of_year", 365),
29
+ ("week_of_year", 52),
30
+ ("month_of_year", 12),
31
+ ]
32
+
33
+ timestamps = df.index.get_level_values("timestamp")
34
+
35
+ for component_name in CALENDAR_COMPONENT:
36
+ df[component_name] = getattr(timestamps, component_name)
37
+
38
+ for feature_name, seasonality in CALENDAR_FEATURES:
39
+ feature_func = getattr(gluonts.time_feature, f"{feature_name}_index")
40
+ feature = feature_func(timestamps).astype(np.int32)
41
+ if seasonality is not None:
42
+ df[f"{feature_name}_sin"] = np.sin(
43
+ 2 * np.pi * feature / (seasonality - 1)
44
+ ) # seasonality - 1 because the value starts from 0
45
+ df[f"{feature_name}_cos"] = np.cos(
46
+ 2 * np.pi * feature / (seasonality - 1)
47
+ )
48
+ else:
49
+ df[feature_name] = feature
50
+
51
+ return df
52
+
53
+
54
+ class FeatureTransformer:
55
+ @staticmethod
56
+ def add_features(
57
+ train_tsdf: TimeSeriesDataFrame,
58
+ test_tsdf: TimeSeriesDataFrame,
59
+ feature_generators: List[Callable[[TimeSeriesDataFrame], TimeSeriesDataFrame]],
60
+ target_column: str = "target",
61
+ ) -> Tuple[TimeSeriesDataFrame, TimeSeriesDataFrame]:
62
+ assert target_column in train_tsdf.columns
63
+ assert test_tsdf[target_column].isna().all()
64
+
65
+ # Join train and test tsdf
66
+ tsdf = pd.concat([train_tsdf, test_tsdf])
67
+
68
+ # Apply feature generators
69
+ for func in feature_generators:
70
+ tsdf = tsdf.groupby(level="item_id", group_keys=False).apply(func)
71
+
72
+ # Split train and test tsdf
73
+ train_tsdf = tsdf.iloc[: len(train_tsdf)]
74
+ test_tsdf = tsdf.iloc[len(train_tsdf) :]
75
+
76
+ assert test_tsdf[target_column].isna().all()
77
+
78
+ return train_tsdf, test_tsdf
@@ -0,0 +1,189 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+
5
+ from autogluon.timeseries import TimeSeriesDataFrame
6
+
7
+
8
+ def is_subset(tsdf_A: TimeSeriesDataFrame, tsdf_B: TimeSeriesDataFrame) -> bool:
9
+ tsdf_index_set_A, tsdf_index_set_B = set(tsdf_A.index), set(tsdf_B.index)
10
+ return tsdf_index_set_A.issubset(tsdf_index_set_B)
11
+
12
+
13
+ def plot_time_series(
14
+ df: TimeSeriesDataFrame,
15
+ item_ids: list[int] | None = None,
16
+ in_single_plot: bool = False,
17
+ y_limit: tuple[float, float] | None = None,
18
+ show_points: bool = False,
19
+ target_col: str = "target",
20
+ ):
21
+ if item_ids is None:
22
+ item_ids = df.index.get_level_values("item_id").unique()
23
+ elif not set(item_ids).issubset(df.index.get_level_values("item_id").unique()):
24
+ raise ValueError(f"Item IDs {item_ids} not found in the dataframe")
25
+
26
+ if not in_single_plot:
27
+ # create subplots
28
+ fig, axes = plt.subplots(
29
+ len(item_ids), 1, figsize=(10, 3 * len(item_ids)), sharex=True
30
+ )
31
+
32
+ if len(item_ids) == 1:
33
+ axes = [axes]
34
+
35
+ for ax, item_id in zip(axes, item_ids):
36
+ df_item = df.xs(item_id, level="item_id")
37
+ ax.plot(df_item.index, df_item[target_col])
38
+ if show_points:
39
+ ax.scatter(
40
+ df_item.index,
41
+ df_item[target_col],
42
+ color="lightcoral",
43
+ s=8,
44
+ alpha=0.8,
45
+ )
46
+ ax.set_title(f"Item ID: {item_id}")
47
+ ax.set_xlabel("Timestamp")
48
+ ax.set_ylabel("Target")
49
+ if y_limit is not None:
50
+ ax.set_ylim(*y_limit)
51
+
52
+ else:
53
+ fig, ax = plt.subplots(1, 1, figsize=(10, 3))
54
+ for item_id in item_ids:
55
+ df_item = df.xs(item_id, level="item_id")
56
+ ax.plot(df_item.index, df_item[target_col], label=f"Item ID: {item_id}")
57
+ if show_points:
58
+ ax.scatter(
59
+ df_item.index,
60
+ df_item[target_col],
61
+ color="lightcoral",
62
+ s=8,
63
+ alpha=0.8,
64
+ )
65
+ ax.legend()
66
+ if y_limit is not None:
67
+ ax.set_ylim(*y_limit)
68
+
69
+ plt.tight_layout()
70
+ plt.show()
71
+
72
+
73
+ def plot_actual_ts(
74
+ train: TimeSeriesDataFrame,
75
+ test: TimeSeriesDataFrame,
76
+ item_ids: list[int] | None = None,
77
+ show_points: bool = False,
78
+ ):
79
+ if item_ids is None:
80
+ item_ids = train.index.get_level_values("item_id").unique()
81
+ elif not set(item_ids).issubset(train.index.get_level_values("item_id").unique()):
82
+ raise ValueError(f"Item IDs {item_ids} not found in the dataframe")
83
+
84
+ _, ax = plt.subplots(len(item_ids), 1, figsize=(10, 3 * len(item_ids)))
85
+ ax = [ax] if not isinstance(ax, np.ndarray) else ax
86
+
87
+ def plot_single_item(ax, item_id):
88
+ train_item = train.xs(item_id, level="item_id")
89
+ test_item = test.xs(item_id, level="item_id")
90
+
91
+ if is_subset(train_item, test_item):
92
+ ground_truth = test_item["target"]
93
+ else:
94
+ ground_truth = pd.concat([train_item[["target"]], test_item[["target"]]])
95
+ ax.plot(ground_truth.index, ground_truth, label="Ground Truth")
96
+ if show_points:
97
+ ax.scatter(
98
+ ground_truth.index, ground_truth, color="lightblue", s=8, alpha=0.8
99
+ )
100
+
101
+ train_item_length = train.xs(item_id, level="item_id").iloc[-1].name
102
+ ax.axvline(
103
+ x=train_item_length, color="r", linestyle="--", label="Train/Test Split"
104
+ )
105
+
106
+ ax.set_title(f"Item ID: {item_id}")
107
+ ax.legend()
108
+
109
+ for i, item_id in enumerate(item_ids):
110
+ plot_single_item(ax[i], item_id)
111
+
112
+ plt.tight_layout()
113
+ plt.show()
114
+
115
+
116
+ def plot_pred_and_actual_ts(
117
+ pred: TimeSeriesDataFrame,
118
+ train: TimeSeriesDataFrame,
119
+ test: TimeSeriesDataFrame,
120
+ item_ids: list[int] | None = None,
121
+ show_quantiles: bool = True,
122
+ show_points: bool = False,
123
+ ):
124
+ if item_ids is None:
125
+ item_ids = train.index.get_level_values("item_id").unique()
126
+ elif not set(item_ids).issubset(train.index.get_level_values("item_id").unique()):
127
+ raise ValueError(f"Item IDs {item_ids} not found in the dataframe")
128
+
129
+ if pred.shape[0] != test.shape[0]:
130
+ if not is_subset(pred, test):
131
+ raise ValueError(
132
+ "Pred and Test have different number of items and Pred is not a subset of Test"
133
+ )
134
+
135
+ filled_pred = test.copy()
136
+ filled_pred["target"] = np.nan
137
+ for col in pred.columns:
138
+ filled_pred.loc[pred.index, col] = pred[col]
139
+ pred = filled_pred
140
+
141
+ assert pred.shape[0] == test.shape[0]
142
+
143
+ _, ax = plt.subplots(len(item_ids), 1, figsize=(10, 3 * len(item_ids)))
144
+ ax = [ax] if not isinstance(ax, np.ndarray) else ax
145
+
146
+ def plot_single_item(ax, item_id):
147
+ pred_item = pred.xs(item_id, level="item_id")
148
+ train_item = train.xs(item_id, level="item_id")
149
+ test_item = test.xs(item_id, level="item_id")
150
+
151
+ if is_subset(train_item, test_item):
152
+ ground_truth = test_item["target"]
153
+ else:
154
+ ground_truth = pd.concat([train_item[["target"]], test_item[["target"]]])
155
+ ax.plot(ground_truth.index, ground_truth, label="Ground Truth")
156
+ ax.plot(pred_item.index, pred_item["target"], label="Prediction")
157
+ if show_points:
158
+ ax.scatter(
159
+ ground_truth.index, ground_truth, color="lightblue", s=8, alpha=0.8
160
+ )
161
+
162
+ if show_quantiles:
163
+ # Plot the lower and upper bound of the quantile predictions
164
+ quantile_config = sorted(
165
+ pred_item.columns.drop(["target"]).tolist(), key=lambda x: float(x)
166
+ )
167
+ lower_quantile = quantile_config[0]
168
+ upper_quantile = quantile_config[-1]
169
+ ax.fill_between(
170
+ pred_item.index,
171
+ pred_item[lower_quantile],
172
+ pred_item[upper_quantile],
173
+ color="gray",
174
+ alpha=0.2,
175
+ label=f"{lower_quantile}-{upper_quantile} Quantile Range",
176
+ )
177
+
178
+ train_item_length = train.xs(item_id, level="item_id").iloc[-1].name
179
+ ax.axvline(
180
+ x=train_item_length, color="r", linestyle="--", label="Train/Test Split"
181
+ )
182
+ ax.set_title(f"Item ID: {item_id}")
183
+ ax.legend(loc="upper left", bbox_to_anchor=(0, 1))
184
+
185
+ for i, item_id in enumerate(item_ids):
186
+ plot_single_item(ax[i], item_id)
187
+
188
+ plt.tight_layout()
189
+ plt.show()
@@ -0,0 +1,47 @@
1
+ import logging
2
+ from enum import Enum
3
+
4
+ from autogluon.timeseries import TimeSeriesDataFrame
5
+
6
+ from tabpfn_time_series.tabpfn_worker import TabPFNClient, LocalTabPFN
7
+ from tabpfn_time_series.defaults import TABPFN_DEFAULT_QUANTILE_CONFIG, TABPFN_DEFAULT_CONFIG
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class TabPFNMode(Enum):
13
+ LOCAL = "tabpfn-local"
14
+ CLIENT = "tabpfn-client"
15
+
16
+
17
+ class TabPFNTimeSeriesPredictor:
18
+ """
19
+ Given a TimeSeriesDataFrame (multiple time series), perform prediction on each time series individually.
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ tabpfn_mode: TabPFNMode = TabPFNMode.CLIENT,
25
+ tabpfn_config: dict = TABPFN_DEFAULT_CONFIG,
26
+ ) -> None:
27
+ worker_mapping = {
28
+ TabPFNMode.CLIENT: lambda: TabPFNClient(tabpfn_config),
29
+ TabPFNMode.LOCAL: lambda: LocalTabPFN(tabpfn_config),
30
+ }
31
+ self.tabpfn_worker = worker_mapping[tabpfn_mode]()
32
+
33
+ def predict(
34
+ self,
35
+ train_tsdf: TimeSeriesDataFrame, # with features and target
36
+ test_tsdf: TimeSeriesDataFrame, # with features only
37
+ quantile_config: list[float] = TABPFN_DEFAULT_QUANTILE_CONFIG,
38
+ ) -> TimeSeriesDataFrame:
39
+ """
40
+ Predict on each time series individually (local forecasting).
41
+ """
42
+
43
+ logger.info(
44
+ f"Predicting {len(train_tsdf.item_ids)} time series with config{self.tabpfn_worker.tabpfn_config}"
45
+ )
46
+
47
+ return self.tabpfn_worker.predict(train_tsdf, test_tsdf, quantile_config)
@@ -0,0 +1,224 @@
1
+ import logging
2
+ from abc import ABC, abstractmethod
3
+ from joblib import Parallel, delayed
4
+
5
+ import pandas as pd
6
+ import numpy as np
7
+ from scipy.stats import norm
8
+ from autogluon.timeseries import TimeSeriesDataFrame
9
+
10
+ from tabpfn_time_series.data_preparation import split_time_series_to_X_y
11
+ from tabpfn_time_series.defaults import TABPFN_DEFAULT_QUANTILE_CONFIG
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class TabPFNWorker(ABC):
17
+ def __init__(
18
+ self,
19
+ tabpfn_config: dict = {},
20
+ num_workers: int = 1,
21
+ ):
22
+ self.tabpfn_config = tabpfn_config
23
+ self.num_workers = num_workers
24
+
25
+ def predict(
26
+ self,
27
+ train_tsdf: TimeSeriesDataFrame,
28
+ test_tsdf: TimeSeriesDataFrame,
29
+ quantile_config: list[float],
30
+ ):
31
+ predictions = Parallel(
32
+ n_jobs=self.num_workers,
33
+ backend="loky",
34
+ )(
35
+ delayed(self._prediction_routine)(
36
+ item_id,
37
+ train_tsdf.loc[item_id],
38
+ test_tsdf.loc[item_id],
39
+ quantile_config,
40
+ )
41
+ for item_id in train_tsdf.item_ids
42
+ )
43
+
44
+ predictions = pd.concat(predictions)
45
+
46
+ # Sort predictions according to original item_ids order (important for MASE and WQL calculation)
47
+ predictions = predictions.loc[train_tsdf.item_ids]
48
+
49
+ return TimeSeriesDataFrame(predictions)
50
+
51
+ def _prediction_routine(
52
+ self,
53
+ item_id: str,
54
+ single_train_tsdf: TimeSeriesDataFrame,
55
+ single_test_tsdf: TimeSeriesDataFrame,
56
+ quantile_config: list[float],
57
+ ) -> pd.DataFrame:
58
+ test_index = single_test_tsdf.index
59
+ train_X, train_y = split_time_series_to_X_y(single_train_tsdf.copy())
60
+ test_X, _ = split_time_series_to_X_y(single_test_tsdf.copy())
61
+ train_y = train_y.squeeze()
62
+
63
+ train_y_has_constant_value = train_y.nunique() == 1
64
+ if train_y_has_constant_value:
65
+ logger.info("Found time-series with constant target")
66
+ result = self._predict_on_constant_train_target(
67
+ single_train_tsdf, single_test_tsdf, quantile_config
68
+ )
69
+ else:
70
+ # Call worker-specific prediction routine
71
+ result = self._worker_specific_prediction_routine(
72
+ train_X,
73
+ train_y,
74
+ test_X,
75
+ quantile_config,
76
+ )
77
+
78
+ result = pd.DataFrame(result, index=test_index)
79
+ result["item_id"] = item_id
80
+ result.set_index(["item_id", result.index], inplace=True)
81
+ return result
82
+
83
+ @abstractmethod
84
+ def _worker_specific_prediction_routine(
85
+ self,
86
+ train_X: pd.DataFrame,
87
+ train_y: pd.Series,
88
+ test_X: pd.DataFrame,
89
+ quantile_config: list[float],
90
+ ) -> pd.DataFrame:
91
+ pass
92
+
93
+ def _predict_on_constant_train_target(
94
+ self,
95
+ single_train_tsdf: TimeSeriesDataFrame,
96
+ single_test_tsdf: TimeSeriesDataFrame,
97
+ quantile_config: list[float],
98
+ ) -> pd.DataFrame:
99
+ # If train_y is constant, we return the constant value from the training set
100
+ mean_constant = single_train_tsdf.target.iloc[0]
101
+ result = {"target": np.full(len(single_test_tsdf), mean_constant)}
102
+
103
+ # For quantile prediction, we assume that the uncertainty follows a standard normal distribution
104
+ quantile_pred_with_uncertainty = norm.ppf(
105
+ quantile_config, loc=mean_constant, scale=1
106
+ )
107
+ result.update(
108
+ {
109
+ q: np.full(len(single_test_tsdf), v)
110
+ for q, v in zip(quantile_config, quantile_pred_with_uncertainty)
111
+ }
112
+ )
113
+
114
+ return result
115
+
116
+
117
+ class TabPFNClient(TabPFNWorker):
118
+ def __init__(
119
+ self,
120
+ tabpfn_config: dict = {},
121
+ num_workers: int = 2,
122
+ ):
123
+ super().__init__(tabpfn_config, num_workers)
124
+
125
+ # Initialize the TabPFN client (e.g. sign up, login, etc.)
126
+ from tabpfn_client import init
127
+
128
+ init()
129
+
130
+ def predict(
131
+ self,
132
+ train_tsdf: TimeSeriesDataFrame,
133
+ test_tsdf: TimeSeriesDataFrame,
134
+ quantile_config: list[float],
135
+ ):
136
+ if not set(quantile_config).issubset(set(TABPFN_DEFAULT_QUANTILE_CONFIG)):
137
+ raise NotImplementedError(
138
+ f"TabPFNClient currently only supports {TABPFN_DEFAULT_QUANTILE_CONFIG} for quantile prediction,"
139
+ f" but got {quantile_config}."
140
+ )
141
+
142
+ return super().predict(train_tsdf, test_tsdf, quantile_config)
143
+
144
+ def _worker_specific_prediction_routine(
145
+ self,
146
+ train_X: pd.DataFrame,
147
+ train_y: pd.Series,
148
+ test_X: pd.DataFrame,
149
+ quantile_config: list[float],
150
+ ) -> pd.DataFrame:
151
+ from tabpfn_client import TabPFNRegressor
152
+
153
+ tabpfn = TabPFNRegressor(**self.tabpfn_config)
154
+ tabpfn.fit(train_X, train_y)
155
+ full_pred = tabpfn.predict_full(test_X)
156
+
157
+ result = {"target": full_pred[self._get_optimization_mode()]}
158
+ result.update({q: full_pred[f"quantile_{q:.2f}"] for q in quantile_config})
159
+
160
+ return result
161
+
162
+ def _get_optimization_mode(self):
163
+ if (
164
+ "optimize_metric" not in self.tabpfn_config
165
+ or self.tabpfn_config["optimize_metric"] is None
166
+ ):
167
+ return "mean"
168
+ elif self.tabpfn_config["optimize_metric"] in ["rmse", "mse", "r2", "mean"]:
169
+ return "mean"
170
+ elif self.tabpfn_config["optimize_metric"] in ["mae", "median"]:
171
+ return "median"
172
+ elif self.tabpfn_config["optimize_metric"] in ["mode", "exact_match"]:
173
+ return "mode"
174
+ else:
175
+ raise ValueError(f"Unknown metric {self.tabpfn_config['optimize_metric']}")
176
+
177
+
178
+ class LocalTabPFN(TabPFNWorker):
179
+ def __init__(
180
+ self,
181
+ tabpfn_config: dict = {},
182
+ ):
183
+ # Local TabPFN has a different interface for declaring the model
184
+ if "model" in tabpfn_config:
185
+ config = tabpfn_config.copy()
186
+ config["model_path"] = self._parse_model_path(config["model"])
187
+ del config["model"]
188
+ tabpfn_config = config
189
+
190
+ super().__init__(tabpfn_config, num_workers=1)
191
+
192
+ def _worker_specific_prediction_routine(
193
+ self,
194
+ train_X: pd.DataFrame,
195
+ train_y: pd.Series,
196
+ test_X: pd.DataFrame,
197
+ quantile_config: list[float],
198
+ ) -> pd.DataFrame:
199
+ from tabpfn import TabPFNRegressor
200
+
201
+ tabpfn = TabPFNRegressor(**self.tabpfn_config)
202
+ tabpfn.fit(train_X, train_y)
203
+ full_pred = tabpfn.predict_full(test_X)
204
+
205
+ result = {"target": full_pred[tabpfn.get_optimization_mode()]}
206
+ if set(quantile_config).issubset(set(TABPFN_DEFAULT_QUANTILE_CONFIG)):
207
+ result.update({q: full_pred[f"quantile_{q:.2f}"] for q in quantile_config})
208
+ else:
209
+ import torch
210
+
211
+ criterion = full_pred["criterion"]
212
+ logits = torch.tensor(full_pred["logits"])
213
+ result.update({q: criterion.icdf(logits, q) for q in quantile_config})
214
+
215
+ return result
216
+
217
+ def _parse_model_path(self, model_name: str) -> str:
218
+ from pathlib import Path
219
+ import importlib.util
220
+
221
+ tabpfn_path = Path(importlib.util.find_spec("tabpfn").origin).parent
222
+ return str(
223
+ tabpfn_path / "model_cache" / f"model_hans_regression_{model_name}.ckpt"
224
+ )
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.4
2
+ Name: tabpfn_time_series
3
+ Version: 0.1.0
4
+ Summary: Zero-shot time series forecasting with TabPFN
5
+ Project-URL: Homepage, https://github.com/liam-sbhoo/tabpfn-time-series
6
+ Project-URL: Bug Tracker, https://github.com/liam-sbhoo/tabpfn-time-series/issues
7
+ Author-email: Liam Shi Bin Hoo <hoos@tf.uni-freiburg.de>
8
+ License-File: LICENSE.txt
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.10
13
+ Requires-Dist: autogluon-timeseries
14
+ Requires-Dist: gluonts
15
+ Requires-Dist: pandas
16
+ Requires-Dist: tabpfn-client
17
+ Requires-Dist: tqdm
18
+ Provides-Extra: dev
19
+ Requires-Dist: build; extra == 'dev'
20
+ Requires-Dist: pre-commit; extra == 'dev'
21
+ Requires-Dist: ruff; extra == 'dev'
22
+ Requires-Dist: twine; extra == 'dev'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # Time Series Forecasting with TabPFN
26
+
27
+ [![colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/liam-sbhoo/tabpfn-time-series/blob/main/demo.ipynb)
28
+ [![Discord](https://img.shields.io/discord/1285598202732482621?color=7289da&label=Discord&logo=discord&logoColor=ffffff)](https://discord.com/channels/1285598202732482621/)
29
+ [![arXiv](https://img.shields.io/badge/arXiv-<INDEX>-<COLOR>.svg)](https://arxiv.org/abs/2501.02945)
30
+
31
+
32
+ We demonstrate that the tabular foundation model **TabPFN**, when paired with minimal featurization, can perform zero-shot time series forecasting. Its performance on point forecasting matches or even slightly outperforms state-of-the-art methods.
33
+
34
+ ## 📖 How does it work?
35
+
36
+ Our work proposes to frame **univariate time series forecasting** as a **tabular regression problem**.
37
+
38
+ ![How it works](docs/tabpfn-ts-method-overview.png)
39
+
40
+ Concretely, we:
41
+ 1. Transform a time series into a table
42
+ 2. Extract features from timestamp and add them to the table
43
+ 3. Perform regression on the table using TabPFN
44
+ 4. Use regression results as time series forecasting outputs
45
+
46
+ For more details, please refer to our [paper](https://arxiv.org/abs/2501.02945) and our [poster](docs/tabpfn-ts-neurips-poster.pdf) (presented at NeurIPS 2024 TRL and TSALM workshops).
47
+
48
+ ## 👉 **Why gives us a try?**
49
+ - **Zero-shot forecasting**: this method is extremely fast and requires no training, making it highly accessible for experimenting with your own problems.
50
+ - **Point and probabilistic forecasting**: it provides accurate point forecasts as well as probabilistic forecasts.
51
+ - **Support for exogenous variables**: if you have exogenous variables, this method can seemlessly incorporate them into the forecasting model.
52
+
53
+ On top of that, thanks to [tabpfn-client](https://github.com/automl/tabpfn-client) from [Prior Labs](https://priorlabs.ai), you won’t even need your own GPU to run fast inference with TabPFN. 😉 We have included `tabpfn-client` as the default engine in our implementation.
54
+
55
+ ## How to use it?
56
+
57
+ [![colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/liam-sbhoo/tabpfn-time-series/blob/main/demo.ipynb)
58
+
59
+ The demo should explain it all. 😉
@@ -0,0 +1,11 @@
1
+ tabpfn_time_series/__init__.py,sha256=atVNap8tQLI0t5COkkCop-wbY3y1FdVxIMfvCf6VDsQ,257
2
+ tabpfn_time_series/data_preparation.py,sha256=iNW7sAnRkTgmzzOEHBhkkTwm_lQ3p_Q9xgAQ5PbkOts,5416
3
+ tabpfn_time_series/defaults.py,sha256=C9HiD7Zm0BzVfE9e2f8nhpiPQSYx79hWozvzb-93L40,165
4
+ tabpfn_time_series/feature.py,sha256=_9FxfQfgPOOO1MiT8hB8523eZ3Nc5oKuoY7vcohKZZc,2531
5
+ tabpfn_time_series/plot.py,sha256=bwSYcWBanzPrUxXKFsbqG8fyGsOJZfgU2v3NsxzTSXo,6571
6
+ tabpfn_time_series/predictor.py,sha256=YfJIe8KsyzkwgX4EFAHR8dDp-mqSv9WK88_qO_EXlws,1505
7
+ tabpfn_time_series/tabpfn_worker.py,sha256=3xInPzzQtmIBPjbc_5TaQsX3-Bl3WOlxttqj3KZlC9Q,7395
8
+ tabpfn_time_series-0.1.0.dist-info/METADATA,sha256=3lPtIH1qAR58k6Y-19ZPN8fEEtNG1UKkW5qKZ-jh8e4,3147
9
+ tabpfn_time_series-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
10
+ tabpfn_time_series-0.1.0.dist-info/licenses/LICENSE.txt,sha256=iwhPL7kIWQG6gyLZZwIMDItGrNgxMDIq9itxkUSMapY,11345
11
+ tabpfn_time_series-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2025 Prior Labs GmbH
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.