-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReportPart2.qmd
3059 lines (2175 loc) · 111 KB
/
ReportPart2.qmd
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
---
title: "Time series regression - Store sales forecasting, part 2"
author: "Ahmet Zamanis"
format:
gfm:
toc: true
code-fold: true
code-summary: "Show code"
editor: visual
jupyter: python3
execute:
warning: false
---
## Introduction
This is part 2 of a report on time series analysis & regression modeling, performed in Python with the Darts library. In [part 1](https://github.com/AhmetZamanis/KaggleStoreSales/blob/ModelPart2.2/ReportPart1.md), we analyzed & forecasted only the daily national supermarket sales in the [Kaggle Store Sales forecasting competition](https://www.kaggle.com/competitions/store-sales-time-series-forecasting) dataset. Now, we will generate forecasts for each level of the hierarchy: Total sales, store sales (for each of the 54 stores), and disaggregated series (1782 in total, 33 categories in 54 stores). For a more detailed look into the data handling, feature engineering & exploratory analysis process, as well as some of the models used, I suggest looking at part 1 first.
In part 1, we had one series to forecast, so we performed manual exploratory analysis & feature engineering, and achieved the best forecasts using a hybrid model of two linear regressions. This time, we have many series to forecast, so we will use a more automated approach. We'll also try some global deep learning / neural network models, trained on multiple time series at once. Darts offers PyTorch [implementations](https://unit8co.github.io/darts/userguide/torch_forecasting_models.html) of numerous deep learning models specialized for time series forecasting.
```{python Settings}
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import torch
import tensorboard
from tqdm import tqdm
# Set printing options
np.set_printoptions(suppress=True, precision=4)
pd.options.display.float_format = '{:.4f}'.format
pd.set_option('display.max_columns', None)
# Set plotting options
plt.rcParams['figure.dpi'] = 300
plt.rcParams['savefig.dpi'] = 300
plt.rcParams["figure.autolayout"] = True
# Set torch settings
torch.set_float32_matmul_precision("high")
```
```{python ImportDartsFuncs}
# Import Darts time series
from darts import TimeSeries
from darts.utils.timeseries_generation import datetime_attribute_timeseries
# Import transformers
from sklearn.preprocessing import StandardScaler
from darts.dataprocessing.transformers import Scaler
from sktime.transformations.series.difference import Differencer
from darts.dataprocessing.transformers import MissingValuesFiller
# Import baseline models
from darts.models.forecasting.baselines import NaiveDrift, NaiveSeasonal
from darts.models.forecasting.sf_ets import StatsForecastETS as ETS
# Import forecasting models
from darts.models.forecasting.linear_regression_model import LinearRegressionModel
from darts.models.forecasting.auto_arima import AutoARIMA
from darts.models.forecasting.random_forest import RandomForest
from darts.models.forecasting.dlinear import DLinearModel as DLinear
from darts.models.forecasting.rnn_model import RNNModel as RNN
from darts.models.forecasting.tft_model import TFTModel
from sklearn.linear_model import LinearRegression
# Import time decomposition functions
from statsmodels.tsa.deterministic import DeterministicProcess
from darts.utils.statistics import extract_trend_and_seasonality as decomposition
from darts.utils.statistics import remove_from_series
from darts.utils.utils import ModelMode, SeasonalityMode
# Import performance metrics
from darts.metrics import rmse, rmsle, mape, mae, mse
# Import Torch callbacks
from pytorch_lightning.callbacks.early_stopping import EarlyStopping
from pytorch_lightning.callbacks import RichProgressBar, RichModelSummary
```
## Data preparation steps from part 1
The initial data preparation is mostly the same as part 1, so we won't discuss it further, though the code below is a more compact version of the code in part 1.
```{python DataPrepPart1}
#| output: false
# Load original datasets
df_train = pd.read_csv("./OriginalData/train.csv", encoding = "utf-8")
df_test = pd.read_csv("./OriginalData/test.csv", encoding = "utf-8")
df_stores = pd.read_csv("./OriginalData/stores.csv", encoding = "utf-8")
df_oil = pd.read_csv("./OriginalData/oil.csv", encoding = "utf-8")
df_holidays = pd.read_csv("./OriginalData/holidays_events.csv", encoding = "utf-8")
df_trans = pd.read_csv("./OriginalData/transactions.csv", encoding = "utf-8")
# Combine df_train and df_test
df = pd.concat([df_train, df_test])
# Rename columns
df = df.rename(columns = {"family":"category"})
df_holidays = df_holidays.rename(columns = {"type":"holiday_type"})
df_oil = df_oil.rename(columns = {"dcoilwtico":"oil"})
df_stores = df_stores.rename(columns = {
"type":"store_type", "cluster":"store_cluster"})
# Add columns from oil, stores and transactions datasets into main data
df = df.merge(df_stores, on = "store_nbr", how = "left")
df = df.merge(df_trans, on = ["date", "store_nbr"], how = "left")
df = df.merge(df_oil, on = "date", how = "left")
# Split holidays data into local, regional, national and events
events = df_holidays[df_holidays["holiday_type"] == "Event"].copy()
df_holidays = df_holidays.drop(labels=(events.index), axis=0)
local = df_holidays.loc[df_holidays["locale"] == "Local"].copy()
regional = df_holidays.loc[df_holidays["locale"] == "Regional"].copy()
national = df_holidays.loc[df_holidays["locale"] == "National"].copy()
# Drop duplicate rows in holidays-events
local = local.drop(265, axis = 0)
national = national.drop([35, 39, 156], axis = 0)
events = events.drop(244, axis = 0)
# Add local_holiday binary column to local holidays data, to be merged into main
# data
local["local_holiday"] = (
local.holiday_type.isin(["Transfer", "Additional", "Bridge"]) |
((local.holiday_type == "Holiday") & (local.transferred == False))
).astype(int)
# Add regional_holiday binary column to regional holidays data
regional["regional_holiday"] = (
regional.holiday_type.isin(["Transfer", "Additional", "Bridge"]) |
((regional.holiday_type == "Holiday") & (regional.transferred == False))
).astype(int)
# Add national_holiday binary column to national holidays data
national["national_holiday"] = (
national.holiday_type.isin(["Transfer", "Additional", "Bridge"]) |
((national.holiday_type == "Holiday") & (national.transferred == False))
).astype(int)
# Add event column to events
events["event"] = 1
# Merge local holidays binary column to main data, on date and city
local_merge = local.drop(
labels = [
"holiday_type", "locale", "description", "transferred"], axis = 1).rename(
columns = {"locale_name":"city"})
df = df.merge(local_merge, how="left", on=["date", "city"])
df["local_holiday"] = df["local_holiday"].fillna(0).astype(int)
# Merge regional holidays binary column to main data
regional_merge = regional.drop(
labels = [
"holiday_type", "locale", "description", "transferred"], axis = 1).rename(
columns = {"locale_name":"state"})
df = df.merge(regional_merge, how="left", on=["date", "state"])
df["regional_holiday"] = df["regional_holiday"].fillna(0).astype(int)
# Merge national holidays binary column to main data, on date
national_merge = national.drop(
labels = [
"holiday_type", "locale", "locale_name", "description",
"transferred"], axis = 1)
df = df.merge(national_merge, how="left", on="date")
df["national_holiday"] = df["national_holiday"].fillna(0).astype(int)
# Merge events binary column to main data
events_merge = events.drop(
labels = [
"holiday_type", "locale", "locale_name", "description",
"transferred"], axis = 1)
df = df.merge(events_merge, how="left", on="date")
df["event"] = df["event"].fillna(0).astype(int)
# Set datetime index
df = df.set_index(pd.to_datetime(df.date))
df = df.drop("date", axis=1)
# CPI adjust sales and oil, with CPI 2010 = 100
cpis = {
"2010": 100, "2013": 112.8, "2014": 116.8, "2015": 121.5, "2016": 123.6,
"2017": 124.1
}
for year in [2013, 2014, 2015, 2016, 2017]:
df.loc[df.index.year == year, "sales"] = df.loc[
df.index.year == year, "sales"] / cpis[str(year)] * cpis["2010"]
df.loc[df.index.year == year, "oil"] = df.loc[
df.index.year == year, "oil"] / cpis[str(year)] * cpis["2010"]
del year
# Interpolate missing values in oil
df["oil"] = df["oil"].interpolate("time", limit_direction = "both")
# New year's day features
df["ny1"] = ((df.index.day == 1) & (df.index.month == 1)).astype(int)
df["ny2"] = ((df.index.day == 2) & (df.index.month == 1)).astype(int)
# Set holiday dummies to 0 if NY dummies are 1
df.loc[df["ny1"] == 1, ["local_holiday", "regional_holiday", "national_holiday"]] = 0
df.loc[df["ny2"] == 1, ["local_holiday", "regional_holiday", "national_holiday"]] = 0
# NY's eve features
df["ny_eve31"] = ((df.index.day == 31) & (df.index.month == 12)).astype(int)
df["ny_eve30"] = ((df.index.day == 30) & (df.index.month == 12)).astype(int)
df.loc[(df["ny_eve31"] == 1) | (df["ny_eve30"] == 1), ["local_holiday", "regional_holiday", "national_holiday"]] = 0
# Proximity to Christmas sales peak
df["xmas_before"] = 0
df.loc[
(df.index.day.isin(range(13,24))) & (df.index.month == 12), "xmas_before"] = df.loc[
(df.index.day.isin(range(13,24))) & (df.index.month == 12)].copy().index.day - 12
df["xmas_after"] = 0
df.loc[
(df.index.day.isin(range(24,28))) & (df.index.month == 12), "xmas_after"] = abs(df.loc[
(df.index.day.isin(range(24,28))) & (df.index.month == 12)].index.day - 27)
df.loc[(df["xmas_before"] != 0) | (df["xmas_after"] != 0), ["local_holiday", "regional_holiday", "national_holiday"]] = 0
# Strength of earthquake effect on sales
# April 18 > 17 > 19 > 20 > 21 > 22
df["quake_after"] = 0
df.loc[df.index == "2016-04-18", "quake_after"] = 6
df.loc[df.index == "2016-04-17", "quake_after"] = 5
df.loc[df.index == "2016-04-19", "quake_after"] = 4
df.loc[df.index == "2016-04-20", "quake_after"] = 3
df.loc[df.index == "2016-04-21", "quake_after"] = 2
df.loc[df.index == "2016-04-22", "quake_after"] = 1
# Split events, delete events column
df["dia_madre"] = ((df["event"] == 1) & (df.index.month == 5) & (df.index.day.isin([8,10,11,12,14]))).astype(int)
df["futbol"] = ((df["event"] == 1) & (df.index.isin(pd.date_range(start = "2014-06-12", end = "2014-07-13")))).astype(int)
df["black_friday"] = ((df["event"] == 1) & (df.index.isin(["2014-11-28", "2015-11-27", "2016-11-25"]))).astype(int)
df["cyber_monday"] = ((df["event"] == 1) & (df.index.isin(["2014-12-01", "2015-11-30", "2016-11-28"]))).astype(int)
df = df.drop("event", axis=1)
# Days of week dummies
df["tuesday"] = (df.index.dayofweek == 1).astype(int)
df["wednesday"] = (df.index.dayofweek == 2).astype(int)
df["thursday"] = (df.index.dayofweek == 3).astype(int)
df["friday"] = (df.index.dayofweek == 4).astype(int)
df["saturday"] = (df.index.dayofweek == 5).astype(int)
df["sunday"] = (df.index.dayofweek == 6).astype(int)
# Add category X store_nbr column for Darts hierarchy
df["category_store_nbr"] = df["category"].astype(str) + "-" + df["store_nbr"].astype(str)
# Train-test split
df_train = df.loc[:"2017-08-15"]
df_test = df.loc["2017-08-16":]
# Replace transactions NAs in train with 0
df_train = df_train.fillna({"transactions": 0})
# Recombine train and test
df = pd.concat([df_train, df_test])
```
```{python PrintRawData}
print(df.head(2))
```
```{python DeleteRawData}
#| include: false
del df_holidays, df_oil, df_stores, df_trans, events, events_merge, local, local_merge, national, national_merge, regional, regional_merge
```
## Hierarchical time series: Sales
Each row in our original dataset is the sales of one product category, at one store, on one date. We have 33 categories and 54 stores in our data, which means we have a total of 1782 bottom level series we need to forecast for the competition. These series add up in certain ways:
- Total sales = sum of 33 categories' sales = sum of 1782 disaggregated series
- Total sales = sum of 54 stores' sales = sum of 1782 disaggregated series
These are **hierarchical** time series structures, and we will generate forecasts for each hierarchy node. I've attempted working with both hierarchy structures, but had much worse results trying to predict category sales:
- The sales patterns of each store are considerably similar in terms of trend and seasonality, while the sales patterns of each category can be very different. Some categories (such as school supplies) even take zero values for most of a year.
- This makes it much harder to model category sales with a general approach. Therefore, this report will only examine the second hierarchy structure: Total \> store totals \> disaggregated series.
We will create a multivariate Darts TimeSeries, where each series in the hierarchy will be one component. We'll also map the hierarchy structure as a dictionary, and embed this into the Darts TS, so we can perform hierarchical reconciliation later.
```{python TargetDataFrames}
# Create wide dataframes with dates as rows, sales numbers for each hierarchy node as columns
# Total
total = pd.DataFrame(
data = df_train.groupby("date").sales.sum(),
index = df_train.groupby("date").sales.sum().index)
# Stores
store_nbr = pd.DataFrame(
data = df_train.groupby(["date", "store_nbr"]).sales.sum(),
index = df_train.groupby(["date", "store_nbr"]).sales.sum().index)
store_nbr = store_nbr.reset_index(level = 1)
store_nbr = store_nbr.pivot(columns = "store_nbr", values = "sales")
# Categories x stores
category_store_nbr = pd.DataFrame(
data = df_train.groupby(["date", "category_store_nbr"]).sales.sum(),
index = df_train.groupby(["date", "category_store_nbr"]).sales.sum().index)
category_store_nbr = category_store_nbr.reset_index(level = 1)
category_store_nbr = category_store_nbr.pivot(columns = "category_store_nbr", values = "sales")
# Merge all wide dataframes
from functools import reduce
wide_frames = [total, store_nbr, category_store_nbr]
df_sales = reduce(lambda left, right: pd.merge(
left, right, how = "left", on = "date"), wide_frames)
df_sales = df_sales.rename(columns = {"sales":"TOTAL"})
del total, store_nbr, wide_frames, category_store_nbr
# Print wide sales dataframe
print(df_sales.iloc[0:5, [0, 1, 2, 84, 148]])
print("Rows x columns: " + str(df_sales.shape))
```
```{python TargetHierarchy}
# Create multivariate time series with sales series
ts_sales = TimeSeries.from_dataframe(df_sales, freq = "D")
# Create lists of hierarchy nodes
categories = df_train.category.unique().tolist()
stores = df_train.store_nbr.unique().astype(str).tolist()
categories_stores = df_train.category_store_nbr.unique().tolist()
# Initialize empty dict
hierarchy_target = dict()
# Map store sales series to total sales
for store in stores:
hierarchy_target[store] = ["TOTAL"]
# Map category X store combinations to respective stores
from itertools import product
for category, store in product(categories, stores):
hierarchy_target["{}-{}".format(category, store)] = [store]
# Embed hierarchy to ts_train
ts_sales = ts_sales.with_hierarchy(hierarchy_target)
print(ts_sales)
del category, store
```
December 25 (Christmas Day) is missing from our original data. Darts automatically recognizes these gaps in the date, and we can fill in their values.
```{python FillTargetGaps}
# Scan gaps
print(ts_sales.gaps())
# Fill gaps
na_filler = MissingValuesFiller()
ts_sales = na_filler.transform(ts_sales)
```
Let's plot a few examples of the sales in our 54 stores.
```{python StorePlots}
_ = ts_sales["1"].plot()
_ = ts_sales["8"].plot()
_ = ts_sales["23"].plot()
_ = ts_sales["42"].plot()
_ = ts_sales["51"].plot()
_ = plt.title("Sales of 5 select stores")
plt.show()
plt.close("all")
```
We see the seasonality and even cyclicality in store sales are considerably similar to one another, and to the total sales we analyzed in part 1.
- This means a single feature set is likely to perform well for many stores, if not all.
- We will also consider global deep learning models: Models that will train on all 54 series in one go, and will be able to predict all 54 stores (even new ones) with just one set of parameters. This wouldn't be feasible for series that are quite different from one another, such as the sales of 33 categories.
- We also see store 42 likely didn't open until roughly Q3 2015, so it had zero sales until then. Parametric models such as linear regression could struggle with such series.
```{python CatStorePlots1}
_ = ts_sales["BREAD/BAKERY-1"].plot()
_ = ts_sales["BREAD/BAKERY-8"].plot()
_ = ts_sales["BREAD/BAKERY-23"].plot()
_ = plt.title("Sales of one category across 3 stores")
plt.show()
plt.close("all")
```
Some categories, such as bread & bakery, could display fairly consistent seasonality in all stores, though we see the trends can be different across stores.
```{python CatStorePlots2}
_ = ts_sales["CELEBRATION-1"].plot()
_ = ts_sales["CELEBRATION-8"].plot()
_ = ts_sales["CELEBRATION-23"].plot()
_ = plt.title("Sales of one category across 3 stores")
plt.show()
plt.close("all")
```
Other categories such as celebration or school supplies could take zero values for many periods of the year. Their seasonality patterns across stores could differ considerably, making it hard to model them with a single feature set and global models.
To sum up findings from our short exploratory analysis:
- Patterns in store sales are fairly similar to one another, though trends can be different. These could be modeled well by a single global model trained on all 54 stores. We'll compare the performance of such global models with simpler models trained on each store separately.
- The patterns in category sales, both in category totals and single categories across different stores, could differ considerably. Applying global models to category totals (33 series), or to the disaggregated series (1782 series) is not likely to perform well (and indeed, they performed considerably worse than baseline models when I tried).
- One configuration could be promising for modeling the 1782 disaggregated series: Training 33 global models on each category's sales in all 54 stores. This way, we derive a separate set of parameters for each category, as well as take advantage of the similarities across stores.
- This would take a training time of at least 30+ hours on my machine depending on the model used (not to mention coding time and pauses), so I did not explore it further, but I believe it could result in the best predictions.
- One of the best performing [Kaggle notebooks](https://www.kaggle.com/code/ferdinandberr/darts-forecasting-deep-learning-global-models) in the competition had the best results with this approach, but with global XGBoost models instead of global deep learning models. I expect NN models could do even better, as tree-based models may not be able to learn trend and long-term dependencies very well.
## Covariate series
We have the target series for our Darts models, now we need to create the covariate series with our features.
### Total sales covariates
```{python LogTrafoFuncs}
# Define functions to perform log transformation and reverse it. +1 to avoid zeroes
def trafo_log(x):
return x.map(lambda x: np.log(x+1))
def trafo_exp(x):
return x.map(lambda x: np.exp(x)-1)
# Create differencer
diff = Differencer(lags = 1)
```
#### For part 1 hybrid model
The feature engineering for the total sales hybrid model is explained in detail in part 1, so I won't discuss it again here, though the compact code is available below.
```{python TotalCovars1}
# Aggregate time features by mean
total_covars1 = df.drop(
columns=['id', 'store_nbr', 'category', 'sales', 'onpromotion', 'transactions', 'oil', 'city', 'state', 'store_type', 'store_cluster'], axis=1).groupby("date").mean(numeric_only=True)
# Add piecewise linear trend dummies
total_covars1["trend"] = range(1, 1701) # Linear trend dummy 1
total_covars1["trend_knot"] = 0
total_covars1.iloc[728:,-1] = range(0, 972) # Linear trend dummy 2
# Add Fourier features for monthly seasonality
dp = DeterministicProcess(
index = total_covars1.index,
constant = False,
order = 0, # No trend feature
seasonal = False, # No seasonal dummy features
period = 28, # 28-period seasonality (28 days, 1 month)
fourier = 5, # 5 Fourier pairs
drop = True # Drop perfectly collinear terms
)
total_covars1 = total_covars1.merge(dp.in_sample(), how="left", on="date")
# Create Darts time series with time features
ts_totalcovars1 = TimeSeries.from_dataframe(total_covars1, freq = "D")
# Fill gaps in covars
ts_totalcovars1 = na_filler.transform(ts_totalcovars1)
# Retrieve covars with filled gaps
total_covars1 = ts_totalcovars1.pd_dataframe()
```
```{python TotalCovars2}
# Aggregate daily covariate series
total_covars2 = df.groupby("date").agg(
{
# "sales": "sum",
"oil": "mean",
"onpromotion": "sum"}
)
total_covars2["transactions"] = df.groupby(["date", "store_nbr"]).transactions.mean().groupby("date").sum()
# Difference daily covariate series
total_covars2 = diff.fit_transform(total_covars2)
# Replace covariate series with their MAs
# Oil
total_covars2["oil_ma28"] = total_covars2["oil"].rolling(window = 28, center = False).mean()
total_covars2["oil_ma28"] = total_covars2["oil_ma28"].interpolate(
method = "spline", order = 2, limit_direction = "both")
# Onpromotion
total_covars2["onp_ma28"] = total_covars2["onpromotion"].rolling(window = 28, center = False).mean()
total_covars2["onp_ma28"] = total_covars2["onp_ma28"].interpolate(
method = "spline", order = 2, limit_direction = "both")
# Transactions
total_covars2["trns_ma7"] = total_covars2["transactions"].rolling(window = 7, center = False).mean()
total_covars2["trns_ma7"] = total_covars2["trns_ma7"].interpolate("linear", limit_direction = "backward")
# Drop original covariate series
total_covars2 = total_covars2.drop([
"oil", "onpromotion", "transactions"], axis = 1)
# Replace last 16 dates' transactions MAs with NAs
total_covars2.loc[total_covars2.index > "2017-08-15", "trns_ma7"] = np.nan
```
#### For models on raw series
We'll derive a slightly different feature set for the model to be fit on the raw total sales. We'll drop the trend dummies, and replace the Fourier pairs with a cyclical encoding of day of month and month features. We'll discuss the rationale later when we introduce our model.
```{python CommonCovars}
# Retrieve copy of total_covars1, drop Fourier terms, trend knot (leaving daily predictors common to all hierarchy levels).
common_covars = total_covars1[total_covars1.columns[2:21].values.tolist()].copy()
# Add differenced oil price and its MA to common covariates.
common_covars["oil"] = df.groupby("date").oil.mean()
common_covars["oil"] = diff.fit_transform(common_covars["oil"]).interpolate("time", limit_direction = "both")
common_covars["oil_ma28"] = common_covars["oil"].rolling(window = 28, center = False).mean()
common_covars["oil_ma28"] = common_covars["oil_ma28"].interpolate(
method = "spline", order = 2, limit_direction = "both")
# Print common covariates
print(common_covars.columns)
```
```{python TotalCovars}
# Retrieve copy of common covariates
total_covars = common_covars.copy()
# Retrieve local & regional holiday
total_covars["local_holiday"] = total_covars1["local_holiday"].copy()
total_covars["regional_holiday"] = total_covars1["regional_holiday"].copy()
# Retrieve differenced sales EMA
total_covars["sales_ema5"] = diff.fit_transform(
df.groupby("date").sales.sum()
).interpolate(
"linear", limit_direction = "backward"
).rolling(
window = 5, min_periods = 1, center = False, win_type = "exponential").mean()
# Retrieve differenced onpromotion, its MA
total_covars["onpromotion"] = diff.fit_transform(
df.groupby("date").onpromotion.sum()
).interpolate(
"time", limit_direction = "both"
)
total_covars["onp_ma28"] = total_covars["onpromotion"].rolling(
window = 28, center = False
).mean().interpolate(
method = "spline", order = 2, limit_direction = "both"
)
# Retrieve differenced transactions, its MA
total_covars["transactions"] = diff.fit_transform(
df.groupby("date").transactions.sum().interpolate(
"time", limit_direction = "both"
)
)
total_covars["trns_ma7"] = total_covars["transactions"].rolling(
window = 7, center = False
).mean().interpolate(
"linear", limit_direction = "backward"
)
# Create darts TS, fill gaps
x_total = na_filler.transform(
TimeSeries.from_dataframe(total_covars, freq = "D")
)
# Cyclical encode day of month using datetime_attribute_timeseries
x_total = x_total.stack(
datetime_attribute_timeseries(
time_index = x_total,
attribute = "day",
cyclic = True
)
)
# Cyclical encode month using datetime_attribute_timeseries
x_total = x_total.stack(
datetime_attribute_timeseries(
time_index = x_total,
attribute = "month",
cyclic = True
)
)
```
### Store sales covariates
For each of the 54 stores, we will retrieve a different set of covariates.
- Some covariates, such as day of week or oil prices are common to all levels of the hierarchy.
- Others are unique to each series, for example, the local and regional holiday features will take different values for stores in different locations, not to mention the moving averages of past sales or transactions.
- Instead of using Fourier pairs for long-term seasonality features, such as day of month, we use cyclical encoding, which encodes the day of month as a single sine-cosine pair. This will likely generalize better to multiple stores (and algorithms), and is less likely to overfit.
```{python StoreCovars}
# Initialize list of store covariates
store_covars = []
for store in [int(store) for store in stores]:
# Retrieve common covariates
covars = common_covars.copy()
# Retrieve local & regional holiday
covars["local_holiday"] = df[
df["store_nbr"] == store].groupby("date").local_holiday.mean()
covars["regional_holiday"] = df[
df["store_nbr"] == store].groupby("date").regional_holiday.mean()
# Retrieve differenced sales EMA
covars["sales_ema7"] = diff.fit_transform(
df[df["store_nbr"] == store].groupby("date").sales.sum()
).interpolate(
"linear", limit_direction = "backward"
).rolling(
window = 7, min_periods = 1, center = False, win_type = "exponential").mean()
# Retrieve differenced onpromotion, its MA
covars["onpromotion"] = diff.fit_transform(
df[df["store_nbr"] == store].groupby("date").onpromotion.sum()
).interpolate(
"time", limit_direction = "both"
)
covars["onp_ma28"] = covars["onpromotion"].rolling(
window = 28, center = False
).mean().interpolate(
method = "spline", order = 2, limit_direction = "both"
)
# Retrieve differenced transactions, its MA
covars["transactions"] = diff.fit_transform(
df[df["store_nbr"] == store].groupby("date").transactions.sum().interpolate(
"time", limit_direction = "both"
)
)
covars["trns_ma7"] = covars["transactions"].rolling(
window = 7, center = False
).mean().interpolate(
"linear", limit_direction = "backward"
)
# Create darts TS, fill gaps
covars = na_filler.transform(
TimeSeries.from_dataframe(covars, freq = "D")
)
# Cyclical encode day of month using datetime_attribute_timeseries
covars = covars.stack(
datetime_attribute_timeseries(
time_index = covars,
attribute = "day",
cyclic = True
)
)
# Cyclical encode month using datetime_attribute_timeseries
covars = covars.stack(
datetime_attribute_timeseries(
time_index = covars,
attribute = "month",
cyclic = True
)
)
# Append TS to list
store_covars.append(covars)
# Cleanup
del covars, store
```
**Static covariates** are time-invariant covariates, such as store location. Global models use these to differentiate the multiple series they are trained on. They are not used by models trained on one series at a time.
- These could be quite useful for our deep learning models: For example, a complex combination of weights for the store static covariates and the trend features can allow a model adjust its trend predictions for each store.
- We'll retrieve the store location, type and cluster information and one-hot encode them, to be later embedded into the target series. We'll create a Pandas dataframe where columns are static covariates, and the index is the store numbers, to be passed into Darts.
- One-hot encoding will create a lot of columns, and there may be better encoding methods to use here, especially for tree-based models (though we won't apply any tree-based models globally).
```{python StoreStaticCovars}
# Create dataframe where column = static covariate and index = store nbr
store_static = df[["store_nbr", "city", "state", "store_type", "store_cluster"]].reset_index().drop("date", axis=1).drop_duplicates().set_index("store_nbr")
# Convert store cluster to string
store_static["store_cluster"] = store_static["store_cluster"].astype(str)
# One-hot encode static covariates
store_static = pd.get_dummies(store_static, sparse = False, drop_first = True)
```
### Disaggregated sales covariates
We'll retrieve 1782 covariate series for our 1782 bottom level target series. This takes around 10 minutes on my machine, though the code is simpler as no aggregation is necessary.
```{python DisaggCovars}
# Initialize list of disagg covariates
disagg_covars = []
for series in tqdm(categories_stores):
# Retrieve common covariates
covars = common_covars.copy()
# Retrieve local & regional holiday
covars["local_holiday"] = df[
df["category_store_nbr"] == series].local_holiday.copy()
covars["regional_holiday"] = df[
df["category_store_nbr"] == series].regional_holiday.copy()
# Retrieve differenced sales EMA
covars["sales_ema7"] = diff.fit_transform(
df[df["category_store_nbr"] == series].sales.copy()).interpolate(
"linear", limit_direction = "backward"
).rolling(
window = 7, min_periods = 1, center = False, win_type = "exponential").mean()
# Retrieve differenced onpromotion, its MA
covars["onpromotion"] = diff.fit_transform(
df[df["category_store_nbr"] == series].onpromotion.copy()).interpolate(
"time", limit_direction = "both")
covars["onp_ma28"] = covars["onpromotion"].rolling(
window = 28, center = False
).mean().interpolate(
method = "spline", order = 2, limit_direction = "both")
# Retrieve differenced transactions, its MA
covars["transactions"] = diff.fit_transform(
df[df["category_store_nbr"] == series].transactions.copy()).interpolate(
"time", limit_direction = "both")
covars["trns_ma7"] = covars["transactions"].rolling(
window = 7, center = False
).mean().interpolate(
"linear", limit_direction = "backward")
# Create darts TS, fill gaps
covars = na_filler.transform(
TimeSeries.from_dataframe(covars, freq = "D")
)
# Cyclical encode day of month using datetime_attribute_timeseries
covars = covars.stack(
datetime_attribute_timeseries(
time_index = covars,
attribute = "day",
cyclic = True
)
)
# Cyclical encode month using datetime_attribute_timeseries
covars = covars.stack(
datetime_attribute_timeseries(
time_index = covars,
attribute = "month",
cyclic = True
)
)
# Append TS to list
disagg_covars.append(covars)
# Cleanup
del covars, series
```
We'll also retrieve a set of static covariates for the disaggregated series. In addition to the store information, we have the product category available for use as a static covariate.
```{python DisaggStaticCovars}
# Create dataframe where column = static covariate and index = series label
disagg_static = df[["category", "store_nbr", "city", "state", "store_type", "store_cluster", "category_store_nbr"]].reset_index().drop("date", axis=1).drop_duplicates().set_index("category_store_nbr")
# Convert store cluster to string
disagg_static["store_cluster"] = disagg_static["store_cluster"].astype(str)
# One-hot encode static covariates
disagg_static = pd.get_dummies(disagg_static, sparse = False, drop_first = True)
```
## Helper functions for modeling
We'll define some performance scoring, plotting and transformation functions.
We'll look at several performance metrics, but the most important one is RMSLE, as log errors penalize underpredictions more severely, which makes sense for sales forecasts. The competition is also scored on RMSLE.
```{python ScoringFunc}
# Define model scoring function for total sales (one series)
def perf_scores(val, pred, model = "drift", rounding = 4, logtrafo = True):
if logtrafo == True:
scores_dict = {
"MAE": mae(trafo_exp(val), trafo_exp(pred)),
"MSE": mse(trafo_exp(val), trafo_exp(pred)),
"RMSE": rmse(trafo_exp(val), trafo_exp(pred)),
"RMSLE": rmse(val, pred),
"MAPE": mape(trafo_exp(val), trafo_exp(pred))
}
else:
scores_dict = {
"MAE": mae(val, pred),
"MSE": mse(val, pred),
"RMSE": rmse(val, pred),
"RMSLE": rmsle(val, pred),
"MAPE": mape(val, pred)
}
print("Model: " + model)
for key in scores_dict:
print(
key + ": " +
str(round(scores_dict[key], rounding))
)
print("--------")
```
```{python HierarchyScoringFunc}
# Define model scoring function for hierarchy nodes (multiple series)
def scores_hierarchy(val, pred, subset, model, rounding = 4):
def measure_mae(val, pred, subset):
return mae([val[c] for c in subset], [pred[c] for c in subset])
def measure_mse(val, pred, subset):
return mse([val[c] for c in subset], [pred[c] for c in subset])
def measure_rmse(val, pred, subset):
return rmse([val[c] for c in subset], [pred[c] for c in subset])
def measure_rmsle(val, pred, subset):
return rmsle([(val[c]) for c in subset], [pred[c] for c in subset])
scores_dict = {
"MAE": measure_mae(val, pred, subset),
"MSE": measure_mse(val, pred, subset),
"RMSE": measure_rmse(val, pred, subset),
"RMSLE": measure_rmsle(val, pred, subset)
}
print("Model = " + model)
for key in scores_dict:
print(
key + ": mean = " +
str(round(np.nanmean(scores_dict[key]), rounding)) +
", sd = " +
str(round(np.nanstd(scores_dict[key]), rounding)) +
", min = " + str(round(min(scores_dict[key]), rounding)) +
", max = " +
str(round(max(scores_dict[key]), rounding))
)
print("--------")
```
```{python ScorePlotFunc}
# Define model score plotting function for hierarchy nodes
def scores_plot(val, preds_dict, subset, logscale = True, title = "Plot Title"):
# Scoring functions
def measure_mae(val, pred, subset):
return mae([val[c] for c in subset], [pred[c] for c in subset])
def measure_mse(val, pred, subset):
return mse([val[c] for c in subset], [pred[c] for c in subset])
def measure_rmse(val, pred, subset):
return rmse([val[c] for c in subset], [pred[c] for c in subset])
def measure_rmsle(val, pred, subset):
return rmsle([(val[c]) for c in subset], [pred[c] for c in subset])
scores_df_all = []
for key in preds_dict:
# Dict of scores for 1 model
scores_dict = {
"MAE": measure_mae(val, preds_dict[key], subset),
"MSE": measure_mse(val, preds_dict[key], subset),
"RMSE": measure_rmse(val, preds_dict[key], subset),
"RMSLE": measure_rmsle(val, preds_dict[key], subset),
"Model": key
}
# df of scores for 1 model
scores_df = pd.DataFrame(
data = scores_dict
)
# Append to list of score df's
scores_df_all.append(scores_df)
# Combine all models' score dfs
scores_df_all = pd.concat(scores_df_all)
# Create fig. of 4 histplots, one for each metric, grouped by model
fig, ax = plt.subplots(2, 2)
plt.suptitle(title)
_ = sns.histplot(
data = scores_df_all,
x = "MAE",
hue = "Model",
element = "poly",
log_scale = logscale,
ax = ax[0,0],
legend = False
)
_ = sns.histplot(
data = scores_df_all,
x = "MSE",
hue = "Model",
element = "poly",
log_scale = logscale,
ax = ax[0,1]
)
_ = sns.histplot(
data = scores_df_all,
x = "RMSE",
hue = "Model",
element = "poly",
log_scale = logscale,
ax = ax[1,0],
legend = False