models.nhits.ipynb 34.6 KB
Newer Older
chenzk's avatar
v1.0  
chenzk committed
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| default_exp models.nhits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# NHITS"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Long-horizon forecasting is challenging because of the *volatility* of the predictions and the *computational complexity*. To solve this problem we created the Neural Hierarchical Interpolation for Time Series (NHITS). `NHITS` builds upon `NBEATS` and specializes its partial outputs in the different frequencies of the time series through hierarchical interpolation and multi-rate input\n",
    "processing. On the long-horizon forecasting task `NHITS` improved accuracy by 25% on AAAI's best paper award the `Informer`, while being 50x faster.\n",
    "\n",
    "The model is composed of several MLPs with ReLU non-linearities. Blocks are connected via doubly residual stacking principle with the backcast $\\mathbf{\\tilde{y}}_{t-L:t,l}$ and forecast $\\mathbf{\\hat{y}}_{t+1:t+H,l}$ outputs of the l-th block. Multi-rate input pooling, hierarchical interpolation and backcast residual connections together induce the specialization of the additive predictions in different signal bands, reducing memory footprint and computational time, thus improving the architecture parsimony and accuracy.\n",
    "\n",
    "**References**<br>\n",
    "-[Boris N. Oreshkin, Dmitri Carpov, Nicolas Chapados, Yoshua Bengio (2019). \"N-BEATS: Neural basis expansion analysis for interpretable time series forecasting\".](https://arxiv.org/abs/1905.10437)<br>\n",
    "-[Cristian Challu, Kin G. Olivares, Boris N. Oreshkin, Federico Garza, Max Mergenthaler-Canseco, Artur Dubrawski (2023). \"NHITS: Neural Hierarchical Interpolation for Time Series Forecasting\". Accepted at the Thirty-Seventh AAAI Conference on Artificial Intelligence.](https://arxiv.org/abs/2201.12886)<br>\n",
    "-[Zhou, H.; Zhang, S.; Peng, J.; Zhang, S.; Li, J.; Xiong, H.; and Zhang, W. (2020). \"Informer: Beyond Efficient Transformer for Long Sequence Time-Series Forecasting\". Association for the Advancement of Artificial Intelligence Conference 2021 (AAAI 2021).](https://arxiv.org/abs/2012.07436)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Figure 1. Neural Hierarchical Interpolation for Time Series (NHITS).](imgs_models/nhits.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "from typing import Tuple, Optional\n",
    "\n",
    "import numpy as np\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "\n",
    "from neuralforecast.losses.pytorch import MAE\n",
    "from neuralforecast.common._base_windows import BaseWindows"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "import logging\n",
    "import warnings\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "from fastcore.test import test_eq\n",
    "from nbdev.showdoc import show_doc\n",
    "from neuralforecast.utils import generate_series"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "logging.getLogger(\"pytorch_lightning\").setLevel(logging.ERROR)\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "\n",
    "#plt.rcParams[\"axes.grid\"]=True\n",
    "plt.rcParams['font.family'] = 'serif'\n",
    "#plt.rcParams[\"figure.figsize\"] = (4,2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "class _IdentityBasis(nn.Module):\n",
    "    def __init__(self, backcast_size: int, forecast_size: int, \n",
    "                 interpolation_mode: str, out_features: int=1):\n",
    "        super().__init__()\n",
    "        assert (interpolation_mode in ['linear','nearest']) or ('cubic' in interpolation_mode)\n",
    "        self.forecast_size = forecast_size\n",
    "        self.backcast_size = backcast_size\n",
    "        self.interpolation_mode = interpolation_mode\n",
    "        self.out_features = out_features\n",
    " \n",
    "    def forward(self, theta: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n",
    "\n",
    "        backcast = theta[:, :self.backcast_size]\n",
    "        knots = theta[:, self.backcast_size:]\n",
    "\n",
    "        # Interpolation is performed on default dim=-1 := H\n",
    "        knots = knots.reshape(len(knots), self.out_features, -1)\n",
    "        if self.interpolation_mode in ['nearest', 'linear']:\n",
    "            #knots = knots[:,None,:]\n",
    "            forecast = F.interpolate(knots, size=self.forecast_size, mode=self.interpolation_mode)\n",
    "            #forecast = forecast[:,0,:]\n",
    "        elif 'cubic' in self.interpolation_mode:\n",
    "            if self.out_features>1:\n",
    "                raise Exception('Cubic interpolation not available with multiple outputs.')\n",
    "            batch_size = len(backcast)\n",
    "            knots = knots[:,None,:,:]\n",
    "            forecast = torch.zeros((len(knots), self.forecast_size), device=knots.device)\n",
    "            n_batches = int(np.ceil(len(knots)/batch_size))\n",
    "            for i in range(n_batches):\n",
    "                forecast_i = F.interpolate(knots[i*batch_size:(i+1)*batch_size], \n",
    "                                           size=self.forecast_size, mode='bicubic')\n",
    "                forecast[i*batch_size:(i+1)*batch_size] += forecast_i[:,0,0,:] # [B,None,H,H] -> [B,H]\n",
    "            forecast = forecast[:,None,:] # [B,H] -> [B,None,H]\n",
    "\n",
    "        # [B,Q,H] -> [B,H,Q]\n",
    "        forecast = forecast.permute(0, 2, 1)\n",
    "        return backcast, forecast"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exporti\n",
    "ACTIVATIONS = ['ReLU',\n",
    "               'Softplus',\n",
    "               'Tanh',\n",
    "               'SELU',\n",
    "               'LeakyReLU',\n",
    "               'PReLU',\n",
    "               'Sigmoid']\n",
    "\n",
    "POOLING = ['MaxPool1d',\n",
    "           'AvgPool1d']\n",
    "\n",
    "class NHITSBlock(nn.Module):\n",
    "    \"\"\"\n",
    "    NHITS block which takes a basis function as an argument.\n",
    "    \"\"\"\n",
    "    def __init__(self, \n",
    "                 input_size: int,\n",
    "                 h: int,\n",
    "                 n_theta: int,\n",
    "                 mlp_units: list,\n",
    "                 basis: nn.Module,\n",
    "                 futr_input_size: int,\n",
    "                 hist_input_size: int,\n",
    "                 stat_input_size: int,\n",
    "                 n_pool_kernel_size: int,\n",
    "                 pooling_mode: str,\n",
    "                 dropout_prob: float,\n",
    "                 activation: str):\n",
    "        super().__init__()\n",
    "\n",
    "        pooled_hist_size = int(np.ceil(input_size/n_pool_kernel_size))\n",
    "        pooled_futr_size = int(np.ceil((input_size+h)/n_pool_kernel_size))\n",
    "\n",
    "        input_size = pooled_hist_size + \\\n",
    "                     hist_input_size * pooled_hist_size + \\\n",
    "                     futr_input_size * pooled_futr_size + stat_input_size\n",
    "\n",
    "        self.dropout_prob = dropout_prob\n",
    "        self.futr_input_size = futr_input_size\n",
    "        self.hist_input_size = hist_input_size\n",
    "        self.stat_input_size = stat_input_size\n",
    "        \n",
    "        assert activation in ACTIVATIONS, f'{activation} is not in {ACTIVATIONS}'\n",
    "        assert pooling_mode in POOLING, f'{pooling_mode} is not in {POOLING}'\n",
    "\n",
    "        activ = getattr(nn, activation)()\n",
    "\n",
    "        self.pooling_layer = getattr(nn, pooling_mode)(kernel_size=n_pool_kernel_size,\n",
    "                                                       stride=n_pool_kernel_size, ceil_mode=True)\n",
    "\n",
    "        # Block MLPs\n",
    "        hidden_layers = [nn.Linear(in_features=input_size, \n",
    "                                   out_features=mlp_units[0][0])]\n",
    "        for layer in mlp_units:\n",
    "            hidden_layers.append(nn.Linear(in_features=layer[0], \n",
    "                                           out_features=layer[1]))\n",
    "            hidden_layers.append(activ)\n",
    "\n",
    "            if self.dropout_prob>0:\n",
    "                #raise NotImplementedError('dropout')\n",
    "                hidden_layers.append(nn.Dropout(p=self.dropout_prob))\n",
    "\n",
    "        output_layer = [nn.Linear(in_features=mlp_units[-1][1], out_features=n_theta)]\n",
    "        layers = hidden_layers + output_layer\n",
    "        self.layers = nn.Sequential(*layers)\n",
    "        self.basis = basis\n",
    "\n",
    "    def forward(self, insample_y: torch.Tensor, futr_exog: torch.Tensor,\n",
    "                hist_exog: torch.Tensor, stat_exog: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n",
    "\n",
    "        # Pooling\n",
    "        # Pool1d needs 3D input, (B,C,L), adding C dimension\n",
    "        insample_y = insample_y.unsqueeze(1)\n",
    "        insample_y = self.pooling_layer(insample_y)\n",
    "        insample_y = insample_y.squeeze(1)\n",
    "\n",
    "        # Flatten MLP inputs [B, L+H, C] -> [B, (L+H)*C]\n",
    "        # Contatenate [ Y_t, | X_{t-L},..., X_{t} | F_{t-L},..., F_{t+H} | S ]\n",
    "        batch_size = len(insample_y)\n",
    "        if self.hist_input_size > 0:\n",
    "            hist_exog = hist_exog.permute(0,2,1) # [B, L, C] -> [B, C, L]\n",
    "            hist_exog = self.pooling_layer(hist_exog)\n",
    "            hist_exog = hist_exog.permute(0,2,1) # [B, C, L] -> [B, L, C]\n",
    "            insample_y = torch.cat(( insample_y, hist_exog.reshape(batch_size,-1) ), dim=1)\n",
    "\n",
    "        if self.futr_input_size > 0:\n",
    "            futr_exog = futr_exog.permute(0,2,1) # [B, L, C] -> [B, C, L]\n",
    "            futr_exog = self.pooling_layer(futr_exog)\n",
    "            futr_exog = futr_exog.permute(0,2,1) # [B, C, L] -> [B, L, C]\n",
    "            insample_y = torch.cat(( insample_y, futr_exog.reshape(batch_size,-1) ), dim=1)\n",
    "\n",
    "        if self.stat_input_size > 0:\n",
    "            insample_y = torch.cat(( insample_y, stat_exog.reshape(batch_size,-1) ), dim=1)\n",
    "\n",
    "        # Compute local projection weights and projection\n",
    "        theta = self.layers(insample_y)\n",
    "        backcast, forecast = self.basis(theta)\n",
    "        return backcast, forecast"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "class NHITS(BaseWindows):\n",
    "    \"\"\" NHITS\n",
    "\n",
    "    The Neural Hierarchical Interpolation for Time Series (NHITS), is an MLP-based deep\n",
    "    neural architecture with backward and forward residual links. NHITS tackles volatility and\n",
    "    memory complexity challenges, by locally specializing its sequential predictions into\n",
    "    the signals frequencies with hierarchical interpolation and pooling.\n",
    "\n",
    "    **Parameters:**<br>\n",
    "    `h`: int, Forecast horizon. <br>\n",
    "    `input_size`: int, autorregresive inputs size, y=[1,2,3,4] input_size=2 -> y_[t-2:t]=[1,2].<br>\n",
    "    `stat_exog_list`: str list, static exogenous columns.<br>\n",
    "    `hist_exog_list`: str list, historic exogenous columns.<br>\n",
    "    `futr_exog_list`: str list, future exogenous columns.<br>\n",
    "    `exclude_insample_y`: bool=False, the model skips the autoregressive features y[t-input_size:t] if True.<br>\n",
    "    `activation`: str, activation from ['ReLU', 'Softplus', 'Tanh', 'SELU', 'LeakyReLU', 'PReLU', 'Sigmoid'].<br>\n",
    "    `stack_types`: List[str], stacks list in the form N * ['identity'], to be deprecated in favor of `n_stacks`. Note that len(stack_types)=len(n_freq_downsample)=len(n_pool_kernel_size).<br>\n",
    "    `n_blocks`: List[int], Number of blocks for each stack. Note that len(n_blocks) = len(stack_types).<br>\n",
    "    `mlp_units`: List[List[int]], Structure of hidden layers for each stack type. Each internal list should contain the number of units of each hidden layer. Note that len(n_hidden) = len(stack_types).<br>\n",
    "    `n_freq_downsample`: List[int], list with the stack's coefficients (inverse expressivity ratios). Note that len(stack_types)=len(n_freq_downsample)=len(n_pool_kernel_size).<br>\n",
    "    `interpolation_mode`: str='linear', interpolation basis from ['linear', 'nearest', 'cubic'].<br>\n",
    "    `n_pool_kernel_size`: List[int], list with the size of the windows to take a max/avg over. Note that len(stack_types)=len(n_freq_downsample)=len(n_pool_kernel_size).<br>\n",
    "    `pooling_mode`: str, input pooling module from ['MaxPool1d', 'AvgPool1d'].<br>\n",
    "    `dropout_prob_theta`: float, Float between (0, 1). Dropout for NHITS basis.<br>\n",
    "    `loss`: PyTorch module, instantiated train loss class from [losses collection](https://nixtla.github.io/neuralforecast/losses.pytorch.html).<br>\n",
    "    `valid_loss`: PyTorch module=`loss`, instantiated valid loss class from [losses collection](https://nixtla.github.io/neuralforecast/losses.pytorch.html).<br>\n",
    "    `max_steps`: int=1000, maximum number of training steps.<br>\n",
    "    `learning_rate`: float=1e-3, Learning rate between (0, 1).<br>\n",
    "    `num_lr_decays`: int=-1, Number of learning rate decays, evenly distributed across max_steps.<br>\n",
    "    `early_stop_patience_steps`: int=-1, Number of validation iterations before early stopping.<br>\n",
    "    `val_check_steps`: int=100, Number of training steps between every validation loss check.<br>\n",
    "    `batch_size`: int=32, number of different series in each batch.<br>\n",
    "    `valid_batch_size`: int=None, number of different series in each validation and test batch, if None uses batch_size.<br>\n",
    "    `windows_batch_size`: int=1024, number of windows to sample in each training batch, default uses all.<br>\n",
    "    `inference_windows_batch_size`: int=-1, number of windows to sample in each inference batch, -1 uses all.<br>\n",
    "    `start_padding_enabled`: bool=False, if True, the model will pad the time series with zeros at the beginning, by input size.<br>\n",
    "    `step_size`: int=1, step size between each window of temporal data.<br>\n",
    "    `scaler_type`: str='identity', type of scaler for temporal inputs normalization see [temporal scalers](https://nixtla.github.io/neuralforecast/common.scalers.html).<br>\n",
    "    `random_seed`: int, random_seed for pytorch initializer and numpy generators.<br>\n",
    "    `num_workers_loader`: int=os.cpu_count(), workers to be used by `TimeSeriesDataLoader`.<br>\n",
    "    `drop_last_loader`: bool=False, if True `TimeSeriesDataLoader` drops last non-full batch.<br>\n",
    "    `alias`: str, optional,  Custom name of the model.<br>\n",
    "    `optimizer`: Subclass of 'torch.optim.Optimizer', optional, user specified optimizer instead of the default choice (Adam).<br>\n",
    "    `optimizer_kwargs`: dict, optional, list of parameters used by the user specified `optimizer`.<br>\n",
    "    `**trainer_kwargs`: int,  keyword trainer arguments inherited from [PyTorch Lighning's trainer](https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.trainer.trainer.Trainer.html?highlight=trainer).<br>    \n",
    "\n",
    "    **References:**<br>\n",
    "    -[Cristian Challu, Kin G. Olivares, Boris N. Oreshkin, Federico Garza, \n",
    "    Max Mergenthaler-Canseco, Artur Dubrawski (2023). \"NHITS: Neural Hierarchical Interpolation for Time Series Forecasting\".\n",
    "    Accepted at the Thirty-Seventh AAAI Conference on Artificial Intelligence.](https://arxiv.org/abs/2201.12886)\n",
    "    \"\"\"\n",
    "    # Class attributes\n",
    "    SAMPLING_TYPE = 'windows'\n",
    "\n",
    "    def __init__(self, \n",
    "                 h,\n",
    "                 input_size,\n",
    "                 futr_exog_list = None,\n",
    "                 hist_exog_list = None,\n",
    "                 stat_exog_list = None,\n",
    "                 exclude_insample_y = False,\n",
    "                 stack_types: list = ['identity', 'identity', 'identity'],\n",
    "                 n_blocks: list = [1, 1, 1],\n",
    "                 mlp_units: list = 3 * [[512, 512]],\n",
    "                 n_pool_kernel_size: list = [2, 2, 1],\n",
    "                 n_freq_downsample: list = [4, 2, 1],\n",
    "                 pooling_mode: str = 'MaxPool1d',\n",
    "                 interpolation_mode: str = 'linear',\n",
    "                 dropout_prob_theta = 0.,\n",
    "                 activation = 'ReLU',\n",
    "                 loss = MAE(),\n",
    "                 valid_loss = None,\n",
    "                 max_steps: int = 1000,\n",
    "                 learning_rate: float = 1e-3,\n",
    "                 num_lr_decays: int = 3,\n",
    "                 early_stop_patience_steps: int =-1,\n",
    "                 val_check_steps: int = 100,\n",
    "                 batch_size: int = 32,\n",
    "                 valid_batch_size: Optional[int] = None,\n",
    "                 windows_batch_size: int = 1024,\n",
    "                 inference_windows_batch_size: int = -1,\n",
    "                 start_padding_enabled = False,\n",
    "                 step_size: int = 1,\n",
    "                 scaler_type: str = 'identity',\n",
    "                 random_seed: int = 1,\n",
    "                 num_workers_loader = 0,\n",
    "                 drop_last_loader = False,\n",
    "                 optimizer = None,\n",
    "                 optimizer_kwargs = None,\n",
    "                 **trainer_kwargs):\n",
    "\n",
    "        # Inherit BaseWindows class\n",
    "        super(NHITS, self).__init__(h=h,\n",
    "                                    input_size=input_size,\n",
    "                                    futr_exog_list=futr_exog_list,\n",
    "                                    hist_exog_list=hist_exog_list,\n",
    "                                    stat_exog_list=stat_exog_list,\n",
    "                                    exclude_insample_y = exclude_insample_y,\n",
    "                                    loss=loss,\n",
    "                                    valid_loss=valid_loss,\n",
    "                                    max_steps=max_steps,\n",
    "                                    learning_rate=learning_rate,\n",
    "                                    num_lr_decays=num_lr_decays,\n",
    "                                    early_stop_patience_steps=early_stop_patience_steps,\n",
    "                                    val_check_steps=val_check_steps,\n",
    "                                    batch_size=batch_size,\n",
    "                                    windows_batch_size=windows_batch_size,\n",
    "                                    valid_batch_size=valid_batch_size,\n",
    "                                    inference_windows_batch_size=inference_windows_batch_size,\n",
    "                                    start_padding_enabled=start_padding_enabled,\n",
    "                                    step_size=step_size,\n",
    "                                    scaler_type=scaler_type,\n",
    "                                    num_workers_loader=num_workers_loader,\n",
    "                                    drop_last_loader=drop_last_loader,\n",
    "                                    random_seed=random_seed,\n",
    "                                    optimizer=optimizer,\n",
    "                                    optimizer_kwargs=optimizer_kwargs,\n",
    "                                    **trainer_kwargs)\n",
    "\n",
    "        # Architecture\n",
    "        self.futr_input_size = len(self.futr_exog_list)\n",
    "        self.hist_input_size = len(self.hist_exog_list)\n",
    "        self.stat_input_size = len(self.stat_exog_list)\n",
    "\n",
    "        blocks = self.create_stack(h=h,\n",
    "                                   input_size=input_size,\n",
    "                                   stack_types=stack_types,\n",
    "                                   futr_input_size=self.futr_input_size,\n",
    "                                   hist_input_size=self.hist_input_size,\n",
    "                                   stat_input_size=self.stat_input_size,                                   \n",
    "                                   n_blocks=n_blocks,\n",
    "                                   mlp_units=mlp_units,\n",
    "                                   n_pool_kernel_size=n_pool_kernel_size,\n",
    "                                   n_freq_downsample=n_freq_downsample,\n",
    "                                   pooling_mode=pooling_mode,\n",
    "                                   interpolation_mode=interpolation_mode,\n",
    "                                   dropout_prob_theta=dropout_prob_theta,\n",
    "                                   activation=activation)\n",
    "        self.blocks = torch.nn.ModuleList(blocks)\n",
    "\n",
    "    def create_stack(self,\n",
    "                     h, \n",
    "                     input_size,    \n",
    "                     stack_types, \n",
    "                     n_blocks,\n",
    "                     mlp_units,\n",
    "                     n_pool_kernel_size,\n",
    "                     n_freq_downsample,\n",
    "                     pooling_mode,\n",
    "                     interpolation_mode,\n",
    "                     dropout_prob_theta, \n",
    "                     activation,\n",
    "                     futr_input_size, hist_input_size, stat_input_size):                     \n",
    "\n",
    "        block_list = []\n",
    "        for i in range(len(stack_types)):\n",
    "            for block_id in range(n_blocks[i]):\n",
    "\n",
    "                assert stack_types[i] == 'identity', f'Block type {stack_types[i]} not found!'\n",
    "\n",
    "                n_theta = (input_size + self.loss.outputsize_multiplier*max(h//n_freq_downsample[i], 1) )\n",
    "                basis = _IdentityBasis(backcast_size=input_size, forecast_size=h,\n",
    "                                       out_features=self.loss.outputsize_multiplier,\n",
    "                                       interpolation_mode=interpolation_mode)\n",
    "\n",
    "                nbeats_block = NHITSBlock(h=h,\n",
    "                                          input_size=input_size,\n",
    "                                          futr_input_size=futr_input_size,\n",
    "                                          hist_input_size=hist_input_size,\n",
    "                                          stat_input_size=stat_input_size,                                          \n",
    "                                          n_theta=n_theta,\n",
    "                                          mlp_units=mlp_units,\n",
    "                                          n_pool_kernel_size=n_pool_kernel_size[i],\n",
    "                                          pooling_mode=pooling_mode,\n",
    "                                          basis=basis,\n",
    "                                          dropout_prob=dropout_prob_theta,\n",
    "                                          activation=activation)\n",
    "\n",
    "                # Select type of evaluation and apply it to all layers of block\n",
    "                block_list.append(nbeats_block)\n",
    "                \n",
    "        return block_list\n",
    "\n",
    "    def forward(self, windows_batch):\n",
    "        \n",
    "        # Parse windows_batch\n",
    "        insample_y    = windows_batch['insample_y']\n",
    "        insample_mask = windows_batch['insample_mask']\n",
    "        futr_exog     = windows_batch['futr_exog']\n",
    "        hist_exog     = windows_batch['hist_exog']\n",
    "        stat_exog     = windows_batch['stat_exog']\n",
    "        \n",
    "        # insample\n",
    "        residuals = insample_y.flip(dims=(-1,)) #backcast init\n",
    "        insample_mask = insample_mask.flip(dims=(-1,))\n",
    "        \n",
    "        forecast = insample_y[:, -1:, None] # Level with Naive1\n",
    "        block_forecasts = [ forecast.repeat(1, self.h, 1) ]\n",
    "        for i, block in enumerate(self.blocks):\n",
    "            backcast, block_forecast = block(insample_y=residuals, futr_exog=futr_exog,\n",
    "                                             hist_exog=hist_exog, stat_exog=stat_exog)\n",
    "            residuals = (residuals - backcast) * insample_mask\n",
    "            forecast = forecast + block_forecast\n",
    "            \n",
    "            if self.decompose_forecast:\n",
    "                block_forecasts.append(block_forecast)\n",
    "        \n",
    "        # Adapting output's domain\n",
    "        forecast = self.loss.domain_map(forecast)\n",
    "\n",
    "        if self.decompose_forecast:\n",
    "            # (n_batch, n_blocks, h, output_size)\n",
    "            block_forecasts = torch.stack(block_forecasts)\n",
    "            block_forecasts = block_forecasts.permute(1,0,2,3)\n",
    "            block_forecasts = block_forecasts.squeeze(-1) # univariate output\n",
    "            return block_forecasts\n",
    "        else:\n",
    "            return forecast"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(NHITS)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(NHITS.fit, name='NHITS.fit')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(NHITS.predict, name='NHITS.predict')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "import pytorch_lightning as pl\n",
    "\n",
    "from neuralforecast.utils import AirPassengersDF as Y_df\n",
    "from neuralforecast.tsdataset import TimeSeriesDataset, TimeSeriesLoader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "Y_train_df = Y_df[Y_df.ds<Y_df['ds'].values[-24]] # 132 train\n",
    "Y_test_df = Y_df[Y_df.ds>=Y_df['ds'].values[-24]] # 12 test\n",
    "\n",
    "dataset, *_ = TimeSeriesDataset.from_df(df = Y_train_df)\n",
    "model = NHITS(h=24,\n",
    "              input_size=24*2,\n",
    "              max_steps=1,\n",
    "              windows_batch_size=None, \n",
    "              n_freq_downsample=[12,4,1], \n",
    "              pooling_mode='MaxPool1d')\n",
    "model.fit(dataset=dataset)\n",
    "y_hat = model.predict(dataset=dataset)\n",
    "Y_test_df['NHITS'] = y_hat\n",
    "\n",
    "pd.concat([Y_train_df, Y_test_df]).drop('unique_id', axis=1).set_index('ds').plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "# qualitative decomposition evaluation\n",
    "y_hat = model.decompose(dataset=dataset)\n",
    "\n",
    "fig, ax = plt.subplots(5, 1, figsize=(10, 15))\n",
    "\n",
    "ax[0].plot(Y_test_df['y'].values, label='True', color=\"#9C9DB2\", linewidth=4)\n",
    "ax[0].plot(y_hat.sum(axis=1).flatten(), label='Forecast', color=\"#7B3841\")\n",
    "ax[0].legend(prop={'size': 20})\n",
    "for label in (ax[0].get_xticklabels() + ax[0].get_yticklabels()):\n",
    "    label.set_fontsize(18)\n",
    "ax[0].set_ylabel('y', fontsize=20)\n",
    "\n",
    "ax[1].plot(y_hat[0,0], label='level', color=\"#7B3841\")\n",
    "ax[1].set_ylabel('Level', fontsize=20)\n",
    "\n",
    "ax[2].plot(y_hat[0,1], label='stack1', color=\"#7B3841\")\n",
    "ax[2].set_ylabel('Stack 1', fontsize=20)\n",
    "\n",
    "ax[3].plot(y_hat[0,2], label='stack2', color=\"#D9AE9E\")\n",
    "ax[3].set_ylabel('Stack 2', fontsize=20)\n",
    "\n",
    "ax[4].plot(y_hat[0,3], label='stack3', color=\"#D9AE9E\")\n",
    "ax[4].set_ylabel('Stack 3', fontsize=20)\n",
    "\n",
    "ax[4].set_xlabel('Prediction \\u03C4 \\u2208 {t+1,..., t+H}', fontsize=20)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Usage Example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| eval: false\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import pytorch_lightning as pl\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from neuralforecast import NeuralForecast\n",
    "from neuralforecast.models import NHITS\n",
    "from neuralforecast.losses.pytorch import MQLoss, DistributionLoss, PMM, GMM, NBMM\n",
    "from neuralforecast.tsdataset import TimeSeriesDataset\n",
    "from neuralforecast.utils import AirPassengers, AirPassengersPanel, AirPassengersStatic\n",
    "\n",
    "\n",
    "Y_train_df = AirPassengersPanel[AirPassengersPanel.ds<AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 132 train\n",
    "Y_test_df = AirPassengersPanel[AirPassengersPanel.ds>=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test\n",
    "\n",
    "model = NHITS(h=12,\n",
    "              input_size=24,\n",
    "              loss=DistributionLoss(distribution='StudentT', level=[80, 90], return_params=True),\n",
    "              #loss=DistributionLoss(distribution='Normal', level=[80, 90], return_params=True),\n",
    "              #loss=DistributionLoss(distribution='Poisson', level=[80, 90], return_params=True),\n",
    "              #loss=DistributionLoss(distribution='Tweedie', level=[80, 90], rho=1.5),\n",
    "              #loss=DistributionLoss(distribution='NegativeBinomial', level=[80, 90], return_params=True),\n",
    "              #loss=NBMM(n_components=2, level=[80,90]),\n",
    "              #loss=GMM(n_components=2, level=[80,90]),\n",
    "              #loss=PMM(n_components=1, level=[80,90]),\n",
    "              stat_exog_list=['airline1'],\n",
    "              futr_exog_list=['trend'],\n",
    "              n_freq_downsample=[2, 1, 1],\n",
    "              scaler_type='robust',\n",
    "              max_steps=200,\n",
    "              early_stop_patience_steps=2,\n",
    "              inference_windows_batch_size=1,\n",
    "              val_check_steps=10,\n",
    "              learning_rate=1e-3)\n",
    "\n",
    "fcst = NeuralForecast(models=[model], freq='M')\n",
    "fcst.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12)\n",
    "forecasts = fcst.predict(futr_df=Y_test_df)\n",
    "\n",
    "# Plot quantile predictions\n",
    "Y_hat_df = forecasts.reset_index(drop=False).drop(columns=['unique_id','ds'])\n",
    "plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1)\n",
    "plot_df = pd.concat([Y_train_df, plot_df])\n",
    "\n",
    "plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1)\n",
    "plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True')\n",
    "plt.plot(plot_df['ds'], plot_df['NHITS-median'], c='blue', label='median')\n",
    "plt.fill_between(x=plot_df['ds'][-12:], \n",
    "                 y1=plot_df['NHITS-lo-90'][-12:].values, \n",
    "                 y2=plot_df['NHITS-hi-90'][-12:].values,\n",
    "                 alpha=0.4, label='level 90')\n",
    "plt.legend()\n",
    "plt.grid()\n",
    "plt.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| eval: false\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import pytorch_lightning as pl\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from neuralforecast import NeuralForecast\n",
    "from neuralforecast.models import NHITS\n",
    "from neuralforecast.losses.pytorch import DistributionLoss, HuberLoss, MAE\n",
    "from neuralforecast.tsdataset import TimeSeriesDataset\n",
    "from neuralforecast.utils import AirPassengers, AirPassengersPanel, AirPassengersStatic\n",
    "\n",
    "#AirPassengersPanel['y'] = 1 * (AirPassengersPanel['trend'] % 12) < 2\n",
    "Y_train_df = AirPassengersPanel[AirPassengersPanel.ds<AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 132 train\n",
    "Y_test_df = AirPassengersPanel[AirPassengersPanel.ds>=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test\n",
    "\n",
    "model = NHITS(h=12,\n",
    "              input_size=24,\n",
    "              #loss=DistributionLoss(distribution='StudentT', level=[80, 90], return_params=True),\n",
    "              loss=HuberLoss(delta=0.5),\n",
    "              valid_loss=MAE(),\n",
    "              stat_exog_list=['airline1'],\n",
    "              scaler_type='robust',\n",
    "              max_steps=200,\n",
    "              early_stop_patience_steps=2,\n",
    "              val_check_steps=10,\n",
    "              learning_rate=1e-3)\n",
    "\n",
    "fcst = NeuralForecast(models=[model], freq='M')\n",
    "fcst.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12)\n",
    "forecasts = fcst.predict(futr_df=Y_test_df)\n",
    "\n",
    "# Plot quantile predictions\n",
    "Y_hat_df = forecasts.reset_index(drop=False).drop(columns=['unique_id','ds'])\n",
    "plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1)\n",
    "plot_df = pd.concat([Y_train_df, plot_df])\n",
    "\n",
    "plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1)\n",
    "plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True')\n",
    "plt.plot(plot_df['ds'], plot_df['NHITS'], c='blue', label='median')\n",
    "# plt.plot(plot_df['ds'], plot_df['NHITS-median'], c='blue', label='median')\n",
    "# plt.fill_between(x=plot_df['ds'][-12:], \n",
    "#                  y1=plot_df['NHITS-lo-90'][-12:].values, \n",
    "#                  y2=plot_df['NHITS-hi-90'][-12:].values,\n",
    "#                  alpha=0.4, label='level 90')\n",
    "plt.legend()\n",
    "plt.grid()\n",
    "plt.plot()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}