-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
_base.py
2131 lines (1817 loc) · 87.1 KB
/
_base.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
# -*- coding: utf-8 -*-
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
"""
Base class template for forecaster scitype.
class name: BaseForecaster
Scitype defining methods:
fitting - fit(y, X=None, fh=None)
forecasting - predict(fh=None, X=None)
updating - update(y, X=None, update_params=True)
Convenience methods:
fit&forecast - fit_predict(y, X=None, fh=None)
update&forecast - update_predict(cv=None, X=None, update_params=True)
forecast residuals - predict_residuals(y, X=None, fh=None)
forecast scores - score(y, X=None, fh=None)
Optional, special capability methods (check capability tags if available):
forecast intervals - predict_interval(fh=None, X=None, coverage=0.90)
forecast quantiles - predict_quantiles(fh=None, X=None, alpha=[0.05, 0.95])
forecast variance - predict_var(fh=None, X=None, cov=False)
distribution forecast - predict_proba(fh=None, X=None, marginal=True)
Inspection methods:
hyper-parameter inspection - get_params()
fitted parameter inspection - get_fitted_params()
current ForecastingHorizon - fh
State:
fitted model/strategy - by convention, any attributes ending in "_"
fitted state flag - is_fitted (property)
fitted state inspection - check_is_fitted()
"""
__author__ = ["mloning", "big-o", "fkiraly", "sveameyer13"]
__all__ = ["BaseForecaster"]
from contextlib import contextmanager
from warnings import warn
import numpy as np
import pandas as pd
from sklearn import clone
from sktime.base import BaseEstimator
from sktime.datatypes import (
VectorizedDF,
check_is_scitype,
convert_to,
get_cutoff,
mtype_to_scitype,
scitype_to_mtype,
)
from sktime.forecasting.base import ForecastingHorizon
from sktime.utils.datetime import _shift
from sktime.utils.validation._dependencies import _check_dl_dependencies
from sktime.utils.validation.forecasting import check_alpha, check_cv, check_fh, check_X
from sktime.utils.validation.series import check_equal_time_index
DEFAULT_ALPHA = 0.05
def _coerce_to_list(obj):
"""Return [obj] if obj is not a list, otherwise obj."""
if not isinstance(obj, list):
return [obj]
else:
return obj
class BaseForecaster(BaseEstimator):
"""Base forecaster template class.
The base forecaster specifies the methods and method
signatures that all forecasters have to implement.
Specific implementations of these methods is deferred to concrete
forecasters.
"""
# default tag values - these typically make the "safest" assumption
_tags = {
"scitype:y": "univariate", # which y are fine? univariate/multivariate/both
"ignores-exogeneous-X": True, # does estimator ignore the exogeneous X?
"capability:pred_int": False, # can the estimator produce prediction intervals?
"handles-missing-data": False, # can estimator handle missing data?
"y_inner_mtype": "pd.Series", # which types do _fit/_predict, support for y?
"X_inner_mtype": "pd.DataFrame", # which types do _fit/_predict, support for X?
"requires-fh-in-fit": True, # is forecasting horizon already required in fit?
"X-y-must-have-same-index": True, # can estimator handle different X/y index?
"enforce_index_type": None, # index type that needs to be enforced in X/y
"fit_is_empty": False, # is fit empty and can be skipped?
}
def __init__(self):
self._is_fitted = False
self._y = None
self._X = None
# forecasting horizon
self._fh = None
self._cutoff = None # reference point for relative fh
self._converter_store_y = dict() # storage dictionary for in/output conversion
super(BaseForecaster, self).__init__()
def __mul__(self, other):
"""Magic * method, return (right) concatenated TransformedTargetForecaster.
Implemented for `other` being a transformer, otherwise returns `NotImplemented`.
Parameters
----------
other: `sktime` transformer, must inherit from BaseTransformer
otherwise, `NotImplemented` is returned
Returns
-------
TransformedTargetForecaster object,
concatenation of `self` (first) with `other` (last).
not nested, contains only non-TransformerPipeline `sktime` transformers
"""
from sktime.forecasting.compose import TransformedTargetForecaster
from sktime.transformations.base import BaseTransformer
from sktime.transformations.series.adapt import TabularToSeriesAdaptor
from sktime.utils.sklearn import is_sklearn_transformer
# we wrap self in a pipeline, and concatenate with the other
# the TransformedTargetForecaster does the rest, e.g., dispatch on other
if isinstance(other, BaseTransformer):
self_as_pipeline = TransformedTargetForecaster(steps=[self])
return self_as_pipeline * other
elif is_sklearn_transformer(other):
return self * TabularToSeriesAdaptor(other)
else:
return NotImplemented
def __rmul__(self, other):
"""Magic * method, return (left) concatenated TransformerPipeline.
Implemented for `other` being a transformer, otherwise returns `NotImplemented`.
Parameters
----------
other: `sktime` transformer, must inherit from BaseTransformer
otherwise, `NotImplemented` is returned
Returns
-------
TransformedTargetForecaster object,
concatenation of `other` (first) with `self` (last).
not nested, contains only non-TransformerPipeline `sktime` steps
"""
from sktime.forecasting.compose import TransformedTargetForecaster
from sktime.transformations.base import BaseTransformer
from sktime.transformations.series.adapt import TabularToSeriesAdaptor
from sktime.utils.sklearn import is_sklearn_transformer
# we wrap self in a pipeline, and concatenate with the other
# the TransformedTargetForecaster does the rest, e.g., dispatch on other
if isinstance(other, BaseTransformer):
self_as_pipeline = TransformedTargetForecaster(steps=[self])
return other * self_as_pipeline
elif is_sklearn_transformer(other):
return TabularToSeriesAdaptor(other) * self
else:
return NotImplemented
def fit(self, y, X=None, fh=None):
"""Fit forecaster to training data.
State change:
Changes state to "fitted".
Writes to self:
Sets self._is_fitted flag to True.
Writes self._y and self._X with `y` and `X`, respectively.
Sets self.cutoff and self._cutoff to last index seen in `y`.
Sets fitted model attributes ending in "_".
Stores fh to self.fh if fh is passed.
Parameters
----------
y : time series in sktime compatible data container format
Time series to which to fit the forecaster.
y can be in one of the following formats:
Series scitype: pd.Series, pd.DataFrame, or np.ndarray (1D or 2D)
for vanilla forecasting, one time series
Panel scitype: pd.DataFrame with 2-level row MultiIndex,
3D np.ndarray, list of Series pd.DataFrame, or nested pd.DataFrame
for global or panel forecasting
Hierarchical scitype: pd.DataFrame with 3 or more level row MultiIndex
for hierarchical forecasting
Number of columns admissible depend on the "scitype:y" tag:
if self.get_tag("scitype:y")=="univariate":
y must have a single column/variable
if self.get_tag("scitype:y")=="multivariate":
y must have 2 or more columns
if self.get_tag("scitype:y")=="both": no restrictions on columns apply
For further details:
on usage, see forecasting tutorial examples/01_forecasting.ipynb
on specification of formats, examples/AA_datatypes_and_datasets.ipynb
fh : int, list, np.array or ForecastingHorizon, optional (default=None)
The forecasting horizon encoding the time stamps to forecast at.
if self.get_tag("requires-fh-in-fit"), must be passed, not optional
X : time series in sktime compatible format, optional (default=None)
Exogeneous time series to fit to
Should be of same scitype (Series, Panel, or Hierarchical) as y
if self.get_tag("X-y-must-have-same-index"), X.index must contain y.index
there are no restrictions on number of columns (unlike for y)
Returns
-------
self : Reference to self.
"""
# check y is not None
assert y is not None, "y cannot be None, but found None"
# if fit is called, fitted state is re-set
self._is_fitted = False
fh = self._check_fh(fh)
# check and convert X/y
X_inner, y_inner = self._check_X_y(X=X, y=y)
# set internal X/y to the new X/y
# this also updates cutoff from y
self._update_y_X(y_inner, X_inner)
# checks and conversions complete, pass to inner fit
#####################################################
vectorization_needed = isinstance(y_inner, VectorizedDF)
self._is_vectorized = vectorization_needed
# we call the ordinary _fit if no looping/vectorization needed
if not vectorization_needed:
self._fit(y=y_inner, X=X_inner, fh=fh)
else:
# otherwise we call the vectorized version of fit
self._vectorize("fit", y=y_inner, X=X_inner, fh=fh)
# this should happen last
self._is_fitted = True
return self
def predict(
self,
fh=None,
X=None,
):
"""Forecast time series at future horizon.
State required:
Requires state to be "fitted".
Accesses in self:
Fitted model attributes ending in "_".
self.cutoff, self._is_fitted
Writes to self:
Stores fh to self.fh if fh is passed and has not been passed previously.
Parameters
----------
fh : int, list, np.array or ForecastingHorizon, optional (default=None)
The forecasting horizon encoding the time stamps to forecast at.
if has not been passed in fit, must be passed, not optional
X : time series in sktime compatible format, optional (default=None)
Exogeneous time series to fit to
Should be of same scitype (Series, Panel, or Hierarchical) as y in fit
if self.get_tag("X-y-must-have-same-index"), X.index must contain fh.index
there are no restrictions on number of columns (unlike for y)
Returns
-------
y_pred : time series in sktime compatible data container format
Point forecasts at fh, with same index as fh
y_pred has same type as the y that has been passed most recently:
Series, Panel, Hierarchical scitype, same format (see above)
"""
# handle inputs
self.check_is_fitted()
fh = self._check_fh(fh)
# input check and conversion for X
X_inner = self._check_X(X=X)
# we call the ordinary _predict if no looping/vectorization needed
if not self._is_vectorized:
y_pred = self._predict(fh=fh, X=X_inner)
else:
# otherwise we call the vectorized version of predict
y_pred = self._vectorize("predict", X=X_inner, fh=fh)
# convert to output mtype, identical with last y mtype seen
y_out = convert_to(
y_pred,
self._y_mtype_last_seen,
store=self._converter_store_y,
store_behaviour="freeze",
)
return y_out
def fit_predict(self, y, X=None, fh=None):
"""Fit and forecast time series at future horizon.
State change:
Changes state to "fitted".
Writes to self:
Sets is_fitted flag to True.
Writes self._y and self._X with `y` and `X`, respectively.
Sets self.cutoff and self._cutoff to last index seen in `y`.
Sets fitted model attributes ending in "_".
Stores fh to self.fh.
Parameters
----------
y : time series in sktime compatible data container format
Time series to which to fit the forecaster.
y can be in one of the following formats:
Series scitype: pd.Series, pd.DataFrame, or np.ndarray (1D or 2D)
for vanilla forecasting, one time series
Panel scitype: pd.DataFrame with 2-level row MultiIndex,
3D np.ndarray, list of Series pd.DataFrame, or nested pd.DataFrame
for global or panel forecasting
Hierarchical scitype: pd.DataFrame with 3 or more level row MultiIndex
for hierarchical forecasting
Number of columns admissible depend on the "scitype:y" tag:
if self.get_tag("scitype:y")=="univariate":
y must have a single column/variable
if self.get_tag("scitype:y")=="multivariate":
y must have 2 or more columns
if self.get_tag("scitype:y")=="both": no restrictions on columns apply
For further details:
on usage, see forecasting tutorial examples/01_forecasting.ipynb
on specification of formats, examples/AA_datatypes_and_datasets.ipynb
fh : int, list, np.array or ForecastingHorizon (not optional)
The forecasting horizon encoding the time stamps to forecast at.
if has not been passed in fit, must be passed, not optional
X : time series in sktime compatible format, optional (default=None)
Exogeneous time series to fit to
Should be of same scitype (Series, Panel, or Hierarchical) as y in fit
if self.get_tag("X-y-must-have-same-index"),
X.index must contain fh.index and y.index both
Returns
-------
y_pred : time series in sktime compatible data container format
Point forecasts at fh, with same index as fh
y_pred has same type as the y that has been passed most recently:
Series, Panel, Hierarchical scitype, same format (see above)
"""
# if fit is called, fitted state is re-set
self._is_fitted = False
fh = self._check_fh(fh)
# check and convert X/y
X_inner, y_inner = self._check_X_y(X=X, y=y)
# set internal X/y to the new X/y
# this also updates cutoff from y
self._update_y_X(y_inner, X_inner)
# apply fit and then predict
vectorization_needed = isinstance(y_inner, VectorizedDF)
self._is_vectorized = vectorization_needed
# we call the ordinary _fit if no looping/vectorization needed
if not vectorization_needed:
self._fit(y=y_inner, X=X_inner, fh=fh)
else:
# otherwise we call the vectorized version of fit
self._vectorize("fit", y=y_inner, X=X_inner, fh=fh)
self._is_fitted = True
# call the public predict to avoid duplicating output conversions
# input conversions are skipped since we are using X_inner
return self.predict(fh=fh, X=X_inner)
def predict_quantiles(self, fh=None, X=None, alpha=None):
"""Compute/return quantile forecasts.
If alpha is iterable, multiple quantiles will be calculated.
State required:
Requires state to be "fitted".
Accesses in self:
Fitted model attributes ending in "_".
self.cutoff, self._is_fitted
Writes to self:
Stores fh to self.fh if fh is passed and has not been passed previously.
Parameters
----------
fh : int, list, np.array or ForecastingHorizon (not optional)
The forecasting horizon encoding the time stamps to forecast at.
if has not been passed in fit, must be passed, not optional
X : time series in sktime compatible format, optional (default=None)
Exogeneous time series to fit to
Should be of same scitype (Series, Panel, or Hierarchical) as y in fit
if self.get_tag("X-y-must-have-same-index"), must contain fh.index
alpha : float or list of float of unique values, optional (default=[0.05, 0.95])
A probability or list of, at which quantile forecasts are computed.
Returns
-------
quantiles : pd.DataFrame
Column has multi-index: first level is variable name from y in fit,
second level being the values of alpha passed to the function.
Row index is fh, with additional (upper) levels equal to instance levels,
from y seen in fit, if y seen in fit was Panel or Hierarchical.
Entries are quantile forecasts, for var in col index,
at quantile probability in second col index, for the row index.
"""
if not self.get_tag("capability:pred_int"):
raise NotImplementedError(
f"{self.__class__.__name__} does not have the capability to return "
"quantile predictions. If you "
"think this estimator should have the capability, please open "
"an issue on sktime."
)
self.check_is_fitted()
# input checks and conversions
# check fh and coerce to ForecastingHorizon
fh = self._check_fh(fh)
# default alpha
if alpha is None:
alpha = [0.05, 0.95]
# check alpha and coerce to list
alpha = check_alpha(alpha, name="alpha")
# input check and conversion for X
X_inner = self._check_X(X=X)
# we call the ordinary _predict_quantiles if no looping/vectorization needed
if not self._is_vectorized:
quantiles = self._predict_quantiles(fh=fh, X=X_inner, alpha=alpha)
else:
# otherwise we call the vectorized version of predict_quantiles
quantiles = self._vectorize(
"predict_quantiles", fh=fh, X=X_inner, alpha=alpha
)
return quantiles
def predict_interval(
self,
fh=None,
X=None,
coverage=0.90,
):
"""Compute/return prediction interval forecasts.
If coverage is iterable, multiple intervals will be calculated.
State required:
Requires state to be "fitted".
Accesses in self:
Fitted model attributes ending in "_".
self.cutoff, self._is_fitted
Writes to self:
Stores fh to self.fh if fh is passed and has not been passed previously.
Parameters
----------
fh : int, list, np.array or ForecastingHorizon (not optional)
The forecasting horizon encoding the time stamps to forecast at.
if has not been passed in fit, must be passed, not optional
X : time series in sktime compatible format, optional (default=None)
Exogeneous time series to fit to
Should be of same scitype (Series, Panel, or Hierarchical) as y in fit
if self.get_tag("X-y-must-have-same-index"), must contain fh.index
coverage : float or list of float of unique values, optional (default=0.90)
nominal coverage(s) of predictive interval(s)
Returns
-------
pred_int : pd.DataFrame
Column has multi-index: first level is variable name from y in fit,
second level coverage fractions for which intervals were computed.
in the same order as in input `coverage`.
Third level is string "lower" or "upper", for lower/upper interval end.
Row index is fh, with additional (upper) levels equal to instance levels,
from y seen in fit, if y seen in fit was Panel or Hierarchical.
Entries are forecasts of lower/upper interval end,
for var in col index, at nominal coverage in second col index,
lower/upper depending on third col index, for the row index.
Upper/lower interval end forecasts are equivalent to
quantile forecasts at alpha = 0.5 - c/2, 0.5 + c/2 for c in coverage.
"""
if not self.get_tag("capability:pred_int"):
raise NotImplementedError(
f"{self.__class__.__name__} does not have the capability to return "
"prediction intervals. If you "
"think this estimator should have the capability, please open "
"an issue on sktime."
)
self.check_is_fitted()
# input checks and conversions
# check fh and coerce to ForecastingHorizon
fh = self._check_fh(fh)
# check alpha and coerce to list
coverage = check_alpha(coverage, name="coverage")
# check and convert X
X_inner = self._check_X(X=X)
# we call the ordinary _predict_interval if no looping/vectorization needed
if not self._is_vectorized:
pred_int = self._predict_interval(fh=fh, X=X_inner, coverage=coverage)
else:
# otherwise we call the vectorized version of predict_interval
pred_int = self._vectorize(
"predict_interval", fh=fh, X=X_inner, coverage=coverage
)
return pred_int
def predict_var(self, fh=None, X=None, cov=False):
"""Compute/return variance forecasts.
State required:
Requires state to be "fitted".
Accesses in self:
Fitted model attributes ending in "_".
self.cutoff, self._is_fitted
Writes to self:
Stores fh to self.fh if fh is passed and has not been passed previously.
Parameters
----------
fh : int, list, np.array or ForecastingHorizon (not optional)
The forecasting horizon encoding the time stamps to forecast at.
if has not been passed in fit, must be passed, not optional
X : time series in sktime compatible format, optional (default=None)
Exogeneous time series to fit to
Should be of same scitype (Series, Panel, or Hierarchical) as y in fit
if self.get_tag("X-y-must-have-same-index"),
X.index must contain fh.index and y.index both
cov : bool, optional (default=False)
if True, computes covariance matrix forecast.
if False, computes marginal variance forecasts.
Returns
-------
pred_var : pd.DataFrame, format dependent on `cov` variable
If cov=False:
Column names are exactly those of `y` passed in `fit`/`update`.
For nameless formats, column index will be a RangeIndex.
Row index is fh, with additional levels equal to instance levels,
from y seen in fit, if y seen in fit was Panel or Hierarchical.
Entries are variance forecasts, for var in col index.
A variance forecast for given variable and fh index is a predicted
variance for that variable and index, given observed data.
If cov=True:
Column index is a multiindex: 1st level is variable names (as above)
2nd level is fh.
Row index is fh, with additional levels equal to instance levels,
from y seen in fit, if y seen in fit was Panel or Hierarchical.
Entries are (co-)variance forecasts, for var in col index, and
covariance between time index in row and col.
Note: no covariance forecasts are returned between different variables.
"""
if not self.get_tag("capability:pred_int"):
raise NotImplementedError(
f"{self.__class__.__name__} does not have the capability to return "
"variance predictions. If you "
"think this estimator should have the capability, please open "
"an issue on sktime."
)
self.check_is_fitted()
# input checks
fh = self._check_fh(fh)
# check and convert X
X_inner = self._check_X(X=X)
# we call the ordinary _predict_interval if no looping/vectorization needed
if not self._is_vectorized:
pred_var = self._predict_var(fh=fh, X=X_inner, cov=cov)
else:
# otherwise we call the vectorized version of predict_interval
pred_var = self._vectorize("predict_var", fh=fh, X=X_inner, cov=cov)
return pred_var
def predict_proba(self, fh=None, X=None, marginal=True):
"""Compute/return fully probabilistic forecasts.
Note: currently only implemented for Series (non-panel, non-hierarchical) y.
State required:
Requires state to be "fitted".
Accesses in self:
Fitted model attributes ending in "_".
self.cutoff, self._is_fitted
Writes to self:
Stores fh to self.fh if fh is passed and has not been passed previously.
Parameters
----------
fh : int, list, np.array or ForecastingHorizon (not optional)
The forecasting horizon encoding the time stamps to forecast at.
if has not been passed in fit, must be passed, not optional
X : time series in sktime compatible format, optional (default=None)
Exogeneous time series to fit to
Should be of same scitype (Series, Panel, or Hierarchical) as y in fit
if self.get_tag("X-y-must-have-same-index"), must contain fh.index
marginal : bool, optional (default=True)
whether returned distribution is marginal by time index
Returns
-------
pred_dist : tfp Distribution object
if marginal=True:
batch shape is 1D and same length as fh
event shape is 1D, with length equal number of variables being forecast
i-th (batch) distribution is forecast for i-th entry of fh
j-th (event) index is j-th variable, order as y in `fit`/`update`
if marginal=False:
there is a single batch
event shape is 2D, of shape (len(fh), no. variables)
i-th (event dim 1) distribution is forecast for i-th entry of fh
j-th (event dim 1) index is j-th variable, order as y in `fit`/`update`
"""
msg = (
"tensorflow-probability must be installed for fully probabilistic forecasts"
"install `sktime` deep learning dependencies by `pip install sktime[dl]`"
)
_check_dl_dependencies(msg)
if not self.get_tag("capability:pred_int"):
raise NotImplementedError(
f"{self.__class__.__name__} does not have the capability to return "
"fully probabilistic predictions. If you "
"think this estimator should have the capability, please open "
"an issue on sktime."
)
self.check_is_fitted()
# input checks
fh = self._check_fh(fh)
# check and convert X
X_inner = self._check_X(X=X)
pred_dist = self._predict_proba(fh=fh, X=X_inner, marginal=marginal)
return pred_dist
def update(self, y, X=None, update_params=True):
"""Update cutoff value and, optionally, fitted parameters.
If no estimator-specific update method has been implemented,
default fall-back is as follows:
update_params=True: fitting to all observed data so far
update_params=False: updates cutoff and remembers data only
State required:
Requires state to be "fitted".
Accesses in self:
Fitted model attributes ending in "_".
Pointers to seen data, self._y and self.X
self.cutoff, self._is_fitted
If update_params=True, model attributes ending in "_".
Writes to self:
Update self._y and self._X with `y` and `X`, by appending rows.
Updates self. cutoff and self._cutoff to last index seen in `y`.
If update_params=True,
updates fitted model attributes ending in "_".
Parameters
----------
y : time series in sktime compatible data container format
Time series to which to fit the forecaster in the update.
y can be in one of the following formats, must be same scitype as in fit:
Series scitype: pd.Series, pd.DataFrame, or np.ndarray (1D or 2D)
for vanilla forecasting, one time series
Panel scitype: pd.DataFrame with 2-level row MultiIndex,
3D np.ndarray, list of Series pd.DataFrame, or nested pd.DataFrame
for global or panel forecasting
Hierarchical scitype: pd.DataFrame with 3 or more level row MultiIndex
for hierarchical forecasting
Number of columns admissible depend on the "scitype:y" tag:
if self.get_tag("scitype:y")=="univariate":
y must have a single column/variable
if self.get_tag("scitype:y")=="multivariate":
y must have 2 or more columns
if self.get_tag("scitype:y")=="both": no restrictions on columns apply
For further details:
on usage, see forecasting tutorial examples/01_forecasting.ipynb
on specification of formats, examples/AA_datatypes_and_datasets.ipynb
X : time series in sktime compatible format, optional (default=None)
Exogeneous time series to fit to
Should be of same scitype (Series, Panel, or Hierarchical) as y
if self.get_tag("X-y-must-have-same-index"), X.index must contain y.index
there are no restrictions on number of columns (unlike for y)
update_params : bool, optional (default=True)
whether model parameters should be updated
Returns
-------
self : reference to self
"""
self.check_is_fitted()
if y is None or (hasattr(y, "__len__") and len(y) == 0):
warn("empty y passed to update, no update was carried out")
return self
# input checks and minor coercions on X, y
X_inner, y_inner = self._check_X_y(X=X, y=y)
# update internal X/y with the new X/y
# this also updates cutoff from y
self._update_y_X(y_inner, X_inner)
# checks and conversions complete, pass to inner fit
self._update(y=y_inner, X=X_inner, update_params=update_params)
return self
def update_predict(
self,
y,
cv=None,
X=None,
update_params=True,
):
"""Make predictions and update model iteratively over the test set.
State required:
Requires state to be "fitted".
Accesses in self:
Fitted model attributes ending in "_".
Pointers to seen data, self._y and self.X
self.cutoff, self._is_fitted
If update_params=True, model attributes ending in "_".
Writes to self:
Update self._y and self._X with `y` and `X`, by appending rows.
Updates self.cutoff and self._cutoff to last index seen in `y`.
If update_params=True,
updates fitted model attributes ending in "_".
Parameters
----------
y : time series in sktime compatible data container format
Time series to which to fit the forecaster in the update.
y can be in one of the following formats, must be same scitype as in fit:
Series scitype: pd.Series, pd.DataFrame, or np.ndarray (1D or 2D)
for vanilla forecasting, one time series
Panel scitype: pd.DataFrame with 2-level row MultiIndex,
3D np.ndarray, list of Series pd.DataFrame, or nested pd.DataFrame
for global or panel forecasting
Hierarchical scitype: pd.DataFrame with 3 or more level row MultiIndex
for hierarchical forecasting
Number of columns admissible depend on the "scitype:y" tag:
if self.get_tag("scitype:y")=="univariate":
y must have a single column/variable
if self.get_tag("scitype:y")=="multivariate":
y must have 2 or more columns
if self.get_tag("scitype:y")=="both": no restrictions on columns apply
For further details:
on usage, see forecasting tutorial examples/01_forecasting.ipynb
on specification of formats, examples/AA_datatypes_and_datasets.ipynb
cv : temporal cross-validation generator, optional (default=None)
X : time series in sktime compatible format, optional (default=None)
Exogeneous time series for updating and forecasting
Should be of same scitype (Series, Panel, or Hierarchical) as y
if self.get_tag("X-y-must-have-same-index"),
X.index must contain y.index and fh.index both
there are no restrictions on number of columns (unlike for y)
update_params : bool, optional (default=True)
Returns
-------
y_pred : time series in sktime compatible data container format
Point forecasts at fh, with same index as fh
y_pred has same type as the y that has been passed most recently:
Series, Panel, Hierarchical scitype, same format (see above)
"""
self.check_is_fitted()
# input checks and minor coercions on X, y
X_inner, y_inner = self._check_X_y(X=X, y=y)
cv = check_cv(cv)
return self._predict_moving_cutoff(
y=y_inner,
cv=cv,
X=X_inner,
update_params=update_params,
)
def update_predict_single(
self,
y=None,
fh=None,
X=None,
update_params=True,
):
"""Update model with new data and make forecasts.
This method is useful for updating and making forecasts in a single step.
If no estimator-specific update method has been implemented,
default fall-back is first update, then predict.
State required:
Requires state to be "fitted".
Accesses in self:
Fitted model attributes ending in "_".
Pointers to seen data, self._y and self.X
self.cutoff, self._is_fitted
If update_params=True, model attributes ending in "_".
Writes to self:
Update self._y and self._X with `y` and `X`, by appending rows.
Updates self. cutoff and self._cutoff to last index seen in `y`.
If update_params=True,
updates fitted model attributes ending in "_".
Parameters
----------
y : time series in sktime compatible data container format
Time series to which to fit the forecaster in the update.
y can be in one of the following formats, must be same scitype as in fit:
Series scitype: pd.Series, pd.DataFrame, or np.ndarray (1D or 2D)
for vanilla forecasting, one time series
Panel scitype: pd.DataFrame with 2-level row MultiIndex,
3D np.ndarray, list of Series pd.DataFrame, or nested pd.DataFrame
for global or panel forecasting
Hierarchical scitype: pd.DataFrame with 3 or more level row MultiIndex
for hierarchical forecasting
Number of columns admissible depend on the "scitype:y" tag:
if self.get_tag("scitype:y")=="univariate":
y must have a single column/variable
if self.get_tag("scitype:y")=="multivariate":
y must have 2 or more columns
if self.get_tag("scitype:y")=="both": no restrictions on columns apply
For further details:
on usage, see forecasting tutorial examples/01_forecasting.ipynb
on specification of formats, examples/AA_datatypes_and_datasets.ipynb
fh : int, list, np.array or ForecastingHorizon, optional (default=None)
The forecasting horizon encoding the time stamps to forecast at.
if has not been passed in fit, must be passed, not optional
X : time series in sktime compatible format, optional (default=None)
Exogeneous time series for updating and forecasting
Should be of same scitype (Series, Panel, or Hierarchical) as y
if self.get_tag("X-y-must-have-same-index"),
X.index must contain y.index and fh.index both
update_params : bool, optional (default=False)
Returns
-------
y_pred : time series in sktime compatible data container format
Point forecasts at fh, with same index as fh
y_pred has same type as the y that has been passed most recently:
Series, Panel, Hierarchical scitype, same format (see above)
"""
if y is None or (hasattr(y, "__len__") and len(y) == 0):
warn("empty y passed to update_predict, no update was carried out")
return self.predict(fh=fh, X=X)
self.check_is_fitted()
fh = self._check_fh(fh)
# input checks and minor coercions on X, y
X_inner, y_inner = self._check_X_y(X=X, y=y)
# update internal _X/_y with the new X/y
# this also updates cutoff from y
self._update_y_X(y_inner, X_inner)
return self._update_predict_single(
y=y_inner,
fh=fh,
X=X_inner,
update_params=update_params,
)
def predict_residuals(self, y=None, X=None):
"""Return residuals of time series forecasts.
Residuals will be computed for forecasts at y.index.
If fh must be passed in fit, must agree with y.index.
If y is an np.ndarray, and no fh has been passed in fit,
the residuals will be computed at a fh of range(len(y.shape[0]))
State required:
Requires state to be "fitted".
If fh has been set, must correspond to index of y (pandas or integer)
Accesses in self:
Fitted model attributes ending in "_".
self.cutoff, self._is_fitted
Writes to self:
Stores y.index to self.fh if has not been passed previously.
Parameters
----------
y : time series in sktime compatible data container format
Time series with ground truth observations, to compute residuals to.
Must have same type, dimension, and indices as expected return of predict.
if None, the y seen so far (self._y) are used, in particular:
if preceded by a single fit call, then in-sample residuals are produced
if fit requires fh, it must have pointed to index of y in fit
X : pd.DataFrame, or 2D np.ndarray, optional (default=None)
Exogeneous time series to predict from
if self.get_tag("X-y-must-have-same-index"),
X.index must contain fh.index and y.index both
Returns
-------
y_res : time series in sktime compatible data container format
Forecast residuals at fh, with same index as fh
y_res has same type as the y that has been passed most recently:
Series, Panel, Hierarchical scitype, same format (see above)
"""
# if no y is passed, the so far observed y is used
if y is None:
y = self._y
# we want residuals, so fh must be the index of y
# if data frame: take directly from y
# to avoid issues with _set_fh, we convert to relative if self.fh is
if isinstance(y, (pd.DataFrame, pd.Series)):
fh = ForecastingHorizon(y.index, is_relative=False)
if self._fh is not None and self.fh.is_relative:
fh = fh.to_relative(self.cutoff)
fh = self._check_fh(fh)
# if np.ndarray, rows are not indexed
# so will be interpreted as range(len), or existing fh if it is stored
elif isinstance(y, np.ndarray):
if self._fh is None:
fh = range(y.shape[0])
else:
fh = self.fh
else:
raise TypeError("y must be a supported Series mtype")
y_pred = self.predict(fh=fh, X=X)
if not type(y_pred) == type(y):
raise TypeError(
"y must have same type, dims, index as expected predict return. "
f"expected type {type(y_pred)}, but found {type(y)}"
)
y_res = y - y_pred
return y_res
def score(self, y, X=None, fh=None):
"""Scores forecast against ground truth, using MAPE.
Parameters
----------
y : pd.Series, pd.DataFrame, or np.ndarray (1D or 2D)
Time series to score
if self.get_tag("scitype:y")=="univariate":
must have a single column/variable
if self.get_tag("scitype:y")=="multivariate":
must have 2 or more columns
if self.get_tag("scitype:y")=="both": no restrictions apply
fh : int, list, array-like or ForecastingHorizon, optional (default=None)
The forecasters horizon with the steps ahead to to predict.
X : pd.DataFrame, or 2D np.array, optional (default=None)
Exogeneous time series to score
if self.get_tag("X-y-must-have-same-index"), X.index must contain y.index
Returns