-
Notifications
You must be signed in to change notification settings - Fork 499
/
Copy pathdf_utils.py
1647 lines (1429 loc) · 60.3 KB
/
df_utils.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
from __future__ import annotations
import logging
import math
from collections import OrderedDict
from dataclasses import dataclass
from typing import TYPE_CHECKING, List, Optional, Tuple
import numpy as np
import pandas as pd
if TYPE_CHECKING:
from neuralprophet import configure_components
log = logging.getLogger("NP.df_utils")
@dataclass
class ShiftScale:
shift: float = 0.0
scale: float = 1.0
def check_multiple_series_id(df: pd.DataFrame) -> tuple[pd.DataFrame, bool, bool, list[str]]:
"""Copy df if it contains the ID column. Creates ID column with '__df__' if it is a df with a single time series.
Parameters
----------
df : pd.DataFrame
df or dict containing data
Returns
-------
pd.DataFrames
df with ID col
bool
whether the ID col was present
bool
wheter it is a single time series
list
list of IDs
"""
if not isinstance(df, pd.DataFrame):
raise ValueError("Provided DataFrame (df) must be of pd.DataFrame type.")
df_has_id_column = "ID" in df.columns
# If there is no ID column, then add one with a single value
if not df_has_id_column:
log.debug("Provided DataFrame (df) contains a single time series.")
df["ID"] = "__df__"
return df, df_has_id_column, True, ["__df__"]
# Create a list of unique ID values
unique_id_values = list(df["ID"].unique())
# Check if there is only one unique ID value
df_has_single_time_series = len(unique_id_values) == 1
num_time_series_id = len(unique_id_values)
log.debug(f"Provided DataFrame (df) has an ID column and contains {num_time_series_id} time series.")
return df, df_has_id_column, df_has_single_time_series, unique_id_values
def return_df_in_original_format(df, received_ID_col=False, received_single_time_series=True):
"""Return dataframe in the original format.
Parameters
----------
df : pd.DataFrame
df with data
received_ID_col : bool
whether the ID col was present
received_single_time_series: bool
wheter it is a single time series
Returns
-------
pd.Dataframe
original input format
"""
if not received_ID_col and received_single_time_series:
assert len(df["ID"].unique()) == 1
df.drop("ID", axis=1, inplace=True)
log.info("Returning df with no ID column")
return df
def merge_dataframes(df: pd.DataFrame) -> pd.DataFrame:
"""Join dataframes for procedures such as splitting data, set auto seasonalities, and others.
Parameters
----------
df : pd.DataFrame
containing column ``ds``, ``y``, and ``ID`` with data
Returns
-------
pd.Dataframe
Dataframe with concatenated time series (sorted 'ds', duplicates removed, index reset)
"""
if not isinstance(df, pd.DataFrame):
raise ValueError("Can not join other than pd.DataFrames")
if "ID" not in df.columns:
raise ValueError("df does not contain 'ID' column")
df_merged = df.drop("ID", axis=1)
df_merged = df_merged.sort_values("ds")
df_merged = df_merged.drop_duplicates(subset=["ds"])
df_merged = df_merged.reset_index(drop=True)
return df_merged
def data_params_definition(
df,
normalize,
config_lagged_regressors: Optional[configure_components.LaggedRegressors] = None,
config_regressors: Optional[configure_components.FutureRegressors] = None,
config_events: Optional[configure_components.Events] = None,
config_seasonality: Optional[configure_components.Seasonalities] = None,
local_run_despite_global: Optional[bool] = None,
):
"""
Initialize data scaling values.
Note
----
We do a z normalization on the target series ``y``,
unlike OG Prophet, which does shift by min and scale by max.
Parameters
----------
df : pd.DataFrame
Time series to compute normalization parameters from.
normalize : str
Type of normalization to apply to the time series.
options:
``soft`` (default), unless the time series is binary, in which case ``minmax`` is applied.
``off`` bypasses data normalization
``minmax`` scales the minimum value to 0.0 and the maximum value to 1.0
``standardize`` zero-centers and divides by the standard deviation
``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
config_lagged_regressors : configure_components.LaggedRegressors
Configurations for lagged regressors
normalize : bool
data normalization
config_regressors : configure_components.FutureRegressors
extra regressors (with known future values) with sub_parameters normalize (bool)
config_events : configure_components.Events
user specified events configs
config_seasonality : configure_components.Seasonalities
user specified seasonality configs
Returns
-------
OrderedDict
scaling values with ShiftScale entries containing ``shift`` and ``scale`` parameters.
"""
data_params = OrderedDict({})
if df["ds"].dtype == np.int64:
df["ds"] = df.loc[:, "ds"].astype(str)
df["ds"] = pd.to_datetime(df.loc[:, "ds"])
data_params["ds"] = ShiftScale(
shift=df["ds"].min(),
scale=df["ds"].max() - df["ds"].min(),
)
if "y" in df:
data_params["y"] = get_normalization_params(
array=df["y"].values,
norm_type=normalize,
)
if config_lagged_regressors is not None and config_lagged_regressors.regressors is not None:
for covar in config_lagged_regressors.regressors.keys():
if covar not in df.columns:
raise ValueError(f"Lagged regressor {covar} not found in DataFrame.")
norm_type_lag = config_lagged_regressors.regressors[covar].normalize
if local_run_despite_global:
if len(df[covar].unique()) < 2:
norm_type_lag = "soft"
data_params[covar] = get_normalization_params(
array=df[covar].values,
norm_type=norm_type_lag,
)
if config_regressors is not None and config_regressors.regressors is not None:
for reg in config_regressors.regressors.keys():
if reg not in df.columns:
raise ValueError(f"Regressor {reg} not found in DataFrame.")
norm_type = config_regressors.regressors[reg].normalize
if local_run_despite_global:
if len(df[reg].unique()) < 2:
norm_type = "soft"
data_params[reg] = get_normalization_params(
array=df[reg].values,
norm_type=norm_type,
)
if config_events is not None:
for event in config_events.keys():
if event not in df.columns:
raise ValueError(f"Event {event} not found in DataFrame.")
data_params[event] = ShiftScale()
if config_seasonality is not None:
for season in config_seasonality.periods:
condition_name = config_seasonality.periods[season].condition_name
if condition_name is not None:
if condition_name not in df.columns:
raise ValueError(f"Seasonality condition {condition_name} not found in DataFrame.")
data_params[condition_name] = ShiftScale()
return data_params
def init_data_params(
df,
normalize="auto",
config_lagged_regressors: Optional[configure_components.LaggedRegressors] = None,
config_regressors: Optional[configure_components.FutureRegressors] = None,
config_events: Optional[configure_components.Events] = None,
config_seasonality: Optional[configure_components.Seasonalities] = None,
global_normalization=False,
global_time_normalization=False,
):
"""Initialize data scaling values.
Note
----
We compute and store local and global normalization parameters independent of settings.
Parameters
----------
df : pd.DataFrame
data to compute normalization parameters from.
normalize : str
Type of normalization to apply to the time series.
options:
``soft`` (default), unless the time series is binary, in which case ``minmax`` is applied.
``off`` bypasses data normalization
``minmax`` scales the minimum value to 0.0 and the maximum value to 1.0
``standardize`` zero-centers and divides by the standard deviation
``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
config_lagged_regressors : configure_components.LaggedRegressors
Configurations for lagged regressors
config_regressors : configure_components.FutureRegressors
extra regressors (with known future values)
config_events : configure_components.Events
user specified events configs
config_seasonality : configure_components.Seasonalities
user specified seasonality configs
global_normalization : bool
``True``: sets global modeling training with global normalization
``False``: sets global modeling training with local normalization
global_time_normalization : bool
``True``: normalize time globally across all time series
``False``: normalize time locally for each time series
(only valid in case of global modeling - local normalization)
Returns
-------
OrderedDict
nested dict with data_params for each dataset where each contains
OrderedDict
ShiftScale entries containing ``shift`` and ``scale`` parameters for each column
"""
# Compute Global data params
global_data_params = data_params_definition(
df, normalize, config_lagged_regressors, config_regressors, config_events, config_seasonality
)
if global_normalization:
log.debug(
f"Global Normalization Data Parameters (shift, scale): {[(k, v) for k, v in global_data_params.items()]}"
)
# Compute individual data params
local_data_params = OrderedDict()
local_run_despite_global = True if global_normalization else None
for df_name, df_i in df.groupby("ID"):
local_data_params[df_name] = data_params_definition(
df=df_i,
normalize=normalize,
config_lagged_regressors=config_lagged_regressors,
config_regressors=config_regressors,
config_events=config_events,
config_seasonality=config_seasonality,
local_run_despite_global=local_run_despite_global,
)
if global_time_normalization:
# Overwrite local time normalization data_params with global values (pointer)
local_data_params[df_name]["ds"] = global_data_params["ds"]
if not global_normalization:
params = [(k, v) for k, v in local_data_params[df_name].items()]
log.debug(f"Local Normalization Data Parameters (shift, scale): {params}")
return local_data_params, global_data_params
def auto_normalization_setting(array):
if len(np.unique(array)) < 2:
raise ValueError("Encountered variable with singular value in training set. Please remove variable.")
# elif set(series.unique()) in ({True, False}, {1, 0}, {1.0, 0.0}, {-1, 1}, {-1.0, 1.0}):
elif len(np.unique(array)) == 2:
return "minmax" # Don't standardize binary variables.
else:
return "soft" # default setting
def get_normalization_params(array, norm_type):
if norm_type == "auto":
norm_type = auto_normalization_setting(array)
shift = 0.0
scale = 1.0
# FIX Issue#52
# Ignore NaNs (if any) in array for normalization
non_nan_array = array[~np.isnan(array)]
if norm_type == "soft":
lowest = np.min(non_nan_array)
q95 = np.quantile(non_nan_array, 0.95)
width = q95 - lowest
if math.isclose(width, 0):
width = np.max(non_nan_array) - lowest
shift = lowest
scale = width
elif norm_type == "soft1":
lowest = np.min(non_nan_array)
q90 = np.quantile(non_nan_array, 0.9)
width = q90 - lowest
if math.isclose(width, 0):
width = (np.max(non_nan_array) - lowest) / 1.25
shift = lowest - 0.125 * width
scale = 1.25 * width
elif norm_type == "minmax":
shift = np.min(non_nan_array)
scale = np.max(non_nan_array) - shift
elif norm_type == "standardize":
shift = np.mean(non_nan_array)
scale: float = np.std(non_nan_array) # type: ignore
elif norm_type != "off":
log.error(f"Normalization {norm_type} not defined.")
# END FIX
return ShiftScale(shift, scale)
def normalize(df, data_params):
"""
Applies data scaling factors to df using data_params.
Parameters
----------
df : pd.DataFrame
with columns ``ds``, ``y``, (and potentially more regressors)
data_params : OrderedDict
scaling values, as returned by init_data_params with ShiftScale entries containing ``shift`` and ``scale``
parameters
Returns
-------
pd.DataFrame
normalized dataframes
"""
for name in df.columns:
if name == "ID":
continue
if name not in data_params.keys():
raise ValueError(f"Unexpected column {name} in data")
new_name = name
if name == "ds":
new_name = "t"
if name == "y":
new_name = "y_scaled"
df[new_name] = df[name].sub(data_params[name].shift).div(data_params[name].scale)
return df
def check_dataframe(
df: pd.DataFrame,
check_y: bool = True,
covariates=None,
regressors=None,
events=None,
seasonalities=None,
future: Optional[bool] = None,
) -> Tuple[pd.DataFrame, List, List]:
"""Performs basic data sanity checks and ordering,
as well as prepare dataframe for fitting or predicting.
Parameters
----------
df : pd.DataFrame
containing column ``ds``
check_y : bool
if df must have series values
set to True if training or predicting with autoregression
covariates : list or dict
covariate column names
regressors : list or dict
regressor column names
events : list or dict
event column names
seasonalities : list or dict
seasonalities column names
future : bool
if df is a future dataframe
Returns
-------
pd.DataFrame or dict
checked dataframe
"""
# TODO: move call to check_multiple_series_id here
if df.groupby("ID").size().min() < 1:
raise ValueError("Dataframe has no rows.")
if "ds" not in df:
raise ValueError("Dataframe must have columns 'ds' with the dates.")
if df["ds"].isnull().any():
raise ValueError("Found NaN in column ds.")
if not np.issubdtype(df["ds"].to_numpy().dtype, np.datetime64):
df["ds"] = pd.to_datetime(df.loc[:, "ds"], utc=True).dt.tz_convert(None)
if df.groupby("ID").apply(lambda x: x.duplicated("ds").any()).any():
raise ValueError("Column ds has duplicate values. Please remove duplicates.")
regressors_to_remove = []
lag_regressors_to_remove = []
columns = []
if check_y:
columns.append("y")
if regressors is not None:
for reg in regressors:
if len(df[reg].unique()) < 2:
log.warning(
"Encountered future regressor with only unique values in training set across all IDs."
"Automatically removed variable."
)
regressors_to_remove.append(reg)
if isinstance(regressors, list):
columns.extend(regressors)
else: # treat as dict
columns.extend(regressors.keys())
if covariates is not None:
for covar in covariates:
if len(df[covar].unique()) < 2:
log.warning(
"Encountered lagged regressor with only unique values in training set across all IDs."
"Automatically removed variable."
)
lag_regressors_to_remove.append(covar)
if isinstance(covariates, list):
columns.extend(covariates)
else: # treat as dict
columns.extend(covariates.keys())
if events is not None:
if isinstance(events, list):
columns.extend(events)
else: # treat as dict
columns.extend(events.keys())
if seasonalities is not None:
for season in seasonalities.periods:
condition_name = seasonalities.periods[season].condition_name
if condition_name is not None:
if not df[condition_name].isin([True, False]).all() and not df[condition_name].between(0, 1).all():
raise ValueError(f"Condition column {condition_name} must be boolean or numeric between 0 and 1.")
columns.append(condition_name)
for name in columns:
if name not in df:
raise ValueError(f"Column {name!r} missing from dataframe")
if sum(df.loc[:, name].notnull().values) < 1:
raise ValueError(f"Dataframe column {name!r} only has NaN rows.")
if not np.issubdtype(df[name].dtype, np.number):
df[name] = pd.to_numeric(df[name])
if np.isinf(df.loc[:, name].values).any():
df.loc[:, name] = df[name].replace([np.inf, -np.inf], np.nan)
if future:
return df, regressors_to_remove, lag_regressors_to_remove
if len(regressors_to_remove) > 0:
regressors_to_remove = list(set(regressors_to_remove))
df = df.drop(regressors_to_remove, axis=1)
assert df is not None
if len(lag_regressors_to_remove) > 0:
lag_regressors_to_remove = list(set(lag_regressors_to_remove))
df = df.drop(lag_regressors_to_remove, axis=1)
assert df is not None
return df, regressors_to_remove, lag_regressors_to_remove
def _crossvalidation_split_df(df, n_lags, n_forecasts, k, fold_pct, fold_overlap_pct=0.0):
"""Splits data in k folds for crossvalidation.
Parameters
----------
df : pd.DataFrame
data
n_lags : int
identical to NeuralProphet
n_forecasts : int
identical to NeuralProphet
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 (default: 0.0)
Returns
-------
list of k tuples [(df_train, df_val), ...]
training data
validation data
"""
# Receives df with single ID column
assert len(df["ID"].unique()) == 1
if n_lags == 0:
assert n_forecasts == 1
total_samples = len(df) - n_lags + 2 - (2 * n_forecasts)
samples_fold = max(1, int(fold_pct * total_samples))
samples_overlap = int(fold_overlap_pct * samples_fold)
assert samples_overlap < samples_fold
min_train = total_samples - samples_fold - (k - 1) * (samples_fold - samples_overlap)
assert min_train >= samples_fold
folds = []
df_fold = df
for i in range(k, 0, -1):
df_train, df_val = split_df(df_fold, n_lags, n_forecasts, valid_p=samples_fold, inputs_overbleed=True)
folds.append((df_train, df_val))
split_idx = len(df_fold) - samples_fold + samples_overlap
df_fold = df_fold.iloc[:split_idx].reset_index(drop=True)
folds = folds[::-1]
return folds
def find_valid_time_interval_for_cv(df):
"""Find time interval of interception among all the time series from dict.
Parameters
----------
df : pd.DataFrame
data with column ``ds``, ``y``, and ``ID``
Returns
-------
str
time interval start
str
time interval end
"""
# Creates first time interval based on data from first key
time_interval_intersection = df[df["ID"] == df["ID"].iloc[0]]["ds"]
for df_name, df_i in df.groupby("ID"):
time_interval_intersection = pd.merge(time_interval_intersection, df_i, how="inner", on=["ds"])
time_interval_intersection = time_interval_intersection[["ds"]]
start_date = time_interval_intersection["ds"].iloc[0]
end_date = time_interval_intersection["ds"].iloc[-1]
return start_date, end_date
def unfold_dict_of_folds(folds_dict, k):
"""Convert dict of folds for typical format of folding of train and test data.
Parameters
----------
folds_dict : dict
dict of folds
k : int
number of folds initially set
Returns
-------
list of k tuples [(df_train, df_val), ...]
training data
validation data
"""
folds = []
df_train = pd.DataFrame()
df_test = pd.DataFrame()
for j in range(0, k):
for key in folds_dict:
assert k == len(folds_dict[key])
df_train = pd.concat((df_train, folds_dict[key][j][0]), ignore_index=True)
df_test = pd.concat((df_test, folds_dict[key][j][1]), ignore_index=True)
folds.append((df_train, df_test))
df_train = pd.DataFrame()
df_test = pd.DataFrame()
return folds
def _crossvalidation_with_time_threshold(df, n_lags, n_forecasts, k, fold_pct, fold_overlap_pct=0.0):
"""Splits data in k folds for crossvalidation accordingly to time threshold.
Parameters
----------
df : pd.DataFrame
data with column ``ds``, ``y``, and ``ID``
n_lags : int
identical to NeuralProphet
n_forecasts : int
identical to NeuralProphet
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 (default: 0.0)
Returns
-------
list of k tuples [(df_train, df_val), ...]
training data
validation data
"""
df_merged = merge_dataframes(df.copy(deep=True))
total_samples = len(df_merged) - n_lags + 2 - (2 * n_forecasts)
samples_fold = max(1, int(fold_pct * total_samples))
samples_overlap = int(fold_overlap_pct * samples_fold)
assert samples_overlap < samples_fold
min_train = total_samples - samples_fold - (k - 1) * (samples_fold - samples_overlap)
assert min_train >= samples_fold
folds = []
for i in range(k, 0, -1):
threshold_time_stamp = find_time_threshold(df, n_lags, n_forecasts, samples_fold, inputs_overbleed=True)
df_train, df_val = split_considering_timestamp(
df, n_lags, n_forecasts, inputs_overbleed=True, threshold_time_stamp=threshold_time_stamp
)
folds.append((df_train, df_val))
split_idx = len(df_merged) - samples_fold + samples_overlap
df_merged = df_merged[:split_idx].reset_index(drop=True)
threshold_time_stamp = df_merged["ds"].iloc[-1]
df_fold_aux = pd.DataFrame()
for df_name, df_i in df.groupby("ID"):
# df_i = df_i.copy(deep=True)
df_aux = df_i.iloc[: len(df_i[df_i["ds"] < threshold_time_stamp]) + 1].reset_index(drop=True)
df_fold_aux = pd.concat((df_fold_aux, df_aux), ignore_index=True)
df = df_fold_aux
# df = df.copy(deep=True)
folds = folds[::-1]
return folds
def crossvalidation_split_df(
df, n_lags, n_forecasts, k, fold_pct, fold_overlap_pct=0.0, global_model_cv_type="global-time"
):
"""Splits data in k folds for crossvalidation.
Parameters
----------
df : pd.DataFrame
data
n_lags : int
identical to NeuralProphet
n_forecasts : int
identical to NeuralProphet
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 (default: 0.0)
global_model_cv_type : str
Type of crossvalidation to apply to the time series.
options:
``global-time`` (default) crossvalidation is performed according to a time stamp 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
"""
df, _, _, _ = check_multiple_series_id(df)
folds = []
if len(df["ID"].unique()) == 1:
for df_name, df_i in df.groupby("ID"):
folds = _crossvalidation_split_df(df_i, n_lags, n_forecasts, k, fold_pct, fold_overlap_pct)
else:
if global_model_cv_type == "global-time" or global_model_cv_type is None:
# Use time threshold to perform crossvalidation
# (the distribution of data of different episodes may not be equivalent)
folds = _crossvalidation_with_time_threshold(df, n_lags, n_forecasts, k, fold_pct, fold_overlap_pct)
elif global_model_cv_type == "local":
# Crossvalidate time series locally (time leakage may be a problem)
folds_dict = {}
for df_name, df_i in df.groupby("ID"):
folds_dict[df_name] = _crossvalidation_split_df(
df_i, n_lags, n_forecasts, k, fold_pct, fold_overlap_pct
)
folds = unfold_dict_of_folds(folds_dict, k)
elif global_model_cv_type == "intersect":
# Use data only from the time period of intersection among time series
folds_dict = {}
# Check for intersection of time so time leakage does not occur among different time series
start_date, end_date = find_valid_time_interval_for_cv(df)
for df_name, df_i in df.groupby("ID"):
mask = (df_i["ds"] >= start_date) & (df_i["ds"] <= end_date)
df_i = df_i[mask]
folds_dict[df_name] = _crossvalidation_split_df(
df_i, n_lags, n_forecasts, k, fold_pct, fold_overlap_pct
)
folds = unfold_dict_of_folds(folds_dict, k)
else:
raise ValueError(
"Please choose a valid type of global model crossvalidation (i.e. global-time, local, or intersect)"
)
return folds
def double_crossvalidation_split_df(df, n_lags, n_forecasts, k, valid_pct, test_pct):
"""Splits data in two sets of k folds for crossvalidation on validation and test data.
Parameters
----------
df : pd.DataFrame
data
n_lags : int
identical to NeuralProphet
n_forecasts : int
identical to NeuralProphet
k : int
number of CV folds
valid_pct : float
percentage of overall samples to be in validation
test_pct : float
percentage of overall samples to be in test
Returns
-------
tuple of k tuples [(folds_val, folds_test), …]
elements same as :meth:`crossvalidation_split_df` returns
"""
if len(df["ID"].unique()) > 1:
raise NotImplementedError("double_crossvalidation_split_df not implemented for df with many time series")
fold_pct_test = float(test_pct) / k
folds_test = crossvalidation_split_df(df, n_lags, n_forecasts, k, fold_pct=fold_pct_test, fold_overlap_pct=0.0)
df_train = folds_test[0][0]
fold_pct_val = float(valid_pct) / k / (1.0 - test_pct)
folds_val = crossvalidation_split_df(df_train, n_lags, n_forecasts, k, fold_pct=fold_pct_val, fold_overlap_pct=0.0)
return folds_val, folds_test
def find_time_threshold(df, n_lags, n_forecasts, valid_p, inputs_overbleed):
"""Find time threshold for dividing timeseries into train and validation sets.
Prevents overbleed of targets. Overbleed of inputs can be configured.
Parameters
----------
df : pd.DataFrame
data with column ``ds``, ``y``, and ``ID``
n_lags : int
identical to NeuralProphet
valid_p : float
fraction (0,1) of data to use for holdout validation set
inputs_overbleed : bool
Whether to allow last training targets to be first validation inputs (never targets)
Returns
-------
str
time stamp threshold defines the boundary for the train and validation sets split.
"""
df_merged = merge_dataframes(df.copy(deep=True))
n_samples = len(df_merged) - n_lags + 2 - (2 * n_forecasts)
n_samples = n_samples if inputs_overbleed else n_samples - n_lags
if 0.0 < valid_p < 1.0:
n_valid = max(1, int(n_samples * valid_p))
else:
assert valid_p >= 1
assert isinstance(valid_p, int)
n_valid = valid_p
n_train = n_samples - n_valid
threshold_time_stamp = df_merged.loc[n_train, "ds"]
log.debug("Time threshold: ", threshold_time_stamp)
return threshold_time_stamp
def split_considering_timestamp(df, n_lags, n_forecasts, inputs_overbleed, threshold_time_stamp):
"""Splits timeseries into train and validation sets according to given threshold_time_stamp.
Parameters
----------
df : pd.DataFrame
data with column ``ds``, ``y``, and ``ID``
n_lags : int
identical to NeuralProphet
n_forecasts : int
identical to NeuralProphet
inputs_overbleed : bool
Whether to allow last training targets to be first validation inputs (never targets)
threshold_time_stamp : str
time stamp boundary that defines splitting of data
Returns
-------
pd.DataFrame, dict
training data
pd.DataFrame, dict
validation data
"""
df_train = pd.DataFrame()
df_val = pd.DataFrame()
for df_name, df_i in df.groupby("ID"):
if df[df["ID"] == df_name]["ds"].max() < threshold_time_stamp:
# df_i = df_i.copy(deep=True)
df_train = pd.concat((df_train, df_i), ignore_index=True)
elif df[df["ID"] == df_name]["ds"].min() > threshold_time_stamp:
# df_i = df_i.copy(deep=True)
df_val = pd.concat((df_val, df_i), ignore_index=True)
else:
df_aux = df_i
# df_i = df_i.copy(deep=True)
n_train = len(df_aux[df_aux["ds"] < threshold_time_stamp])
split_idx_train = n_train + n_lags + n_forecasts - 1
split_idx_val = split_idx_train - n_lags if inputs_overbleed else split_idx_train
df_train = pd.concat((df_train, df_aux.iloc[:split_idx_train]), ignore_index=True)
df_val = pd.concat((df_val, df_aux.iloc[split_idx_val:]), ignore_index=True)
return df_train, df_val
def split_df(
df: pd.DataFrame,
n_lags: int,
n_forecasts: int,
valid_p: float = 0.2,
inputs_overbleed: bool = True,
local_split: bool = False,
):
"""Splits timeseries df into train and validation sets.
Prevents overbleed of targets. Overbleed of inputs can be configured.
In case of global modeling the split could be either local or global.
Parameters
----------
df : pd.DataFrame
dataframe containing column ``ds``, ``y``, and optionally``ID`` with all data
n_lags : int
identical to NeuralProphet
n_forecasts : int
identical to NeuralProphet
valid_p : float, int
fraction (0,1) of data to use for holdout validation set, or number of validation samples >1
inputs_overbleed : bool
Whether to allow last training targets to be first validation inputs (never targets)
local_split : bool
when set to true, each episode from a dict of dataframes will be split locally
Returns
-------
pd.DataFrame, dict
training data
pd.DataFrame, dict
validation data
"""
df_train = pd.DataFrame()
df_val = pd.DataFrame()
if local_split:
n_samples = df.groupby("ID").size()
n_samples = n_samples - n_lags + 2 - (2 * n_forecasts)
n_samples = n_samples if inputs_overbleed else n_samples - n_lags
if 0.0 < valid_p < 1.0:
n_valid = n_samples.apply(lambda x: max(1, int(x * valid_p)))
else:
assert valid_p >= 1
assert isinstance(valid_p, int)
n_valid = valid_p
n_train = n_samples - n_valid
log.debug(f"{n_train} n_train, {n_samples - n_train} n_eval")
else:
# Split data according to time threshold defined by the valid_p
threshold_time_stamp = find_time_threshold(df, n_lags, n_forecasts, valid_p, inputs_overbleed)
n_train = df["ds"].groupby(df["ID"]).apply(lambda x: x[x < threshold_time_stamp].count())
assert n_train.min() > 1
split_idx_train = n_train + n_lags + n_forecasts - 1
split_idx_val = split_idx_train - n_lags if inputs_overbleed else split_idx_train
df_train = df.groupby("ID", group_keys=False).apply(lambda x: x.iloc[: split_idx_train[x.name]])
df_val = df.groupby("ID", group_keys=False).apply(lambda x: x.iloc[split_idx_val[x.name] :])
return df_train, df_val
def make_future_df(
df_columns,
last_date,
periods,
freq,
config_events: configure_components.Events,
config_regressors: configure_components.FutureRegressors,
events_df=None,
regressors_df=None,
):
"""Extends df periods number steps into future.
Parameters
----------
df_columns : pd.DataFrame
Dataframe columns
last_date : pd.Datetime
last history date
periods : int
number of future steps to predict
freq : str
Data step sizes. Frequency of data recording, any valid frequency
for pd.date_range, such as ``D`` or ``M``
config_events : configure_components.Events
User specified events configs
events_df : pd.DataFrame
containing column ``ds`` and ``event``
config_regressors : configure_components.FutureRegressors
configuration for user specified regressors,
regressors_df : pd.DataFrame
containing column ``ds`` and one column for each of the external regressors
Returns
-------
pd.DataFrame
input df with ``ds`` extended into future, and ``y`` set to None
"""
future_dates = pd.date_range(start=last_date, periods=periods + 1, freq=freq) # An extra in case we include start
future_dates = future_dates[future_dates > last_date] # Drop start if equals last_date
future_dates = future_dates[:periods] # Return correct number of periods
future_df = pd.DataFrame({"ds": future_dates})
# set the events features
if config_events is not None:
future_df = convert_events_to_features(future_df, config_events=config_events, events_df=events_df)
# set the regressors features
if config_regressors is not None and config_regressors.regressors is not None and regressors_df is not None:
for regressor in config_regressors.regressors.keys():
assert regressor in regressors_df.columns, f"Regressor {regressor} not found in regressors_df"
future_df[regressor] = regressors_df[regressor]
for column in df_columns:
if column not in future_df.columns:
if column != "t" and column != "y_scaled":
future_df[column] = None
future_df.reset_index(drop=True, inplace=True)
return future_df
def convert_events_to_features(df, config_events: configure_components.Events, events_df):
"""
Converts events information into binary features of the df
Parameters
----------
df : pd.DataFrame
Dataframe with columns ``ds`` datestamps and ``y`` time series values
config_events : configure_components.Events
User specified events configs
events_df : pd.DataFrame
containing column ``ds`` and ``event``
Returns
-------
pd.DataFrame
input df with columns for user_specified features
"""
for event in config_events.keys():
event_feature = pd.Series(0, index=range(df.shape[0]), dtype="float32")
# events_df may be None in case ID from original df is not provided in events df
if events_df is None:
dates = None
else:
dates = events_df[events_df.event == event].ds
df.reset_index(drop=True, inplace=True)
event_feature[df.ds.isin(dates)] = 1.0
df[event] = event_feature
return df