/
_base.py
2601 lines (2150 loc) · 107 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
# 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
current cutoff - cutoff
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", "miraep8", "ciaran-g"]
__all__ = ["BaseForecaster"]
from copy import deepcopy
from itertools import product
import numpy as np
import pandas as pd
from sktime.base import BaseEstimator
from sktime.datatypes import (
VectorizedDF,
check_is_error_msg,
check_is_scitype,
convert_to,
get_cutoff,
mtype_to_scitype,
scitype_to_mtype,
update_data,
)
from sktime.forecasting.base._fh import ForecastingHorizon
from sktime.utils.datetime import _shift
from sktime.utils.validation._dependencies import _check_estimator_deps
from sktime.utils.validation.forecasting import check_alpha, check_cv, check_fh, check_X
from sktime.utils.validation.series import check_equal_time_index
from sktime.utils.warnings import warn
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
# for more extensive documentation, see extension_templates/forecasting.py
_tags = {
# packaging info
# --------------
"authors": "sktime developers", # author(s) of the object
"maintainers": "sktime developers", # current maintainer(s) of the object
"python_version": None, # PEP 440 python version specifier to limit versions
"python_dependencies": None, # str or list of str, package soft dependencies
# estimator type
# --------------
"object_type": "forecaster", # type of object
"scitype:y": "univariate", # which y are fine? univariate/multivariate/both
"ignores-exogeneous-X": False, # does estimator ignore the exogeneous X?
"capability:insample": True, # can the estimator make in-sample predictions?
"capability:pred_int": False, # can the estimator produce prediction intervals?
"capability:pred_int:insample": True, # if yes, also for in-sample horizons?
"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?
}
# configs and default config values
# see set_config documentation for details
_config = {
"backend:parallel": None, # parallelization backend for broadcasting
# {None, "dask", "loky", "multiprocessing", "threading"}
# None: no parallelization
# "loky", "multiprocessing" and "threading": uses `joblib` Parallel loops
# "joblib": uses custom joblib backend, set via `joblib_backend` tag
# "dask": uses `dask`, requires `dask` package in environment
"backend:parallel:params": None, # params for parallelization backend
"remember_data": True, # whether to remember data in fit - self._X, self._y
}
_config_doc = {
"remember_data": """
remember_data : bool, default=True
whether self._X and self._y are stored in fit, and updated
in update. If True, self._X and self._y are stored and updated.
If False, self._X and self._y are not stored and updated.
This reduces serialization size when using save,
but the update will default to "do nothing" rather than
"refit to all data seen".
""",
}
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().__init__()
_check_estimator_deps(self)
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 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 ``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 __rpow__(self, other):
"""Magic ** method, return (left) concatenated ForecastingPipeline.
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 ForecastingPipeline
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 ForecastingPipeline does the rest, e.g., dispatch on other
if isinstance(other, BaseTransformer):
self_as_pipeline = ForecastingPipeline(steps=[self])
return other**self_as_pipeline
elif is_sklearn_transformer(other):
return TabularToSeriesAdaptor(other) ** self
else:
return NotImplemented
def __or__(self, other):
"""Magic | method, return MultiplexForecaster.
Implemented for ``other`` being either a MultiplexForecaster or a forecaster.
Parameters
----------
other: ``sktime`` forecaster or sktime MultiplexForecaster
Returns
-------
MultiplexForecaster object
"""
from sktime.forecasting.compose import MultiplexForecaster
if isinstance(other, MultiplexForecaster) or isinstance(other, BaseForecaster):
multiplex_self = MultiplexForecaster([self])
return multiplex_self | other
else:
return NotImplemented
def __getitem__(self, key):
"""Magic [...] method, return forecaster with subsetted data.
First index does subsetting of exogeneous input data.
Second index does subsetting of the forecast (but not of endogeneous data).
Keys must be valid inputs for ``columns`` in ``ColumnSelect``.
Parameters
----------
key: valid input for ``columns`` in ``ColumnSelect``, or pair thereof
keys can also be a :-slice, in which case it is considered as not passed
Returns
-------
the following composite pipeline object:
ColumnSelect(columns1) ** self * ColumnSelect(columns2)
where ``columns1`` is first or only item in ``key``, and ``columns2`` is the
last
if only one item is passed in ``key``, only ``columns1`` is applied to input
"""
from sktime.transformations.series.subset import ColumnSelect
def is_noneslice(obj):
res = isinstance(obj, slice)
res = res and obj.start is None and obj.stop is None and obj.step is None
return res
if isinstance(key, tuple):
if not len(key) == 2:
raise ValueError(
"there should be one or two keys when calling [] or getitem, "
"of a forecaster, "
"e.g., mytrafo[key], or mytrafo[key1, key2]. "
f"But {self.__class__.__name__} instance got tuple"
f" with {len(key)} keys."
)
columns1 = key[0]
columns2 = key[1]
if is_noneslice(columns1) and is_noneslice(columns2):
return self
elif is_noneslice(columns2):
return ColumnSelect(columns1) ** self
elif is_noneslice(columns1):
return self * ColumnSelect(columns2)
else:
return ColumnSelect(columns1) ** self * ColumnSelect(columns2)
else:
return ColumnSelect(key) ** self
def fit(self, y, X=None, fh=None):
"""Fit forecaster to training data.
State change:
Changes state to "fitted".
Writes to self:
* Sets fitted model attributes ending in "_", fitted attributes are
inspectable via ``get_fitted_params``.
* Sets ``self.is_fitted`` flag to ``True``.
* Sets ``self.cutoff`` to last index seen in ``y``.
* 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.
Individual data formats in ``sktime`` are so-called :term:`mtype`
specifications, each mtype implements an abstract :term:`scitype`.
* ``Series`` scitype = individual time series, vanilla forecasting.
``pd.DataFrame``, ``pd.Series``, or ``np.ndarray`` (1D or 2D)
* ``Panel`` scitype = collection of time series, global/panel forecasting.
``pd.DataFrame`` with 2-level row ``MultiIndex`` ``(instance, time)``,
``3D np.ndarray`` ``(instance, variable, time)``,
``list`` of ``Series`` typed ``pd.DataFrame``
* ``Hierarchical`` scitype = hierarchical collection, for
hierarchical forecasting. ``pd.DataFrame`` with 3 or more level row
``MultiIndex`` ``(hierarchy_1, ..., hierarchy_n, time)``
For further details on data format, see glossary on :term:`mtype`.
For usage, see forecasting tutorial ``examples/01_forecasting.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")`` is ``True``,
must be passed in ``fit``, not optional
X : time series in ``sktime`` compatible format, optional (default=None).
Exogeneous time series to fit the model to.
Should be of same :term:`scitype` (``Series``, ``Panel``,
or ``Hierarchical``) as ``y``.
If ``self.get_tag("X-y-must-have-same-index")``,
``X.index`` must contain ``y.index``.
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, estimator is reset, including fitted state
self.reset()
# 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)
# check forecasting horizon and coerce to ForecastingHorizon object
fh = self._check_fh(fh)
# 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", i.e., ``self.is_fitted=True``.
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.
Should not be passed if has already been passed in ``fit``.
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 use in prediction.
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 reference.
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()
# input check and conversion for X
X_inner = self._check_X(X=X)
# check fh and coerce to ForecastingHorizon, if not already passed in fit
fh = self._check_fh(fh)
# 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_metadata["mtype"],
store=self._converter_store_y,
store_behaviour="freeze",
)
return y_out
def fit_predict(self, y, X=None, fh=None, X_pred=None):
"""Fit and forecast time series at future horizon.
Same as ``fit(y, X, fh).predict(X_pred)``.
If ``X_pred`` is not passed, same as
``fit(y, fh, X).predict(X)``.
State change:
Changes state to "fitted".
Writes to self:
* Sets fitted model attributes ending in "_", fitted attributes are
inspectable via ``get_fitted_params``.
* Sets ``self.is_fitted`` flag to ``True``.
* Sets ``self.cutoff`` to last index seen in ``y``.
* Stores ``fh`` to ``self.fh``.
Parameters
----------
y : time series in sktime compatible data container format
Time series to which to fit the forecaster.
Individual data formats in ``sktime`` are so-called :term:`mtype`
specifications, each mtype implements an abstract :term:`scitype`.
* ``Series`` scitype = individual time series, vanilla forecasting.
``pd.DataFrame``, ``pd.Series``, or ``np.ndarray`` (1D or 2D)
* ``Panel`` scitype = collection of time series, global/panel forecasting.
``pd.DataFrame`` with 2-level row ``MultiIndex`` ``(instance, time)``,
``3D np.ndarray`` ``(instance, variable, time)``,
``list`` of ``Series`` typed ``pd.DataFrame``
* ``Hierarchical`` scitype = hierarchical collection, for
hierarchical forecasting. ``pd.DataFrame`` with 3 or more level row
``MultiIndex`` ``(hierarchy_1, ..., hierarchy_n, time)``
For further details on data format, see glossary on :term:`mtype`.
For usage, see forecasting tutorial ``examples/01_forecasting.ipynb``
fh : int, list, np.array or ``ForecastingHorizon`` (not optional)
The forecasting horizon encoding the time stamps to forecast at.
X : time series in ``sktime`` compatible format, optional (default=None).
Exogeneous time series to fit the model to.
Should be of same :term:`scitype` (``Series``, ``Panel``,
or ``Hierarchical``) as ``y``.
If ``self.get_tag("X-y-must-have-same-index")``,
``X.index`` must contain ``y.index``.
X_pred : time series in sktime compatible format, optional (default=None)
Exogeneous time series to use in prediction.
If passed, will be used in predict instead of X.
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 reference.
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 X_pred is passed, run fit/predict with different X
if X_pred is not None:
return self.fit(y=y, X=X, fh=fh).predict(X=X_pred)
# otherwise, we use the same X for fit and predict
# below code carries out conversion and checks for X only once
# if fit is called, fitted state is re-set
self._is_fitted = False
# 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)
# check fh and coerce to ForecastingHorizon
fh = self._check_fh(fh)
# 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", i.e., ``self.is_fitted=True``.
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.
Should not be passed if has already been passed in ``fit``.
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 use in prediction.
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 reference.
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, if not already passed in fit
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", i.e., ``self.is_fitted=True``.
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.
Should not be passed if has already been passed in ``fit``.
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 use in prediction.
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 reference.
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, if not already passed in fit
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", i.e., ``self.is_fitted=True``.
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.
Should not be passed if has already been passed in ``fit``.
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 use in prediction.
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 reference.
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 and conversions
# check fh and coerce to ForecastingHorizon, if not already passed in fit
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", i.e., ``self.is_fitted=True``.
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.
Should not be passed if has already been passed in ``fit``.
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 use in prediction.
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 reference.
marginal : bool, optional (default=True)
whether returned distribution is marginal by time index
Returns
-------
pred_dist : sktime BaseDistribution
predictive distribution
if marginal=True, will be marginal distribution by time point
if marginal=False and implemented by method, will be joint
"""
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."
)
if hasattr(self, "_is_vectorized") and self._is_vectorized:
raise NotImplementedError(
"automated vectorization for predict_proba is not implemented"
)
self.check_is_fitted()
# input checks and conversions
# check fh and coerce to ForecastingHorizon, if not already passed in fit
fh = self._check_fh(fh)
# check and convert X
X_inner = self._check_X(X=X)
# pass to inner _predict_proba
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", i.e., ``self.is_fitted=True``.
Accesses in self:
* Fitted model attributes ending in "_".
* ``self.cutoff``, ``self.is_fitted``
Writes to self:
* Updates ``self.cutoff`` to latest 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 with which to update the forecaster.
Individual data formats in ``sktime`` are so-called :term:`mtype`
specifications, each mtype implements an abstract :term:`scitype`.
* ``Series`` scitype = individual time series, vanilla forecasting.
``pd.DataFrame``, ``pd.Series``, or ``np.ndarray`` (1D or 2D)
* ``Panel`` scitype = collection of time series, global/panel forecasting.
``pd.DataFrame`` with 2-level row ``MultiIndex`` ``(instance, time)``,
``3D np.ndarray`` ``(instance, variable, time)``,
``list`` of ``Series`` typed ``pd.DataFrame``
* ``Hierarchical`` scitype = hierarchical collection, for
hierarchical forecasting. ``pd.DataFrame`` with 3 or more level row
``MultiIndex`` ``(hierarchy_1, ..., hierarchy_n, time)``
For further details on data format, see glossary on :term:`mtype`.
For usage, see forecasting tutorial ``examples/01_forecasting.ipynb``
X : time series in ``sktime`` compatible format, optional (default=None).
Exogeneous time series to update the model fit with
Should be of same :term:`scitype` (``Series``, ``Panel``,
or ``Hierarchical``) as ``y``.
If ``self.get_tag("X-y-must-have-same-index")``,
``X.index`` must contain ``y.index``.
update_params : bool, optional (default=True)
whether model parameters should be updated.
If ``False``, only the cutoff is updated, model parameters
(e.g., coefficients) are not updated.
Returns
-------
self : reference to self
"""
self.check_is_fitted()
if y is None or (hasattr(y, "__len__") and len(y) == 0):
warn(
f"empty y passed to update of {self}, no update was carried out",
obj=self,
)
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
if not self._is_vectorized:
self._update(y=y_inner, X=X_inner, update_params=update_params)
else:
self._vectorize("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,
reset_forecaster=True,
):
"""Make predictions and update model iteratively over the test set.
Shorthand to carry out chain of multiple ``update`` / ``predict``
executions, with data playback based on temporal splitter ``cv``.
Same as the following (if only ``y``, ``cv`` are non-default):
1. ``self.update(y=cv.split_series(y)[0][0])``
2. remember ``self.predict()`` (return later in single batch)
3. ``self.update(y=cv.split_series(y)[1][0])``
4. remember ``self.predict()`` (return later in single batch)
5. etc
6. return all remembered predictions
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", i.e., ``self.is_fitted=True``.
Accesses in self:
* Fitted model attributes ending in "_".
* ``self.cutoff``, ``self.is_fitted``
Writes to self (unless ``reset_forecaster=True``):
* Updates ``self.cutoff`` to latest index seen in ``y``.
* If ``update_params=True``, updates fitted model attributes ending in "_".
Does not update state if ``reset_forecaster=True``.