models.nbeats.ipynb 31.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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "524620c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| default_exp models.nbeats"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15392f6f",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12fa25a4",
   "metadata": {},
   "source": [
    "# NBEATS"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "376a8a3a",
   "metadata": {},
   "source": [
    "The Neural Basis Expansion Analysis (`NBEATS`) is an `MLP`-based deep neural architecture with backward and forward residual links. The network has two variants: (1) in its interpretable configuration, `NBEATS` sequentially projects the signal into polynomials and harmonic basis to learn trend and seasonality components; (2) in its generic configuration, it substitutes the polynomial and harmonic basis for identity basis and larger network's depth. The Neural Basis Expansion Analysis with Exogenous (`NBEATSx`), incorporates projections to exogenous temporal variables available at the time of the prediction.\n",
    "\n",
    "This method proved state-of-the-art performance on the M3, M4, and Tourism Competition datasets, improving accuracy by 3% over the `ESRNN` M4 competition winner.\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)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bddd17a6",
   "metadata": {},
   "source": [
    "![Figure 1. Neural Basis Expansion Analysis.](imgs_models/nbeats.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44065066-e72a-431f-938f-1528adef9fe8",
   "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",
    "\n",
    "from neuralforecast.losses.pytorch import MAE\n",
    "from neuralforecast.common._base_windows import BaseWindows"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4a77bb35",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "from fastcore.test import test_eq\n",
    "from nbdev.showdoc import show_doc\n",
    "from neuralforecast.utils import generate_series\n",
    "\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9b7a9fae-2c29-47e2-874e-ca1f20bf7040",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exporti\n",
    "class IdentityBasis(nn.Module):\n",
    "    def __init__(self, backcast_size: int, forecast_size: int,\n",
    "                 out_features: int=1):\n",
    "        super().__init__()\n",
    "        self.out_features = out_features\n",
    "        self.forecast_size = forecast_size\n",
    "        self.backcast_size = backcast_size\n",
    " \n",
    "    def forward(self, theta: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n",
    "        backcast = theta[:, :self.backcast_size]\n",
    "        forecast = theta[:, self.backcast_size:]\n",
    "        forecast = forecast.reshape(len(forecast), -1, self.out_features)\n",
    "        return backcast, forecast\n",
    "\n",
    "class TrendBasis(nn.Module):\n",
    "    def __init__(self, degree_of_polynomial: int,\n",
    "                 backcast_size: int, forecast_size: int,\n",
    "                 out_features: int=1):\n",
    "        super().__init__()\n",
    "        self.out_features = out_features\n",
    "        polynomial_size = degree_of_polynomial + 1\n",
    "        self.backcast_basis = nn.Parameter(\n",
    "            torch.tensor(np.concatenate([np.power(np.arange(backcast_size, dtype=float) / backcast_size, i)[None, :]\n",
    "                                    for i in range(polynomial_size)]), dtype=torch.float32), requires_grad=False)\n",
    "        self.forecast_basis = nn.Parameter(\n",
    "            torch.tensor(np.concatenate([np.power(np.arange(forecast_size, dtype=float) / forecast_size, i)[None, :]\n",
    "                                    for i in range(polynomial_size)]), dtype=torch.float32), requires_grad=False)\n",
    "    \n",
    "    def forward(self, theta: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n",
    "        polynomial_size = self.forecast_basis.shape[0] # [polynomial_size, L+H]\n",
    "        backcast_theta = theta[:, :polynomial_size]\n",
    "        forecast_theta = theta[:, polynomial_size:]\n",
    "        forecast_theta = forecast_theta.reshape(len(forecast_theta),polynomial_size,-1)\n",
    "        backcast = torch.einsum('bp,pt->bt', backcast_theta, self.backcast_basis)\n",
    "        forecast = torch.einsum('bpq,pt->btq', forecast_theta, self.forecast_basis)\n",
    "        return backcast, forecast\n",
    "\n",
    "class SeasonalityBasis(nn.Module):\n",
    "    def __init__(self, harmonics: int, \n",
    "                 backcast_size: int, forecast_size: int,\n",
    "                 out_features: int=1):\n",
    "        super().__init__()\n",
    "        self.out_features = out_features\n",
    "        frequency = np.append(np.zeros(1, dtype=float),\n",
    "                                        np.arange(harmonics, harmonics / 2 * forecast_size,\n",
    "                                                    dtype=float) / harmonics)[None, :]\n",
    "        backcast_grid = -2 * np.pi * (\n",
    "                np.arange(backcast_size, dtype=float)[:, None] / forecast_size) * frequency\n",
    "        forecast_grid = 2 * np.pi * (\n",
    "                np.arange(forecast_size, dtype=float)[:, None] / forecast_size) * frequency\n",
    "\n",
    "        backcast_cos_template = torch.tensor(np.transpose(np.cos(backcast_grid)), dtype=torch.float32)\n",
    "        backcast_sin_template = torch.tensor(np.transpose(np.sin(backcast_grid)), dtype=torch.float32)\n",
    "        backcast_template = torch.cat([backcast_cos_template, backcast_sin_template], dim=0)\n",
    "\n",
    "        forecast_cos_template = torch.tensor(np.transpose(np.cos(forecast_grid)), dtype=torch.float32)\n",
    "        forecast_sin_template = torch.tensor(np.transpose(np.sin(forecast_grid)), dtype=torch.float32)\n",
    "        forecast_template = torch.cat([forecast_cos_template, forecast_sin_template], dim=0)\n",
    "\n",
    "        self.backcast_basis = nn.Parameter(backcast_template, requires_grad=False)\n",
    "        self.forecast_basis = nn.Parameter(forecast_template, requires_grad=False)\n",
    "\n",
    "    def forward(self, theta: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n",
    "        harmonic_size = self.forecast_basis.shape[0] # [harmonic_size, L+H]\n",
    "        backcast_theta = theta[:, :harmonic_size]\n",
    "        forecast_theta = theta[:, harmonic_size:]\n",
    "        forecast_theta = forecast_theta.reshape(len(forecast_theta),harmonic_size,-1)\n",
    "        backcast = torch.einsum('bp,pt->bt', backcast_theta, self.backcast_basis)\n",
    "        forecast = torch.einsum('bpq,pt->btq', forecast_theta, self.forecast_basis)\n",
    "        return backcast, forecast"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17382790-7d84-4a89-959b-5676afa46392",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exporti\n",
    "ACTIVATIONS = ['ReLU',\n",
    "               'Softplus',\n",
    "               'Tanh',\n",
    "               'SELU',\n",
    "               'LeakyReLU',\n",
    "               'PReLU',\n",
    "               'Sigmoid']\n",
    "\n",
    "class NBEATSBlock(nn.Module):\n",
    "    \"\"\"\n",
    "    N-BEATS block which takes a basis function as an argument.\n",
    "    \"\"\"\n",
    "    def __init__(self, \n",
    "                 input_size: int,\n",
    "                 n_theta: int, \n",
    "                 mlp_units: list,\n",
    "                 basis: nn.Module, \n",
    "                 dropout_prob: float, \n",
    "                 activation: str):\n",
    "        \"\"\"\n",
    "        \"\"\"\n",
    "        super().__init__()\n",
    "\n",
    "        self.dropout_prob = dropout_prob\n",
    "        \n",
    "        assert activation in ACTIVATIONS, f'{activation} is not in {ACTIVATIONS}'\n",
    "        activ = getattr(nn, activation)()\n",
    "        \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) -> Tuple[torch.Tensor, torch.Tensor]:\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,
   "id": "be997aeb-778f-442d-a97a-ff47de2deab6",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "class NBEATS(BaseWindows):\n",
    "    \"\"\" NBEATS\n",
    "\n",
    "    The Neural Basis Expansion Analysis for Time Series (NBEATS), is a simple and yet\n",
    "    effective architecture, it is built with a deep stack of MLPs with the doubly \n",
    "    residual connections. It has a generic and interpretable architecture depending\n",
    "    on the blocks it uses. Its interpretable architecture is recommended for scarce\n",
    "    data settings, as it regularizes its predictions through projections unto harmonic\n",
    "    and trend basis well-suited for most forecasting tasks.\n",
    "\n",
    "    **Parameters:**<br>\n",
    "    `h`: int, forecast horizon.<br>\n",
    "    `input_size`: int, considered autorregresive inputs (lags), y=[1,2,3,4] input_size=2 -> lags=[1,2].<br>\n",
    "    `n_harmonics`: int, Number of harmonic terms for seasonality stack type. Note that len(n_harmonics) = len(stack_types). Note that it will only be used if a seasonality stack is used.<br>\n",
    "    `n_polynomials`: int, polynomial degree for trend stack. Note that len(n_polynomials) = len(stack_types). Note that it will only be used if a trend stack is used.<br>\n",
    "    `stack_types`: List[str], List of stack types. Subset from ['seasonality', 'trend', 'identity'].<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",
    "    `dropout_prob_theta`: float, Float between (0, 1). Dropout for N-BEATS basis.<br>\n",
    "    `shared_weights`: bool, If True, all blocks within each stack will share parameters. <br>\n",
    "    `activation`: str, activation from ['ReLU', 'Softplus', 'Tanh', 'SELU', 'LeakyReLU', 'PReLU', 'Sigmoid'].<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=3, 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",
    "    -[Boris N. Oreshkin, Dmitri Carpov, Nicolas Chapados, Yoshua Bengio (2019). \n",
    "    \"N-BEATS: Neural basis expansion analysis for interpretable time series forecasting\".](https://arxiv.org/abs/1905.10437)\n",
    "    \"\"\"\n",
    "    # Class attributes\n",
    "    SAMPLING_TYPE = 'windows'\n",
    "    \n",
    "    def __init__(self,\n",
    "                 h,\n",
    "                 input_size,\n",
    "                 n_harmonics: int = 2,\n",
    "                 n_polynomials: int = 2,\n",
    "                 stack_types: list = ['identity', 'trend', 'seasonality'],\n",
    "                 n_blocks: list = [1, 1, 1],\n",
    "                 mlp_units: list = 3 * [[512, 512]],\n",
    "                 dropout_prob_theta: float = 0.,\n",
    "                 activation: str = 'ReLU',\n",
    "                 shared_weights: bool = False,                 \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: int = 0,\n",
    "                 drop_last_loader: bool = False,\n",
    "                 optimizer = None,\n",
    "                 optimizer_kwargs = None,\n",
    "                 **trainer_kwargs):\n",
    "        \n",
    "        # Protect horizon collapsed seasonality and trend NBEATSx-i basis\n",
    "        if h == 1 and ((\"seasonality\" in stack_types) or (\"trend\" in stack_types)):\n",
    "            raise Exception(\n",
    "                \"Horizon `h=1` incompatible with `seasonality` or `trend` in stacks\"\n",
    "            )\n",
    "\n",
    "        # Inherit BaseWindows class\n",
    "        super(NBEATS, self).__init__(h=h,\n",
    "                                     input_size=input_size,\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",
    "        blocks = self.create_stack(h=h,\n",
    "                                   input_size=input_size,\n",
    "                                   stack_types=stack_types, \n",
    "                                   n_blocks=n_blocks,\n",
    "                                   mlp_units=mlp_units,\n",
    "                                   dropout_prob_theta=dropout_prob_theta,\n",
    "                                   activation=activation,\n",
    "                                   shared_weights=shared_weights,\n",
    "                                   n_polynomials=n_polynomials, \n",
    "                                   n_harmonics=n_harmonics)\n",
    "        self.blocks = torch.nn.ModuleList(blocks)\n",
    "\n",
    "    def create_stack(self, stack_types, \n",
    "                     n_blocks, \n",
    "                     input_size, \n",
    "                     h, \n",
    "                     mlp_units, \n",
    "                     dropout_prob_theta, \n",
    "                     activation, shared_weights,\n",
    "                     n_polynomials, n_harmonics):                     \n",
    "\n",
    "        block_list = []\n",
    "        for i in range(len(stack_types)):\n",
    "            for block_id in range(n_blocks[i]):\n",
    "\n",
    "                # Shared weights\n",
    "                if shared_weights and block_id>0:\n",
    "                    nbeats_block = block_list[-1]\n",
    "                else:\n",
    "                    if stack_types[i] == 'seasonality':\n",
    "                        n_theta = 2 * (self.loss.outputsize_multiplier + 1) * \\\n",
    "                                  int(np.ceil(n_harmonics / 2 * h) - (n_harmonics - 1))\n",
    "                        basis = SeasonalityBasis(harmonics=n_harmonics,\n",
    "                                                 backcast_size=input_size,forecast_size=h,\n",
    "                                                 out_features=self.loss.outputsize_multiplier)\n",
    "\n",
    "                    elif stack_types[i] == 'trend':\n",
    "                        n_theta = (self.loss.outputsize_multiplier + 1) * (n_polynomials + 1)\n",
    "                        basis = TrendBasis(degree_of_polynomial=n_polynomials,\n",
    "                                           backcast_size=input_size,forecast_size=h,\n",
    "                                           out_features=self.loss.outputsize_multiplier)\n",
    "\n",
    "                    elif stack_types[i] == 'identity':\n",
    "                        n_theta = input_size + self.loss.outputsize_multiplier * h\n",
    "                        basis = IdentityBasis(backcast_size=input_size, forecast_size=h,\n",
    "                                              out_features=self.loss.outputsize_multiplier)\n",
    "                    else:\n",
    "                        raise ValueError(f'Block type {stack_types[i]} not found!')\n",
    "\n",
    "                    nbeats_block = NBEATSBlock(input_size=input_size,\n",
    "                                               n_theta=n_theta,\n",
    "                                               mlp_units=mlp_units,\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",
    "\n",
    "        # NBEATS' forward\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)\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, out_features)\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,
   "id": "c57a831f-94bc-4616-b579-c114c3fc57c7",
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(NBEATS)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9013b63-f65b-4a92-913c-b696e6e69914",
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(NBEATS.fit, name='NBEATS.fit')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a66184ee-7a71-4598-976c-c79b83089a6f",
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(NBEATS.predict, name='NBEATS.predict')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c2bf3e1d-2935-4503-afb6-fe3d6f52622c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "import logging\n",
    "import warnings\n",
    "\n",
    "import pandas as pd\n",
    "import pytorch_lightning as pl\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from neuralforecast.tsdataset import TimeSeriesDataset, TimeSeriesLoader\n",
    "from neuralforecast.utils import AirPassengersDF as Y_df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6bb4c6c6-ef60-47c9-8c90-4002e68410d3",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "Y_train_df = Y_df[Y_df.ds<Y_df['ds'].values[-12]] # 132 train\n",
    "Y_test_df = Y_df[Y_df.ds>=Y_df['ds'].values[-12]]   # 12 test\n",
    "\n",
    "dataset, *_ = TimeSeriesDataset.from_df(df = Y_train_df)\n",
    "nbeats = NBEATS(h=12, input_size=24, windows_batch_size=None, \n",
    "                stack_types=['identity', 'trend', 'seasonality'], max_steps=1)\n",
    "nbeats.fit(dataset=dataset)\n",
    "y_hat = nbeats.predict(dataset=dataset)\n",
    "Y_test_df['N-BEATS'] = 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,
   "id": "db94b63e-d82c-423f-8f75-184ae285904d",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "#test we recover the same forecast\n",
    "y_hat2 = nbeats.predict(dataset=dataset)\n",
    "test_eq(y_hat, y_hat2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46090447-8e67-4f08-8a3d-9547183983f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "#test no leakage with test_size\n",
    "dataset, *_ = TimeSeriesDataset.from_df(Y_df)\n",
    "model = NBEATS(input_size=24, h=12, \n",
    "               windows_batch_size=None, max_steps=1)\n",
    "model.fit(dataset=dataset, test_size=12)\n",
    "y_hat_test = model.predict(dataset=dataset, step_size=1)\n",
    "np.testing.assert_almost_equal(y_hat, y_hat_test, decimal=4)\n",
    "#test we recover the same forecast\n",
    "y_hat_test2 = model.predict(dataset=dataset, step_size=1)\n",
    "test_eq(y_hat_test, y_hat_test2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0298fce5-eb13-40dc-9964-b026fd2a8928",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "# test validation step\n",
    "dataset, *_ = TimeSeriesDataset.from_df(Y_train_df)\n",
    "model = NBEATS(input_size=24, h=12, windows_batch_size=None, max_steps=1)\n",
    "model.fit(dataset=dataset, val_size=12)\n",
    "y_hat_w_val = model.predict(dataset=dataset)\n",
    "Y_test_df['N-BEATS'] = y_hat_w_val\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,
   "id": "6f987ed0-ee6e-4f66-bd8f-96acc6fbd56c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "# test no leakage with test_size and val_size\n",
    "dataset, *_ = TimeSeriesDataset.from_df(Y_train_df)\n",
    "model = NBEATS(input_size=24, h=12, windows_batch_size=None, max_steps=1)\n",
    "model.fit(dataset=dataset, val_size=12)\n",
    "y_hat_w_val = model.predict(dataset=dataset)\n",
    "\n",
    "dataset, *_ = TimeSeriesDataset.from_df(Y_df)\n",
    "model = NBEATS(input_size=24, h=12, windows_batch_size=None, max_steps=1)\n",
    "model.fit(dataset=dataset, val_size=12, test_size=12)\n",
    "\n",
    "y_hat_test_w_val = model.predict(dataset=dataset, step_size=1)\n",
    "\n",
    "np.testing.assert_almost_equal(y_hat_test_w_val, y_hat_w_val, decimal=4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba4e41b3",
   "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].grid()\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].grid()\n",
    "ax[1].set_ylabel('Level', fontsize=20)\n",
    "\n",
    "ax[2].plot(y_hat[0,1], label='stack1', color=\"#7B3841\")\n",
    "ax[2].grid()\n",
    "ax[2].set_ylabel('Identity', fontsize=20)\n",
    "\n",
    "ax[3].plot(y_hat[0,2], label='stack2', color=\"#D9AE9E\")\n",
    "ax[3].grid()\n",
    "ax[3].set_ylabel('Trend', fontsize=20)\n",
    "\n",
    "ax[4].plot(y_hat[0,3], label='stack3', color=\"#D9AE9E\")\n",
    "ax[4].grid()\n",
    "ax[4].set_ylabel('Seasonality', fontsize=20)\n",
    "\n",
    "ax[4].set_xlabel('Prediction \\u03C4 \\u2208 {t+1,..., t+H}', fontsize=20)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cdc17eef",
   "metadata": {},
   "source": [
    "## Usage Example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3017c43a",
   "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 NBEATS\n",
    "from neuralforecast.losses.pytorch import MQLoss, DistributionLoss\n",
    "from neuralforecast.tsdataset import TimeSeriesDataset\n",
    "from neuralforecast.utils import AirPassengers, AirPassengersPanel, AirPassengersStatic\n",
    "\n",
    "Y_train_df = AirPassengersPanel[AirPassengersPanel.ds<AirPassengersPanel['ds'].values[-12]] # 132 train\n",
    "Y_test_df = AirPassengersPanel[AirPassengersPanel.ds>=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test\n",
    "\n",
    "model = NBEATS(h=12, input_size=24,\n",
    "               loss=DistributionLoss(distribution='Poisson', level=[80, 90]),\n",
    "               stack_types = ['identity', 'trend', 'seasonality'],\n",
    "               max_steps=100,\n",
    "               val_check_steps=10,\n",
    "               early_stop_patience_steps=2)\n",
    "\n",
    "fcst = NeuralForecast(\n",
    "    models=[model],\n",
    "    freq='M'\n",
    ")\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['NBEATS-median'], c='blue', label='median')\n",
    "plt.fill_between(x=plot_df['ds'][-12:], \n",
    "                 y1=plot_df['NBEATS-lo-90'][-12:].values, \n",
    "                 y2=plot_df['NBEATS-hi-90'][-12:].values,\n",
    "                 alpha=0.4, label='level 90')\n",
    "plt.grid()\n",
    "plt.legend()\n",
    "plt.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d7cbd9ad",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}