-
-
Notifications
You must be signed in to change notification settings - Fork 185
Expand file tree
/
Copy pathcsdi_forecasting_example.py
More file actions
65 lines (54 loc) · 2 KB
/
Copy pathcsdi_forecasting_example.py
File metadata and controls
65 lines (54 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""
A minimalist, standalone example of the PyPOTS CSDI model for time-series forecasting.
This script is auto-generated by extracting hyperparameters from the test code.
"""
import numpy as np
from benchpots.datasets import preprocess_random_walk
from pypots.nn.functional import calc_mse
from pypots.forecasting import CSDI
def main():
n_steps = 48
n_pred_steps = 12
n_features = 35
# 1. Generate a random walk time-series dataset
dataset = preprocess_random_walk(
n_steps=n_steps + n_pred_steps, n_features=n_features, n_classes=5, n_samples_each_class=40, missing_rate=0.1
)
# 2. Extract training and test sets
train_X = dataset["train_X"]
val_X = dataset["val_X"]
test_X = dataset["test_X"]
train_set = {"X": train_X[:, :n_steps], "X_pred": train_X[:, n_steps:]}
val_set = {"X": val_X[:, :n_steps], "X_pred": val_X[:, n_steps:]}
test_set = {"X": test_X[:, :n_steps], "X_pred": test_X[:, n_steps:]}
# 3. Initialize the model
model = CSDI(
n_steps=n_steps,
n_features=n_features,
n_pred_steps=n_pred_steps,
n_pred_features=n_features,
n_layers=1,
n_channels=8,
d_time_embedding=32,
d_feature_embedding=3,
d_diffusion_embedding=32,
n_diffusion_steps=5,
n_heads=1,
epochs=2,
device="cpu",
)
# 4. Train the model
print("🚀 Training the CSDI forecasting model...")
model.fit(train_set, val_set)
# 5. Forecast
print("🔮 Forecasting future steps...")
results = model.predict(
test_set,
n_sampling_times=2, # for generation models like CSDI, we can sample multiple times to get multiple predications per data instance
)
forecasts = results["forecasting"]
forecasts = forecasts.mean(axis=1) # mean over sampling times
test_MSE = calc_mse(forecasts, np.nan_to_num(test_set["X_pred"]), ~np.isnan(test_set["X_pred"]))
print(f"✅ CSDI forecasting MSE: {test_MSE:.4f}")
if __name__ == "__main__":
main()