-
Notifications
You must be signed in to change notification settings - Fork 97
/
basics.py
1952 lines (1787 loc) · 75.5 KB
/
basics.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
"""
Naives and Others Requiring No Additional Packages Beyond Numpy and Pandas
"""
from math import ceil
import warnings
import random
import datetime
import numpy as np
import pandas as pd
from autots.models.base import ModelObject, PredictionObject
from autots.tools import seasonal_int
from autots.tools.probabilistic import Point_to_Probability, historic_quantile
from autots.tools.window_functions import window_id_maker
# optional requirement
try:
from scipy.spatial.distance import cdist
except Exception:
pass
class ZeroesNaive(ModelObject):
"""Naive forecasting predicting a dataframe of zeroes (0's)
Args:
name (str): String to identify class
frequency (str): String alias of datetime index frequency or else 'infer'
prediction_interval (float): Confidence interval for probabilistic forecast
"""
def __init__(
self,
name: str = "ZeroesNaive",
frequency: str = 'infer',
prediction_interval: float = 0.9,
holiday_country: str = 'US',
random_seed: int = 2020,
verbose: int = 0,
**kwargs
):
ModelObject.__init__(
self,
name,
frequency,
prediction_interval,
holiday_country=holiday_country,
random_seed=random_seed,
verbose=verbose,
)
def fit(self, df, future_regressor=None):
"""Train algorithm given data supplied
Args:
df (pandas.DataFrame): Datetime Indexed
"""
df = self.basic_profile(df)
self.fit_runtime = datetime.datetime.now() - self.startTime
return self
def predict(
self, forecast_length: int, future_regressor=None, just_point_forecast=False
):
"""Generates forecast data immediately following dates of index supplied to .fit()
Args:
forecast_length (int): Number of periods of data to forecast ahead
regressor (numpy.Array): additional regressor, not used
just_point_forecast (bool): If True, return a pandas.DataFrame of just point forecasts
Returns:
Either a PredictionObject of forecasts and metadata, or
if just_point_forecast == True, a dataframe of point forecasts
"""
predictStartTime = datetime.datetime.now()
df = pd.DataFrame(
np.zeros((forecast_length, (self.train_shape[1]))),
columns=self.column_names,
index=self.create_forecast_index(forecast_length=forecast_length),
)
if just_point_forecast:
return df
else:
predict_runtime = datetime.datetime.now() - predictStartTime
prediction = PredictionObject(
model_name=self.name,
forecast_length=forecast_length,
forecast_index=df.index,
forecast_columns=df.columns,
lower_forecast=df,
forecast=df,
upper_forecast=df,
prediction_interval=self.prediction_interval,
predict_runtime=predict_runtime,
fit_runtime=self.fit_runtime,
model_parameters=self.get_params(),
)
return prediction
def get_new_params(self, method: str = 'random'):
"""Returns dict of new parameters for parameter tuning"""
return {}
def get_params(self):
"""Return dict of current parameters"""
return {}
class LastValueNaive(ModelObject):
"""Naive forecasting predicting a dataframe of the last series value
Args:
name (str): String to identify class
frequency (str): String alias of datetime index frequency or else 'infer'
prediction_interval (float): Confidence interval for probabilistic forecast
"""
def __init__(
self,
name: str = "LastValueNaive",
frequency: str = 'infer',
prediction_interval: float = 0.9,
holiday_country: str = 'US',
random_seed: int = 2020,
**kwargs
):
ModelObject.__init__(
self,
name,
frequency,
prediction_interval,
holiday_country=holiday_country,
random_seed=random_seed,
)
def fit(self, df, future_regressor=None):
"""Train algorithm given data supplied
Args:
df (pandas.DataFrame): Datetime Indexed
"""
df = self.basic_profile(df)
self.last_values = df.tail(1).to_numpy()
# self.df_train = df
self.lower, self.upper = historic_quantile(
df, prediction_interval=self.prediction_interval
)
self.fit_runtime = datetime.datetime.now() - self.startTime
return self
def predict(
self, forecast_length: int, future_regressor=None, just_point_forecast=False
):
"""Generates forecast data immediately following dates of index supplied to .fit()
Args:
forecast_length (int): Number of periods of data to forecast ahead
regressor (numpy.Array): additional regressor, not used
just_point_forecast (bool): If True, return a pandas.DataFrame of just point forecasts
Returns:
Either a PredictionObject of forecasts and metadata, or
if just_point_forecast == True, a dataframe of point forecasts
"""
predictStartTime = datetime.datetime.now()
df = pd.DataFrame(
np.tile(self.last_values, (forecast_length, 1)),
columns=self.column_names,
index=self.create_forecast_index(forecast_length=forecast_length),
)
if just_point_forecast:
return df
else:
# upper_forecast, lower_forecast = Point_to_Probability(self.df_train, df, prediction_interval = self.prediction_interval, method = 'historic_quantile')
upper_forecast = df.astype(float) + (self.upper * 0.8)
lower_forecast = df.astype(float) - (self.lower * 0.8)
predict_runtime = datetime.datetime.now() - predictStartTime
prediction = PredictionObject(
model_name=self.name,
forecast_length=forecast_length,
forecast_index=df.index,
forecast_columns=df.columns,
lower_forecast=lower_forecast,
forecast=df,
upper_forecast=upper_forecast,
prediction_interval=self.prediction_interval,
predict_runtime=predict_runtime,
fit_runtime=self.fit_runtime,
model_parameters=self.get_params(),
)
return prediction
def get_new_params(self, method: str = 'random'):
"""Returns dict of new parameters for parameter tuning"""
return {}
def get_params(self):
"""Return dict of current parameters"""
return {}
class AverageValueNaive(ModelObject):
"""Naive forecasting predicting a dataframe of the series' median values
Args:
name (str): String to identify class
frequency (str): String alias of datetime index frequency or else 'infer'
prediction_interval (float): Confidence interval for probabilistic forecast
"""
def __init__(
self,
name: str = "AverageValueNaive",
frequency: str = 'infer',
prediction_interval: float = 0.9,
holiday_country: str = 'US',
random_seed: int = 2020,
verbose: int = 0,
method: str = 'Median',
**kwargs
):
ModelObject.__init__(
self,
name,
frequency,
prediction_interval,
holiday_country=holiday_country,
random_seed=random_seed,
verbose=verbose,
)
self.method = method
def fit(self, df, future_regressor=None):
"""Train algorithm given data supplied.
Args:
df (pandas.DataFrame): Datetime Indexed
"""
df = self.basic_profile(df)
method = str(self.method).lower()
if method == 'median':
self.average_values = df.median(axis=0).to_numpy()
elif method == 'mean':
self.average_values = df.mean(axis=0).to_numpy()
elif method == 'mode':
self.average_values = (
df.mode(axis=0).iloc[0].fillna(df.median(axis=0)).to_numpy()
)
elif method == "midhinge":
results = df.to_numpy()
q1 = np.nanquantile(results, q=0.25, axis=0)
q2 = np.nanquantile(results, q=0.75, axis=0)
self.average_values = (q1 + q2) / 2
elif method in ["weighted_mean", "exp_weighted_mean"]:
weights = pd.to_numeric(df.index)
weights = weights - weights.min()
if method == "exp_weighted_mean":
weights = (weights / weights[weights != 0].min()) ** 2
self.average_values = np.average(df.to_numpy(), axis=0, weights=weights)
self.fit_runtime = datetime.datetime.now() - self.startTime
self.lower, self.upper = historic_quantile(
df, prediction_interval=self.prediction_interval
)
return self
def predict(
self, forecast_length: int, future_regressor=None, just_point_forecast=False
):
"""Generates forecast data immediately following dates of index supplied to .fit()
Args:
forecast_length (int): Number of periods of data to forecast ahead
regressor (numpy.Array): additional regressor, not used
just_point_forecast (bool): If True, return a pandas.DataFrame of just point forecasts
Returns:
Either a PredictionObject of forecasts and metadata, or
if just_point_forecast == True, a dataframe of point forecasts
"""
predictStartTime = datetime.datetime.now()
df = pd.DataFrame(
np.tile(self.average_values, (forecast_length, 1)),
columns=self.column_names,
index=self.create_forecast_index(forecast_length=forecast_length),
)
if just_point_forecast:
return df
else:
upper_forecast = df.astype(float) + self.upper
lower_forecast = df.astype(float) - self.lower
predict_runtime = datetime.datetime.now() - predictStartTime
prediction = PredictionObject(
model_name=self.name,
forecast_length=forecast_length,
forecast_index=df.index,
forecast_columns=df.columns,
lower_forecast=lower_forecast,
forecast=df,
upper_forecast=upper_forecast,
prediction_interval=self.prediction_interval,
predict_runtime=predict_runtime,
fit_runtime=self.fit_runtime,
model_parameters=self.get_params(),
)
return prediction
def get_new_params(self, method: str = 'random'):
"""Returns dict of new parameters for parameter tuning"""
method_choice = random.choices(
[
"Mean",
"Median",
"Mode",
"Midhinge",
"Weighted_Mean",
"Exp_Weighted_Mean",
],
[0.3, 0.3, 0.01, 0.1, 0.4, 0.1],
)[0]
return {'method': method_choice}
def get_params(self):
"""Return dict of current parameters."""
return {'method': self.method}
class SeasonalNaive(ModelObject):
"""Naive forecasting predicting a dataframe with seasonal (lag) forecasts.
Concerto No. 2 in G minor, Op. 8, RV 315
Args:
name (str): String to identify class
frequency (str): String alias of datetime index frequency or else 'infer'
prediction_interval (float): Confidence interval for probabilistic forecast
method (str): Either 'LastValue' (use last value of lag n) or 'Mean' (avg of all lag n)
lag_1 (int): The lag of the seasonality, should int > 1.
lag_2 (int): Optional second lag of seasonality which is averaged with first lag to produce forecast.
"""
def __init__(
self,
name: str = "SeasonalNaive",
frequency: str = 'infer',
prediction_interval: float = 0.9,
holiday_country: str = 'US',
random_seed: int = 2020,
verbose: int = 0,
lag_1: int = 7,
lag_2: int = None,
method: str = 'LastValue',
**kwargs
):
ModelObject.__init__(
self,
name,
frequency,
prediction_interval,
holiday_country=holiday_country,
random_seed=random_seed,
verbose=verbose,
)
self.lag_1 = abs(int(lag_1))
self.lag_2 = lag_2
if str(self.lag_2).isdigit():
self.lag_2 = abs(int(self.lag_2))
if str(self.lag_2) == str(self.lag_1):
self.lag_2 = 1
self.method = method
def fit(self, df, future_regressor=None):
"""Train algorithm given data supplied.
Args:
df (pandas.DataFrame): Datetime Indexed
"""
df = self.basic_profile(df)
self.df_train = df
df_length = self.train_shape[0]
self.tile_values_lag_2 = None
if self.method in ['Mean', 'Median']:
tile_index = np.tile(
np.arange(self.lag_1), int(np.ceil(df_length / self.lag_1))
)
tile_index = tile_index[len(tile_index) - (df_length) :]
df.index = tile_index
if self.method == "Median":
self.tile_values_lag_1 = df.groupby(level=0, axis=0).median()
else:
self.tile_values_lag_1 = df.groupby(level=0, axis=0).mean()
if str(self.lag_2).isdigit():
if self.lag_2 == 1:
self.tile_values_lag_2 = df.tail(self.lag_2)
else:
tile_index = np.tile(
np.arange(self.lag_2), int(np.ceil(df_length / self.lag_2))
)
tile_index = tile_index[len(tile_index) - (df_length) :]
df.index = tile_index
if self.method == "Median":
self.tile_values_lag_2 = df.groupby(level=0, axis=0).median()
else:
self.tile_values_lag_2 = df.groupby(level=0, axis=0).mean()
else:
self.method == 'LastValue'
self.tile_values_lag_1 = df.tail(self.lag_1)
if str(self.lag_2).isdigit():
self.tile_values_lag_2 = df.tail(self.lag_2)
self.fit_runtime = datetime.datetime.now() - self.startTime
return self
def predict(
self,
forecast_length: int,
future_regressor=None,
just_point_forecast: bool = False,
):
"""Generate forecast data immediately following dates of .fit().
Args:
forecast_length (int): Number of periods of data to forecast ahead
regressor (numpy.Array): additional regressor, not used
just_point_forecast (bool): If True, return a pandas.DataFrame of just point forecasts
Returns:
Either a PredictionObject of forecasts and metadata, or
if just_point_forecast == True, a dataframe of point forecasts
"""
predictStartTime = datetime.datetime.now()
tile_len = len(self.tile_values_lag_1.index)
df = pd.DataFrame(
np.tile(
self.tile_values_lag_1, (int(np.ceil(forecast_length / tile_len)), 1)
)[0:forecast_length],
columns=self.column_names,
index=self.create_forecast_index(forecast_length=forecast_length),
)
if str(self.lag_2).isdigit():
y = pd.DataFrame(
np.tile(
self.tile_values_lag_2,
(
int(
np.ceil(forecast_length / len(self.tile_values_lag_2.index))
),
1,
),
)[0:forecast_length],
columns=self.column_names,
index=self.create_forecast_index(forecast_length=forecast_length),
)
df = (df + y) / 2
# df = df.apply(pd.to_numeric, errors='coerce')
df = df.astype(float)
if just_point_forecast:
return df
else:
upper_forecast, lower_forecast = Point_to_Probability(
self.df_train,
df,
method='inferred_normal',
prediction_interval=self.prediction_interval,
)
predict_runtime = datetime.datetime.now() - predictStartTime
prediction = PredictionObject(
model_name=self.name,
forecast_length=forecast_length,
forecast_index=df.index,
forecast_columns=df.columns,
lower_forecast=lower_forecast,
forecast=df,
upper_forecast=upper_forecast,
prediction_interval=self.prediction_interval,
predict_runtime=predict_runtime,
fit_runtime=self.fit_runtime,
model_parameters=self.get_params(),
)
return prediction
def get_new_params(self, method: str = 'random'):
"""Return dict of new parameters for parameter tuning."""
lag_1_choice = seasonal_int()
lag_2_choice = random.choices(
[None, seasonal_int(include_one=True)], [0.3, 0.7]
)[0]
if str(lag_2_choice) == str(lag_1_choice):
lag_2_choice = 1
method_choice = random.choices(
['Mean', 'Median', 'LastValue'], [0.4, 0.2, 0.4]
)[0]
return {'method': method_choice, 'lag_1': lag_1_choice, 'lag_2': lag_2_choice}
def get_params(self):
"""Return dict of current parameters."""
return {'method': self.method, 'lag_1': self.lag_1, 'lag_2': self.lag_2}
class MotifSimulation(ModelObject):
"""More dark magic created by the evil mastermind of this project.
Basically a highly-customized KNN
Warning: if you are forecasting many steps (large forecast_length), and interested in probabilistic upper/lower forecasts, then set recency_weighting <= 0, and have a larger cutoff_minimum
Args:
name (str): String to identify class
frequency (str): String alias of datetime index frequency or else 'infer'
prediction_interval (float): Confidence interval for probabilistic forecast
phrase_len (int): length of motif vectors to compare as samples
comparison (str): method to process data before comparison, 'magnitude' is original data
shared (bool): whether to compare motifs across all series together, or separately
distance_metric (str): passed through to sklearn pairwise_distances
max_motifs (float): number of motifs to compare per series. If less 1, used as % of length training data
recency_weighting (float): amount to the value of more recent data.
cutoff_threshold (float): lowest value of distance metric to allow into forecast
cutoff_minimum (int): minimum number of motif vectors to include in forecast.
point_method (str): summarization method to choose forecast on, 'sample', 'mean', 'sign_biased_mean', 'median'
"""
def __init__(
self,
name: str = "MotifSimulation",
frequency: str = 'infer',
prediction_interval: float = 0.9,
holiday_country: str = 'US',
random_seed: int = 2020,
phrase_len: str = '5',
comparison: str = 'magnitude_pct_change_sign',
shared: bool = False,
distance_metric: str = 'l2',
max_motifs: float = 50,
recency_weighting: float = 0.1,
cutoff_threshold: float = 0.9,
cutoff_minimum: int = 20,
point_method: str = 'median',
n_jobs: int = -1,
verbose: int = 1,
**kwargs
):
ModelObject.__init__(
self,
name,
frequency,
prediction_interval,
holiday_country=holiday_country,
random_seed=random_seed,
n_jobs=n_jobs,
)
self.phrase_len = phrase_len
self.comparison = comparison
self.shared = shared
self.distance_metric = distance_metric
self.max_motifs = max_motifs
self.recency_weighting = recency_weighting
self.cutoff_threshold = cutoff_threshold
self.cutoff_minimum = cutoff_minimum
self.point_method = point_method
def fit(self, df, future_regressor=None):
"""Train algorithm given data supplied.
Args:
df (pandas.DataFrame): Datetime Indexed
"""
if abs(float(self.max_motifs)) > 1:
self.max_motifs_n = abs(int(self.max_motifs))
elif float(self.max_motifs) == 1:
self.max_motifs_n = 2
elif float(self.max_motifs) < 1:
self.max_motifs_n = int(abs(np.floor(self.max_motifs * df.shape[0])))
else:
self.max_motifs = 10
self.max_motifs_n = 10
self.phrase_n = int(self.phrase_len)
# df = df_wide[df_wide.columns[0:3]].fillna(0).astype(float)
df = self.basic_profile(df)
"""
comparison = 'magnitude' # pct_change, pct_change_sign, magnitude_pct_change_sign, magnitude, magnitude_pct_change
distance_metric = 'cityblock'
max_motifs_n = 100
phrase_n = 5
shared = False
recency_weighting = 0.1
# cutoff_threshold = 0.8
cutoff_minimum = 20
prediction_interval = 0.9
na_threshold = 0.1
point_method = 'mean'
"""
phrase_n = abs(int(self.phrase_n))
max_motifs_n = abs(int(self.max_motifs_n))
comparison = self.comparison
distance_metric = self.distance_metric
shared = self.shared
recency_weighting = float(self.recency_weighting)
# cutoff_threshold = float(self.cutoff_threshold)
cutoff_minimum = abs(int(self.cutoff_minimum))
prediction_interval = float(self.prediction_interval)
na_threshold = 0.1
point_method = self.point_method
parallel = True
if self.n_jobs in [0, 1] or df.shape[1] < 3:
parallel = False
else:
try:
from joblib import Parallel, delayed
except Exception:
parallel = False
# import timeit
# start_time_1st = timeit.default_timer()
# transform the data into different views (contour = percent_change)
original_df = None
if 'pct_change' in comparison:
if comparison in ['magnitude_pct_change', 'magnitude_pct_change_sign']:
original_df = df.copy()
df = df.replace([0], np.nan)
df = df.fillna(abs(df[df != 0]).min()).fillna(0.1)
last_row = df.tail(1)
df = (
df.pct_change(periods=1, fill_method='ffill')
.tail(df.shape[0] - 1)
.fillna(0)
)
df = df.replace([np.inf, -np.inf], 0)
# else:
# self.comparison = 'magnitude'
if 'pct_change_sign' in comparison:
last_motif = df.where(df >= 0, -1).where(df <= 0, 1).tail(phrase_n)
else:
last_motif = df.tail(phrase_n)
max_samps = df.shape[0] - phrase_n
numbers = np.random.choice(
max_samps,
size=max_motifs_n if max_motifs_n < max_samps else max_samps,
replace=False,
)
# make this faster
motif_vecs_list = []
# takes random slices of the time series and rearranges as phrase_n length vectors
for z in numbers:
rand_slice = df.iloc[
z : (z + phrase_n),
]
rand_slice = (
rand_slice.reset_index(drop=True)
.transpose()
.set_index(np.repeat(z, (df.shape[1],)), append=True)
)
# motif_vecs = pd.concat([motif_vecs, rand_slice], axis=0)
motif_vecs_list.append(rand_slice)
motif_vecs = pd.concat(motif_vecs_list, axis=0)
if 'pct_change_sign' in comparison:
motif_vecs = motif_vecs.where(motif_vecs >= 0, -1).where(motif_vecs <= 0, 1)
# elapsed_1st = timeit.default_timer() - start_time_1st
# start_time_2nd = timeit.default_timer()
# compare the motif vectors to the most recent vector of the series
from sklearn.metrics.pairwise import pairwise_distances
args = {
"cutoff_minimum": cutoff_minimum,
"comparison": comparison,
"point_method": point_method,
"prediction_interval": prediction_interval,
"phrase_n": phrase_n,
"distance_metric": distance_metric,
"shared": shared,
"na_threshold": na_threshold,
"original_df": original_df,
"df": df,
}
if shared:
comparative = pd.DataFrame(
pairwise_distances(
motif_vecs.to_numpy(),
last_motif.transpose().to_numpy(),
metric=distance_metric,
)
)
comparative.index = motif_vecs.index
comparative.columns = last_motif.columns
if not shared:
def create_comparative(motif_vecs, last_motif, args, col):
distance_metric = args["distance_metric"]
x = motif_vecs[motif_vecs.index.get_level_values(0) == col]
y = last_motif[col].to_numpy().reshape(1, -1)
current_comparative = pd.DataFrame(
pairwise_distances(x.to_numpy(), y, metric=distance_metric)
)
current_comparative.index = x.index
current_comparative.columns = [col]
return current_comparative
if parallel:
verbs = 0 if self.verbose < 1 else self.verbose - 1
df_list = Parallel(n_jobs=self.n_jobs, verbose=(verbs))(
delayed(create_comparative)(
motif_vecs=motif_vecs, last_motif=last_motif, args=args, col=col
)
for col in last_motif.columns
)
else:
df_list = []
for col in last_motif.columns:
df_list.append(
create_comparative(motif_vecs, last_motif, args, col)
)
comparative = pd.concat(df_list, axis=0)
comparative = comparative.groupby(level=[0, 1]).sum(min_count=0)
# comparative comes out of this looking kinda funny, but get_level_values works with that later
# it might be possible to reshape it to a more memory efficient design
# comparative is a df of motifs (in index) with their value to each series (per column)
if recency_weighting != 0:
rec_weights = np.repeat(
((comparative.index.get_level_values(1)) / df.shape[0])
.to_numpy()
.reshape(-1, 1)
* recency_weighting,
len(comparative.columns),
axis=1,
)
comparative = comparative.add(rec_weights, fill_value=0)
def seek_the_oracle(comparative, args, col):
# comparative.idxmax()
cutoff_minimum = args["cutoff_minimum"]
comparison = args["comparison"]
point_method = args["point_method"]
prediction_interval = args["prediction_interval"]
phrase_n = args["phrase_n"]
shared = args["shared"]
na_threshold = args["na_threshold"]
original_df = args["original_df"]
df = args["df"]
vals = comparative[col].sort_values(ascending=False)
if not shared:
vals = vals[vals.index.get_level_values(0) == col]
# vals = vals[vals > cutoff_threshold]
# if vals.shape[0] < cutoff_minimum:
vals = comparative[col].sort_values(ascending=False)
if not shared:
vals = vals[vals.index.get_level_values(0) == col]
vals = vals.head(cutoff_minimum)
pos_forecasts = pd.DataFrame()
for val_index, val_value in vals.items():
sec_start = val_index[1] + phrase_n
if comparison in ['magnitude_pct_change', 'magnitude_pct_change_sign']:
current_pos = original_df[val_index[0]].iloc[sec_start + 1 :]
else:
current_pos = df[val_index[0]].iloc[sec_start:]
pos_forecasts = pd.concat(
[pos_forecasts, current_pos.reset_index(drop=True)],
axis=1,
sort=False,
)
thresh = int(np.ceil(pos_forecasts.shape[1] * na_threshold))
if point_method == 'mean':
current_forecast = pos_forecasts.mean(axis=1)
elif point_method == 'sign_biased_mean':
axis_means = pos_forecasts.mean(axis=0)
if axis_means.mean() > 0:
pos_forecasts = pos_forecasts[
pos_forecasts.columns[~(axis_means < 0)]
]
else:
pos_forecasts = pos_forecasts[
pos_forecasts.columns[~(axis_means > 0)]
]
current_forecast = pos_forecasts.mean(axis=1)
else:
point_method = 'median'
current_forecast = pos_forecasts.median(axis=1)
# current_forecast.columns = [col]
forecast = current_forecast.copy()
forecast.name = col
current_forecast = (
pos_forecasts.dropna(thresh=thresh, axis=0)
.quantile(q=[(1 - prediction_interval), prediction_interval], axis=1)
.transpose()
)
lower_forecast = pd.Series(current_forecast.iloc[:, 0], name=col)
upper_forecast = pd.Series(current_forecast.iloc[:, 1], name=col)
return (forecast, lower_forecast, upper_forecast)
# seek_the_oracle(comparative, args, comparative.columns[0])
if parallel:
verbs = 0 if self.verbose < 1 else self.verbose - 1
df_list = Parallel(n_jobs=self.n_jobs, verbose=(verbs))(
delayed(seek_the_oracle)(comparative=comparative, args=args, col=col)
for col in comparative.columns
)
complete = list(map(list, zip(*df_list)))
else:
df_list = []
for col in comparative.columns:
df_list.append(seek_the_oracle(comparative, args, col))
complete = list(map(list, zip(*df_list)))
forecasts = pd.concat(
complete[0], axis=1
) # .reindex(self.column_names, axis=1)
lower_forecasts = pd.concat(complete[1], axis=1)
upper_forecasts = pd.concat(complete[2], axis=1)
if comparison in ['pct_change', 'pct_change_sign']:
forecasts = (forecasts + 1).replace([0], np.nan)
forecasts = forecasts.fillna(abs(df[df != 0]).min()).fillna(0.1)
forecasts = pd.concat(
[last_row.reset_index(drop=True), (forecasts)], axis=0, sort=False
).cumprod()
upper_forecasts = (upper_forecasts + 1).replace([0], np.nan)
upper_forecasts = upper_forecasts.fillna(abs(df[df != 0]).min()).fillna(0.1)
upper_forecasts = pd.concat(
[last_row.reset_index(drop=True), (upper_forecasts)], axis=0, sort=False
).cumprod()
lower_forecasts = (lower_forecasts + 1).replace([0], np.nan)
lower_forecasts = lower_forecasts.fillna(abs(df[df != 0]).min()).fillna(0.1)
lower_forecasts = pd.concat(
[last_row.reset_index(drop=True), (lower_forecasts)], axis=0, sort=False
).cumprod()
# reindex might be unnecessary but I assume the cost worth the safety
self.forecasts = forecasts
self.lower_forecasts = lower_forecasts
self.upper_forecasts = upper_forecasts
# elapsed_3rd = timeit.default_timer() - start_time_3rd
# print(f"1st {elapsed_1st}\n2nd {elapsed_2nd}\n3rd {elapsed_3rd}")
"""
In fit phase, only select motifs.
table: start index, weight, column it applies to, and count of rows that follow motif
slice into possible motifs
compare motifs (efficiently)
choose the motifs to use for each series
if not shared, can drop column part of index ref
combine the following values into forecasts
consider the weights
magnitude and percentage change
account for forecasts not running the full length of forecast_length
if longer than comparative, append na df then ffill
Profile speed and which code to improve first
Remove for loops
Quantile not be calculated until after pos_forecasts narrowed down to only forecast length
https://krstn.eu/np.nanpercentile()-there-has-to-be-a-faster-way/
"""
self.fit_runtime = datetime.datetime.now() - self.startTime
return self
def predict(
self, forecast_length: int, future_regressor=None, just_point_forecast=False
):
"""Generates forecast data immediately following dates of index supplied to .fit()
Args:
forecast_length (int): Number of periods of data to forecast ahead
regressor (numpy.Array): additional regressor, not used
just_point_forecast (bool): If True, return a pandas.DataFrame of just point forecasts
Returns:
Either a PredictionObject of forecasts and metadata, or
if just_point_forecast == True, a dataframe of point forecasts
"""
predictStartTime = datetime.datetime.now()
forecasts = self.forecasts.head(forecast_length)
if forecasts.shape[0] < forecast_length:
extra_len = forecast_length - forecasts.shape[0]
empty_frame = pd.DataFrame(
index=np.arange(extra_len), columns=forecasts.columns
)
forecasts = pd.concat([forecasts, empty_frame], axis=0, sort=False).fillna(
method='ffill'
)
forecasts.columns = self.column_names
forecasts.index = self.create_forecast_index(forecast_length=forecast_length)
if just_point_forecast:
return forecasts
else:
lower_forecasts = self.lower_forecasts.head(forecast_length)
upper_forecasts = self.upper_forecasts.head(forecast_length)
if lower_forecasts.shape[0] < forecast_length:
extra_len = forecast_length - lower_forecasts.shape[0]
empty_frame = pd.DataFrame(
index=np.arange(extra_len), columns=lower_forecasts.columns
)
lower_forecasts = pd.concat(
[lower_forecasts, empty_frame], axis=0, sort=False
).fillna(method='ffill')
lower_forecasts.columns = self.column_names
lower_forecasts.index = self.create_forecast_index(
forecast_length=forecast_length
)
if upper_forecasts.shape[0] < forecast_length:
extra_len = forecast_length - upper_forecasts.shape[0]
empty_frame = pd.DataFrame(
index=np.arange(extra_len), columns=upper_forecasts.columns
)
upper_forecasts = pd.concat(
[upper_forecasts, empty_frame], axis=0, sort=False
).fillna(method='ffill')
upper_forecasts.columns = self.column_names
upper_forecasts.index = self.create_forecast_index(
forecast_length=forecast_length
)
predict_runtime = datetime.datetime.now() - predictStartTime
prediction = PredictionObject(
model_name=self.name,
forecast_length=forecast_length,
forecast_index=forecasts.index,
forecast_columns=forecasts.columns,
lower_forecast=lower_forecasts,
forecast=forecasts,
upper_forecast=upper_forecasts,
prediction_interval=self.prediction_interval,
predict_runtime=predict_runtime,
fit_runtime=self.fit_runtime,
model_parameters=self.get_params(),
)
return prediction
def get_new_params(self, method: str = 'random'):
"""Return dict of new parameters for parameter tuning."""
comparison_choice = np.random.choice(
a=[
'pct_change',
'pct_change_sign',
'magnitude_pct_change_sign',
'magnitude',
'magnitude_pct_change',
],
size=1,
p=[0.2, 0.1, 0.4, 0.2, 0.1],
).item()
phrase_len_choice = np.random.choice(
a=[5, 10, 15, 20, 30, 90, 360],
p=[0.2, 0.2, 0.1, 0.25, 0.1, 0.1, 0.05],
size=1,
).item()
shared_choice = np.random.choice(a=[True, False], size=1, p=[0.05, 0.95]).item()
distance_metric_choice = np.random.choice(
a=[
'other',
'hamming',
'cityblock',
'cosine',
'euclidean',
'l1',
'l2',
'manhattan',
],
size=1,
p=[0.44, 0.05, 0.1, 0.1, 0.1, 0.2, 0.0, 0.01],
).item()
if distance_metric_choice == 'other':
distance_metric_choice = np.random.choice(
a=[
'braycurtis',
'canberra',
'chebyshev',
'correlation',
'dice',
'hamming',
'jaccard',
'kulsinski',
'mahalanobis',
'minkowski',
'rogerstanimoto',
'russellrao',
# 'seuclidean',
'sokalmichener',
'sokalsneath',
'sqeuclidean',
'yule',