-
Notifications
You must be signed in to change notification settings - Fork 465
/
forecaster.py
2931 lines (2626 loc) · 125 KB
/
forecaster.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
import time
from collections import OrderedDict
import numpy as np
import pandas as pd
import torch
from torch.utils.data import DataLoader
import logging
from tqdm import tqdm
from neuralprophet import configure
from neuralprophet import time_net
from neuralprophet import time_dataset
from neuralprophet import df_utils
from neuralprophet import utils
from neuralprophet.plot_forecast import plot, plot_components
from neuralprophet.plot_forecast_plotly import plot as plot_plotly, plot_components as plot_components_plotly
from neuralprophet.plot_model_parameters_plotly import plot_parameters as plot_parameters_plotly
from neuralprophet.plot_model_parameters import plot_parameters
from neuralprophet import metrics
log = logging.getLogger("NP.forecaster")
METRICS = {
"mae": metrics.MAE,
"mse": metrics.MSE,
"rmse": metrics.RMSE,
}
class NeuralProphet:
"""NeuralProphet forecaster.
A simple yet powerful forecaster that models:
Trend, seasonality, events, holidays, auto-regression, lagged covariates, and future-known regressors.
Can be regularized and configured to model nonlinear relationships.
Parameters
----------
COMMENT
Trend Config
COMMENT
growth : {'off' or 'linear'}, default 'linear'
Set use of trend growth type.
Options:
* ``off``: no trend.
* (default) ``linear``: fits a piece-wise linear trend with ``n_changepoints + 1`` segments
* ``discontinuous``: For advanced users only - not a conventional trend,
allows arbitrary jumps at each trend changepoint
changepoints : {list of str, list of np.datetimes or np.array of np.datetimes}, optional
Manually set dates at which to include potential changepoints.
Note
----
Does not accept ``np.array`` of ``np.str``. If not specified, potential changepoints are selected automatically.
n_changepoints : int
Number of potential trend changepoints to include.
Note
----
Changepoints are selected uniformly from the first ``changepoint_range`` proportion of the history.
Ignored if manual ``changepoints`` list is supplied.
changepoints_range : float
Proportion of history in which trend changepoints will be estimated.
e.g. set to 0.8 to allow changepoints only in the first 80% of training data.
Ignored if manual ``changepoints`` list is supplied.
trend_reg : float, optional
Parameter modulating the flexibility of the automatic changepoint selection.
Note
----
Large values (~1-100) will limit the variability of changepoints.
Small values (~0.001-1.0) will allow changepoints to change faster.
default: 0 will fully fit a trend to each segment.
trend_reg_threshold : bool, optional
Allowance for trend to change without regularization.
Options
* ``True``: Automatically set to a value that leads to a smooth trend.
* (default) ``False``: All changes in changepoints are regularized
COMMENT
Seasonality Config
COMMENT
yearly_seasonality : bool, int
Fit yearly seasonality.
Options
* ``True`` or ``False``
* ``auto``: set automatically
* ``value``: number of Fourier/linear terms to generate
weekly_seasonality : bool, int
Fit monthly seasonality.
Options
* ``True`` or ``False``
* ``auto``: set automatically
* ``value``: number of Fourier/linear terms to generate
daily_seasonality : bool, int
Fit daily seasonality.
Options
* ``True`` or ``False``
* ``auto``: set automatically
* ``value``: number of Fourier/linear terms to generate
seasonality_mode : str
Specifies mode of seasonality
Options
* (default) ``additive``
* ``multiplicative``
seasonality_reg : float, optional
Parameter modulating the strength of the seasonality model.
Note
----
Smaller values (~0.1-1) allow the model to fit larger seasonal fluctuations,
larger values (~1-100) dampen the seasonality.
default: None, no regularization
COMMENT
AR Config
COMMENT
n_lags : int
Previous time series steps to include in auto-regression. Aka AR-order
ar_reg : float, optional
how much sparsity to induce in the AR-coefficients
Note
----
Large values (~1-100) will limit the number of nonzero coefficients dramatically.
Small values (~0.001-1.0) will allow more non-zero coefficients.
default: 0 no regularization of coefficients.
COMMENT
Model Config
COMMENT
n_forecasts : int
Number of steps ahead of prediction time step to forecast.
num_hidden_layers : int, optional
number of hidden layer to include in AR-Net (defaults to 0)
d_hidden : int, optional
dimension of hidden layers of the AR-Net. Ignored if ``num_hidden_layers`` == 0.
COMMENT
Train Config
COMMENT
learning_rate : float
Maximum learning rate setting for 1cycle policy scheduler.
Note
----
Default ``None``: Automatically sets the ``learning_rate`` based on a learning rate range test.
For manual user input, (try values ~0.001-10).
epochs : int
Number of epochs (complete iterations over dataset) to train model.
Note
----
Default ``None``: Automatically sets the number of epochs based on dataset size.
For best results also leave batch_size to None. For manual values, try ~5-500.
batch_size : int
Number of samples per mini-batch.
If not provided, ``batch_size`` is approximated based on dataset size.
For manual values, try ~8-1024.
For best results also leave ``epochs`` to ``None``.
newer_samples_weight: float, default 2.0
Sets factor by which the model fit is skewed towards more recent observations.
Controls the factor by which final samples are weighted more compared to initial samples.
Applies a positional weighting to each sample's loss value.
e.g. ``newer_samples_weight = 2``: final samples are weighted twice as much as initial samples.
newer_samples_start: float, default 0.0
Sets beginning of 'newer' samples as fraction of training data.
Throughout the range of 'newer' samples, the weight is increased
from ``1.0/newer_samples_weight`` initially to 1.0 at the end,
in a monotonously increasing function (cosine from pi to 2*pi).
loss_func : str, torch.nn.functional.loss
Type of loss to use:
Options
* (default) ``Huber``: Huber loss function
* ``MSE``: Mean Squared Error loss function
* ``MAE``: Mean Absolute Error loss function
* ``torch.nn.functional.loss.``: loss or callable for custom loss, eg. L1-Loss
Examples
--------
>>> from neuralprophet import NeuralProphet
>>> import torch
>>> import torch.nn as nn
>>> m = NeuralProphet(loss_func=torch.nn.L1Loss)
collect_metrics : list of str, bool
Set metrics to compute.
Options
* (default) ``True``: [``mae``, ``rmse``]
* ``False``: No metrics
* ``list``: Valid options: [``mae``, ``rmse``, ``mse``]
Examples
--------
>>> from neuralprophet import NeuralProphet
>>> m = NeuralProphet(collect_metrics=["MSE", "MAE", "RMSE"])
COMMENT
Uncertainty Estimation
COMMENT
uncertainty_method : str, default ``auto``
Specifies the type of uncertainty estimation technique that is being deployed
Options
* (default) ``auto``: Automatically infers the uncertainty estimation technique based on the prediction interval or quantiles params.
* ``quantile_regression``: Requires the quantiles to be specified while leaving prediction_interval as None.
Examples
--------
>>> from neuralprophet import NeuralProphet
>>> m = NeuralProphet(uncertainty_method="quantile_regression", quantiles=[0.05, 0.95])
prediction_interval : float, default None
Width of the uncertainty or confidence intervals provided for the forecast. Must be between (0, 1).
quantiles : list, default None
A list of float values between (0, 1) which indicate the set of quantiles to be estimated.
COMMENT
Missing Data
COMMENT
impute_missing : bool
whether to automatically impute missing dates/values
Note
----
imputation follows a linear method up to 20 missing values, more are filled with trend.
impute_linear : int
maximal number of missing dates/values to be imputed linearly (default: ``10``)
impute_rolling : int
maximal number of missing dates/values to be imputed
using rolling average (default: ``10``)
drop_missing : bool
whether to automatically drop missing samples from the data
Options
* (default) ``False``: Samples containing NaN values are not dropped.
* ``True``: Any sample containing at least one NaN value will be dropped.
COMMENT
Data Normalization
COMMENT
normalize : str
Type of normalization to apply to the time series.
Options
* ``off`` bypasses data normalization
* (default, binary timeseries) ``minmax`` scales the minimum value to 0.0 and the maximum value to 1.0
* ``standardize`` zero-centers and divides by the standard deviation
* (default) ``soft`` scales the minimum value to 0.0 and the 95th quantile to 1.0
* ``soft1`` scales the minimum value to 0.1 and the 90th quantile to 0.9
global_normalization : bool
Activation of global normalization
Options
* ``True``: dict of dataframes is used as global_time_normalization
* (default) ``False``: local normalization
global_time_normalization (bool):
Specifies global time normalization
Options
* (default) ``True``: only valid in case of global modeling local normalization
* ``False``: set time data_params locally
unknown_data_normalization : bool
Specifies unknown data normalization
Options
* ``True``: test data is normalized with global data params even if trained with local data params (global modeling with local normalization)
* (default) ``False``: no global modeling with local normalization
"""
def __init__(
self,
growth="linear",
changepoints=None,
n_changepoints=10,
changepoints_range=0.9,
trend_reg=0,
trend_reg_threshold=False,
yearly_seasonality="auto",
weekly_seasonality="auto",
daily_seasonality="auto",
seasonality_mode="additive",
seasonality_reg=0,
n_forecasts=1,
n_lags=0,
num_hidden_layers=0,
d_hidden=None,
ar_reg=None,
learning_rate=None,
epochs=None,
batch_size=None,
loss_func="Huber",
optimizer="AdamW",
newer_samples_weight=2,
newer_samples_start=0.0,
uncertainty_method="auto",
prediction_interval=None,
quantiles=None,
impute_missing=True,
impute_linear=10,
impute_rolling=10,
drop_missing=False,
collect_metrics=True,
normalize="auto",
global_normalization=False,
global_time_normalization=True,
unknown_data_normalization=False,
):
kwargs = locals()
print(kwargs)
# General
self.name = "NeuralProphet"
self.n_forecasts = n_forecasts
# Data Normalization settings
self.config_normalization = configure.Normalization(
normalize=normalize,
global_normalization=global_normalization,
global_time_normalization=global_time_normalization,
unknown_data_normalization=unknown_data_normalization,
)
# Missing Data Preprocessing
self.config_missing = configure.from_kwargs(configure.MissingDataHandling, kwargs)
# Training
self.config_train = configure.from_kwargs(configure.Train, kwargs)
if len(self.config_train.quantiles) > 1:
loss = metrics.LossMetric(self.config_train.loss_func.loss_func)
else:
loss = metrics.LossMetric(self.config_train.loss_func)
if collect_metrics is None:
collect_metrics = []
elif collect_metrics is True:
collect_metrics = ["mae", "rmse"]
elif isinstance(collect_metrics, str):
if not collect_metrics.lower() in METRICS.keys():
raise ValueError("Received unsupported argument for collect_metrics.")
collect_metrics = [collect_metrics]
elif isinstance(collect_metrics, list):
if not all([m.lower() in METRICS.keys() for m in collect_metrics]):
raise ValueError("Received unsupported argument for collect_metrics.")
elif collect_metrics is not False:
raise ValueError("Received unsupported argument for collect_metrics.")
self.metrics = None
if isinstance(collect_metrics, list):
self.metrics = metrics.MetricsCollection(
metrics=[loss] + [METRICS[m.lower()]() for m in collect_metrics],
value_metrics=[metrics.ValueMetric("Loss"), metrics.ValueMetric("RegLoss")],
)
# AR
self.config_ar = configure.from_kwargs(configure.AR, kwargs)
self.n_lags = self.config_ar.n_lags
self.max_lags = self.n_lags
# Model
self.config_model = configure.from_kwargs(configure.Model, kwargs)
# Trend
self.config_trend = configure.from_kwargs(configure.Trend, kwargs)
# Seasonality
self.config_season = configure.AllSeason(
mode=seasonality_mode,
reg_lambda=seasonality_reg,
yearly_arg=yearly_seasonality,
weekly_arg=weekly_seasonality,
daily_arg=daily_seasonality,
)
self.config_train.reg_lambda_season = self.config_season.reg_lambda
# Events
self.config_events = None
self.config_country_holidays = None
# Extra Regressors
self.config_covar = None
self.config_regressors = None
# set during fit()
self.data_freq = None
# Set during _train()
self.fitted = False
self.data_params = None
self.optimizer = None
self.scheduler = None
self.model = None
# set during prediction
self.future_periods = None
# later set by user (optional)
self.highlight_forecast_step_n = None
self.true_ar_weights = None
def add_lagged_regressor(self, names, n_lags="auto", regularization=None, normalize="auto"):
"""Add a covariate or list of covariate time series as additional lagged regressors to be used for fitting and predicting.
The dataframe passed to ``fit`` and ``predict`` will have the column with the specified name to be used as
lagged regressor. When normalize=True, the covariate will be normalized unless it is binary.
Parameters
----------
names : string or list
name of the regressor/list of regressors.
n_lags : int
previous regressors time steps to use as input in the predictor (covar order)
if ``auto``, time steps will be equivalent to the AR order (default)
if ``scalar``, all the regressors will only use last known value as input
regularization : float
optional scale for regularization strength
normalize : bool
optional, specify whether this regressor will benormalized prior to fitting.
if ``auto``, binary regressors will not be normalized.
"""
if n_lags == 0 or n_lags is None:
n_lags = 0
log.warning(
"Please, set n_lags to a value greater than 0 or to the options 'scalar' or 'auto'. No lags will be added to regressors when n_lags = 0 or n_lags is None"
)
if n_lags == "auto":
if self.n_lags is not None and self.n_lags > 0:
n_lags = self.n_lags
log.info(
"n_lags = 'auto', number of lags for regressor is set to Autoregression number of lags ({})".format(
self.n_lags
)
)
else:
n_lags = 1
log.info(
"n_lags = 'auto', but there is no lags for Autoregression. Number of lags for regressor is automatically set to 1"
)
if n_lags == "scalar":
n_lags = 1
log.info("n_lags = 'scalar', number of lags for regressor is set to 1")
only_last_value = False if n_lags > 1 else True
if self.fitted:
raise Exception("Regressors must be added prior to model fitting.")
if not isinstance(names, list):
names = [names]
for name in names:
self._validate_column_name(name)
if self.config_covar is None:
self.config_covar = OrderedDict({})
self.config_covar[name] = configure.Covar(
reg_lambda=regularization,
normalize=normalize,
as_scalar=only_last_value,
n_lags=n_lags,
)
return self
def add_future_regressor(self, name, regularization=None, normalize="auto", mode="additive"):
"""Add a regressor as lagged covariate with order 1 (scalar) or as known in advance (also scalar).
The dataframe passed to :meth:`fit` and :meth:`predict` will have a column with the specified name to be used as
a regressor. When normalize=True, the regressor will be normalized unless it is binary.
Note
----
Future Regressors have to be known for the entire forecast horizon, e.g. ``n_forecasts`` into the future.
Parameters
----------
name : string
name of the regressor.
regularization : float
optional scale for regularization strength
normalize : bool
optional, specify whether this regressor will be normalized prior to fitting.
Note
----
if ``auto``, binary regressors will not be normalized.
mode : str
``additive`` (default) or ``multiplicative``.
"""
if self.fitted:
raise Exception("Regressors must be added prior to model fitting.")
if regularization is not None:
if regularization < 0:
raise ValueError("regularization must be >= 0")
if regularization == 0:
regularization = None
self._validate_column_name(name)
if self.config_regressors is None:
self.config_regressors = {}
self.config_regressors[name] = configure.Regressor(reg_lambda=regularization, normalize=normalize, mode=mode)
return self
def add_events(self, events, lower_window=0, upper_window=0, regularization=None, mode="additive"):
"""
Add user specified events and their corresponding lower, upper windows and the
regularization parameters into the NeuralProphet object
Parameters
----------
events : str, list
name or list of names of user specified events
lower_window : int
the lower window for the events in the list of events
upper_window : int
the upper window for the events in the list of events
regularization : float
optional scale for regularization strength
mode : str
``additive`` (default) or ``multiplicative``.
"""
if self.fitted:
raise Exception("Events must be added prior to model fitting.")
if self.config_events is None:
self.config_events = OrderedDict({})
if regularization is not None:
if regularization < 0:
raise ValueError("regularization must be >= 0")
if regularization == 0:
regularization = None
if not isinstance(events, list):
events = [events]
for event_name in events:
self._validate_column_name(event_name)
self.config_events[event_name] = configure.Event(
lower_window=lower_window, upper_window=upper_window, reg_lambda=regularization, mode=mode
)
return self
def add_country_holidays(self, country_name, lower_window=0, upper_window=0, regularization=None, mode="additive"):
"""
Add a country into the NeuralProphet object to include country specific holidays
and create the corresponding configs such as lower, upper windows and the regularization
parameters
Holidays can only be added for a single country. Calling the function
multiple times will override already added country holidays.
Parameters
----------
country_name : string
name of the country
lower_window : int
the lower window for all the country holidays
upper_window : int
the upper window for all the country holidays
regularization : float
optional scale for regularization strength
mode : str
``additive`` (default) or ``multiplicative``.
"""
if self.fitted:
raise Exception("Country must be specified prior to model fitting.")
if self.config_country_holidays:
log.warning(
"Country holidays can only be added for a single country. Previous country holidays were overridden."
)
if regularization is not None:
if regularization < 0:
raise ValueError("regularization must be >= 0")
if regularization == 0:
regularization = None
self.config_country_holidays = configure.Holidays(
country=country_name,
lower_window=lower_window,
upper_window=upper_window,
reg_lambda=regularization,
mode=mode,
)
self.config_country_holidays.init_holidays()
return self
def add_seasonality(self, name, period, fourier_order):
"""Add a seasonal component with specified period, number of Fourier components, and regularization.
Increasing the number of Fourier components allows the seasonality to change more quickly
(at risk of overfitting).
Note: regularization and mode (additive/multiplicative) are set in the main init.
Parameters
----------
name : string
name of the seasonality component.
period : float
number of days in one period.
fourier_order : int
number of Fourier components to use.
"""
if self.fitted:
raise Exception("Seasonality must be added prior to model fitting.")
if name in ["daily", "weekly", "yearly"]:
log.error("Please use inbuilt daily, weekly, or yearly seasonality or set another name.")
# Do not Allow overwriting built-in seasonalities
self._validate_column_name(name, seasons=True)
if fourier_order <= 0:
raise ValueError("Fourier Order must be > 0")
self.config_season.append(name=name, period=period, resolution=fourier_order, arg="custom")
return self
def fit(self, df, freq="auto", validation_df=None, progress="bar", minimal=False):
"""Train, and potentially evaluate model.
Training/validation metrics may be distorted in case of auto-regression,
if a large number of NaN values are present in df and/or validation_df.
Parameters
----------
df : pd.DataFrame, dict (deprecated)
containing column ``ds``, ``y`` with all data
freq : str
Data step sizes. Frequency of data recording,
Note
----
Any valid frequency for pd.date_range, such as ``5min``, ``D``, ``MS`` or ``auto`` (default) to automatically set frequency.
validation_df : pd.DataFrame, dict
if provided, model with performance will be evaluated after each training epoch over this data.
epochs : int
number of epochs to train (overrides default setting).
default: if not specified, uses self.epochs
progress : str
Method of progress display
Options
* (default) ``bar`` display updating progress bar (tqdm)
* ``print`` print out progress (fallback option)
* ``plot`` plot a live updating graph of the training loss, requires [live] install or livelossplot package installed.
* ``plot-all`` extended to all recorded metrics.
minimal : bool
whether to train without any printouts or metrics collection
Returns
-------
pd.DataFrame
metrics with training and potentially evaluation metrics
"""
df, _, _, _ = df_utils.prep_or_copy_df(df)
if self.fitted is True:
log.error("Model has already been fitted. Re-fitting may break or produce different results.")
self.max_lags = df_utils.get_max_num_lags(self.config_covar, self.n_lags)
if self.max_lags == 0 and self.n_forecasts > 1:
self.n_forecasts = 1
log.warning(
"Changing n_forecasts to 1. Without lags, the forecast can be "
"computed for any future time, independent of lagged values"
)
df = self._check_dataframe(df, check_y=True, exogenous=True)
self.data_freq = df_utils.infer_frequency(df, n_lags=self.max_lags, freq=freq)
df = self._handle_missing_data(df, freq=self.data_freq)
if validation_df is not None and (self.metrics is None or minimal):
log.warning("Ignoring validation_df because no metrics set or minimal training set.")
validation_df = None
if validation_df is None:
if minimal:
self._train_minimal(df, progress_bar=progress == "bar")
metrics_df = None
else:
metrics_df = self._train(df, progress=progress)
else:
df_val, _, _, _ = df_utils.prep_or_copy_df(validation_df)
df_val = self._check_dataframe(df_val, check_y=False, exogenous=False)
df_val = self._handle_missing_data(df_val, freq=self.data_freq)
metrics_df = self._train(df, df_val=df_val, progress=progress)
self.fitted = True
return metrics_df
def predict(self, df, decompose=True, raw=False):
"""Runs the model to make predictions.
Expects all data needed to be present in dataframe.
If you are predicting into the unknown future and need to add future regressors or events,
please prepare data with make_future_dataframe.
Parameters
----------
df : pd.DataFrame, dict (deprecated)
dataframe or dict of dataframes containing column ``ds``, ``y`` with data
decompose : bool
whether to add individual components of forecast to the dataframe
raw : bool
specifies raw data
Options
* (default) ``False``: returns forecasts sorted by target (highlighting forecast age)
* ``True``: return the raw forecasts sorted by forecast start date
Returns
-------
pd.DataFrame
dependent on ``raw``
Note
----
``raw == True``: columns ``ds``, ``y``, and [``step<i>``] where step<i> refers to the i-step-ahead
prediction *made at* this row's datetime, e.g. step3 is the prediction for 3 steps into the future,
predicted using information up to (excluding) this datetime.
``raw == False``: columns ``ds``, ``y``, ``trend`` and [``yhat<i>``] where yhat<i> refers to
the i-step-ahead prediction for this row's datetime,
e.g. yhat3 is the prediction for this datetime, predicted 3 steps ago, "3 steps old".
"""
if raw:
log.warning("Raw forecasts are incompatible with plotting utilities")
if self.fitted is False:
raise ValueError("Model has not been fitted. Predictions will be random.")
df, received_ID_col, received_single_time_series, received_dict = df_utils.prep_or_copy_df(df)
# to get all forecasteable values with df given, maybe extend into future:
df, periods_added = self._maybe_extend_df(df)
df = self._prepare_dataframe_to_predict(df)
# normalize
df = self._normalize(df)
forecast = pd.DataFrame()
for df_name, df_i in df.groupby("ID"):
dates, predicted, components = self._predict_raw(df_i, df_name, include_components=decompose)
if raw:
fcst = self._convert_raw_predictions_to_raw_df(dates, predicted, components)
if periods_added[df_name] > 0:
fcst = fcst[:-1]
else:
fcst = self._reshape_raw_predictions_to_forecst_df(df_i, predicted, components)
if periods_added[df_name] > 0:
fcst = fcst[: -periods_added[df_name]]
forecast = pd.concat((forecast, fcst), ignore_index=True)
df = df_utils.return_df_in_original_format(
forecast, received_ID_col, received_single_time_series, received_dict
)
return df
def test(self, df):
"""Evaluate model on holdout data.
Parameters
----------
df : pd.DataFrame, dict (deprecated)
dataframe or dict of dataframes containing column ``ds``, ``y`` with with holdout data
Returns
-------
pd.DataFrame
evaluation metrics
"""
df, _, _, _ = df_utils.prep_or_copy_df(df)
if self.fitted is False:
log.warning("Model has not been fitted. Test results will be random.")
df = self._check_dataframe(df, check_y=True, exogenous=True)
_ = df_utils.infer_frequency(df, n_lags=self.max_lags, freq=self.data_freq)
df = self._handle_missing_data(df, freq=self.data_freq)
loader = self._init_val_loader(df)
val_metrics_df = self._evaluate(loader)
if not self.config_normalization.global_normalization:
log.warning("Note that the metrics are displayed in normalized scale because of local normalization.")
return val_metrics_df
def split_df(self, df, freq="auto", valid_p=0.2, local_split=False):
"""Splits timeseries df into train and validation sets.
Prevents leakage of targets. Sharing/Overbleed of inputs can be configured.
Also performs basic data checks and fills in missing data, unless impute_missing is set to ``False``.
Parameters
----------
df : pd.DataFrame, dict (deprecated)
dataframe or dict of dataframes containing column ``ds``, ``y`` with all data
freq : str
data step sizes. Frequency of data recording,
Note
----
Any valid frequency for pd.date_range, such as ``5min``, ``D``, ``MS`` or ``auto`` (default) to automatically set frequency.
valid_p : float
fraction of data to use for holdout validation set, targets will still never be shared.
local_split : bool
Each dataframe will be split according to valid_p locally (in case of dict of dataframes
Returns
-------
tuple of two pd.DataFrames
training data
validation data
See Also
--------
crossvalidation_split_df : Splits timeseries data in k folds for crossvalidation.
double_crossvalidation_split_df : Splits timeseries data in two sets of k folds for crossvalidation on training and testing data.
Examples
--------
>>> df1 = pd.DataFrame({'ds': pd.date_range(start = '2022-12-01', periods = 5,
... freq='D'), 'y': [9.59, 8.52, 8.18, 8.07, 7.89]})
>>> df2 = pd.DataFrame({'ds': pd.date_range(start = '2022-12-09', periods = 5,
... freq='D'), 'y': [8.71, 8.09, 7.84, 7.65, 8.02]})
>>> df3 = pd.DataFrame({'ds': pd.date_range(start = '2022-12-09', periods = 5,
... freq='D'), 'y': [7.67, 7.64, 7.55, 8.25, 8.3]})
>>> df3
ds y
0 2022-12-09 7.67
1 2022-12-10 7.64
2 2022-12-11 7.55
3 2022-12-12 8.25
4 2022-12-13 8.30
One can define a dict with many time series.
>>> df_dict = {'data1': df1, 'data2': df2, 'data3': df3}
You can split a single dataframe, which also may contain NaN values.
Please be aware this may affect training/validation performance.
>>> (df_train, df_val) = m.split_df(df3, valid_p=0.2)
>>> df_train
ds y
0 2022-12-09 7.67
1 2022-12-10 7.64
2 2022-12-11 7.55
3 2022-12-12 8.25
>>> df_val
ds y
0 2022-12-13 8.3
You can also use a dict of dataframes (especially useful for global modeling), which will account for the time range of the whole group of time series as default.
>>> (df_dict_train, df_dict_val) = m.split_df(df_dict, valid_p = 0.2)
>>> df_dict_train
{'data1': ds y
0 2022-12-01 9.59
1 2022-12-02 8.52
2 2022-12-03 8.18
3 2022-12-04 8.07
4 2022-12-05 7.89,
'data2': ds y
0 2022-12-09 8.71
1 2022-12-10 8.09
2 2022-12-11 7.84,
'data3': ds y
0 2022-12-09 7.67
1 2022-12-10 7.64
2 2022-12-11 7.55}
>>> df_dict_val
{'data2': ds y
0 2022-12-12 7.65
1 2022-12-13 8.02,
'data3': ds y
0 2022-12-12 8.25
1 2022-12-13 8.30}
In some applications, splitting locally each time series may be helpful. In this case, one should set `local_split` to True.
>>> (df_dict_train, df_dict_val) = m.split_df(df_dict, valid_p = 0.2,
... local_split = True)
>>> df_dict_train
{'data1': ds y
0 2022-12-01 9.59
1 2022-12-02 8.52
2 2022-12-03 8.18
3 2022-12-04 8.07,
'data2': ds y
0 2022-12-09 8.71
1 2022-12-10 8.09
2 2022-12-11 7.84
3 2022-12-12 7.65,
'data3': ds y
0 2022-12-09 7.67
1 2022-12-10 7.64
2 2022-12-11 7.55
3 2022-12-12 8.25}
>>> df_dict_val
{'data1': ds y
0 2022-12-05 7.89,
'data2': ds y
0 2022-12-13 8.02,
'data3': ds y
0 2022-12-13 8.3}
"""
df, received_ID_col, received_single_time_series, received_dict = df_utils.prep_or_copy_df(df)
df = self._check_dataframe(df, check_y=False, exogenous=False)
freq = df_utils.infer_frequency(df, n_lags=self.max_lags, freq=freq)
df = self._handle_missing_data(df, freq=freq, predicting=False)
df_train, df_val = df_utils.split_df(
df,
n_lags=self.max_lags,
n_forecasts=self.n_forecasts,
valid_p=valid_p,
inputs_overbleed=True,
local_split=local_split,
)
df_train = df_utils.return_df_in_original_format(
df_train, received_ID_col, received_single_time_series, received_dict
)
df_val = df_utils.return_df_in_original_format(
df_val, received_ID_col, received_single_time_series, received_dict
)
return df_train, df_val
def crossvalidation_split_df(
self, df, freq="auto", k=5, fold_pct=0.1, fold_overlap_pct=0.5, global_model_cv_type="global-time"
):
"""Splits timeseries data in k folds for crossvalidation.
Parameters
----------
df : pd.DataFrame, dict (deprecated)
dataframe or dict of dataframes containing column ``ds``, ``y`` with all data
freq : str
data step sizes. Frequency of data recording,
Note
----
Any valid frequency for pd.date_range, such as ``5min``, ``D``, ``MS`` or ``auto`` (default) to automatically set frequency.
k : int
number of CV folds
fold_pct : float
percentage of overall samples to be in each fold
fold_overlap_pct : float
percentage of overlap between the validation folds.
global_model_cv_type : str
Type of crossvalidation to apply to the dict of time series.
options:
``global-time`` (default) crossvalidation is performed according to a timestamp threshold.
``local`` each episode will be crossvalidated locally (may cause time leakage among different episodes)
``intersect`` only the time intersection of all the episodes will be considered. A considerable amount of data may not be used. However, this approach guarantees an equal number of train/test samples for each episode.
Returns
-------
list of k tuples [(df_train, df_val), ...]
training data
validation data
See Also
--------
split_df : Splits timeseries df into train and validation sets.
double_crossvalidation_split_df : Splits timeseries data in two sets of k folds for crossvalidation on training and testing data.
Examples
--------
>>> df1 = pd.DataFrame({'ds': pd.date_range(start = '2022-12-01', periods = 10, freq = 'D'),
... 'y': [9.59, 8.52, 8.18, 8.07, 7.89, 8.09, 7.84, 7.65, 8.71, 8.09]})
>>> df2 = pd.DataFrame({'ds': pd.date_range(start = '2022-12-02', periods = 10, freq = 'D'),
... 'y': [8.71, 8.09, 7.84, 7.65, 8.02, 8.52, 8.18, 8.07, 8.25, 8.30]})
>>> df3 = pd.DataFrame({'ds': pd.date_range(start = '2022-12-03', periods = 10, freq = 'D'),
... 'y': [7.67, 7.64, 7.55, 8.25, 8.32, 9.59, 8.52, 7.55, 8.25, 8.09]})
>>> df3
ds y
0 2022-12-03 7.67
1 2022-12-04 7.64
2 2022-12-05 7.55
3 2022-12-06 8.25
4 2022-12-07 8.32
5 2022-12-08 9.59
6 2022-12-09 8.52
7 2022-12-10 7.55
8 2022-12-11 8.25
9 2022-12-12 8.09
One can define a dict with many time series.
>>> df_dict = {'data1': df1, 'data2': df2, 'data3': df3}
You can create a fold for a single dataframe.
>>> fold = m.crossvalidation_split_df(df3, k = 2, fold_pct = 0.2)
>>> fold
[( ds y
0 2022-12-03 7.67
1 2022-12-04 7.64
2 2022-12-05 7.55
3 2022-12-06 8.25
4 2022-12-07 8.32
5 2022-12-08 9.59
6 2022-12-09 8.52,
ds y
0 2022-12-10 7.55
1 2022-12-11 8.25),
( ds y
0 2022-12-03 7.67