-
Notifications
You must be signed in to change notification settings - Fork 89
/
_split.py
1440 lines (1217 loc) · 51.9 KB
/
_split.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
#!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
# copyright: aeon developers, BSD-3-Clause License (see LICENSE file)
"""Implement dataset splitting for model evaluation and selection."""
__all__ = [
"ExpandingWindowSplitter",
"SlidingWindowSplitter",
"CutoffSplitter",
"SingleWindowSplitter",
"temporal_train_test_split",
]
__author__ = ["mloning", "kkoralturk", "khrapovs", "chillerobscuro"]
from typing import Iterator, Optional, Tuple, Union
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split as _train_test_split
from aeon.base import BaseObject
from aeon.datatypes import check_is_scitype, convert_to
from aeon.datatypes._utilities import get_index_for_series, get_time_index, get_window
from aeon.forecasting.base import ForecastingHorizon
from aeon.forecasting.base._fh import VALID_FORECASTING_HORIZON_TYPES
from aeon.utils.validation import (
ACCEPTED_WINDOW_LENGTH_TYPES,
NON_FLOAT_WINDOW_LENGTH_TYPES,
all_inputs_are_iloc_like,
all_inputs_are_time_like,
array_is_datetime64,
array_is_int,
check_window_length,
is_datetime,
is_int,
is_timedelta,
is_timedelta_or_date_offset,
)
from aeon.utils.validation.forecasting import (
VALID_CUTOFF_TYPES,
check_cutoffs,
check_fh,
check_step_length,
)
from aeon.utils.validation.series import check_equal_time_index
DEFAULT_STEP_LENGTH = 1
DEFAULT_WINDOW_LENGTH = 10
DEFAULT_FH = 1
ACCEPTED_Y_TYPES = Union[pd.Series, pd.DataFrame, np.ndarray, pd.Index]
FORECASTING_HORIZON_TYPES = Union[
Union[VALID_FORECASTING_HORIZON_TYPES], ForecastingHorizon
]
SPLIT_TYPE = Union[
Tuple[pd.Series, pd.Series], Tuple[pd.Series, pd.Series, pd.DataFrame, pd.DataFrame]
]
SPLIT_ARRAY_TYPE = Tuple[np.ndarray, np.ndarray]
SPLIT_GENERATOR_TYPE = Iterator[SPLIT_ARRAY_TYPE]
PANDAS_MTYPES = ["pd.DataFrame", "pd.Series", "pd-multiindex", "pd_multiindex_hier"]
def _check_fh(fh: VALID_FORECASTING_HORIZON_TYPES) -> ForecastingHorizon:
"""Check and convert fh to format expected by CV splitters."""
return check_fh(fh, enforce_relative=True)
def _get_end(y_index: pd.Index, fh: ForecastingHorizon) -> int:
"""Compute the end of the last training window for a forecasting horizon.
For a time series index `y_index`, `y_index[end]` will give
the index of the training window.
Correspondingly, for a time series `y` with index `y_index`,
`y.iloc[end]` or `y.loc[y_index[end]]`
will provide the last index of the training window.
Parameters
----------
y_index : pd.Index
Index of time series
fh : int, timedelta, list or np.ndarray of ints or timedeltas
Returns
-------
end : int
0-indexed integer end of the training window
"""
# `fh` is assumed to be ordered and checked by `_check_fh` and `window_length` by
# `check_window_length`.
n_timepoints = y_index.shape[0]
assert isinstance(y_index, pd.Index)
# For purely in-sample forecasting horizons, the last split point is the end of the
# training data.
# Otherwise, the last point must ensure that the last horizon is within the data.
null = 0 if array_is_int(fh) else pd.Timedelta(0)
fh_offset = null if fh.is_all_in_sample() else fh[-1]
if array_is_int(fh):
return n_timepoints - fh_offset - 1
return y_index.get_loc(y_index[-1] - fh_offset)
def _check_window_lengths(
y: pd.Index,
fh: ForecastingHorizon,
window_length: NON_FLOAT_WINDOW_LENGTH_TYPES,
initial_window: NON_FLOAT_WINDOW_LENGTH_TYPES,
) -> None:
"""Check that combination of inputs is compatible.
Parameters
----------
y : pd.Index
Index of time series
fh : int, timedelta, list or np.ndarray of ints or timedeltas
window_length : int or timedelta or pd.DateOffset
initial_window : int or timedelta or pd.DateOffset
Window length of first window
Raises
------
ValueError
if window length plus max horizon is above the last observation in `y`,
or if initial window plus max horizon is above the last observation in `y`
TypeError
if type of the input is not supported
"""
n_timepoints = y.shape[0]
fh_max = fh[-1]
error_msg_for_incompatible_window_length = (
f"The `window_length` and the forecasting horizon are incompatible "
f"with the length of `y`. Found `window_length`={window_length}, "
f"`max(fh)`={fh_max}, but len(y)={n_timepoints}. "
f"It is required that the window length plus maximum forecast horizon "
f"is smaller than the length of the time series `y` itself."
)
if is_timedelta_or_date_offset(x=window_length):
if y[0] + window_length + fh_max > y[-1]:
raise ValueError(error_msg_for_incompatible_window_length)
else:
if window_length + fh_max > n_timepoints:
raise ValueError(error_msg_for_incompatible_window_length)
error_msg_for_incompatible_initial_window = (
f"The `initial_window` and the forecasting horizon are incompatible "
f"with the length of `y`. Found `initial_window`={initial_window}, "
f"`max(fh)`={fh_max}, but len(y)={n_timepoints}. "
f"It is required that the initial window plus maximum forecast horizon "
f"is smaller than the length of the time series `y` itself."
)
error_msg_for_incompatible_types = (
"The `initial_window` and `window_length` types are incompatible. "
"They should be either all timedelta or all int."
)
if initial_window is not None:
if is_timedelta_or_date_offset(x=initial_window):
if y[0] + initial_window + fh_max > y[-1]:
raise ValueError(error_msg_for_incompatible_initial_window)
if not is_timedelta_or_date_offset(x=window_length):
raise TypeError(error_msg_for_incompatible_types)
else:
if initial_window + fh_max > n_timepoints:
raise ValueError(error_msg_for_incompatible_initial_window)
if is_timedelta_or_date_offset(x=window_length):
raise TypeError(error_msg_for_incompatible_types)
def _inputs_are_supported(args: list) -> bool:
"""Check that combination of inputs is supported.
Currently, only two cases are allowed:
either all inputs are iloc-friendly, or they are all time-like
Parameters
----------
args : list of inputs to check
Returns
-------
True if all inputs are compatible, False otherwise
"""
return all_inputs_are_iloc_like(args) or all_inputs_are_time_like(args)
def _check_inputs_for_compatibility(args: list) -> None:
"""Check that combination of inputs is supported.
Currently, only two cases are allowed:
either all inputs are iloc-friendly, or they are time-like
Parameters
----------
args : list of inputs
Raises
------
TypeError
if combination of inputs is not supported
"""
if not _inputs_are_supported(args):
raise TypeError("Unsupported combination of types")
def _check_cutoffs_and_y(cutoffs: VALID_CUTOFF_TYPES, y: ACCEPTED_Y_TYPES) -> None:
"""Check that combination of inputs is compatible.
Parameters
----------
cutoffs : np.array or pd.Index
cutoff points, positive and integer- or datetime-index like
y : pd.Series, pd.DataFrame, np.ndarray, or pd.Index
coerced and checked version of input y
Raises
------
ValueError
if max cutoff is above the last observation in `y`
TypeError
if `cutoffs` type is not supported
"""
max_cutoff = np.max(cutoffs)
msg = (
"`cutoffs` are incompatible with given `y`. "
"Maximum cutoff is not smaller than the "
)
if array_is_int(cutoffs):
if max_cutoff >= y.shape[0]:
raise ValueError(msg + "number of observations.")
elif array_is_datetime64(cutoffs):
if max_cutoff >= np.max(y):
raise ValueError(msg + "maximum index value of `y`.")
else:
raise TypeError("Unsupported type of `cutoffs`")
def _check_cutoffs_fh_y(
cutoffs: VALID_CUTOFF_TYPES, fh: FORECASTING_HORIZON_TYPES, y: pd.Index
) -> None:
"""Check that combination of inputs is compatible.
Currently, only two cases are allowed:
either both `cutoffs` and `fh` are integers, or they are datetime or timedelta.
Parameters
----------
cutoffs : np.array or pd.Index
Cutoff points, positive and integer- or datetime-index like.
Type should match the type of `fh` input.
fh : int, timedelta, list or np.ndarray of ints or timedeltas
Type should match the type of `cutoffs` input.
y : pd.Index
Index of time series
Raises
------
ValueError
if max cutoff plus max `fh` is above the last observation in `y`
TypeError
if `cutoffs` and `fh` type combination is not supported
"""
max_cutoff = np.max(cutoffs)
max_fh = fh.max()
msg = "`fh` is incompatible with given `cutoffs` and `y`."
if is_int(x=max_cutoff) and is_int(x=max_fh):
if max_cutoff + max_fh > y.shape[0]:
raise ValueError(msg)
elif is_datetime(x=max_cutoff) and is_timedelta(x=max_fh):
if max_cutoff + max_fh > y.max():
raise ValueError(msg)
else:
raise TypeError("Unsupported type of `cutoffs` and `fh`")
class BaseSplitter(BaseObject):
r"""Base class for temporal cross-validation splitters.
The purpose of this implementation is to fill the gap relative to
`sklearn.model_selection.TimeSeriesSplit
<https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.TimeSeriesSplit.html>`__
which implements only expanding window split strategy, and only integer based.
The most important method in this class is `.split(y)` which generates indices
of non-overlapping train/test splits of a time series `y`.
The length of the train split is determined by `window_length`.
The length of the test split is determined by forecasting horizon `fh`.
In general, splitting a time series :math:`y=(y_1,\ldots,y_T)`
into train/test splits means separating it into two non-overlapping series:
train :math:`(y_{t(1)},\ldots,y_{t(k)})`
and test :math:`(y_{t(k+1)},\ldots,y_{t(k+l)})`,
where :math:`k,l` are all integers greater than zero,
and :math:`t(k)<t(k+1)` are ordered time indices.
The exact set of indices depends on a concrete splitter.
Method `.split` is used to generate a pair of index sets:
train :math:`(t(1),\ldots,t(k))` and test :math:`(t(k+1),\ldots,t(k+l))`.
In case `window_length` and `fh` are integer valued,
they translate into :math:`k` and :math:`l`, respectively.
In case `window_length` and `fh` can be interpreted
as time interval length (time deltas), then they correspond to
:math:`t(k)-t(1)` and :math:`t(k+l)-t(k+1)`, respectively.
Method `.get_n_splits` returns the number of splitting iterations.
This number depends on a concrete splitting strategy and splitter parameters.
Method `.get_cutoffs` returns the cutoff points between each train/test split.
Using the above notation, for a single split it corresponds
to the last integer index of the training window, :math:`k`
In order to illustrate the difference in integer/interval arithmetic
in calculating train/test indices, let us consider the following examples.
Suppose, the arguments of a splitter are `cutoff = 10` and `window_length = 6`.
Then, we have `train_start = cutoff - window_length = 4`.
For timedelta-like values the logic is a bit more complicated.
The time point corresponding to the `cutoff`
(index value of the `y` series) is shifted back
by the timedelta `window_length`,
and then the integer position of the resulting datetime
is considered to be the training window start.
For example, for `cutoff = 10`, and `window_length = pd.Timedelta(6, unit="D")`,
we have `y[cutoff] = pd.Timestamp("2021-01-10")`,
and `y[cutoff] - window_length = pd.Timestamp("2021-01-04")`,
which leads to `train_start = y.loc(y[cutoff] - window_length) = 4`.
Similar timedelta arithmetic applies to other splitter arguments.
Parameters
----------
window_length : int or timedelta or pd.DateOffset
Length of rolling window
fh : array-like or int, optional, (default=None)
Single step ahead or array of steps ahead to forecast.
"""
def __init__(
self,
fh: FORECASTING_HORIZON_TYPES = DEFAULT_FH,
window_length: NON_FLOAT_WINDOW_LENGTH_TYPES = DEFAULT_WINDOW_LENGTH,
) -> None:
self.window_length = window_length
self.fh = fh
super(BaseSplitter, self).__init__()
def split(self, y: ACCEPTED_Y_TYPES) -> SPLIT_GENERATOR_TYPE:
"""Get iloc references to train/test splits of `y`.
Parameters
----------
y : pd.Index or time series in aeon compatible time series format,
time series can be in any Series, Panel, or Hierarchical mtype format
Index of time series to split, or time series to split
If time series, considered as index of equivalent pandas type container:
pd.DataFrame, pd.Series, pd-multiindex, or pd_multiindex_hier mtype
Yields
------
train : 1D np.ndarray of dtype int
Training window indices, iloc references to training indices in y
test : 1D np.ndarray of dtype int
Test window indices, iloc references to test indices in y
"""
y_index = self._coerce_to_index(y)
if not isinstance(y_index, pd.MultiIndex):
split = self._split
else:
split = self._split_vectorized
for train, test in split(y_index):
yield train[train >= 0], test[test >= 0]
def _split(self, y: pd.Index) -> SPLIT_GENERATOR_TYPE:
"""Get iloc references to train/test splits of `y`.
private _split containing the core logic, called from split
Parameters
----------
y : pd.Index or time series in aeon compatible time series format
Time series to split, or index of time series to split
Yields
------
train : 1D np.ndarray of dtype int
Training window indices, iloc references to training indices in y
test : 1D np.ndarray of dtype int
Test window indices, iloc references to test indices in y
"""
raise NotImplementedError("abstract method")
def _split_vectorized(self, y: pd.MultiIndex) -> SPLIT_GENERATOR_TYPE:
"""Get iloc references to train/test splits of `y`, for pd.MultiIndex.
This applies _split per time series instance in the multiindex.
Instances in this context are defined by levels except last level.
Parameters
----------
y : pd.MultiIndex, with last level time-like
as used in pd_multiindex and pd_multiindex_hier aeon mtypes
Yields
------
train : 1D np.ndarray of dtype int
Training window indices, iloc references to training indices in y
test : 1D np.ndarray of dtype int
Test window indices, iloc references to test indices in y
"""
srs = pd.DataFrame(index=y).reset_index(-1).iloc[:, 0]
index = srs.index
anchors = pd.Series(range(len(srs)), index).groupby(index).first().tolist()
splits = (self._split(pd.Index(inst.values)) for _, inst in srs.groupby(index))
train = []
test = []
for split_inst, anchor in zip(splits, anchors):
train_inst, test_inst = zip(*split_inst)
train.append(tuple(indices + anchor for indices in train_inst))
test.append(tuple(indices + anchor for indices in test_inst))
train = map(np.concatenate, zip(*train))
test = map(np.concatenate, zip(*test))
yield from zip(train, test)
def split_loc(self, y: ACCEPTED_Y_TYPES) -> Iterator[Tuple[pd.Index, pd.Index]]:
"""Get loc references to train/test splits of `y`.
Parameters
----------
y : pd.Index or time series in aeon compatible time series format,
time series can be in any Series, Panel, or Hierarchical mtype format
Time series to split, or index of time series to split
Yields
------
train : pd.Index
Training window indices, loc references to training indices in y
test : pd.Index
Test window indices, loc references to test indices in y
"""
y_index = self._coerce_to_index(y)
for train, test in self.split(y_index):
yield y_index[train], y_index[test]
def split_series(self, y: ACCEPTED_Y_TYPES) -> Iterator[SPLIT_TYPE]:
"""Split `y` into training and test windows.
Parameters
----------
y : time series in aeon compatible time series format,
time series can be in any Series, Panel, or Hierarchical mtype format
e.g., pd.Series, pd.DataFrame, np.ndarray
Time series to split, or index of time series to split
Yields
------
train : time series of same aeon mtype as `y`
training series in the split
test : time series of same aeon mtype as `y`
test series in the split
"""
y, y_orig_mtype = self._check_y(y)
for train, test in self.split(y.index):
y_train = y.iloc[train]
y_test = y.iloc[test]
y_train = convert_to(y_train, y_orig_mtype)
y_test = convert_to(y_test, y_orig_mtype)
yield y_train, y_test
def _coerce_to_index(self, y: ACCEPTED_Y_TYPES) -> pd.Index:
"""Check and coerce y to pandas index.
Parameters
----------
y : pd.Index or time series in aeon compatible time series format (any)
Index of time series to split, or time series to split
If time series, considered as index of equivalent pandas type container:
pd.DataFrame, pd.Series, pd-multiindex, or pd_multiindex_hier mtype
Returns
-------
y_index : y, if y was pd.Index; otherwise _check_y(y).index
"""
if not isinstance(y, pd.Index):
y, _ = self._check_y(y, allow_index=True)
y_index = y.index
else:
y_index = y
return y_index
def _check_y(self, y, allow_index=False):
"""Check and coerce y to a pandas based mtype.
Parameters
----------
y : pd.Series, pd.DataFrame, or np.ndarray (1D or 2D), optional (default=None)
Time series to check, must conform with one of the aeon type conventions.
Returns
-------
y_inner : time series y coerced to one of the aeon pandas based mtypes:
pd.DataFrame, pd.Series, pd-multiindex, pd_multiindex_hier
returns pd.Series only if y was pd.Series, otherwise a pandas.DataFrame
y_mtype : original mtype of y
Raises
------
TypeError if y is not one of the permissible mtypes
"""
if allow_index and isinstance(y, pd.Index):
return y, "pd.Index"
ALLOWED_SCITYPES = ["Series", "Panel", "Hierarchical"]
ALLOWED_MTYPES = [
"pd.Series",
"pd.DataFrame",
"np.ndarray",
"nested_univ",
"numpy3D",
# "numpyflat",
"pd-multiindex",
# "pd-wide",
# "pd-long",
"df-list",
"pd_multiindex_hier",
]
y_valid, _, y_metadata = check_is_scitype(
y, scitype=ALLOWED_SCITYPES, return_metadata=True, var_name="y"
)
if allow_index:
msg = (
"y must be a pandas.Index, or a time series in an aeon compatible "
"format, of scitype Series, Panel or Hierarchical, "
"for instance a pandas.DataFrame with aeon compatible time indices, "
"or with MultiIndex and last(-1) level an aeon compatible time index."
f" Allowed compatible mtype format specifications are: {ALLOWED_MTYPES}"
"For further details see examples/forecasting, or examples/datasets"
"If you think y is already in an aeon supported input format, "
"run aeon.datatypes.check_raise(y, mtype) to diagnose the error, "
"where mtype is the string of the type specification you want for y. "
)
else:
msg = (
"y must be in an aeon compatible format, "
"of scitype Series, Panel or Hierarchical, "
"for instance a pandas.DataFrame with aeon compatible time indices, "
"or with MultiIndex and last(-1) level an aeon compatible time index."
f" Allowed compatible mtype format specifications are: {ALLOWED_MTYPES}"
"See examples/forecasting, or examples/datasets, "
"If you think y is already in an aeon supported input format, "
"run aeon.datatypes.check_raise(y, mtype) to diagnose the error, "
"where mtype is the string of the type specification you want for y. "
)
if not y_valid:
raise TypeError(msg)
y_inner = convert_to(y, to_type=PANDAS_MTYPES)
mtype = y_metadata["mtype"]
return y_inner, mtype
def get_n_splits(self, y: Optional[ACCEPTED_Y_TYPES] = None) -> int:
"""Return the number of splits.
Parameters
----------
y : pd.Series or pd.Index, optional (default=None)
Time series to split
Returns
-------
n_splits : int
The number of splits.
"""
raise NotImplementedError("abstract method")
def get_cutoffs(self, y: Optional[ACCEPTED_Y_TYPES] = None) -> np.ndarray:
"""Return the cutoff points in .iloc[] context.
Parameters
----------
y : pd.Series or pd.Index, optional (default=None)
Time series to split
Returns
-------
cutoffs : 1D np.ndarray of int
iloc location indices, in reference to y, of cutoff indices
"""
raise NotImplementedError("abstract method")
def get_fh(self) -> ForecastingHorizon:
"""Return the forecasting horizon.
Returns
-------
fh : ForecastingHorizon
The forecasting horizon
"""
return check_fh(self.fh)
@staticmethod
def _get_train_window(
y: pd.Index, train_start: int, split_point: int
) -> np.ndarray:
"""Get train window.
For formal definition of the train window see docstring of the `BaseSplitter`
Parameters
----------
y : pd.Index
Index of time series to split
train_start : int
Integer index of the training window start
split_point : int
Integer index of the train window end
Returns
-------
np.ndarray with integer indices of the train window
"""
if split_point > max(0, train_start):
return np.argwhere(
(y >= y[max(train_start, 0)]) & (y <= y[min(split_point, len(y)) - 1])
).flatten()
return np.array([], dtype=int)
class CutoffSplitter(BaseSplitter):
r"""Cutoff window splitter.
Split time series at given cutoff points into a fixed-length training and test set.
Here the user is expected to provide a set of cutoffs (train set endpoints),
which using the notation provided in :class:`BaseSplitter`,
can be written as :math:`(k_1,\ldots,k_n)` for integer based indexing,
or :math:`(t(k_1),\ldots,t(k_n))` for datetime based indexing.
For a cutoff :math:`k_i` and a `window_length` :math:`w`
the training window is :math:`(k_i-w+1,k_i-w+2,k_i-w+3,\ldots,k_i)`.
Training window's last point is equal to the cutoff.
Test window is defined by forecasting horizons
relative to the end of the training window.
It will contain as many indices
as there are forecasting horizons provided to the `fh` argument.
For a forecasating horizon :math:`(h_1,\ldots,h_H)`, the test window will
consist of the indices :math:`(k_n+h_1,\ldots, k_n+h_H)`.
The number of splits returned by `.get_n_splits`
is then trivially equal to :math:`n`.
The sorted array of cutoffs returned by `.get_cutoffs` is then equal to
:math:(t(k_1),\ldots,t(k_n))` with :math:`k_i<k_{i+1}`.
Parameters
----------
cutoffs : list or np.ndarray or pd.Index
Cutoff points, positive and integer- or datetime-index like.
Type should match the type of `fh` input.
fh : int, timedelta, list or np.ndarray of ints or timedeltas
Type should match the type of `cutoffs` input.
window_length : int or timedelta or pd.DateOffset
Examples
--------
>>> import numpy as np
>>> from aeon.forecasting.model_selection import CutoffSplitter
>>> ts = np.arange(10)
>>> splitter = CutoffSplitter(fh=[2, 4], cutoffs=np.array([3, 5]), window_length=3)
>>> list(splitter.split(ts)) # doctest: +SKIP
[(array([1, 2, 3]), array([5, 7])), (array([3, 4, 5]), array([7, 9]))]
"""
def __init__(
self,
cutoffs: VALID_CUTOFF_TYPES,
fh: FORECASTING_HORIZON_TYPES = DEFAULT_FH,
window_length: ACCEPTED_WINDOW_LENGTH_TYPES = DEFAULT_WINDOW_LENGTH,
) -> None:
_check_inputs_for_compatibility([fh, cutoffs, window_length])
self.cutoffs = cutoffs
super(CutoffSplitter, self).__init__(fh, window_length)
def _split(self, y: pd.Index) -> SPLIT_GENERATOR_TYPE:
n_timepoints = y.shape[0]
cutoffs = check_cutoffs(cutoffs=self.cutoffs)
fh = _check_fh(fh=self.fh)
window_length = check_window_length(
window_length=self.window_length, n_timepoints=n_timepoints
)
if isinstance(y, (pd.DatetimeIndex, pd.PeriodIndex)) and is_int(window_length):
window_length = y.freq * window_length
_check_cutoffs_and_y(cutoffs=cutoffs, y=y)
_check_cutoffs_fh_y(cutoffs=cutoffs, fh=fh, y=y)
for cutoff in cutoffs:
null = 0 if is_int(cutoff) else pd.Timestamp(0)
if cutoff >= null:
train_end = y[cutoff] if is_int(cutoff) else cutoff
y_train = pd.Series(index=y[y <= train_end], dtype=y.dtype)
training_window = get_window(y_train, window_length=window_length).index
else:
training_window = []
training_window = y.get_indexer(training_window)
test_window = cutoff + fh.to_numpy()
if is_datetime(x=cutoff):
test_window = y.get_indexer(test_window[test_window >= y.min()])
yield training_window, test_window
def get_n_splits(self, y: Optional[ACCEPTED_Y_TYPES] = None) -> int:
"""Return the number of splits.
For this splitter the number is trivially equal to
the number of cutoffs given during instance initialization.
Parameters
----------
y : pd.Series or pd.Index, optional (default=None)
Time series to split
Returns
-------
n_splits : int
The number of splits.
"""
return len(self.cutoffs)
def get_cutoffs(self, y: Optional[ACCEPTED_Y_TYPES] = None) -> np.ndarray:
"""Return the cutoff points in .iloc[] context.
This method trivially returns the cutoffs given during instance initialization,
in case these cutoffs are integer .iloc[] friendly indices.
The only change is that the set of cutoffs is sorted from smallest to largest.
When the given cutoffs are datetime-like,
then this method returns corresponding integer indices.
Parameters
----------
y : pd.Series or pd.Index, optional (default=None)
Time series to split
Returns
-------
cutoffs : 1D np.ndarray of int
iloc location indices, in reference to y, of cutoff indices
"""
if array_is_int(self.cutoffs):
return check_cutoffs(self.cutoffs)
return np.argwhere(y.index.isin(check_cutoffs(self.cutoffs))).flatten()
@classmethod
def get_test_params(cls, parameter_set="default"):
"""Return testing parameter settings for the splitter.
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`
"""
return {"cutoffs": np.array([3, 7, 10])}
class BaseWindowSplitter(BaseSplitter):
"""Base class for sliding and expanding window splitter."""
def __init__(
self,
fh: FORECASTING_HORIZON_TYPES,
initial_window: ACCEPTED_WINDOW_LENGTH_TYPES,
window_length: ACCEPTED_WINDOW_LENGTH_TYPES,
step_length: NON_FLOAT_WINDOW_LENGTH_TYPES,
start_with_window: bool,
) -> None:
_check_inputs_for_compatibility(
[fh, initial_window, window_length, step_length]
)
self.step_length = step_length
self.start_with_window = start_with_window
self.initial_window = initial_window
super(BaseWindowSplitter, self).__init__(fh=fh, window_length=window_length)
@property
def _initial_window(self):
if hasattr(self, "initial_window"):
return self.initial_window
return None
def _split(self, y: pd.Index) -> SPLIT_GENERATOR_TYPE:
n_timepoints = y.shape[0]
window_length = check_window_length(
window_length=self.window_length,
n_timepoints=n_timepoints,
name="window_length",
)
initial_window = check_window_length(
window_length=self._initial_window,
n_timepoints=n_timepoints,
name="initial_window",
)
fh = _check_fh(self.fh)
_check_window_lengths(
y=y, fh=fh, window_length=window_length, initial_window=initial_window
)
if self._initial_window is not None:
yield self._split_for_initial_window(y)
for train, test in self._split_windows(window_length=window_length, y=y, fh=fh):
yield train, test
def _split_for_initial_window(self, y: pd.Index) -> SPLIT_ARRAY_TYPE:
"""Get train/test splits for non-empty initial window.
Parameters
----------
y : pd.Index
Index of the time series to split
Returns
-------
(np.ndarray, np.ndarray)
Integer indices of the train/test windows
"""
fh = _check_fh(self.fh)
if not self.start_with_window:
raise ValueError(
"`start_with_window` must be True if `initial_window` is given"
)
if self._initial_window <= self.window_length:
raise ValueError("`initial_window` must greater than `window_length`")
if is_int(x=self._initial_window):
end = self._initial_window
else:
end = y.get_loc(y[0] + self._initial_window)
train = self._get_train_window(y=y, train_start=0, split_point=end)
if array_is_int(fh):
test = end + fh.to_numpy() - 1
else:
test = np.argwhere(y.isin(y[end - 1] + fh)).flatten()
return train, test
def _split_windows(
self,
window_length: ACCEPTED_WINDOW_LENGTH_TYPES,
y: pd.Index,
fh: ForecastingHorizon,
) -> SPLIT_GENERATOR_TYPE:
"""Abstract method for sliding/expanding windows."""
raise NotImplementedError("abstract method")
def _split_windows_generic(
self,
window_length: ACCEPTED_WINDOW_LENGTH_TYPES,
y: pd.Index,
fh: ForecastingHorizon,
expanding: bool,
) -> SPLIT_GENERATOR_TYPE:
"""Split `y` into training and test windows.
This function encapsulates common functionality
shared by concrete implementations of this abstract class.
Parameters
----------
window_length : int or timedelta or pd.DateOffset
Length of training window
y : pd.Index
Index of time series to split
fh : ForecastingHorizon
Single step ahead or array of steps ahead to forecast.
expanding : bool
Expanding (True) or sliding window (False) splitter
Yields
------
train : 1D np.ndarray of int
Training window iloc indices, in reference to y
test : 1D np.ndarray of int
Test window iloc indices, in reference to y
"""
start = self._get_start(y=y, fh=fh)
split_points = self.get_cutoffs(pd.Series(index=y, dtype=float)) + 1
split_points = (
split_points if self._initial_window is None else split_points[1:]
)
for split_point in split_points:
train_start = self._get_train_start(
start=start if expanding else split_point,
window_length=window_length,
y=y,
)
train = self._get_train_window(
y=y, train_start=train_start, split_point=split_point
)
if array_is_int(fh):
test = split_point + fh.to_numpy() - 1
else:
test = np.argwhere(
y.isin(y[max(0, split_point - 1)] + fh.to_pandas())
).flatten()
if split_point == 0:
test -= 1
yield train, test
@staticmethod
def _get_train_start(
start: int, window_length: ACCEPTED_WINDOW_LENGTH_TYPES, y: pd.Index
) -> int:
if is_timedelta_or_date_offset(x=window_length):
train_start = y.get_loc(
max(y[min(start, len(y) - 1)] - window_length, min(y))
)
if start >= len(y):
train_start += 1
else:
train_start = start - window_length
return train_start
def _get_start(self, y: pd.Index, fh: ForecastingHorizon) -> int:
"""Get the first split point."""
# By default, the first split point is the index zero, the first
# observation in
# the data.
start = 0
# If we start with a full window, the first split point depends on the window
# length.
if hasattr(self, "start_with_window") and self.start_with_window:
if self._initial_window not in [None, 0]:
if is_timedelta_or_date_offset(x=self._initial_window):
start = y.get_loc(
y[start] + self._initial_window + self.step_length
)
else:
start += self._initial_window + self.step_length
else:
if is_timedelta_or_date_offset(x=self.window_length):
start = y.get_loc(y[start] + self.window_length)
else:
start += self.window_length
# For in-sample forecasting horizons, the first split must ensure that
# in-sample test set is still within the data.
if not fh.is_all_out_of_sample():
fh_min = abs(fh[0])
if is_int(fh_min):
start = fh_min + 1 if fh_min >= start else start
else:
shifted_y0 = y[0] + fh_min
start = np.argmin(y <= shifted_y0) if shifted_y0 >= y[start] else start
return start
def get_n_splits(self, y: Optional[ACCEPTED_Y_TYPES] = None) -> int:
"""Return the number of splits.
Parameters
----------
y : pd.Series or pd.Index, optional (default=None)
Time series to split
Returns
-------
n_splits : int
The number of splits.
"""
if y is None:
raise ValueError(
f"{self.__class__.__name__} requires `y` to compute the "
f"number of splits."
)
return len(self.get_cutoffs(y))
def get_cutoffs(self, y: Optional[ACCEPTED_Y_TYPES] = None) -> np.ndarray:
"""Return the cutoff points in .iloc[] context.
Parameters
----------
y : pd.Series or pd.Index, optional (default=None)
Time series to split
Returns