-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmodels.py
More file actions
1858 lines (1633 loc) · 61.3 KB
/
Copy pathmodels.py
File metadata and controls
1858 lines (1633 loc) · 61.3 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pandas as pd
import numpy as np
import lightgbm as lgb
import torch
import torch.nn as nn
from torch.autograd import grad as autograd
import time
from hypertrees.models import (
HyperTreeETS,
HyperTreeAR,
HyperTreeNetAR,
)
from hypertrees.models.mlp import MLP
from sklearn.preprocessing import StandardScaler
from chronos import ChronosPipeline
from gluonts.dataset.common import ListDataset
from gluonts.dataset.field_names import FieldName
from gluonts.evaluation import make_evaluation_predictions
from gluonts.torch import (
DeepAREstimator,
TemporalFusionTransformerEstimator
)
from sktime.transformations.series.detrend import Deseasonalizer, Detrender
from sktime.forecasting.trend import PolynomialTrendForecaster
from sktime.forecasting.compose import make_reduction
from sktime.transformations.series.summarize import WindowSummarizer
from sktime.forecasting.compose import TransformedTargetForecaster
from statsforecast import StatsForecast
from statsforecast.models import (
AutoARIMA as SFAutoARIMA,
ARIMA as SFARIMA,
AutoETS as SFAutoETS,
)
from experiments.utils import (
cleanup_lightning_artifacts,
create_lag_features,
to_offset_freq,
to_period_freq,
to_statsforecast_frames,
to_statsforecast_output,
col_order
)
def LightGBMForecast(
params_lgb: dict,
train: pd.DataFrame,
test: pd.DataFrame,
features: list
) -> pd.DataFrame:
"""
Train a LightGBM model and generate forecasts.
Parameters
----------
params_lgb : dict
Parameters for the LightGBM model.
train : pd.DataFrame
Training dataset containing the time series data.
test : pd.DataFrame
Test dataset for generating forecasts.
features : list
List of feature names to be used in the model.
Returns
-------
pd.DataFrame
DataFrame containing the forecasted values.
"""
# Dataset
dtrain_lgb = lgb.Dataset(
data=train[features].values,
label=train["value"].to_numpy().reshape(-1,),
)
# Train model
start = time.time()
lgb_model = lgb.train(
{k: v for k, v in params_lgb.items() if k not in ["num_boost_round", "use_time_index"]},
dtrain_lgb,
num_boost_round=params_lgb["num_boost_round"],
)
# Forecast
lgb_fcst = pd.DataFrame.from_dict(
{
"series_id": test["series_id"],
"date": test["date"],
"fcst": lgb_model.predict(test[features]),
"model": "LightGBM",
}
)
end = time.time()
runtime = (end - start) / 60
lgb_fcst["runtime"] = runtime
lgb_fcst = lgb_fcst[col_order]
return lgb_fcst
def LightGBMARForecast(
params_lgb: dict,
train: pd.DataFrame,
test: pd.DataFrame,
features: list,
freq: str,
fcst_h: int,
lags: list,
max_lag: int,
n_series: int = 1
) -> pd.DataFrame:
"""
Train an autoregressive LightGBM model and generate multi-step forecasts.
Parameters
----------
params_lgb : dict
Parameters for the LightGBM model.
train : pd.DataFrame
Training dataset containing the time series data.
test : pd.DataFrame
Test dataset for generating forecasts.
features : list
List of feature names to be used in the model.
freq : str
Frequency of the time series data (e.g., 'D' for daily).
fcst_h : int
Forecast horizon, i.e., the number of time steps to forecast.
lags : list
List of lags to be used in the autoregressive model.
max_lag : int
Maximum lag to consider for the autoregressive model.
n_series : int, optional
Number of time series in the dataset (default is 1).
Returns
-------
pd.DataFrame
DataFrame containing the forecasted values from the autoregressive model.
"""
# Create lag features
preprocess_df = create_lag_features(train, lags=lags, features=features)
train_lags = preprocess_df.filter(regex="lag").values
train_targets = preprocess_df["value"].to_numpy().reshape(-1, 1)
train_features = preprocess_df[features].values
# Data
dtrain_lgb_ar = lgb.Dataset(
data=np.concatenate([train_features, train_lags], axis=1),
label=train_targets.reshape(-1, )
)
# Train model
start = time.time()
lgb_ar_model = lgb.train(
{k: v for k, v in params_lgb.items() if k not in ["num_boost_round", "use_time_index"]},
dtrain_lgb_ar,
num_boost_round=params_lgb["num_boost_round"],
)
# Forecast
lgb_lags = train.groupby(["series_id"], sort=False).apply(lambda x: x["value"][-max_lag:][::-1]).reset_index(
drop=True).to_numpy().reshape(n_series, -1)
lgb_ar_fcsts = []
x_test = test[features].to_numpy().reshape(n_series, fcst_h, -1)
for h in range(fcst_h):
next_val = lgb_ar_model.predict(np.concatenate([x_test[:, h, :], lgb_lags], axis=1)).reshape(-1, 1)
lgb_ar_fcsts.append(next_val)
lgb_lags = np.concatenate([next_val, lgb_lags[:, :-1]], axis=1)
end = time.time()
runtime = (end - start) / 60
lgb_ar_fcst = pd.DataFrame.from_dict(
{
"series_id": test["series_id"].to_numpy().flatten(),
"date": test["date"].to_numpy().flatten(),
"fcst": np.hstack(lgb_ar_fcsts).flatten(),
"runtime": runtime,
"model": f"LightGBM-AR({max_lag})",
}
)
return lgb_ar_fcst
def LightGBMSTLForecast(
params_lgb: dict,
train: pd.DataFrame,
test: pd.DataFrame,
features: list,
fcst_h: int,
lags: list
) -> pd.DataFrame:
"""
Train a LightGBM model with STL decomposition and generate forecasts.
Parameters
----------
params_lgb : dict
Parameters for the LightGBM model.
train : pd.DataFrame
Training dataset containing the time series data.
test : pd.DataFrame
Test dataset for generating forecasts.
features : list
List of feature names to be used in the model.
fcst_h : int
Forecast horizon, i.e., the number of time steps to forecast.
lags : list
List of lags to be used in the autoregressive model.
Returns
-------
pd.DataFrame
DataFrame containing the forecasted values from the LightGBM-STL model.
"""
regressor = lgb.LGBMRegressor(
**{k: v for k, v in params_lgb.items() if k not in ["num_boost_round", "use_time_index", "degree"]},
n_estimators=params_lgb["num_boost_round"])
kwargs = {
"lag_feature": {
"lag": [i + 1 for i in range(max(lags))],
}
}
forecaster = TransformedTargetForecaster(
[
("deseasonalise", Deseasonalizer(model="multiplicative", sp=max(lags))),
("detrend", Detrender(forecaster=PolynomialTrendForecaster(degree=params_lgb["degree"]))),
("forecast", make_reduction(
regressor,
transformers=[WindowSummarizer(**kwargs, n_jobs=-1)],
window_length=None,
strategy="recursive",
pooling="global",
),
),
]
)
fh = [i + 1 for i in range(fcst_h)]
start = time.time()
forecaster.fit(train["value"].to_numpy().reshape(-1, ), train[features].values, fh=fh)
stl_fcst = forecaster.predict(fh, test[features].values)
end = time.time()
runtime = (end - start) / 60
lgb_stl_fcst = pd.DataFrame({
"series_id": test["series_id"].to_numpy().flatten(),
"date": test["date"].to_numpy().flatten(),
"fcst": stl_fcst.flatten(),
"runtime": runtime,
"model": f"LightGBM-STL",
})
return lgb_stl_fcst
def create_gluonts_dataset(
train: pd.DataFrame,
test: pd.DataFrame,
meta: dict,
freq: str
) -> tuple:
"""
Create GluonTS ListDatasets for training and testing.
Parameters
----------
train : pd.DataFrame
Training dataset containing the time series data.
test : pd.DataFrame
Test dataset for generating forecasts.
meta : dict
Metadata containing information about the dataset, such as dynamic and static covariates.
freq : str
Frequency of the time series data (e.g., 'D' for daily, 'M' for monthly).
Returns
-------
tuple of (ListDataset, ListDataset)
Training and test GluonTS datasets.
"""
# GluonTS uses pandas Period frequencies; normalize in case the caller
# passed a DateOffset-style freq (e.g. "MS", "QS", "AS-JAN").
freq_gluonts = to_period_freq(freq)
# Train
list_data_train = [i for _, i in train.groupby("series_id")]
target_train = [np.array(item["value"]) for item in list_data_train]
start_train = [pd.Timestamp(item["date"].min()) for item in list_data_train]
series_id_train = [str(item["series_id"].iloc[0]) for item in list_data_train]
feat_dynamic_real_train = [np.array(item[meta["dynamic_cov"] + meta["time_derived_feats"]]).T for item in
list_data_train]
feat_static_real_train = np.array([np.array(item[meta["static_cov"]])[0] for item in list_data_train])
train_ds = ListDataset([{
FieldName.TARGET: target,
FieldName.START: start,
FieldName.ITEM_ID: series_id,
FieldName.FEAT_DYNAMIC_REAL: feat_dynamic_real,
FieldName.FEAT_STATIC_REAL: feat_static_real
} for
target,
start,
series_id,
feat_dynamic_real,
feat_static_real
in zip(
target_train,
start_train,
series_id_train,
feat_dynamic_real_train,
feat_static_real_train
)], freq=freq_gluonts)
# Test
gluonts_df = pd.concat([train, test], axis=0, ignore_index=True)
list_data_test = [i for _, i in gluonts_df.groupby("series_id")]
target_test = [np.array(item["value"]) for item in list_data_test]
start_test = [pd.Timestamp(item["date"].min()) for item in list_data_test]
series_id_test = [str(item["series_id"].iloc[0]) for item in list_data_test]
feat_dynamic_real_test = [np.array(item[meta["dynamic_cov"] + meta["time_derived_feats"]]).T for item in
list_data_test]
feat_static_real_test = np.array([np.array(item[meta["static_cov"]])[0] for item in list_data_test])
test_ds = ListDataset([{
FieldName.TARGET: target,
FieldName.START: start,
FieldName.ITEM_ID: series_id,
FieldName.FEAT_DYNAMIC_REAL: feat_dynamic_real,
FieldName.FEAT_STATIC_REAL: feat_static_real,
} for
target,
start,
series_id,
feat_dynamic_real,
feat_static_real
in zip(
target_test,
start_test,
series_id_test,
feat_dynamic_real_test,
feat_static_real_test
)], freq=freq_gluonts)
return train_ds, test_ds
def DeepARForecast(
train: pd.DataFrame,
test: pd.DataFrame,
meta: dict,
freq: str,
fcst_h: int,
lags: list,
max_lag: int,
config: dict,
series_ids: list,
device: torch.device
) -> pd.DataFrame:
"""
Train a DeepAR model via GluonTS and generate forecasts.
Parameters
----------
train : pd.DataFrame
Training dataset containing the time series data.
test : pd.DataFrame
Test dataset for generating forecasts.
meta : dict
Metadata containing information about the dataset, such as dynamic and static covariates.
freq : str
Frequency of the time series data (e.g., 'D' for daily, 'M' for monthly).
fcst_h : int
Forecast horizon, i.e., the number of time steps to forecast.
lags : list
List of lags to be used in the autoregressive model.
max_lag : int
Maximum lag to consider for the autoregressive model.
config : dict
Configuration dictionary containing parameters for the model.
series_ids : list
List of series IDs for which forecasts are to be generated.
device : torch.device
Device to be used for training the model (e.g., 'cuda' or 'cpu').
Returns
-------
pd.DataFrame
DataFrame containing the forecasted values from the model.
"""
freq_gluonts = to_period_freq(freq)
# Create GluonTS datasets
train_ds, test_ds = create_gluonts_dataset(train, test, meta, freq_gluonts)
# Initialize model
deepar_model = DeepAREstimator(
freq=freq_gluonts,
prediction_length=fcst_h,
context_length=2 * fcst_h,
num_feat_dynamic_real=len(meta["dynamic_cov"] + meta["time_derived_feats"]),
num_feat_static_real=len(meta["static_cov"]) if len(meta["static_cov"]) > 0 else 0,
time_features=[], # disable built-in time features and use the sames as in the HyperTree models
lags_seq=lags, # disable built-in lags and use the sames as in the HyperTree models
nonnegative_pred_samples=True,
scaling=True,
lr=config["deep_learning"]["learning_rate"],
batch_size=config["deep_learning"]["batch_size"],
num_layers=config["deep_learning"]["num_layers"],
hidden_size=config["deep_learning"]["hidden_size"],
trainer_kwargs=dict(
accelerator=device.type,
max_epochs=config["deep_learning"]["num_epochs"],
enable_progress_bar=False,
enable_model_summary=False,
logger=False,
)
)
# Train model
start = time.time()
deepar_predictor = deepar_model.train(train_ds)
# Forecast
forecast_it, ts_it = make_evaluation_predictions(
dataset=test_ds,
predictor=deepar_predictor,
num_samples=config["deep_learning"]["num_samples"],
)
forecasts_deepar = list(forecast_it)
fcst_df_list = []
for i in range(len(forecasts_deepar)):
fcst_df_list.append(
pd.DataFrame.from_dict(
{
"series_id": forecasts_deepar[i].item_id,
"fcst": np.round(forecasts_deepar[i].samples.mean(axis=0)).flatten(),
}
)
)
deepar_fcst_df = pd.concat(fcst_df_list, axis=0, ignore_index=True)
end = time.time()
runtime = (end - start) / 60
deepar_fcst_list = []
for series in series_ids:
test_gluonts = test[test["series_id"] == series]
deepar_fcst = deepar_fcst_df[deepar_fcst_df["series_id"] == str(series)].copy()
deepar_fcst_list.append(
pd.DataFrame.from_dict({
"series_id": series,
"date": pd.to_datetime(test_gluonts["date"].values),
"fcst": np.array(deepar_fcst["fcst"].values).flatten(),
"runtime": runtime,
"model": f"Deep-AR({max_lag})",
})
)
deepar_fcst = pd.concat(deepar_fcst_list, axis=0)
cleanup_lightning_artifacts()
return deepar_fcst
def TFTForecast(
train: pd.DataFrame,
test: pd.DataFrame,
meta: dict,
freq: str,
fcst_h: int,
config: dict,
series_ids: list,
device: torch.device
) -> pd.DataFrame:
"""
Train a Temporal Fusion Transformer via GluonTS and generate forecasts.
Parameters
----------
train : pd.DataFrame
Training dataset containing the time series data.
test : pd.DataFrame
Test dataset for generating forecasts.
meta : dict
Metadata containing information about the dataset, such as dynamic and static covariates.
freq : str
Frequency of the time series data (e.g., 'D' for daily, 'M' for monthly).
fcst_h : int
Forecast horizon, i.e., the number of time steps to forecast.
config : dict
Configuration dictionary containing parameters for the model.
series_ids : list
List of series IDs for which forecasts are to be generated.
device : torch.device
Device to be used for training the model (e.g., 'cuda' or 'cpu').
Returns
-------
pd.DataFrame
DataFrame containing the forecasted values from the model.
"""
freq_gluonts = to_period_freq(freq)
# Create GluonTS datasets
train_ds, test_ds = create_gluonts_dataset(train, test, meta, freq_gluonts)
# Initialize model
dynamic_dims = len(meta["dynamic_cov"] + meta["time_derived_feats"])
tft_model = TemporalFusionTransformerEstimator(
freq=freq_gluonts,
prediction_length=fcst_h,
context_length=2 * fcst_h,
dynamic_dims=[dynamic_dims] if dynamic_dims > 0 else [],
static_dims=[len(meta["static_cov"])] if len(meta["static_cov"]) > 0 else [],
time_features=[], # disable built-in time features and use the sames as in the HyperTree models
quantiles=config["deep_learning"]["quantiles_tft"],
num_heads=config["deep_learning"]["num_heads"],
hidden_dim=config["deep_learning"]["hidden_size"],
variable_dim=config["deep_learning"]["variable_dim"],
batch_size=config["deep_learning"]["batch_size"],
lr=config["deep_learning"]["learning_rate"],
trainer_kwargs=dict(
accelerator=device.type,
max_epochs=config["deep_learning"]["num_epochs"],
enable_progress_bar=False,
enable_model_summary=False,
logger=False,
)
)
# Train model
start = time.time()
tft_predictor = tft_model.train(train_ds)
# Forecast
forecast_it_tft, ts_it_tft = make_evaluation_predictions(
dataset=test_ds,
predictor=tft_predictor,
)
forecasts_tft = list(forecast_it_tft)
fcst_df_list_tft = []
for i in range(len(forecasts_tft)):
fcst_df_list_tft.append(
pd.DataFrame.from_dict(
{
"series_id": forecasts_tft[i].item_id,
"fcst": np.round(forecasts_tft[i]["p50"]).flatten(),
}
)
)
tft_fcst_df = pd.concat(fcst_df_list_tft, axis=0, ignore_index=True)
end = time.time()
runtime = (end - start) / 60
tft_fcst_list = []
for series in series_ids:
test_tft = test[test["series_id"] == series]
tft_fcst = tft_fcst_df[tft_fcst_df["series_id"] == str(series)].copy()
tft_fcst_list.append(
pd.DataFrame.from_dict({
"series_id": series,
"date": pd.to_datetime(test_tft["date"].values),
"fcst": np.array(tft_fcst["fcst"].values).flatten(),
"runtime": runtime,
"model": "TFT",
})
)
tft_fcst = pd.concat(tft_fcst_list, axis=0)
cleanup_lightning_artifacts()
return tft_fcst
def ChronosForecast(
train: pd.DataFrame,
test: pd.DataFrame,
series_ids: list,
fcst_h: int,
config: dict,
device: torch.device
) -> pd.DataFrame:
"""
Generate forecasts using the pretrained Chronos foundation model.
Parameters
----------
train : pd.DataFrame
Training dataset containing the time series data.
test : pd.DataFrame
Test dataset for generating forecasts.
series_ids : list
List of series IDs for which forecasts are to be generated.
fcst_h : int
Forecast horizon, i.e., the number of time steps to forecast.
config : dict
Configuration dictionary containing parameters for the model.
device : torch.device
Device to be used for training the model (e.g., 'cuda' or 'cpu').
Returns
-------
pd.DataFrame
DataFrame containing the forecasted values from the model.
"""
# Initialize model
chronos_model = ChronosPipeline.from_pretrained(
"amazon/chronos-t5-base",
device_map=device,
torch_dtype=torch.float32,
)
# Forecast
chronos_fcst_list = []
start = time.time()
for series in series_ids:
train_chronos = train[train["series_id"] == series]
test_chronos = test[test["series_id"] == series]
context = torch.tensor(train_chronos[train_chronos["series_id"] == series]["value"].to_numpy().reshape(-1, ))
fcsts = np.array(
chronos_model.predict(
context,
prediction_length=fcst_h,
num_samples=config["deep_learning"]["num_samples_chronos"]
)
)
chronos_fcst_list.append(
pd.DataFrame.from_dict({
"series_id": series,
"date": pd.to_datetime(test_chronos["date"].values),
"fcst": np.mean(fcsts, axis=1).flatten(),
"model": "Chronos",
})
)
end = time.time()
runtime = (end - start) / 60
chronos_fcst = pd.concat(chronos_fcst_list, axis=0)
chronos_fcst["runtime"] = runtime
chronos_fcst = chronos_fcst[col_order]
return chronos_fcst
def HyperTreeARForecast(
htar_params: dict,
train: pd.DataFrame,
test: pd.DataFrame,
features: list,
freq: str,
fcst_h: int,
max_lag: int,
loss_fn: nn.Module,
seed: int,
return_extras: bool = False,
) -> pd.DataFrame:
"""
Train a Hyper-Tree-AR model and generate forecasts.
Parameters
----------
htar_params : dict
Parameters for the HyperTree autoregressive model.
train : pd.DataFrame
Training dataset containing the time series data.
test : pd.DataFrame
Test dataset for generating forecasts.
features : list
List of feature names to be used in the model.
freq : str
Frequency of the time series data (e.g., 'D' for daily).
fcst_h : int
Forecast horizon, i.e., the number of time steps to forecast.
max_lag : int
Maximum lag to consider for the autoregressive model.
loss_fn : nn.Module
Loss function to be used for training the model.
seed : int
Random seed for reproducibility.
return_extras : bool, default False
If True, also return learned AR parameters over the full
(train + test) date range.
Returns
-------
pd.DataFrame or tuple
``fcst_df`` when ``return_extras=False``; otherwise
``(fcst_df, params_df)``.
"""
# Initialize model
ht_ar = HyperTreeAR(
p=max_lag,
freq=freq,
fcst_h=fcst_h,
loss_fn=loss_fn,
)
# Train model
start = time.time()
ht_ar.train(
lgb_params={k: v for k, v in htar_params.items() if k != "num_boost_round"},
num_iterations=htar_params["num_boost_round"],
train_data=train[["series_id", "date", "value"] + features],
seed=seed,
)
# Forecast
ht_ar_fcst = ht_ar.forecast(
test_data=test[["series_id", "date"] + features]
)
end = time.time()
runtime = (end - start) / 60
ht_ar_fcst["runtime"] = runtime
ht_ar_fcst = ht_ar_fcst[col_order]
if return_extras:
full_range = pd.concat(
[
train[["series_id", "date"] + features],
test[["series_id", "date"] + features],
],
axis=0, ignore_index=True,
).sort_values(["series_id", "date"]).reset_index(drop=True)
params_df = ht_ar.forecast(test_data=full_range, type="parameters")
params_df["model"] = "Hyper-Tree-AR"
return ht_ar_fcst, params_df
return ht_ar_fcst
def HyperTreeNetARForecast(
htnetar_params: dict,
htnetar_params_lgb: dict,
htnetar_network_params: dict,
train: pd.DataFrame,
test: pd.DataFrame,
features: list,
freq: str,
fcst_h: int,
max_lag: int,
loss_fn: nn.Module,
seed: int,
device: torch.device,
return_extras: bool = False,
) -> pd.DataFrame:
"""
Train a Hyper-TreeNet-AR model and generate forecasts.
Parameters
----------
htnetar_params : dict
Parameters for the HyperTreeNet autoregressive model.
htnetar_params_lgb : dict
Parameters for the LightGBM model used in HyperTreeNet.
htnetar_network_params : dict
Parameters for the MLP used in HyperTreeNet.
train : pd.DataFrame
Training dataset containing the time series data.
test : pd.DataFrame
Test dataset for generating forecasts.
features : list
List of feature names to be used in the model.
freq : str
Frequency of the time series data (e.g., 'D' for daily).
fcst_h : int
Forecast horizon, i.e., the number of time steps to forecast.
max_lag : int
Maximum lag to consider for the autoregressive model.
loss_fn : nn.Module
Loss function to be used for training the model.
seed : int
Random seed for reproducibility.
device : torch.device
Device to be used for training the model (e.g., 'cuda' or 'cpu').
return_extras : bool, default False
If True, also return learned AR parameters and tree embeddings
over the full (train + test) date range.
Returns
-------
pd.DataFrame or tuple
``fcst_df`` when ``return_extras=False``; otherwise
``(fcst_df, params_df, embeddings_df)``.
"""
# Initialize model
htnet_ar = HyperTreeNetAR(
p=max_lag,
freq=freq,
fcst_h=fcst_h,
loss_fn=loss_fn,
device=device
)
# Train model
start = time.time()
htnet_ar.train(
lgb_params=htnetar_params_lgb,
network_params=htnetar_network_params,
gradient_mode="separate",
num_iterations=htnetar_params["num_boost_round"],
train_data=train[["series_id", "date", "value"] + features],
seed=seed,
)
# Forecast
htnet_ar_fcst = htnet_ar.forecast(
test_data=test[["series_id", "date"] + features]
)
end = time.time()
runtime = (end - start) / 60
htnet_ar_fcst["runtime"] = runtime
# Arrange columns
htnet_ar_fcst = htnet_ar_fcst[col_order]
if return_extras:
full_range = pd.concat(
[
train[["series_id", "date"] + features],
test[["series_id", "date"] + features],
],
axis=0, ignore_index=True,
).sort_values(["series_id", "date"]).reset_index(drop=True)
params_df = htnet_ar.forecast(test_data=full_range, type="parameters")
params_df["model"] = "Hyper-TreeNet-AR"
embeddings_df = htnet_ar.forecast(test_data=full_range, type="tree_embeddings")
embeddings_df["model"] = "Hyper-TreeNet-AR"
return htnet_ar_fcst, params_df, embeddings_df
return htnet_ar_fcst
def HyperTreeETSForecast(
htets_params: dict,
train: pd.DataFrame,
test: pd.DataFrame,
features: list,
freq: str,
fcst_h: int,
seasonality_ets: str,
loss_fn: nn.Module,
manual_param: float = None
) -> pd.DataFrame:
"""
Train a Hyper-Tree-ETS model and generate forecasts.
Parameters
----------
htets_params : dict
Parameters for the HyperTreeETS model.
train : pd.DataFrame
Training dataset containing the time series data.
test : pd.DataFrame
Test dataset for generating forecasts.
features : list
List of feature names to be used in the model.
freq : str
Frequency of the time series data (e.g., 'D' for daily).
fcst_h : int
Forecast horizon, i.e., the number of time steps to forecast.
seasonality_ets : str
Feature to be used for seasonality.
loss_fn : nn.Module
Loss function to be used for training the model.
manual_param : float, optional
Manual parameter for the ETS model (default is None). If provided, the model is not trained and
forecasts are generated directly using the provided parameter.
Returns
-------
pd.DataFrame
DataFrame containing the forecasted values from the model.
"""
start = time.time()
if htets_params["train"]:
# Warn on zero / near-zero values only when the multiplicative ETS
# variant is used (``ets_type == "triple"`` in our implementation),
# because that's where divergence actually happens.
if htets_params["ets_type"] == "triple":
_min = float(train["value"].min())
if _min <= 1e-6:
import warnings
warnings.warn(
f"Hyper-Tree-ETS Forecast (ets_type='triple'): "
f"train['value'].min() = {_min:.6g} is zero or near-zero. "
"Multiplicative ETS components may diverge. Consider "
"enabling ``htets_params['scaling']`` or preprocessing "
"the series to be strictly positive.",
stacklevel=2,
)
# Copy to avoid modifying the caller's DataFrames
train = train.copy()
test = test.copy()
# Scaling
if htets_params["scaling"]:
scaling_factor = np.mean(train["value"])
train["value"] = train["value"] + scaling_factor
# Initialize model
ht_ets = HyperTreeETS(
ets_type=htets_params["ets_type"],
seasonality_feature=seasonality_ets,
season_length=htets_params["season_length"],
freq=freq,
fcst_h=fcst_h,
loss_fn=loss_fn
)
# Train model
if manual_param is None:
ht_ets.train(
lgb_params={k: v for k, v in htets_params.items() if k not in ["num_boost_round", "season_length", "ets_type", "manual_param", "scaling", "train"]},
num_iterations=htets_params["num_boost_round"],
train_data=train[["series_id", "date", "value"] + features],
seed=123,
)
# Forecast
ht_ets_fcst = ht_ets.forecast(
test_data=test[["series_id", "date"] + features]
)
else: # Generate forecasts using the manually provided parameter
n_obs = train.shape[0] + test.shape[0]
n_params = ht_ets.n_params
n_series = train["series_id"].nunique()
ht_ets.n_series = n_series
params = torch.ones(
(n_obs, ht_ets.n_params), dtype=ht_ets.dtype
).reshape(n_series, -1, n_params) * manual_param
fit_params = params[:, :-fcst_h, :]
fcst_params = params[:, -fcst_h:, :]
# Create mask for training data
train_mask = torch.tensor(
np.ones_like(train["value"]),
dtype=ht_ets.dtype
).reshape(n_series, -1)
# Forward pass to update states using training data
target = torch.tensor(
train["value"].to_numpy().reshape(n_series, -1),
dtype=ht_ets.dtype
)
ht_ets.is_trained = True
dfit = lgb.Dataset(
data=train[features],
label=train["value"].to_numpy().reshape(-1, ),
free_raw_data=False,
)
level, trend, seasonality, fit = ht_ets.forward(fit_params, dfit, target, train_mask)
# Extract last states (forward returns final scalars directly)
last_level = level
last_trend = trend
# Generate forecasts using roll-forward state-space recursion,
# matching HyperTreeETS.forecast().
if ht_ets.ets_type == "triple":
seasonality_idxs = torch.tensor(
test[ht_ets.seasonality_feature].values - 1
).reshape(n_series, fcst_h)
batch_idx = torch.arange(n_series, dtype=torch.long)
alpha_fcst = fcst_params[:, :, 0]
beta_fcst = fcst_params[:, :, 1]
gamma_fcst = fcst_params[:, :, 2]
phi_fcst = fcst_params[:, :, 3]
fcsts = []
level_h = last_level
trend_h = last_trend
for h in range(fcst_h):
alpha = alpha_fcst[:, h]
beta = beta_fcst[:, h]
gamma = gamma_fcst[:, h]
phi = phi_fcst[:, h]
s_idx = seasonality_idxs[:, h].long()
s_h = seasonality[batch_idx, s_idx]
pseudo_y = (level_h + phi * trend_h) * s_h