forked from unit8co/darts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregression_model.py
2033 lines (1826 loc) · 90.2 KB
/
regression_model.py
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
"""
Regression Model
----------------
A `RegressionModel` forecasts future values of a target series based on
* The target series (past lags only)
* An optional past_covariates series (past lags only)
* An optional future_covariates series (possibly past and future lags)
* Available static covariates
The regression models are learned in a supervised way, and they can wrap around any "scikit-learn like" regression model
acting on tabular data having ``fit()`` and ``predict()`` methods.
Darts also provides :class:`LinearRegressionModel` and :class:`RandomForest`, which are regression models
wrapping around scikit-learn linear regression and random forest regression, respectively.
Behind the scenes this model is tabularizing the time series data to make it work with regression models.
The lags can be specified either using an integer - in which case it represents the _number_ of (past or future) lags
to take into consideration, or as a list - in which case the lags have to be enumerated (strictly negative values
denoting past lags and positive values including 0 denoting future lags).
When static covariates are present, they are appended to the lagged features. When multiple time series are passed,
if their static covariates do not have the same size, the shorter ones are padded with 0 valued features.
"""
from collections import OrderedDict
from collections.abc import Sequence
from typing import Any, Callable, Literal, Optional, Union
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.utils.validation import has_fit_parameter
from darts.logging import get_logger, raise_if, raise_if_not, raise_log
from darts.models.forecasting.forecasting_model import GlobalForecastingModel
from darts.timeseries import TimeSeries
from darts.utils.data.tabularization import (
_create_lagged_data_autoregression,
create_lagged_component_names,
create_lagged_training_data,
)
from darts.utils.historical_forecasts import (
_check_optimizable_historical_forecasts_global_models,
_optimized_historical_forecasts_all_points,
_optimized_historical_forecasts_last_points_only,
_process_historical_forecast_input,
)
from darts.utils.multioutput import MultiOutputRegressor
from darts.utils.ts_utils import get_single_series, seq2series, series2seq
from darts.utils.utils import (
_check_quantiles,
likelihood_component_names,
quantile_names,
)
logger = get_logger(__name__)
LAGS_TYPE = Union[int, list[int], dict[str, Union[int, list[int]]]]
FUTURE_LAGS_TYPE = Union[
tuple[int, int], list[int], dict[str, Union[tuple[int, int], list[int]]]
]
class RegressionModel(GlobalForecastingModel):
def __init__(
self,
lags: Optional[LAGS_TYPE] = None,
lags_past_covariates: Optional[LAGS_TYPE] = None,
lags_future_covariates: Optional[FUTURE_LAGS_TYPE] = None,
output_chunk_length: int = 1,
output_chunk_shift: int = 0,
add_encoders: Optional[dict] = None,
model=None,
multi_models: Optional[bool] = True,
use_static_covariates: bool = True,
):
"""Regression Model
Can be used to fit any scikit-learn-like regressor class to predict the target time series from lagged values.
Parameters
----------
lags
Lagged target `series` values used to predict the next time step/s.
If an integer, must be > 0. Uses the last `n=lags` past lags; e.g. `(-1, -2, ..., -lags)`, where `0`
corresponds the first predicted time step of each sample. If `output_chunk_shift > 0`, then
lag `-1` translates to `-1 - output_chunk_shift` steps before the first prediction step.
If a list of integers, each value must be < 0. Uses only the specified values as lags.
If a dictionary, the keys correspond to the `series` component names (of the first series when
using multiple series) and the values correspond to the component lags (integer or list of integers). The
key 'default_lags' can be used to provide default lags for un-specified components. Raises and error if some
components are missing and the 'default_lags' key is not provided.
lags_past_covariates
Lagged `past_covariates` values used to predict the next time step/s.
If an integer, must be > 0. Uses the last `n=lags_past_covariates` past lags; e.g. `(-1, -2, ..., -lags)`,
where `0` corresponds to the first predicted time step of each sample. If `output_chunk_shift > 0`, then
lag `-1` translates to `-1 - output_chunk_shift` steps before the first prediction step.
If a list of integers, each value must be < 0. Uses only the specified values as lags.
If a dictionary, the keys correspond to the `past_covariates` component names (of the first series when
using multiple series) and the values correspond to the component lags (integer or list of integers). The
key 'default_lags' can be used to provide default lags for un-specified components. Raises and error if some
components are missing and the 'default_lags' key is not provided.
lags_future_covariates
Lagged `future_covariates` values used to predict the next time step/s. The lags are always relative to the
first step in the output chunk, even when `output_chunk_shift > 0`.
If a tuple of `(past, future)`, both values must be > 0. Uses the last `n=past` past lags and `n=future`
future lags; e.g. `(-past, -(past - 1), ..., -1, 0, 1, .... future - 1)`, where `0` corresponds the first
predicted time step of each sample. If `output_chunk_shift > 0`, the position of negative lags differ from
those of `lags` and `lags_past_covariates`. In this case a future lag `-5` would point at the same
step as a target lag of `-5 + output_chunk_shift`.
If a list of integers, uses only the specified values as lags.
If a dictionary, the keys correspond to the `future_covariates` component names (of the first series when
using multiple series) and the values correspond to the component lags (tuple or list of integers). The key
'default_lags' can be used to provide default lags for un-specified components. Raises and error if some
components are missing and the 'default_lags' key is not provided.
output_chunk_length
Number of time steps predicted at once (per chunk) by the internal model. It is not the same as forecast
horizon `n` used in `predict()`, which is the desired number of prediction points generated using a
one-shot- or autoregressive forecast. Setting `n <= output_chunk_length` prevents auto-regression. This is
useful when the covariates don't extend far enough into the future, or to prohibit the model from using
future values of past and / or future covariates for prediction (depending on the model's covariate
support).
output_chunk_shift
Optionally, the number of steps to shift the start of the output chunk into the future (relative to the
input chunk end). This will create a gap between the input (history of target and past covariates) and
output. If the model supports `future_covariates`, the `lags_future_covariates` are relative to the first
step in the shifted output chunk. Predictions will start `output_chunk_shift` steps after the end of the
target `series`. If `output_chunk_shift` is set, the model cannot generate autoregressive predictions
(`n > output_chunk_length`).
add_encoders
A large number of past and future covariates can be automatically generated with `add_encoders`.
This can be done by adding multiple pre-defined index encoders and/or custom user-made functions that
will be used as index encoders. Additionally, a transformer such as Darts' :class:`Scaler` can be added to
transform the generated covariates. This happens all under one hood and only needs to be specified at
model creation.
Read :meth:`SequentialEncoder <darts.dataprocessing.encoders.SequentialEncoder>` to find out more about
``add_encoders``. Default: ``None``. An example showing some of ``add_encoders`` features:
.. highlight:: python
.. code-block:: python
def encode_year(idx):
return (idx.year - 1950) / 50
add_encoders={
'cyclic': {'future': ['month']},
'datetime_attribute': {'future': ['hour', 'dayofweek']},
'position': {'past': ['relative'], 'future': ['relative']},
'custom': {'past': [encode_year]},
'transformer': Scaler(),
'tz': 'CET'
}
..
model
Scikit-learn-like model with ``fit()`` and ``predict()`` methods. Also possible to use model that doesn't
support multi-output regression for multivariate timeseries, in which case one regressor
will be used per component in the multivariate series.
If None, defaults to: ``sklearn.linear_model.LinearRegression(n_jobs=-1)``.
multi_models
If True, a separate model will be trained for each future lag to predict. If False, a single model
is trained to predict all the steps in 'output_chunk_length' (features lags are shifted back by
`output_chunk_length - n` for each step `n`). Default: True.
use_static_covariates
Whether the model should use static covariate information in case the input `series` passed to ``fit()``
contain static covariates. If ``True``, and static covariates are available at fitting time, will enforce
that all target `series` have the same static covariate dimensionality in ``fit()`` and ``predict()``.
Examples
--------
>>> from darts.datasets import WeatherDataset
>>> from darts.models import RegressionModel
>>> from sklearn.linear_model import Ridge
>>> series = WeatherDataset().load()
>>> # predicting atmospheric pressure
>>> target = series['p (mbar)'][:100]
>>> # optionally, use past observed rainfall (pretending to be unknown beyond index 100)
>>> past_cov = series['rain (mm)'][:100]
>>> # optionally, use future temperatures (pretending this component is a forecast)
>>> future_cov = series['T (degC)'][:106]
>>> # wrap around the sklearn Ridge model
>>> model = RegressionModel(
>>> model=Ridge(),
>>> lags=12,
>>> lags_past_covariates=4,
>>> lags_future_covariates=(0,6),
>>> output_chunk_length=6
>>> )
>>> model.fit(target, past_covariates=past_cov, future_covariates=future_cov)
>>> pred = model.predict(6)
>>> pred.values()
array([[1005.73340676],
[1005.71159051],
[1005.7322616 ],
[1005.76314504],
[1005.82204348],
[1005.89100967]])
"""
super().__init__(add_encoders=add_encoders)
self.model = model
self.lags: dict[str, list[int]] = {}
self.component_lags: dict[str, dict[str, list[int]]] = {}
self.input_dim = None
self.multi_models = True if multi_models or output_chunk_length == 1 else False
self._considers_static_covariates = use_static_covariates
self._static_covariates_shape: Optional[tuple[int, int]] = None
self._lagged_feature_names: Optional[list[str]] = None
self._lagged_label_names: Optional[list[str]] = None
# check and set output_chunk_length
raise_if_not(
isinstance(output_chunk_length, int) and output_chunk_length > 0,
f"output_chunk_length must be an integer greater than 0. Given: {output_chunk_length}",
logger=logger,
)
self._output_chunk_length = output_chunk_length
self._output_chunk_shift = output_chunk_shift
# model checks
if self.model is None:
self.model = LinearRegression(n_jobs=-1)
if not callable(getattr(self.model, "fit", None)):
raise_log(
Exception("Provided model object must have a fit() method", logger)
)
if not callable(getattr(self.model, "predict", None)):
raise_log(
Exception("Provided model object must have a predict() method", logger)
)
# check lags
raise_if(
(lags is None)
and (lags_future_covariates is None)
and (lags_past_covariates is None),
"At least one of `lags`, `lags_future_covariates` or `lags_past_covariates` must be not None.",
)
# convert lags arguments to list of int
# lags attribute should always be accessed with self._get_lags(), not self.lags.get()
self.lags, self.component_lags = self._generate_lags(
lags=lags,
lags_past_covariates=lags_past_covariates,
lags_future_covariates=lags_future_covariates,
output_chunk_shift=output_chunk_shift,
)
self.pred_dim = self.output_chunk_length if self.multi_models else 1
@staticmethod
def _generate_lags(
lags: Optional[LAGS_TYPE],
lags_past_covariates: Optional[LAGS_TYPE],
lags_future_covariates: Optional[FUTURE_LAGS_TYPE],
output_chunk_shift: int,
) -> tuple[dict[str, list[int]], dict[str, dict[str, list[int]]]]:
"""
Based on the type of the argument and the nature of the covariates, perform some sanity checks before
converting the lags to a list of integer.
If lags are provided as a dictionary, the lags values are contained in self.component_lags and the self.lags
attributes contain only the extreme values
If the lags are provided as integer, list, tuple or dictionary containing only the 'default_lags' keys, the lags
values are contained in the self.lags attribute and the self.component_lags is an empty dictionary.
If `output_chunk_shift > 0`, the `lags_future_covariates` are shifted into the future.
"""
processed_lags: dict[str, list[int]] = dict()
processed_component_lags: dict[str, dict[str, list[int]]] = dict()
for lags_values, lags_name, lags_abbrev in zip(
[lags, lags_past_covariates, lags_future_covariates],
["lags", "lags_past_covariates", "lags_future_covariates"],
["target", "past", "future"],
):
if lags_values is None:
continue
# converting to dictionary to run sanity checks
if not isinstance(lags_values, dict):
lags_values = {"default_lags": lags_values}
elif len(lags_values) == 0:
raise_log(
ValueError(
f"When passed as a dictionary, `{lags_name}` must contain at least one key."
),
logger,
)
invalid_type = False
supported_types = ""
min_lags = None
max_lags = None
tmp_components_lags: dict[str, list[int]] = dict()
for comp_name, comp_lags in lags_values.items():
if lags_name == "lags_future_covariates":
if isinstance(comp_lags, tuple):
raise_if_not(
len(comp_lags) == 2
and isinstance(comp_lags[0], int)
and isinstance(comp_lags[1], int),
f"`{lags_name}` - `{comp_name}`: tuple must be of length 2, and must contain two integers",
logger,
)
raise_if(
isinstance(comp_lags[0], bool)
or isinstance(comp_lags[1], bool),
f"`{lags_name}` - `{comp_name}`: tuple must contain integers, not bool",
logger,
)
raise_if_not(
comp_lags[0] >= 0 and comp_lags[1] >= 0,
f"`{lags_name}` - `{comp_name}`: tuple must contain positive integers. Given: {comp_lags}.",
logger,
)
raise_if(
comp_lags[0] == 0 and comp_lags[1] == 0,
f"`{lags_name}` - `{comp_name}`: tuple cannot be (0, 0) as it corresponds to an empty "
f"list of lags.",
logger,
)
tmp_components_lags[comp_name] = list(
range(-comp_lags[0], comp_lags[1])
)
elif isinstance(comp_lags, list):
for lag in comp_lags:
raise_if(
not isinstance(lag, int) or isinstance(lag, bool),
f"`{lags_name}` - `{comp_name}`: list must contain only integers. Given: {comp_lags}.",
logger,
)
tmp_components_lags[comp_name] = sorted(comp_lags)
else:
invalid_type = True
supported_types = "tuple or a list"
else:
if isinstance(comp_lags, int):
raise_if_not(
comp_lags > 0,
f"`{lags_name}` - `{comp_name}`: integer must be strictly positive . Given: {comp_lags}.",
logger,
)
tmp_components_lags[comp_name] = list(range(-comp_lags, 0))
elif isinstance(comp_lags, list):
for lag in comp_lags:
raise_if(
not isinstance(lag, int) or (lag >= 0),
f"`{lags_name}` - `{comp_name}`: list must contain only strictly negative integers. "
f"Given: {comp_lags}.",
logger,
)
tmp_components_lags[comp_name] = sorted(comp_lags)
else:
invalid_type = True
supported_types = "strictly positive integer or a list"
if invalid_type:
raise_log(
ValueError(
f"`{lags_name}` - `{comp_name}`: must be either a {supported_types}. "
f"Given : {type(comp_lags)}."
),
logger,
)
# extracting min and max lags va
if min_lags is None:
min_lags = tmp_components_lags[comp_name][0]
else:
min_lags = min(min_lags, tmp_components_lags[comp_name][0])
if max_lags is None:
max_lags = tmp_components_lags[comp_name][-1]
else:
max_lags = max(max_lags, tmp_components_lags[comp_name][-1])
# Check if only default lags are provided
has_default_lags = list(tmp_components_lags.keys()) == ["default_lags"]
# revert to shared lags logic when applicable
if has_default_lags:
processed_lags[lags_abbrev] = tmp_components_lags["default_lags"]
else:
processed_lags[lags_abbrev] = [min_lags, max_lags]
processed_component_lags[lags_abbrev] = tmp_components_lags
# if output chunk is shifted, shift future covariates lags with it
if output_chunk_shift and lags_abbrev == "future":
processed_lags[lags_abbrev] = [
lag_ + output_chunk_shift for lag_ in processed_lags[lags_abbrev]
]
if processed_component_lags and not has_default_lags:
processed_component_lags[lags_abbrev] = {
comp_: [lag_ + output_chunk_shift for lag_ in lags_]
for comp_, lags_ in processed_component_lags[
lags_abbrev
].items()
}
return processed_lags, processed_component_lags
def _get_lags(self, lags_type: str):
"""
If lags were specified in a component-wise manner, they are contained in self.component_lags and
the values in self.lags should be ignored as they correspond just the extreme values.
"""
if lags_type in self.component_lags:
return self.component_lags[lags_type]
else:
return self.lags.get(lags_type, None)
@property
def _model_encoder_settings(
self,
) -> tuple[int, int, bool, bool, Optional[list[int]], Optional[list[int]]]:
target_lags = self.lags.get("target", [0])
lags_past_covariates = self.lags.get("past", None)
if lags_past_covariates is not None:
lags_past_covariates = [
min(lags_past_covariates)
- int(not self.multi_models) * (self.output_chunk_length - 1),
max(lags_past_covariates),
]
lags_future_covariates = self.lags.get("future", None)
if lags_future_covariates is not None:
lags_future_covariates = [
min(lags_future_covariates)
- int(not self.multi_models) * (self.output_chunk_length - 1),
max(lags_future_covariates),
]
return (
abs(min(target_lags)),
self.output_chunk_length + self.output_chunk_shift,
lags_past_covariates is not None,
lags_future_covariates is not None,
lags_past_covariates,
lags_future_covariates,
)
@property
def extreme_lags(
self,
) -> tuple[
Optional[int],
Optional[int],
Optional[int],
Optional[int],
Optional[int],
Optional[int],
int,
Optional[int],
]:
min_target_lag = self.lags["target"][0] if "target" in self.lags else None
max_target_lag = self.output_chunk_length - 1 + self.output_chunk_shift
min_past_cov_lag = self.lags["past"][0] if "past" in self.lags else None
max_past_cov_lag = self.lags["past"][-1] if "past" in self.lags else None
min_future_cov_lag = self.lags["future"][0] if "future" in self.lags else None
max_future_cov_lag = self.lags["future"][-1] if "future" in self.lags else None
return (
min_target_lag,
max_target_lag,
min_past_cov_lag,
max_past_cov_lag,
min_future_cov_lag,
max_future_cov_lag,
self.output_chunk_shift,
None,
)
@property
def supports_multivariate(self) -> bool:
"""
If available, uses `model`'s native multivariate support. If not available, obtains multivariate support by
wrapping the univariate model in a `sklearn.multioutput.MultiOutputRegressor`.
"""
return True
@property
def min_train_series_length(self) -> int:
return max(
3,
(
-self.lags["target"][0] + self.output_chunk_length
if "target" in self.lags
else self.output_chunk_length
)
+ self.output_chunk_shift,
)
@property
def min_train_samples(self) -> int:
return 2
@property
def output_chunk_length(self) -> int:
return self._output_chunk_length
@property
def output_chunk_shift(self) -> int:
return self._output_chunk_shift
def get_multioutput_estimator(self, horizon: int, target_dim: int):
"""Returns the estimator that forecasts the `horizon`th step of the `target_dim`th target component.
Internally, estimators are grouped by `output_chunk_length` position, then by component.
Parameters
----------
horizon
The index of the forecasting point within `output_chunk_length`.
target_dim
The index of the target component.
"""
raise_if_not(
isinstance(self.model, MultiOutputRegressor),
"The sklearn model is not a MultiOutputRegressor object.",
logger,
)
raise_if_not(
0 <= horizon < self.output_chunk_length,
f"`horizon` must be `>= 0` and `< output_chunk_length={self.output_chunk_length}`.",
logger,
)
raise_if_not(
0 <= target_dim < self.input_dim["target"],
f"`target_dim` must be `>= 0`, and `< n_target_components={self.input_dim['target']}`.",
logger,
)
# when multi_models=True, one model per horizon and target component
idx_estimator = (
self.multi_models * self.input_dim["target"] * horizon + target_dim
)
return self.model.estimators_[idx_estimator]
def get_estimator(self, horizon: int, target_dim: int):
"""Returns the estimator that forecasts the `horizon`th step of the `target_dim`th target component.
The model is returned directly if it supports multi-output natively.
Parameters
----------
horizon
The index of the forecasting point within `output_chunk_length`.
target_dim
The index of the target component.
"""
if isinstance(self.model, MultiOutputRegressor):
return self.get_multioutput_estimator(
horizon=horizon, target_dim=target_dim
)
else:
logger.info(
"Model supports multi-output; a single estimator forecasts all the horizons and components."
)
return self.model
def _add_val_set_to_kwargs(
self,
kwargs: dict,
val_series: Sequence[TimeSeries],
val_past_covariates: Optional[Sequence[TimeSeries]],
val_future_covariates: Optional[Sequence[TimeSeries]],
val_sample_weight: Optional[Union[Sequence[TimeSeries], str]],
max_samples_per_ts: int,
) -> dict:
"""Creates a validation set and returns a new set of kwargs passed to `self.model.fit()` including the
validation set. This method can be overridden if the model requires a different logic to add the eval set."""
val_samples, val_labels, val_weight = self._create_lagged_data(
series=val_series,
past_covariates=val_past_covariates,
future_covariates=val_future_covariates,
max_samples_per_ts=max_samples_per_ts,
sample_weight=val_sample_weight,
last_static_covariates_shape=self._static_covariates_shape,
)
# create validation sets for MultiOutputRegressor
if val_labels.ndim == 2 and isinstance(self.model, MultiOutputRegressor):
val_sets, val_weights = [], []
for i in range(val_labels.shape[1]):
val_sets.append((val_samples, val_labels[:, i]))
if val_weight is not None:
val_weights.append(val_weight[:, i])
val_weights = val_weights or None
else:
val_sets = [(val_samples, val_labels)]
val_weights = val_weight
val_set_name, val_weight_name = self.val_set_params
return dict(kwargs, **{val_set_name: val_sets, val_weight_name: val_weights})
def _create_lagged_data(
self,
series: Sequence[TimeSeries],
past_covariates: Sequence[TimeSeries],
future_covariates: Sequence[TimeSeries],
max_samples_per_ts: int,
sample_weight: Optional[Union[TimeSeries, str]] = None,
last_static_covariates_shape: Optional[tuple[int, int]] = None,
):
(
features,
labels,
_,
self._static_covariates_shape,
sample_weights,
) = create_lagged_training_data(
target_series=series,
output_chunk_length=self.output_chunk_length,
output_chunk_shift=self.output_chunk_shift,
past_covariates=past_covariates,
future_covariates=future_covariates,
lags=self._get_lags("target"),
lags_past_covariates=self._get_lags("past"),
lags_future_covariates=self._get_lags("future"),
uses_static_covariates=self.uses_static_covariates,
last_static_covariates_shape=last_static_covariates_shape,
max_samples_per_ts=max_samples_per_ts,
multi_models=self.multi_models,
check_inputs=False,
concatenate=False,
sample_weight=sample_weight,
)
expected_nb_feat = (
features[0].shape[1]
if isinstance(features, Sequence)
else features.shape[1]
)
for i, (X_i, y_i) in enumerate(zip(features, labels)):
# TODO: account for scenario where two wrong shapes can silently hide the problem
if expected_nb_feat != X_i.shape[1]:
shape_error_msg = []
for ts, cov_name, arg_name in zip(
[series, past_covariates, future_covariates],
["target", "past", "future"],
["series", "past_covariates", "future_covariates"],
):
if ts is not None and ts[i].width != self.input_dim[cov_name]:
shape_error_msg.append(
f"Expected {self.input_dim[cov_name]} components but received "
f"{ts[i].width} components at index {i} of `{arg_name}`."
)
raise_log(ValueError("\n".join(shape_error_msg)), logger)
features[i] = X_i[:, :, 0]
labels[i] = y_i[:, :, 0]
if sample_weights is not None:
sample_weights[i] = sample_weights[i][:, :, 0]
features = np.concatenate(features, axis=0)
labels = np.concatenate(labels, axis=0)
if sample_weights is not None:
sample_weights = np.concatenate(sample_weights, axis=0)
# if labels are of shape (n_samples, 1) flatten it to shape (n_samples,)
if labels.ndim == 2 and labels.shape[1] == 1:
labels = labels.ravel()
if (
sample_weights is not None
and sample_weights.ndim == 2
and sample_weights.shape[1] == 1
):
sample_weights = sample_weights.ravel()
return features, labels, sample_weights
def _fit_model(
self,
series: Sequence[TimeSeries],
past_covariates: Sequence[TimeSeries],
future_covariates: Sequence[TimeSeries],
max_samples_per_ts: int,
sample_weight: Optional[Union[Sequence[TimeSeries], str]],
val_series: Optional[Sequence[TimeSeries]] = None,
val_past_covariates: Optional[Sequence[TimeSeries]] = None,
val_future_covariates: Optional[Sequence[TimeSeries]] = None,
val_sample_weight: Optional[Union[Sequence[TimeSeries], str]] = None,
**kwargs,
):
"""
Function that fit the model. Deriving classes can override this method for adding additional
parameters (e.g., adding validation data), keeping the sanity checks on series performed by fit().
"""
training_samples, training_labels, sample_weights = self._create_lagged_data(
series=series,
past_covariates=past_covariates,
future_covariates=future_covariates,
max_samples_per_ts=max_samples_per_ts,
sample_weight=sample_weight,
last_static_covariates_shape=None,
)
if self.supports_val_set and val_series is not None:
kwargs = self._add_val_set_to_kwargs(
kwargs=kwargs,
val_series=val_series,
val_past_covariates=val_past_covariates,
val_future_covariates=val_future_covariates,
val_sample_weight=val_sample_weight,
max_samples_per_ts=max_samples_per_ts,
)
# only use `sample_weight` if model supports it
sample_weight_kwargs = dict()
if sample_weights is not None:
if self.supports_sample_weight:
sample_weight_kwargs = {"sample_weight": sample_weights}
else:
logger.warning(
"`sample_weight` was ignored since underlying regression model's "
"`fit()` method does not support it."
)
self.model.fit(
training_samples, training_labels, **sample_weight_kwargs, **kwargs
)
# generate and store the lagged components names (for feature importance analysis)
self._lagged_feature_names, self._lagged_label_names = (
create_lagged_component_names(
target_series=series,
past_covariates=past_covariates,
future_covariates=future_covariates,
lags=self._get_lags("target"),
lags_past_covariates=self._get_lags("past"),
lags_future_covariates=self._get_lags("future"),
output_chunk_length=self.output_chunk_length,
concatenate=False,
use_static_covariates=self.uses_static_covariates,
)
)
def _native_support_multioutput(self) -> bool:
"""
Returns True if the model supports multi-output regression natively.
"""
return (
callable(getattr(self.model, "_get_tags", None))
and isinstance(self.model._get_tags(), dict)
and self.model._get_tags().get("multioutput")
)
def fit(
self,
series: Union[TimeSeries, Sequence[TimeSeries]],
past_covariates: Optional[Union[TimeSeries, Sequence[TimeSeries]]] = None,
future_covariates: Optional[Union[TimeSeries, Sequence[TimeSeries]]] = None,
max_samples_per_ts: Optional[int] = None,
n_jobs_multioutput_wrapper: Optional[int] = None,
sample_weight: Optional[Union[TimeSeries, Sequence[TimeSeries], str]] = None,
**kwargs,
):
"""
Fit/train the model on one or multiple series.
Parameters
----------
series
TimeSeries or Sequence[TimeSeries] object containing the target values.
past_covariates
Optionally, a series or sequence of series specifying past-observed covariates
future_covariates
Optionally, a series or sequence of series specifying future-known covariates
max_samples_per_ts
This is an integer upper bound on the number of tuples that can be produced
per time series. It can be used in order to have an upper bound on the total size of the dataset and
ensure proper sampling. If `None`, it will read all of the individual time series in advance (at dataset
creation) to know their sizes, which might be expensive on big datasets.
If some series turn out to have a length that would allow more than `max_samples_per_ts`, only the
most recent `max_samples_per_ts` samples will be considered.
n_jobs_multioutput_wrapper
Number of jobs of the MultiOutputRegressor wrapper to run in parallel. Only used if the model doesn't
support multi-output regression natively.
sample_weight
Optionally, some sample weights to apply to the target `series` labels. They are applied per observation,
per label (each step in `output_chunk_length`), and per component.
If a series or sequence of series, then those weights are used. If the weight series only have a single
component / column, then the weights are applied globally to all components in `series`. Otherwise, for
component-specific weights, the number of components must match those of `series`.
If a string, then the weights are generated using built-in weighting functions. The available options are
`"linear"` or `"exponential"` decay - the further in the past, the lower the weight. The weights are
computed globally based on the length of the longest series in `series`. Then for each series, the weights
are extracted from the end of the global weights. This gives a common time weighting across all series.
**kwargs
Additional keyword arguments passed to the `fit` method of the model.
"""
# guarantee that all inputs are either list of TimeSeries or None
series = series2seq(series)
past_covariates = series2seq(past_covariates)
future_covariates = series2seq(future_covariates)
val_series = series2seq(kwargs.pop("val_series", None))
val_past_covariates = series2seq(kwargs.pop("val_past_covariates", None))
val_future_covariates = series2seq(kwargs.pop("val_future_covariates", None))
if not isinstance(sample_weight, str):
sample_weight = series2seq(sample_weight)
val_sample_weight = kwargs.pop("val_sample_weight", None)
if not isinstance(val_sample_weight, str):
val_sample_weight = series2seq(val_sample_weight)
self.encoders = self.initialize_encoders()
if self.encoders.encoding_available:
past_covariates, future_covariates = self.generate_fit_encodings(
series=series,
past_covariates=past_covariates,
future_covariates=future_covariates,
)
if past_covariates is not None:
self._uses_past_covariates = True
if future_covariates is not None:
self._uses_future_covariates = True
if (
get_single_series(series).static_covariates is not None
and self.supports_static_covariates
and self.considers_static_covariates
):
self._verify_static_covariates(get_single_series(series).static_covariates)
self._uses_static_covariates = True
for covs, name in zip([past_covariates, future_covariates], ["past", "future"]):
raise_if(
covs is not None and name not in self.lags,
f"`{name}_covariates` not None in `fit()` method call, but `lags_{name}_covariates` is None in "
f"constructor.",
)
raise_if(
covs is None and name in self.lags,
f"`{name}_covariates` is None in `fit()` method call, but `lags_{name}_covariates` is not None in "
"constructor.",
)
if self.supports_val_set:
val_series, val_past_covariates, val_future_covariates = (
self._process_validation_set(
series=series,
past_covariates=past_covariates,
future_covariates=future_covariates,
val_series=val_series,
val_past_covariates=val_past_covariates,
val_future_covariates=val_future_covariates,
)
)
# saving the dims of all input series to check at prediction time
self.input_dim = {
"target": series[0].width,
"past": past_covariates[0].width if past_covariates else None,
"future": future_covariates[0].width if future_covariates else None,
}
# Check if multi-output regression is required
require_multioutput = not series[0].is_univariate or (
self.output_chunk_length > 1
and self.multi_models
and not isinstance(self.model, MultiOutputRegressor)
)
# If multi-output required and model doesn't support it natively, wrap it in a MultiOutputRegressor
if require_multioutput and (
not self._native_support_multioutput() or sample_weight is not None
):
val_set_name, val_weight_name = self.val_set_params
mor_kwargs = {
"eval_set_name": val_set_name,
"eval_weight_name": val_weight_name,
"n_jobs": n_jobs_multioutput_wrapper,
}
self.model = MultiOutputRegressor(self.model, **mor_kwargs)
if (
not isinstance(self.model, MultiOutputRegressor)
and n_jobs_multioutput_wrapper is not None
):
logger.warning("Provided `n_jobs_multioutput_wrapper` wasn't used.")
super().fit(
series=seq2series(series),
past_covariates=seq2series(past_covariates),
future_covariates=seq2series(future_covariates),
)
variate2arg = {
"target": "lags",
"past": "lags_past_covariates",
"future": "lags_future_covariates",
}
# if provided, component-wise lags must be defined for all the components of the first series
component_lags_error_msg = []
for variate_type, variate in zip(
["target", "past", "future"], [series, past_covariates, future_covariates]
):
if variate_type not in self.component_lags:
continue
# ignore the fallback lags entry
provided_components = set(self.component_lags[variate_type].keys())
required_components = set(variate[0].components)
wrong_components = list(
provided_components - {"default_lags"} - required_components
)
missing_keys = list(required_components - provided_components)
# lags were specified for unrecognized components
if len(wrong_components) > 0:
component_lags_error_msg.append(
f"The `{variate2arg[variate_type]}` dictionary specifies lags for components that are not "
f"present in the series : {wrong_components}. They must be removed to avoid any ambiguity."
)
elif len(missing_keys) > 0 and "default_lags" not in provided_components:
component_lags_error_msg.append(
f"The {variate2arg[variate_type]} dictionary is missing the lags for the following components "
f"present in the series: {missing_keys}. The key 'default_lags' can be used to provide lags for "
f"all the non-explicitely defined components."
)
else:
# reorder the components based on the input series, insert the default when necessary
self.component_lags[variate_type] = {
comp_name: (
self.component_lags[variate_type][comp_name]
if comp_name in self.component_lags[variate_type]
else self.component_lags[variate_type]["default_lags"]
)
for comp_name in variate[0].components
}
# single error message for all the lags arguments
if len(component_lags_error_msg) > 0:
raise_log(ValueError("\n".join(component_lags_error_msg)), logger)
self._fit_model(
series=series,
past_covariates=past_covariates,
future_covariates=future_covariates,
val_series=val_series,
val_past_covariates=val_past_covariates,
val_future_covariates=val_future_covariates,
sample_weight=sample_weight,
val_sample_weight=val_sample_weight,
max_samples_per_ts=max_samples_per_ts,
**kwargs,
)
return self
def predict(
self,
n: int,
series: Optional[Union[TimeSeries, Sequence[TimeSeries]]] = None,
past_covariates: Optional[Union[TimeSeries, Sequence[TimeSeries]]] = None,
future_covariates: Optional[Union[TimeSeries, Sequence[TimeSeries]]] = None,
num_samples: int = 1,
verbose: bool = False,
predict_likelihood_parameters: bool = False,
show_warnings: bool = True,
**kwargs,
) -> Union[TimeSeries, Sequence[TimeSeries]]:
"""Forecasts values for `n` time steps after the end of the series.
Parameters
----------
n : int
Forecast horizon - the number of time steps after the end of the series for which to produce predictions.
series : TimeSeries or list of TimeSeries, optional
Optionally, one or several input `TimeSeries`, representing the history of the target series whose future
is to be predicted. If specified, the method returns the forecasts of these series. Otherwise, the method
returns the forecast of the (single) training series.
past_covariates : TimeSeries or list of TimeSeries, optional
Optionally, the past-observed covariates series needed as inputs for the model.
They must match the covariates used for training in terms of dimension and type.
future_covariates : TimeSeries or list of TimeSeries, optional
Optionally, the future-known covariates series needed as inputs for the model.
They must match the covariates used for training in terms of dimension and type.
num_samples : int, default: 1
Number of times a prediction is sampled from a probabilistic model. Should be set to 1
for deterministic models.
verbose
Whether to print the progress.
predict_likelihood_parameters
If set to `True`, the model predicts the parameters of its `likelihood` instead of the target. Only
supported for probabilistic models with a likelihood, `num_samples = 1` and `n<=output_chunk_length`.
Default: ``False``
**kwargs : dict, optional
Additional keyword arguments passed to the `predict` method of the model. Only works with
univariate target series.
show_warnings
Optionally, control whether warnings are shown. Not effective for all models.
"""
if series is None:
# then there must be a single TS, and that was saved in super().fit as self.training_series
if self.training_series is None:
raise_log(
ValueError(
"Input `series` must be provided. This is the result either from fitting on multiple series, "