-
Notifications
You must be signed in to change notification settings - Fork 89
/
_reduce.py
2411 lines (2002 loc) · 89.4 KB
/
_reduce.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
"""Composition functionality for reduction approaches to forecasting."""
__author__ = [
"mloning",
"AyushmaanSeth",
"kAnand77",
"LuisZugasti",
"Lovkush-A",
"fkiraly",
]
__all__ = [
"make_reduction",
"DirectTimeSeriesRegressionForecaster",
"RecursiveTimeSeriesRegressionForecaster",
"MultioutputTimeSeriesRegressionForecaster",
"DirectTabularRegressionForecaster",
"RecursiveTabularRegressionForecaster",
"MultioutputTabularRegressionForecaster",
"DirRecTabularRegressionForecaster",
"DirRecTimeSeriesRegressionForecaster",
"DirectReductionForecaster",
]
from warnings import warn
import numpy as np
import pandas as pd
from sklearn.base import clone
from sklearn.multioutput import MultiOutputRegressor
from aeon.forecasting.base import BaseForecaster, ForecastingHorizon
from aeon.forecasting.base._aeon import _BaseWindowForecaster
from aeon.forecasting.base._base import DEFAULT_ALPHA
from aeon.forecasting.base._fh import _index_range
from aeon.regression.base import BaseRegressor
from aeon.transformations.compose import FeatureUnion
from aeon.transformations.summarize import WindowSummarizer
from aeon.utils.datetime import _shift
from aeon.utils.index_functions import get_time_index
from aeon.utils.sklearn import is_sklearn_regressor
from aeon.utils.validation import check_window_length
def _concat_y_X(y, X):
"""Concatenate y and X prior to sliding-window transform."""
z = y.to_numpy()
if z.ndim == 1:
z = z.reshape(-1, 1)
if X is not None:
z = np.column_stack([z, X.to_numpy()])
return z
def _check_fh(fh):
"""Check fh prior to sliding-window transform."""
assert fh.is_relative
assert fh.is_all_out_of_sample()
return fh.to_indexer().to_numpy()
def _sliding_window_transform(
y,
window_length,
fh,
X=None,
transformers=None,
scitype="tabular-regressor",
pooling="local",
windows_identical=True,
):
"""Transform time series data using sliding window.
See `test_sliding_window_transform_explicit` in test_reduce.py for explicit
example.
Parameters
----------
y : pd.Series
Endogenous time series
window_length : int
Window length for transformed feature variables
fh : ForecastingHorizon
Forecasting horizon for transformed target variable
X : pd.DataFrame, optional (default=None)
Exogenous series.
transformers: list of transformers (default = None)
A suitable list of transformers that allows for using an en-bloc approach with
make_reduction. This means that instead of using the raw past observations of
y across the window length, suitable features will be generated directly from
the past raw observations. Currently only supports WindowSummarizer (or a list
of WindowSummarizers) to generate features e.g. the mean of the past 7
observations.
pooling: str {"local", "global"}, optional
Specifies whether separate models will be fit at the level of each instance
(local) of if you wish to fit a single model to all instances ("global").
scitype : str {"tabular-regressor", "time-series-regressor"}, optional
Scitype of estimator to use with transformed data.
- If "tabular-regressor", returns X as tabular 2d array
- If "time-series-regressor", returns X as panel 3d array
windows_identical: bool, (default = True)
Direct forecasting only.
Specifies whether all direct models use the same number of observations
(True: Total observations + 1 - window_length - maximum forecasting horizon)
or a different number of observations (False: Total observations + 1
- window_length - forecasting horizon).
Returns
-------
yt : np.ndarray, shape = (n_timepoints - window_length, 1)
Transformed target variable.
Xt : np.ndarray, shape = (n_timepoints - window_length, n_variables,
window_length)
Transformed lagged values of target variable and exogenous variables,
excluding contemporaneous values.
"""
# There are different ways to implement this transform. Pre-allocating an
# array and filling it by iterating over the window length seems to be the most
# efficient one.
ts_index = get_time_index(y)
n_timepoints = ts_index.shape[0]
window_length = check_window_length(window_length, n_timepoints)
if pooling == "global":
if len(transformers) == 1:
tf_fit = transformers[0].fit(y)
else:
feat = [("trafo_" + str(index), i) for index, i in enumerate(transformers)]
tf_fit = FeatureUnion(feat).fit(y)
X_from_y = tf_fit.transform(y)
X_from_y_cut = _cut_df(X_from_y, n_obs=n_timepoints - window_length)
yt = _cut_df(y, n_obs=n_timepoints - window_length)
if X is not None:
X_cut = _cut_df(X, n_obs=n_timepoints - window_length)
Xt = pd.concat([X_from_y_cut, X_cut], axis=1)
else:
Xt = X_from_y_cut
else:
z = _concat_y_X(y, X)
n_timepoints, n_variables = z.shape
fh = _check_fh(fh)
fh_max = fh[-1]
if window_length + fh_max >= n_timepoints:
raise ValueError(
"The `window_length` and `fh` are incompatible with the length of `y`"
)
# Get the effective window length accounting for the forecasting horizon.
effective_window_length = window_length + fh_max
Zt = np.zeros(
(
n_timepoints + effective_window_length,
n_variables,
effective_window_length + 1,
)
)
# Transform data.
for k in range(effective_window_length + 1):
i = effective_window_length - k
j = n_timepoints + effective_window_length - k
Zt[i:j, :, k] = z
# Truncate data, selecting only full windows, discarding incomplete ones.
if windows_identical is True:
Zt = Zt[effective_window_length:-effective_window_length]
else:
Zt = Zt[effective_window_length:-window_length]
# Return transformed feature and target variables separately. This
# excludes contemporaneous values of the exogenous variables. Including them
# would lead to unequal-length data, with more time points for
# exogenous series than the target series, which is currently not supported.
yt = Zt[:, 0, window_length + fh]
Xt = Zt[:, :, :window_length]
# Pre-allocate array for sliding windows.
# If the scitype is tabular regression, we have to convert X into a 2d array.
if scitype == "tabular-regressor":
if transformers is not None:
return yt, Xt
else:
return yt, Xt.reshape(Xt.shape[0], -1)
else:
return yt, Xt
def construct_dispatch(cls, params=None):
"""Construct an estimator with an overspecified parameter dictionary.
Constructs and returns an instance of `cls`, using parameters in a dict `params`.
The dict `params` may contain keys that `cls` does not have, which are ignored.
This is useful in multiplexing or dispatching over multiple `cls` which have
different and potentially intersecting parameter sets.
Parameters
----------
cls : aeon estimator, inheriting from `BaseObject`
params : dict with str keys, optional, default = None = {}
Examples
--------
>>> from aeon.forecasting.compose._reduce import construct_dispatch
>>> from aeon.forecasting.naive import NaiveForecaster
>>> params = {"strategy": "drift", "foo": "bar", "bar": "foo"}
>>> construct_dispatch(NaiveForecaster, params)
NaiveForecaster(strategy='drift')
"""
cls_param_names = cls.get_param_names()
cls_params_in_dict = set(cls_param_names).intersection(params.keys())
params_for_cls = {key: params[key] for key in cls_params_in_dict}
obj = cls(**params_for_cls)
return obj
class _Reducer(_BaseWindowForecaster):
"""Base class for reducing forecasting to regression."""
_tags = {
"ignores-exogeneous-X": False, # reduction uses X in non-trivial way
"capability:missing_values": True,
}
def __init__(
self,
estimator,
window_length=10,
transformers=None,
pooling="local",
):
super().__init__(window_length=window_length)
self.transformers = transformers
self.transformers_ = None
self.estimator = estimator
self.pooling = pooling
self._cv = None
# it seems that the sklearn tags are not fully reliable
# see discussion in PR #3405 and issue #3402
# therefore this is commented out until aeon and sklearn are better aligned
# self.set_tags(
# **{"capability:missing_values": estimator._get_tags()["allow_nan"]}
# )
def _is_predictable(self, last_window):
"""Check if we can make predictions from last window."""
return (
len(last_window) == self.window_length_
and np.sum(np.isnan(last_window)) == 0
and np.sum(np.isinf(last_window)) == 0
)
def _predict_in_sample(self, fh, X=None, return_pred_int=False, alpha=None):
# Note that we currently only support out-of-sample predictions. For the
# direct and multioutput strategy, we need to check this already during fit,
# as the fh is required for fitting.
raise NotImplementedError(
f"Generating in-sample predictions is not yet "
f"implemented for {self.__class__.__name__}."
)
@classmethod
def get_test_params(cls, parameter_set="default"):
"""Return testing parameter settings for the estimator.
Parameters
----------
parameter_set : str, default="default"
Name of the set of test parameters to return, for use in tests. If no
special parameters are defined for a value, will return `"default"` set.
Returns
-------
params : dict or list of dict, default = {}
Parameters to create testing instances of the class
Each dict are parameters to construct an "interesting" test instance, i.e.,
`MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
`create_test_instance` uses the first (or only) dictionary in `params`
"""
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from aeon.transformations.collection.reduce import Tabularizer
# naming convention is as follows:
# reducers with Tabular take an sklearn estimator, e.g., LinearRegressor
# reducers with TimeSeries take an aeon supervised estimator
# e.g., pipeline of Tabularizer and Linear Regression
# which of these is the case, we check by checking substring in the class name
est = LinearRegression()
if "TimeSeries" in cls.__name__:
est = make_pipeline(Tabularizer(), est)
params = {"estimator": est, "window_length": 3}
return params
def _get_shifted_window(self, shift=0, y_update=None, X_update=None):
"""Get the start and end points of a shifted window.
In recursive forecasting, the time based features need to be recalculated for
every time step that is forecast. This is done in an iterative fashion over
every forecasting horizon step. Shift specifies the timestemp over which the
iteration is done, i.e. a shift of 0 will get a window between window_length
steps in the past and t=0, shift = 1 will be window_length - 1 steps in the past
and t= 1 etc- up to the forecasting horizon.
Will also apply any transformers passed to the recursive reducer to y. This en
bloc approach of directly applying the transformers is more efficient than
creating all lags first across the window and then applying the transformers
to the lagged data.
Please see below a graphical representation of the logic using the following
symbols:
``z`` = first observation to forecast.
Not part of the window.
``*`` = (other) time stamps in the window which is summarized
``x`` = observations, past or future, not part of the window
For`window_length = 7` and `fh = [3]` we get the following windows
`shift = 0`
|----------------------------|
| x x x x * * * * * * * z x x|
|----------------------------|
`shift = 1`
|----------------------------|
| x x x x x * * * * * * * z x|
|----------------------------|
`shift = 2`
|----------------------------|
| x x x x x x * * * * * * * z|
|----------------------------|
Parameters
----------
shift: int, default=0
this will be correspond to the shift of the window_length into the future
y_update : a pandas Series or Dataframe
y values that were obtained in the recursive fashion.
X_update : a pandas Series or Dataframe
X values also need to be cut based on the into windows, see above.
Returns
-------
y, X: A pandas dataframe or series
contains the y and X data prepared for the respective windows, see above.
"""
if hasattr(self._timepoints, "freq"):
if self._timepoints.freq is None:
freq_inferred = pd.infer_freq(self._timepoints)
cutoff_with_freq = self._cutoff
cutoff_with_freq.freq = freq_inferred
else:
cutoff_with_freq = self._cutoff
else:
cutoff_with_freq = self._cutoff
cutoff = _shift(cutoff_with_freq, by=shift, return_index=True)
relative_int = pd.Index(list(map(int, range(-self.window_length_ + 1, 2))))
# relative _int will give the integer indices of the window. Also contains the
# first observation after the window (this is what the window is summarized to).
index_range = _index_range(relative_int, cutoff)
# index_range will convert the indices to the date format of cutoff
y_raw = _create_fcst_df(index_range, self._y)
# y_raw is a dataframe window_length forecasting steps into the past in order to
# calculate the new X from y features based on the transformer provided
y_raw.update(self._y)
# Historical values are passed here for all time steps of y_raw that lie in
# the past .
if y_update is not None:
y_raw.update(y_update)
# The y_raw dataframe will is updated with recursively forecast values.
if len(self.transformers_) == 1:
X_from_y = self.transformers_[0].fit_transform(y_raw)
else:
ref = self.transformers_
feat = [("trafo_" + str(index), i) for index, i in enumerate(ref)]
X_from_y = FeatureUnion(feat).fit_transform(y_raw)
# After filling the empty y_raw frame with historic / forecast values
# X from y features can be calculated based on the passed transformer.
X_from_y_cut = _cut_df(X_from_y)
# We are only interested in the last observation, since only that one
# contains the value the window is summarized to.
if self._X is not None:
X = _create_fcst_df([index_range[-1]], self._X)
X.update(self._X)
if X_update is not None:
X.update(X_update)
X_cut = _cut_df(X)
X = pd.concat([X_from_y_cut, X_cut], axis=1)
# X_from_y_cut is added to X dataframe (no features need to be calculated).
else:
X = X_from_y_cut
y = _cut_df(y_raw)
return y, X
class _DirectReducer(_Reducer):
strategy = "direct"
_tags = {
"requires-fh-in-fit": True, # is the forecasting horizon required in fit?
}
def __init__(
self,
estimator,
window_length=10,
transformers=None,
pooling="local",
windows_identical=True,
):
self.windows_identical = windows_identical
super().__init__(
estimator=estimator,
window_length=window_length,
transformers=transformers,
pooling=pooling,
)
def _transform(self, y, X=None):
fh = self.fh.to_relative(self.cutoff)
return _sliding_window_transform(
y,
window_length=self.window_length_,
fh=fh,
X=X,
transformers=self.transformers_,
scitype=self._estimator_scitype,
pooling=self.pooling,
windows_identical=self.windows_identical,
)
def _fit(self, y, X=None, fh=None):
"""Fit to training data.
Parameters
----------
y : pd.Series
Target time series to which to fit the forecaster.
X : pd.DataFrame, optional (default=None)
Exogenous variables are ignored
fh : int, list or np.array, optional (default=None)
The forecasters horizon with the steps ahead to to predict.
Returns
-------
self : Estimator
An fitted instance of self.
"""
# We currently only support out-of-sample predictions. For the direct
# strategy, we need to check this at the beginning of fit, as the fh is
# required for fitting.
self._timepoints = get_time_index(y)
n_timepoints = len(self._timepoints)
if self.pooling is not None and self.pooling not in ["local", "global"]:
raise ValueError(
"pooling must be one of local, global" + f" but found {self.pooling}"
)
if self.window_length is not None and self.transformers is not None:
raise ValueError(
"Transformers provided, suggesting en-bloc approach"
+ " to derive reduction features. Window length will be"
+ " inferred, please set to None"
)
if self.transformers is not None and self.pooling == "local":
raise ValueError(
"Transformers currently cannot be provided"
+ "for models that run locally"
)
pd_format = isinstance(y, pd.Series) or isinstance(y, pd.DataFrame)
if self.pooling == "local":
if pd_format is True and isinstance(y, pd.MultiIndex):
warn(
"Pooling has been changed by default to 'local', which"
+ " means that separate models will be fit at the level of"
+ " each instance. If you wish to fit a single model to"
+ " all instances, please specify pooling = 'global'.",
DeprecationWarning,
)
self.window_length_ = check_window_length(
self.window_length, n_timepoints=len(y)
)
if self.transformers is not None:
self.transformers_ = clone(self.transformers)
if self.transformers is None and self.pooling == "global":
kwargs = {
"lag_feature": {
"lag": list(range(1, self.window_length + 1)),
}
}
self.transformers_ = [WindowSummarizer(**kwargs, n_jobs=1)]
if self.window_length is None:
trafo = self.transformers_
fit_trafo = [i.fit(y) for i in trafo]
ts = [i.truncate_start for i in fit_trafo if hasattr(i, "truncate_start")]
if len(ts) > 0:
self.window_length_ = max(ts)
else:
raise ValueError(
"Reduce must either have window length as argument"
+ "or needs to have it passed by transformer via"
+ "truncate_start"
)
if self.transformers_ is not None and n_timepoints < max(ts):
raise ValueError(
"Not sufficient observations to calculate transformations"
+ "Please reduce window length / window lagging to match"
+ "observation size"
)
if not self.fh.is_all_out_of_sample(self.cutoff):
raise NotImplementedError("In-sample predictions are not implemented.")
yt, Xt = self._transform(y, X)
# Iterate over forecasting horizon, fitting a separate estimator for each step.
self.estimators_ = []
for i in range(len(self.fh)):
fh_rel = fh.to_relative(self.cutoff)
estimator = clone(self.estimator)
if self.transformers_ is not None:
fh_rel = fh.to_relative(self.cutoff)
yt = _cut_df(yt, n_timepoints - fh_rel[i] + 1)
Xt = _cut_df(Xt, n_timepoints - fh_rel[i] + 1, type="head")
estimator.fit(Xt, yt)
else:
if self.windows_identical is True:
estimator.fit(Xt, yt[:, i])
else:
if (fh_rel[i] - 1) == 0:
estimator.fit(Xt, yt[:, i])
else:
estimator.fit(Xt[: -(fh_rel[i] - 1)], yt[: -(fh_rel[i] - 1), i])
self.estimators_.append(estimator)
return self
def _predict_last_window(
self, fh, X=None, return_pred_int=False, alpha=DEFAULT_ALPHA
):
""".
In recursive reduction, iteration must be done over the
entire forecasting horizon. Specifically, when transformers are
applied to y that generate features in X, forecasting must be done step by
step to integrate the latest prediction of for the new set of features in
X derived from that y.
Parameters
----------
fh : int, list, np.array or ForecastingHorizon
Forecasting horizon
X : pd.DataFrame, optional (default=None)
Exogenous time series
return_pred_int : bool
alpha : float or array-like
Returns
-------
y_return = pd.Series or pd.DataFrame
"""
if self._X is not None and X is None:
raise ValueError(
"`X` must be passed to `predict` if `X` is given in `fit`."
)
if self.pooling == "global":
y_last, X_last = self._get_shifted_window(X_update=X)
ys = np.array(y_last)
if not np.sum(np.isnan(ys)) == 0 and np.sum(np.isinf(ys)) == 0:
return self._predict_nan(fh)
else:
y_last, X_last = self._get_last_window()
if not self._is_predictable(y_last):
return self._predict_nan(fh)
# Get last window of available data.
# If we cannot generate a prediction from the available data, return nan.
if self.pooling == "global":
fh_abs = fh.to_absolute(self.cutoff).to_pandas()
y_pred = _create_fcst_df(fh_abs, self._y)
for i, estimator in enumerate(self.estimators_):
y_pred_short = estimator.predict(X_last)
y_pred_curr = _create_fcst_df([fh_abs[i]], self._y, fill=y_pred_short)
y_pred.update(y_pred_curr)
else:
# Pre-allocate arrays.
if self._X is None:
n_columns = 1
else:
# X is ignored here, since we currently only look at lagged values for
# exogenous variables and not contemporaneous ones.
n_columns = self._X.shape[1] + 1
# Pre-allocate arrays.
window_length = self.window_length_
X_pred = np.zeros((1, n_columns, window_length))
# Fill pre-allocated arrays with available data.
X_pred[:, 0, :] = y_last
if self._X is not None:
X_pred[:, 1:, :] = X_last.T
# We need to make sure that X has the same order as used in fit.
if self._estimator_scitype == "tabular-regressor":
X_pred = X_pred.reshape(1, -1)
# Allocate array for predictions.
y_pred = np.zeros(len(fh))
# Iterate over estimators/forecast horizon
for i, estimator in enumerate(self.estimators_):
y_pred[i] = estimator.predict(X_pred)
return y_pred
class _MultioutputReducer(_Reducer):
strategy = "multioutput"
_tags = {
"requires-fh-in-fit": True, # is the forecasting horizon required in fit?
}
def _transform(self, y, X=None):
fh = self.fh.to_relative(self.cutoff)
return _sliding_window_transform(
y,
window_length=self.window_length,
fh=fh,
X=X,
scitype=self._estimator_scitype,
)
def _fit(self, y, X=None, fh=None):
"""Fit to training data.
Parameters
----------
y : pd.Series
Target time series to which to fit the forecaster.
X : pd.DataFrame, optional (default=None)
Exogenous variables are ignored
fh : int, list or np.array, optional (default=None)
The forecasters horizon with the steps ahead to to predict.
Returns
-------
self : returns an instance of self.
"""
# We currently only support out-of-sample predictions. For the direct
# strategy, we need to check this at the beginning of fit, as the fh is
# required for fitting.
if not self.fh.is_all_out_of_sample(self.cutoff):
raise NotImplementedError("In-sample predictions are not implemented.")
self.window_length_ = check_window_length(
self.window_length, n_timepoints=len(y)
)
yt, Xt = self._transform(y, X)
# Fit a multi-output estimator to the transformed data.
self.estimator_ = clone(self.estimator)
self.estimator_.fit(Xt, yt)
return self
def _predict_last_window(
self, fh, X=None, return_pred_int=False, alpha=DEFAULT_ALPHA
):
"""Predict to training data.
Parameters
----------
fh : int, list, np.array or ForecastingHorizon
Forecasting horizon
X : pd.DataFrame, optional (default=None)
Exogenous time series
return_pred_int : bool
alpha : float or array-like
Returns
-------
y_pred = pd.Series or pd.DataFrame
"""
# Get last window of available data.
y_last, X_last = self._get_last_window()
# If we cannot generate a prediction from the available data, return nan.
if not self._is_predictable(y_last):
return self._predict_nan(fh)
if self._X is None:
n_columns = 1
else:
# X is ignored here, since we currently only look at lagged values for
# exogenous variables and not contemporaneous ones.
n_columns = self._X.shape[1] + 1
# Pre-allocate arrays.
window_length = self.window_length_
X_pred = np.zeros((1, n_columns, window_length))
# Fill pre-allocated arrays with available data.
X_pred[:, 0, :] = y_last
if self._X is not None:
X_pred[:, 1:, :] = X_last.T
# We need to make sure that X has the same order as used in fit.
if self._estimator_scitype == "tabular-regressor":
X_pred = X_pred.reshape(1, -1)
# Iterate over estimators/forecast horizon
y_pred = self.estimator_.predict(X_pred)
return y_pred.ravel()
class _RecursiveReducer(_Reducer):
strategy = "recursive"
def _transform(self, y, X=None):
# For the recursive strategy, the forecasting horizon for the sliding-window
# transform is simply a one-step ahead horizon, regardless of the horizon
# used during prediction.
fh = ForecastingHorizon([1])
return _sliding_window_transform(
y,
self.window_length_,
fh,
X=X,
transformers=self.transformers_,
scitype=self._estimator_scitype,
pooling=self.pooling,
)
def _fit(self, y, X=None, fh=None):
"""Fit to training data.
Parameters
----------
y : pd.Series
Target time series to which to fit the forecaster.
X : pd.DataFrame, optional (default=None)
Exogenous variables are ignored
fh : int, list or np.array, optional (default=None)
The forecasters horizon with the steps ahead to to predict.
Returns
-------
self : returns an instance of self.
"""
if self.pooling is not None and self.pooling not in ["local", "global"]:
raise ValueError(
"pooling must be one of local, global" + f" but found {self.pooling}"
)
if self.window_length is not None and self.transformers is not None:
raise ValueError(
"Transformers provided, suggesting en-bloc approach"
+ " to derive reduction features. Window length will be"
+ " inferred, please set to None"
)
if self.transformers is not None and self.pooling == "local":
raise ValueError(
"Transformers currently cannot be provided"
+ "for models that run locally"
)
pd_format = isinstance(y, pd.Series) or isinstance(y, pd.DataFrame)
self._timepoints = get_time_index(y)
n_timepoints = len(self._timepoints)
self.window_length_ = check_window_length(
self.window_length, n_timepoints=n_timepoints
)
if self.pooling == "local":
if pd_format is True and isinstance(y, pd.MultiIndex):
warn(
"Pooling has been changed by default to 'local', which"
+ " means that separate models will be fit at the level of"
+ " each instance. If you wish to fit a single model to"
+ " all instances, please specify pooling = 'global'.",
DeprecationWarning,
)
if self.transformers is not None:
self.transformers_ = clone(self.transformers)
if self.transformers is None and self.pooling == "global":
kwargs = {
"lag_feature": {
"lag": list(range(1, self.window_length + 1)),
}
}
self.transformers_ = [WindowSummarizer(**kwargs, n_jobs=1)]
if self.window_length is None:
trafo = self.transformers_
fit_trafo = [i.fit(y) for i in trafo]
ts = [i.truncate_start for i in fit_trafo if hasattr(i, "truncate_start")]
if len(ts) > 0:
self.window_length_ = max(ts)
else:
raise ValueError(
"Reduce must either have window length as argument"
+ "or needs to have it passed by transformer via"
+ "truncate_start"
)
if self.transformers_ is not None and n_timepoints < max(ts):
raise ValueError(
"Not sufficient observations to calculate transformations"
+ "Please reduce window length / window lagging to match"
+ "observation size"
)
yt, Xt = self._transform(y, X)
# Make sure yt is 1d array to avoid DataConversion warning from scikit-learn.
if self.transformers_ is not None:
yt = yt.to_numpy().ravel()
else:
yt = yt.ravel()
self.estimator_ = clone(self.estimator)
self.estimator_.fit(Xt, yt)
return self
def _predict_last_window(
self, fh, X=None, return_pred_int=False, alpha=DEFAULT_ALPHA
):
""".
In recursive reduction, iteration must be done over the
entire forecasting horizon. Specifically, when transformers are
applied to y that generate features in X, forecasting must be done step by
step to integrate the latest prediction of for the new set of features in
X derived from that y.
Parameters
----------
fh : int, list, np.array or ForecastingHorizon
Forecasting horizon
X : pd.DataFrame, optional (default=None)
Exogenous time series
return_pred_int : bool
alpha : float or array-like
Returns
-------
y_return = pd.Series or pd.DataFrame
"""
if self._X is not None and X is None:
raise ValueError(
"`X` must be passed to `predict` if `X` is given in `fit`."
)
# Get last window of available data.
# If we cannot generate a prediction from the available data, return nan.
if self.pooling == "global":
y_last, X_last = self._get_shifted_window(X_update=X)
ys = np.array(y_last)
if not np.sum(np.isnan(ys)) == 0 and np.sum(np.isinf(ys)) == 0:
return self._predict_nan(fh)
else:
y_last, X_last = self._get_last_window()
if not self._is_predictable(y_last):
return self._predict_nan(fh)
if self.pooling == "global":
fh_max = fh.to_relative(self.cutoff)[-1]
relative = pd.Index(list(map(int, range(1, fh_max + 1))))
index_range = _index_range(relative, self.cutoff)
y_pred = _create_fcst_df(index_range, self._y)
for i in range(fh_max):
# Generate predictions.
y_pred_vector = self.estimator_.predict(X_last)
y_pred_curr = _create_fcst_df(
[index_range[i]], self._y, fill=y_pred_vector
)
y_pred.update(y_pred_curr)
# # Update last window with previous prediction.
if i + 1 != fh_max:
y_last, X_last = self._get_shifted_window(
y_update=y_pred, X_update=X, shift=i + 1
)
else:
# Pre-allocate arrays.
if X is None:
n_columns = 1
else:
n_columns = X.shape[1] + 1
window_length = self.window_length_
fh_max = fh.to_relative(self.cutoff)[-1]
y_pred = np.zeros(fh_max)
last = np.zeros((1, n_columns, window_length + fh_max))
# Fill pre-allocated arrays with available data.
last[:, 0, :window_length] = y_last
if X is not None:
last[:, 1:, :window_length] = X_last.T
last[:, 1:, window_length:] = X.iloc[
-(last.shape[2] - window_length) :, :
].T
# Recursively generate predictions by iterating over forecasting horizon.
for i in range(fh_max):
# Slice prediction window.
X_pred = last[:, :, i : window_length + i]
# Reshape data into tabular array.
if self._estimator_scitype == "tabular-regressor":
X_pred = X_pred.reshape(1, -1)
# Generate predictions.
y_pred[i] = self.estimator_.predict(X_pred)
# Update last window with previous prediction.
last[:, 0, window_length + i] = y_pred[i]
# While the recursive strategy requires to generate predictions for all steps
# until the furthest step in the forecasting horizon, we only return the
# requested ones.
fh_idx = fh.to_indexer(self.cutoff)
if isinstance(self._y.index, pd.MultiIndex):
yi_grp = self._y.index.names[0:-1]
y_return = y_pred.groupby(yi_grp, as_index=False).nth(fh_idx.to_list())
elif isinstance(y_pred, pd.Series) or isinstance(y_pred, pd.DataFrame):
y_return = y_pred.iloc[fh_idx]
if hasattr(y_return.index, "freq"):
if y_return.index.freq != y_pred.index.freq:
y_return.index.freq = None
else:
y_return = y_pred[fh_idx]
return y_return
class _DirRecReducer(_Reducer):
strategy = "dirrec"
_tags = {
"requires-fh-in-fit": True, # is the forecasting horizon required in fit?
"ignores-exogeneous-X": True,
}
def _transform(self, y, X=None):
# Note that the transform for dirrec is the same as in the direct
# strategy.
fh = self.fh.to_relative(self.cutoff)
return _sliding_window_transform(
y,
window_length=self.window_length,
fh=fh,
X=X,
scitype=self._estimator_scitype,
)
def _fit(self, y, X=None, fh=None):
"""Fit to training data.
Parameters
----------
y : pd.Series
Target time series to which to fit the forecaster.
X : pd.DataFrame, optional (default=None)
Exogenous variables are ignored
fh : int, list or np.array, optional (default=None)
The forecasters horizon with the steps ahead to to predict.
Returns