AI Logic

Architectures

N-BEATS

Updated:

Structure of N-BEATS. The left shows the overall flow: the lookback window passes through the blocks in order, each block's backcast is subtracted before the next block, and the blocks' forecasts are summed into the forecast window prediction. The right shows the inside of a block, where four fully connected layers produce coefficients that a basis turns into the backcast and the forecast, along with the three choices of basis.

Background and overview

N-BEATS is a time series forecasting model that passes the lookback window through blocks made only of fully connected layers, where each block outputs "part of the forecast window prediction" and "the part of the lookback window it can explain by itself" and hands the remainder to the next block, with this pattern stacked deep. The name stands for Neural Basis Expansion Analysis for Time Series. It was published in 2019 by Oreshkin, Carpov, and Chapados of Element AI and Bengio of Mila, and accepted at ICLR 2020.

At the time, deep learning kept losing to statistical methods in time series forecasting competitions. In the 2018 M4 Competition, the six pure machine learning methods ranked between 23rd and 57th out of 60 entries, and the winner was a hybrid combining an LSTM with a statistical method (Holt-Winters). The organizers concluded that "hybrids and combinations are the way forward."

N-BEATS challenged this conclusion. As a pure deep learning model that uses no time-series-specific components (seasonal decomposition, feature engineering, input scaling), it achieved the best accuracy on all three competition datasets: M4, M3, and TOURISM. On M4, it improved on the statistical benchmark by 11% and on the M4 winner by 3%.

Another goal was interpretable forecasts. Restricting the basis (the building blocks that shape the forecast) to polynomials and Fourier series lets the forecast be shown as two components: "trend" and "seasonality."

In this article, the past interval used as input for the forecast is called the lookback window, and the interval to be predicted is called the forecast window. In N-BEATS, the lookback window is 2 to 7 times the forecast window length HH (2H2H to 7H7H). The model reads the whole lookback window at once and also outputs all HH values of the forecast window at once.

Architecture

N-BEATS handles point forecasts for a single series (univariate). The input is the lookback window x∈Rtx \in \mathbb{R}^{t} (an interval of length tt ending at the last observation), and the output is the HH values of the forecast window y^∈RH\hat{y} \in \mathbb{R}^{H}. In the figure at the top of the article, the left shows the overall flow and the right shows the inside of one block.

Inside a block

The ℓ\ell-th block takes the input xℓx_\ell and returns two outputs.

  1. Pass through four fully connected layers: Four fully connected layers with ReLU are stacked (Eq. 1).
  2. Split in two and output coefficients: Two linear layers in parallel output the backward coefficients θℓb\theta^b_\ell and the forward coefficients θℓf\theta^f_\ell.
  3. Turn them into waveforms with a basis: The coefficients weight the basis vectors, which are summed to produce the estimate of the lookback window x^ℓ\hat{x}_\ell (backcast) and part of the forecast window prediction y^ℓ\hat{y}_\ell (forecast).
hℓ,1=FCℓ,1(xℓ),…,hℓ,4=FCℓ,4(hℓ,3),θℓb=LINEARℓb(hℓ,4),θℓf=LINEARℓf(hℓ,4)h_{\ell,1} = \mathrm{FC}_{\ell,1}(x_\ell), \quad \ldots, \quad h_{\ell,4} = \mathrm{FC}_{\ell,4}(h_{\ell,3}), \qquad \theta^b_\ell = \mathrm{LINEAR}^b_\ell(h_{\ell,4}), \quad \theta^f_\ell = \mathrm{LINEAR}^f_\ell(h_{\ell,4}) y^ℓ=∑i=1dim⁡(θℓf)θℓ,if vif,x^ℓ=∑i=1dim⁡(θℓb)θℓ,ib vib\hat{y}_\ell = \sum_{i=1}^{\dim(\theta^f_\ell)} \theta^f_{\ell,i}\, v^f_i, \qquad \hat{x}_\ell = \sum_{i=1}^{\dim(\theta^b_\ell)} \theta^b_{\ell,i}\, v^b_i

vifv^f_i and vibv^b_i are the basis vectors. The name "basis expansion" comes from expressing the forecast as a weighted sum of basis vectors.

Connecting blocks with a double residual

Blocks are connected by two residual streams (Section 3.2).

xℓ=xℓ−1−x^ℓ−1,y^=∑ℓy^ℓx_\ell = x_{\ell-1} - \hat{x}_{\ell-1}, \qquad \hat{y} = \sum_\ell \hat{y}_\ell
  • Subtraction on the lookback side: The next block receives what remains after subtracting the part x^ℓ−1\hat{x}_{\ell-1} that the previous block could explain. Later blocks only have to deal with the part that has not been explained yet.
  • Addition on the forecast side: The sum of all blocks' partial forecasts is the final forecast.

A group of several blocks is called a stack. A stack's forecast is also the sum of its blocks' forecasts, so each stack's share of the forecast can be extracted.

Two configurations, depending on the choice of basis

Section 3.3 presents two configurations based on how the basis layers gℓbg^b_\ell and gℓfg^f_\ell are chosen.

  • Generic configuration (N-BEATS-G): The basis is also a learned linear layer, y^ℓ=Vℓfθℓf+bℓf\hat{y}_\ell = V^f_\ell \theta^f_\ell + b^f_\ell. This form injects no time series knowledge; the paper uses 30 stacks × 1 block with fully connected layers of width 512. The learned basis has no fixed shape, so the outputs cannot be interpreted.
  • Interpretable configuration (N-BEATS-I): A trend stack (3 blocks) is followed by a seasonality stack (3 blocks), and the shape of the basis is fixed. Blocks within a stack also share weights.

The trend stack uses a low-degree polynomial of degree pp as its basis to represent slowly changing shapes (Eq. 2; the paper uses p=2p = 2). The time vector is t=[0,1,…,H−1]⊤/Ht = [0, 1, \ldots, H-1]^\top / H.

y^s,ℓtr=∑i=0pθs,ℓ,if ti\hat{y}^{\mathrm{tr}}_{s,\ell} = \sum_{i=0}^{p} \theta^f_{s,\ell,i}\, t^i

The seasonality stack uses a Fourier series as its basis to represent repeating shapes (Eq. 3).

y^s,ℓseas=∑i=0⌊H/2−1⌋θs,ℓ,ifcos⁡(2πit)+θs,ℓ,i+⌊H/2⌋fsin⁡(2πit)\hat{y}^{\mathrm{seas}}_{s,\ell} = \sum_{i=0}^{\lfloor H/2 - 1 \rfloor} \theta^f_{s,\ell,i} \cos(2\pi i t) + \theta^f_{s,\ell,i+\lfloor H/2 \rfloor} \sin(2\pi i t)

Because the trend stack comes first, the seasonality stack receives what remains after the trend is removed. Looking at the two stacks' forecasts separately explains the forecast as a split into trend and seasonality.

Training and ensembling

  • One model per forecast horizon: Within a dataset, one model is trained on all series for each forecast horizon (for M4, each subset such as yearly, quarterly, or monthly).
  • Building batches: 1,024 series are sampled at random. For each, a forecast start point is chosen near the end of the training interval (within LHL_H times the horizon length), and the lookback and forecast windows are cut out.
  • Loss and optimization: The competition metrics themselves (sMAPE, MASE, MAPE) are used as losses, and training uses Adam (learning rate 0.001) with early stopping.
  • An ensemble of 180 models: Combining 3 loss types, 6 lookback lengths (2H2H to 7H7H), and different random initializations, 180 models are trained and the median of their forecasts is taken. The paper reports that the ensemble acted as a stronger regularizer than dropout or L2 regularization.

Why it works

The paper gives the following reasons for the strength of N-BEATS.

  • Deep stacks still train: Like the residual connections in ResNet, the subtractive residual makes gradients flow easily. The generic configuration is a deep network chaining 30 blocks of four fully connected layers each, yet it trains stably.
  • Blocks "analyze" the signal in turn: Each block removes from the input the part the previous block explained, so later blocks can focus on what remains. This works much like classical decomposition methods that break a signal down step by step.
  • One model learned from many series: For the M4 monthly subset, a single model is trained on 48,000 series. The paper argues that if each series is viewed as a task, learning from many tasks acts as regularization, close to a meta-learning view.
  • The basis constrains the output shape: In the interpretable configuration, the forecast is limited to the sum of "a low-degree polynomial" and "a Fourier series." Its accuracy is still almost the same as the generic configuration, showing that constraining the shape does not hurt accuracy.

As an analogy, N-BEATS is "a relay that passes a drawing from a rough sketcher to detail artists in turn." The first person draws the broad trend, the next draws only the remaining waves, and so on. Overlaying everyone's drawings gives the final forecast, and in the interpretable configuration the first person is fixed as "the trend artist" and the next as "the seasonality artist".

Experimental results

Accuracy on competition data (lower is better; Table 1 of the paper)

M4 consists of 100,000 series, M3 of 3,003, and TOURISM of 1,311, covering various frequencies (yearly, quarterly, monthly, weekly, daily, hourly, and so on) and domains. The metrics follow each competition's rules: sMAPE and OWA for M4 (OWA is the average of the sMAPE and MASE ratios relative to a seasonal naive forecast set to 1), sMAPE for M3, and MAPE for TOURISM.

M4 modelsMAPEOWA
Best pure ML entry12.8940.915
Best statistical entry11.9860.861
ML/statistical combination (2nd place)11.7200.838
DL/statistical hybrid (winner)11.3740.821
N-BEATS-G11.1680.797
N-BEATS-I11.1740.798
N-BEATS-I+G11.1350.795
DataPrevious bestN-BEATS-GN-BEATS-IN-BEATS-I+G
M3 (sMAPE)12.71 (EXP)12.4712.4312.37
TOURISM (MAPE)19.35 (LeeCBaker)18.4718.9718.52

N-BEATS-I+G is an ensemble combining all models of the generic and interpretable configurations. On M4, the OWA gap between N-BEATS and the winner (0.821 − 0.795 = 0.026) was larger than the gap between the winner and 2nd place (0.838 − 0.821 = 0.017). Since the generic configuration uses no time series knowledge, the paper concludes that "deep learning can achieve high accuracy on a wide range of forecasting problems without help from statistical methods or hand-crafted features."

Comparison with DeepAR and others (ND: the sum of absolute errors divided by the sum of absolute ground-truth values; lower is better; Table 17 of the paper)

ModelM4 (hourly)TOURISM (monthly)TOURISM (quarterly)
DeepAR0.090.1070.11
DeepState0.0440.1380.098
N-BEATS-G0.0230.0970.080
N-BEATS-I0.0270.1030.079
N-BEATS-I+G0.0250.0990.077

Interpretable outputs

In Figure 2 of the paper, the trend stack of the interpretable configuration produced monotonic, slowly changing outputs, and the seasonality stack produced regularly repeating shapes. The two stacks of the generic configuration produced outputs mixing trend and seasonality, with no readable meaning.

Training time: Training one model of the ensemble on all of M4 took 30 minutes to 2 hours on a GPU.

Practical considerations

Keep the following points in mind when using N-BEATS.

  • A univariate model: The input is only the past values of one series; other variables and covariates such as day of the week are not used. It is not suited as-is to data where covariates help the forecast.
  • Point forecasts only: It outputs neither distributions nor prediction intervals. When a range is needed, for example for inventory decisions, use a probabilistic model such as DeepAR, or adapt it, for example by retraining with a quantile loss.
  • The forecast horizon is built into the model: The input width of the fully connected layers is set by the lookback length, and the basis length by the forecast window length HH. Changing HH requires retraining.
  • Competition accuracy includes the ensemble: The numbers in the paper's tables are medians over 180 models. Assume a single model will not reach the same accuracy (Appendix B of the paper compares different ensemble sizes).
  • Only the I configuration is interpretable: The basis of the generic configuration (G) is learned freely, so its stack outputs cannot be read as trend or seasonality.
  • No built-in PyTorch implementation: The paper's implementation is in TensorFlow. The structure is simple, so it can be written in a few dozen lines, as in the example below.

N-BEATS is designed without input scaling (the policy in Chapter 3 of the paper). The paper makes this work by using scale-insensitive metrics (sMAPE, MASE, MAPE) as losses on the competition data. When using a loss such as MSE on data whose magnitudes differ greatly across series, the preprocessing, such as dividing each series by its own scale, must be decided by the user.

Comparison with other models

The following table compares representative time series forecasting models from the same viewpoints. LL is the lookback length.

ModelHow it captures timeHow it outputs the forecast windowOutputCost with respect to input length LL
DeepARUpdates an LSTM state one step at a timeAutoregressive, one step at a time (samples fed back as the next input)Probability distribution (sample paths)Linear in length (computed in time order)
N-BEATSReads the whole lookback window with fully connected layers and outputs basis weightsAll at oncePoint forecastLinear in length (input width of the fully connected layers)
InformerProbSparse self-attention and distillingAll at once (generative decoder)Point forecastO(Llog⁡L)O(L \log L)
AutoformerSeries decomposition and auto-correlation (aggregation by periodic lags)All at oncePoint forecastO(Llog⁡L)O(L \log L)
FEDformerSeries decomposition and a subset of modes in the frequency domainAll at oncePoint forecastO(L)O(L)
PyraformerPyramidal attention (stacking coarser time resolutions)All at oncePoint forecastO(L)O(L)
TSMixer (Google)MLPs along the time and variable axesAll at once (linear projection)Point forecastLinear in length
ChronosTurns values into tokens and reads them with a language modelAutoregressive, one token at a timeProbability distribution (sample paths)O(L2)O(L^2) (standard attention)

N-BEATS was built for many short univariate series such as M4. Informer, Autoformer, FEDformer, and similar models are compared on problems that forecast hundreds of steps ahead on a few long multivariate series, such as ETT.

Rough guidelines for choosing:

  • Many univariate series, and high-accuracy point forecasts are needed: N-BEATS fits well. It is a strong baseline even without combining it with statistical methods.
  • The forecast should be explained as trend and seasonality: The interpretable configuration of N-BEATS fits well.
  • A forecast range (distribution) is needed, or covariates should be used: DeepAR fits well.
  • Forecasting hundreds of steps ahead on a few long multivariate series: Autoformer, FEDformer, or the simpler TSMixer (Google) are candidates.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn

"""
A small implementation of N-BEATS (follows Chapter 3 and Eqs. 1-3 of arXiv:1905.10437)
Input x: [batch, lookback length t] -> output: [batch, forecast length H]
"""


class Block(nn.Module):
  def __init__(self, backcast_len, horizon, width, theta_b_dim, theta_f_dim, basis="generic"):
    super().__init__()
    # Four fully connected layers + ReLU (Eq. 1)
    self.fc = nn.Sequential(
      nn.Linear(backcast_len, width), nn.ReLU(),
      nn.Linear(width, width), nn.ReLU(),
      nn.Linear(width, width), nn.ReLU(),
      nn.Linear(width, width), nn.ReLU(),
    )
    # Linear layers that split in two and output coefficients θ^b and θ^f
    self.theta_b = nn.Linear(width, theta_b_dim, bias=False)
    self.theta_f = nn.Linear(width, theta_f_dim, bias=False)
    self.basis = basis
    if basis == "generic":
      # Generic: the basis is also a learned linear layer (V θ + b)
      self.g_b = nn.Linear(theta_b_dim, backcast_len)
      self.g_f = nn.Linear(theta_f_dim, horizon)
    else:
      # Trend/seasonality: the basis matrix is fixed (not learned)
      self.register_buffer("V_b", self.make_basis(basis, backcast_len, theta_b_dim))
      self.register_buffer("V_f", self.make_basis(basis, horizon, theta_f_dim))

  @staticmethod
  def make_basis(kind, length, dim):
    t = torch.arange(length, dtype=torch.float32) / length       # t = [0, 1, ..., length-1] / length
    if kind == "trend":                                          # Eq. 2: t^0, t^1, ..., t^p (dim = p + 1)
      return torch.stack([t ** i for i in range(dim)])
    half = dim // 2                                              # Eq. 3: cos(2π i t) and sin(2π i t)
    cos = [torch.cos(2 * math.pi * i * t) for i in range(half)]
    sin = [torch.sin(2 * math.pi * i * t) for i in range(half)]
    return torch.stack(cos + sin)

  def forward(self, x):
    h = self.fc(x)
    tb, tf = self.theta_b(h), self.theta_f(h)
    if self.basis == "generic":
      return self.g_b(tb), self.g_f(tf)
    return tb @ self.V_b, tf @ self.V_f                          # Weight the basis by the coefficients and sum


class NBeats(nn.Module):
  def __init__(self, blocks):
    super().__init__()
    self.blocks = nn.ModuleList(blocks)

  def forward(self, x):
    residual, forecast = x, 0
    for block in self.blocks:
      backcast, partial = block(residual)
      residual = residual - backcast                             # Subtraction on the lookback side
      forecast = forecast + partial                              # Addition on the forecast side
    return forecast


H, L = 18, 6 * 18                                                # Forecast window 18 (M4 monthly), lookback 6H

# Generic configuration (N-BEATS-G): 30 stacks × 1 block, width 512
generic = NBeats([Block(L, H, 512, 32, 32, "generic") for _ in range(30)])

# Interpretable configuration (N-BEATS-I): trend (3 blocks, shared weights) -> seasonality (3 blocks, shared weights)
trend = Block(L, H, 256, 3, 3, "trend")                          # Polynomial degree p = 2 -> 3 coefficients
season = Block(L, H, 2048, 2 * (H // 2), 2 * (H // 2), "seasonality")
interpretable = NBeats([trend] * 3 + [season] * 3)               # Using the same block 3 times = weight sharing

model = interpretable
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)


def smape(y_hat, y):
  # When training with sMAPE, the paper stops the gradient through the denominator for stability
  denom = (y.abs() + y_hat.abs()).detach().clamp_min(1e-8)
  return (200 * (y - y_hat).abs() / denom).mean()


x = torch.rand(1024, L) + 1.0                                     # Lookback windows (cut from 1,024 series)
y = torch.rand(1024, H) + 1.0                                     # Ground truth for the forecast window

model.train()
optimizer.zero_grad()
loss = smape(model(x), y)
loss.backward()
optimizer.step()

model.eval()
with torch.no_grad():
  pred = model(x)                                                # [1024, 18]

FAQ

Q. What is "basis expansion"?
A.

It means expressing the forecast as a weighted sum of a few fixed waveforms (the basis). For example, with the basis 1,t,t21, t, t^2, the forecast is limited to a parabola, and the network only has to output three weights (the coefficients θ\theta). Each N-BEATS block outputs these coefficients with fully connected layers and multiplies them with the basis to produce part of the forecast. In the generic configuration, the basis itself is also learned.

Q. What is the backcast (the estimate of the lookback window) for?
A.

It reduces the work of later blocks. Each block outputs the part of the lookback window it can explain, x^ℓ\hat{x}_\ell, and passes what remains after subtracting it from the input to the next block. Later blocks can then focus only on the part not yet explained. In the interpretable configuration, this means the seasonality stack receives a series with the trend removed.

Q. Can it be used for multivariate series or benchmarks such as ETT?
A.

N-BEATS is a univariate model, so for multivariate series it is used by forecasting each variable separately (with the same weights). The original paper evaluates on M4, M3, and TOURISM and reports no results on ETT. To exploit relationships between variables, also compare multivariate models such as TSMixer (Google).

References

  1. Oreshkin, B. N., Carpov, D., Chapados, N., & Bengio, Y. (2020). N-BEATS: Neural basis expansion analysis for interpretable time series forecasting. ICLR 2020.
  2. Makridakis, S., Spiliotis, E., & Assimakopoulos, V. (2020). The M4 Competition: 100,000 time series and 61 forecasting methods. International Journal of Forecasting, 36(1), 54–74.
  3. Salinas, D., Flunkert, V., Gasthaus, J., & Januschowski, T. (2020). DeepAR: Probabilistic forecasting with autoregressive recurrent networks. International Journal of Forecasting, 36(3), 1181–1191.
  4. He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep Residual Learning for Image Recognition. CVPR 2016.