AI Logic

Architectures

DeepAR

Updated:

The flow of DeepAR. The left side shows the overall flow: divide the lookback window by a scale, read it with an LSTM, forecast the forecast window one step at a time, and build a distribution from 200 sample paths. The right side shows how, at each timestep of the forecast window, the LSTM produces distribution parameters and a sample, and the sample is fed back as the input for the next timestep

Background and overview

DeepAR is a model that trains a single LSTM jointly on many related time series and forecasts the values of the forecast window from the lookback window as a "probability distribution", one step at a time. It was published on arXiv in 2017 by Salinas, Flunkert, and Gasthaus at Amazon, and a version with Januschowski added was published in the International Journal of Forecasting in 2020.

Until then, the mainstream approach to forecasting was to fit a separate model to each series, as with ARIMA or exponential smoothing. In retail demand forecasting, however, sales of tens of thousands to millions of items must be forecast at the same time. Building a model for each series is laborious, and items that have just been released and have short histories cannot be forecast well.

DeepAR solves this problem by learning similar series together.

  1. Learn one model across all series: seasonal patterns and the effects of price, day of the week, and so on can be learned from other series too. Even items with short histories can be forecast using the behavior of similar items as a guide.
  2. Forecast a distribution rather than a point: instead of "12 units next week", it forecasts something like "median 12 units, 20 or fewer with 90% probability". Decisions such as how much inventory to hold need the range of possible misses.

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 the paper's terms, they are the "conditioning range" [1,t0−1][1, t_0 - 1] and the "prediction range" [t0,T][t_0, T]. Training cuts out intervals where both windows have ground truth, while at prediction time the values of the forecast window are unknown.

The paper shows that the sales volumes of Amazon items follow a power law spanning several orders of magnitude (only a small fraction of items sell a lot, and most sell only a little), and it also proposes techniques suited to this skew (scaling and weighted sampling).

Architecture

Let the value of time series ii at time tt be zi,tz_{i,t}, and the covariates such as day of the week and item category be xi,tx_{i,t}. What DeepAR wants is the distribution of the forecast window values given the lookback window values and the covariates at all timesteps, P(zi,t0:T∣zi,1:t0−1,xi,1:T)P(z_{i,t_0:T} \mid z_{i,1:t_0-1}, x_{i,1:T}). In the figure at the top of the article, the left side shows the overall flow and the right side shows how the forecast window is predicted one step at a time.

The model factorizes this distribution into a product of per-timestep distributions.

QΘ(zi,t0:T∣zi,1:t0−1,xi,1:T)=∏t=t0Tℓ(zi,t∣θ(hi,t,Θ))Q_\Theta(z_{i,t_0:T} \mid z_{i,1:t_0-1}, x_{i,1:T}) = \prod_{t=t_0}^{T} \ell\bigl(z_{i,t} \mid \theta(h_{i,t}, \Theta)\bigr)

hi,th_{i,t} is the output of the LSTM, computed from the previous output, the previous value, and the covariates at that timestep (Eq. 1).

hi,t=h(hi,t−1,zi,t−1,xi,t,Θ)h_{i,t} = h(h_{i,t-1}, z_{i,t-1}, x_{i,t}, \Theta)

The forecasting flow is as follows.

  1. Divide by a scale: for each series, compute νi=1+1t0∑t=1t0zi,t\nu_i = 1 + \frac{1}{t_0}\sum_{t=1}^{t_0} z_{i,t} (the mean of the lookback window plus 1), and divide the value zi,t−1z_{i,t-1} fed into the LSTM by νi\nu_i.
  2. Read the lookback window: feed the previous value and the covariates into a multi-layer LSTM in order from t=1t = 1 to t0−1t_0 - 1 to produce the state hi,t0−1h_{i,t_0-1}. The initial state hi,0h_{i,0} and value zi,0z_{i,0} are 0.
  3. Output the distribution parameters: apply a fully connected layer to the output hi,th_{i,t} at each timestep to produce the distribution parameters θi,t\theta_{i,t}. Parameters related to magnitude are multiplied by νi\nu_i to restore the original scale.
  4. Sample the forecast window one step at a time: starting from t=t0t = t_0, draw one value z~i,t\tilde{z}_{i,t} from the distribution ℓ(⋅∣θi,t)\ell(\cdot \mid \theta_{i,t}), feed it back as the input for the next timestep, and proceed to TT. This produces "one sample path" for the forecast window.
  5. Draw many to form a distribution: repeat step 4 to produce many sample paths (200 in the paper's experiments) and compute quantiles (such as the median and the 90th percentile) at each timestep.

The part that reads the lookback window (encoder) and the part that produces the forecast window (decoder) are the same LSTM with shared weights. It can be described as the Sequence to Sequence form, with one network handling both roles.

Choosing the distribution

The distribution ℓ\ell is chosen to suit the nature of the data. The paper used two.

  • Real values: a Gaussian distribution. The mean μ\mu is a linear transformation of hi,th_{i,t}, and the standard deviation σ\sigma is a linear transformation followed by Softplus to make it positive.
  • Non-negative counts (such as sales): a negative binomial distribution. The mean μ\mu and the shape parameter α\alpha are both produced by a linear transformation and Softplus.
μ(hi,t)=wμ⊤hi,t+bμ,σ(hi,t)=log⁡(1+exp⁡(wσ⊤hi,t+bσ))\mu(h_{i,t}) = w_\mu^\top h_{i,t} + b_\mu, \qquad \sigma(h_{i,t}) = \log\bigl(1 + \exp(w_\sigma^\top h_{i,t} + b_\sigma)\bigr) ℓNB(z∣μ,α)=Γ(z+1α)Γ(z+1) Γ(1α)(11+αμ)1α(αμ1+αμ)z\ell_{\mathrm{NB}}(z \mid \mu, \alpha) = \frac{\Gamma(z + \frac{1}{\alpha})}{\Gamma(z + 1)\,\Gamma(\frac{1}{\alpha})} \left(\frac{1}{1 + \alpha\mu}\right)^{\frac{1}{\alpha}} \left(\frac{\alpha\mu}{1 + \alpha\mu}\right)^{z}

The variance of the negative binomial distribution is Var[z]=μ+μ2α\mathrm{Var}[z] = \mu + \mu^2 \alpha; the larger α\alpha, the larger the spread relative to the mean. With scaling, the parameters are restored as μ=νilog⁡(1+exp⁡(oμ))\mu = \nu_i \log(1 + \exp(o_\mu)) and α=log⁡(1+exp⁡(oα))/νi\alpha = \log(1 + \exp(o_\alpha)) / \sqrt{\nu_i} (oμ,oαo_\mu, o_\alpha are the network outputs).

Training

Training uses intervals where both windows have ground truth and maximizes the sum of the log of the probability (likelihood) assigned to the true values (Eq. 2).

L=∑i=1N∑t=t0Tlog⁡ℓ(zi,t∣θ(hi,t))\mathcal{L} = \sum_{i=1}^{N} \sum_{t=t_0}^{T} \log \ell\bigl(z_{i,t} \mid \theta(h_{i,t})\bigr)
  • Inputs are the true values: during training, the true zi,t−1z_{i,t-1} rather than a sample is used as input even in the forecast window. Since the encoder and decoder are the same, the experiments also included the likelihood at lookback window timesteps in the sum (equivalent to setting t0=0t_0 = 0).
  • Cut out shifted windows: many windows with shifted start points are cut out of one series. Windows that start before the beginning of the series are also created, with missing values filled with 0. This lets the model learn the behavior of "new" series with short histories.
  • Choose large series more often: the probability of choosing a window is made proportional to νi\nu_i (weighted sampling).

Covariates

In all experiments, the distance from the first observation of the series ("age") and, depending on the time granularity, the day of the week, hour of the day, week of the year, and month were fed in as numerical values. In addition, the item category (or the series index) is fed in as a single categorical feature through an embedding. Covariates are standardized to mean 0 and variance 1.

Only covariates whose values are known at forecast window timesteps as well can be used, because xi,tx_{i,t} is fed in at every timestep. The day of the week and planned price cuts can be used, but things like actual weather observations that are not yet known cannot be used as is.

Why it works

Summarizing the paper's claims, DeepAR has four strengths.

  • It learns from similar series: because one model is trained across all series, seasonal patterns and covariate effects can be learned from the histories of other series too. It reduces the work of hand-crafting features or choosing a model for each series.
  • It can forecast even with short histories: through windows that start before the beginning of a series and the "age" feature, it learns how items behave right after release. Per-series models cannot forecast items with almost no history.
  • It can use a distribution that fits the data: it does not assume a Gaussian and can choose a distribution suited to the data, such as the negative binomial for count data. Any distribution from which samples can be drawn easily and whose log-likelihood and gradient can be computed can be used.
  • It produces distributions that preserve dependencies between timesteps: since sampled values are fed back as the next input, dependencies such as "if this week is high, next week is high too" are preserved within each sample path. As a result, quantiles of quantities that combine several timesteps, such as "the total over the next 4 weeks", can be obtained simply by summing along the sample paths.

The paper also explains why scaling is needed. The autoregressive input zi,t−1z_{i,t-1} and the output μ\mu both scale with the magnitude of the series, but the nonlinear functions inside the LSTM work well only in a limited range of values. Dividing by the per-series νi\nu_i lets the network learn only the shape without worrying about differences in magnitude. For count distributions, standardizing values in preprocessing would make them no longer "non-negative integers", so this form, dividing the input and multiplying back into the output parameters, is necessary.

As an analogy, DeepAR is "a clerk who has read hundreds of thousands of sales ledgers from very similar stores". Even for a new item, the clerk can guess from how similar items sold that "it will grow like this in the first few weeks". The clerk answers with a range, such as "probably 12, at most 20", and reads ahead in order, thinking about the week after next based on the answer for next week.

Experimental results

The paper evaluated on five datasets: monthly sales of auto parts (parts, 1,046 series), hourly electricity consumption of 370 households (electricity), hourly occupancy of 963 lanes in San Francisco (traffic), and weekly Amazon sales (ec-sub with 39,700 series and ec with 534,884 series).

Accuracy of the distribution (ρ\rho-risk: quantile loss divided by the sum of the true values, lower is better; ratio relative to the strongest previous method set to 1.00; the "average" column of Table 1 in the paper)

Modelpartsec-subec
Snyder (negative binomial autoregressive)1.001.161.05
Croston1.971.201.34
ISSM (state space model)1.081.001.00
ETS (exponential smoothing)1.231.071.11
rnn-gaussian1.191.211.01
rnn-negbin0.991.170.93
DeepAR0.940.770.85

rnn-gaussian and rnn-negbin are comparisons to check the effect of DeepAR's techniques, and both use the same LSTM. rnn-gaussian uses a Gaussian distribution for count data, and rnn-negbin uses the negative binomial distribution but without scaling or weighted sampling.

  • The choice of distribution matters: rnn-gaussian, which used a Gaussian for count data, was much worse than DeepAR.
  • Handling the skew in magnitude matters: on ec and ec-sub, which follow a power law, accuracy dropped for rnn-negbin, which removes scaling and weighted sampling. On parts, which has no such skew, the gap between rnn-negbin and DeepAR was small.

Accuracy of point forecasts (comparison with the matrix factorization method MatFact; ND is the sum of absolute errors divided by the sum of absolute true values, RMSE is the normalized root mean squared error; lower is better; Table 2 of the paper)

DataMetricMatFactDeepAR
electricityND0.160.07
electricityRMSE1.151.00
trafficND0.200.17
trafficRMSE0.430.42

The paper's abstract summarizes these results as "an accuracy improvement of around 15% compared to state-of-the-art methods".

The following was also reported.

  • It learns how uncertainty grows: ISSM assumes uncertainty grows linearly with the horizon, but DeepAR learned from the data a shape in which uncertainty grows during the year-end shopping season and then shrinks (Figure 4).
  • Quantile coverage (calibration) is good: the fraction of true values falling below the forecast pp-quantile was close to pp, better than ISSM. Shuffling the per-timestep values of the sample paths to break the dependencies between timesteps worsened calibration over intervals combining multiple timesteps and raised the 0.9-risk by 10% (Figure 5).
  • Computational scale: the LSTM had 3 layers with 40 units each (120 for ec and ec-sub), and the whole training and prediction on ec, with over 500,000 series, took less than 10 hours on a single AWS instance with one GPU (Section 4 and Table 3 of the paper).

Practical notes

Keep the following points in mind when using DeepAR.

  • Choose a distribution that fits the data: using a Gaussian for count data greatly reduced accuracy. Choose one that matches the range and shape of the values, such as a beta distribution for values in 0-1 or a Bernoulli distribution for 0 or 1.
  • Prediction can only proceed in time order: at each timestep of the forecast window, the LSTM is run once to draw a value. Since this is repeated for hundreds of sample paths, a long forecast window makes prediction slow. Sample paths are independent, so they can be computed in parallel.
  • Inputs differ between training and prediction: training feeds the true values, while prediction feeds the model's own samples. This mismatch is known to be a problem for language models, but the paper reports that no harmful effect was seen in its forecasting experiments, and that trying a method that mixes samples in during training (scheduled sampling) did not improve accuracy.
  • The choice of scale is a heuristic: νi\nu_i (mean of the lookback window + 1) is a choice that worked well in experiments. The paper itself admits that an appropriate value is hard to determine for series with many missing values or series whose values change greatly within the same series.
  • Exclude missing values from the likelihood: for timesteps where sales were 0 due to stockouts and similar, the paper's supplementary material describes replacing the value at that timestep with a sample from the distribution when feeding the LSTM and excluding it from the likelihood sum. Training with the 0s as is leads to underestimating demand.
  • Not built into PyTorch: the paper's implementation is in MXNet. GluonTS, Amazon's time series library, has a PyTorch implementation, and it can also be written in a few dozen lines with torch.distributions, as in the implementation example below.

What DeepAR outputs are samples drawn from a distribution, so the values change slightly every time a forecast is produced, even for the same input. Quantiles such as the median fluctuate when there are few sample paths. For reporting and comparison, fix the number of paths (the paper uses 200) and use quantiles.

Comparison with other models

Lining up representative time series forecasting models from the same viewpoints gives the following. LL is the lookback window length.

ModelHow it handles the time directionHow the forecast window is producedOutputCost with respect to input length LL
DeepARUpdates the state one step at a time with an LSTMAutoregressive, one step at a time (samples fed back as the next input)Probability distribution (sample paths)Proportional to length (computed in time order)
N-BEATSReads the whole lookback window with fully connected layers and outputs basis weightsAll at oncePoint forecastProportional to length (input width of the fully connected layers)
InformerProbSparse self-attention and distillationAll at once (generative decoder)Point forecastO(Llog⁡L)O(L \log L)
AutoformerSeries decomposition and auto-correlation (aggregation by period lags)All at oncePoint forecastO(Llog⁡L)O(L \log L)
FEDformerSeries decomposition and a subset of frequency-domain modesAll 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 directionsAll at once (linear projection)Point forecastProportional to 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)

DeepAR is evaluated in a different setting from Informer and later models. Informer, Autoformer, FEDformer, and others compare point forecasts up to hundreds of steps ahead by MSE on a few long series such as ETT. DeepAR was built for settings that compare how well distributions fit across tens of thousands of short series.

Rough guidelines for choosing:

  • Thousands or more related series, and decisions such as inventory need forecast ranges: DeepAR is a good fit. It works even when series with short histories are mixed in.
  • A few series, with long forecasts up to hundreds of steps ahead: models that produce the forecast window all at once, such as Informer, Autoformer, FEDformer, Pyraformer, or the simpler TSMixer (Google), are a good fit.
  • To explain the forecast by splitting it into trend and seasonality: the interpretable configuration of N-BEATS is a good fit.
  • To forecast distributions without training on your own data: the pretrained Chronos is a candidate.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import NegativeBinomial, Normal

"""
A small implementation of DeepAR (following Section 3 of arXiv:1704.04110)
z: values of shape [batch, length], x: covariates of shape [batch, length, number of covariates] (known for forecast window timesteps too)
"""


class DeepAR(nn.Module):
  def __init__(self, n_cov, n_items, emb_dim=20, hidden=40, layers=3, likelihood="negbin"):
    super().__init__()
    self.likelihood = likelihood
    self.item_emb = nn.Embedding(n_items, emb_dim)       # embedding of the item (series) category
    self.lstm = nn.LSTM(1 + n_cov + emb_dim, hidden, num_layers=layers, batch_first=True)
    self.out_mu = nn.Linear(hidden, 1)                    # μ (mean of the Gaussian / negative binomial)
    self.out_shape = nn.Linear(hidden, 1)                 # σ (Gaussian) or α (negative binomial)

  def _inputs(self, z_prev, x, item):
    # concatenate the previous value (divided by the scale), covariates, and item embedding
    e = self.item_emb(item).unsqueeze(1).expand(-1, x.size(1), -1)
    return torch.cat([z_prev.unsqueeze(-1), x, e], dim=-1)

  def _dist(self, h, nu):
    o_mu, o_s = self.out_mu(h).squeeze(-1), self.out_shape(h).squeeze(-1)
    if self.likelihood == "gaussian":
      # μ is linear, σ uses Softplus; both depend on magnitude, so multiply back by ν
      return Normal(o_mu * nu, F.softplus(o_s) * nu + 1e-6)
    # negative binomial: μ = ν·softplus(o_μ), α = softplus(o_α)/√ν (Section 3.3)
    mu = nu * F.softplus(o_mu) + 1e-6
    alpha = F.softplus(o_s) / nu.sqrt() + 1e-6
    # the mean of torch's NegativeBinomial(total_count=r, probs=p) is r·p/(1−p). With r = 1/α, p = αμ/(1+αμ), the mean is μ and the variance μ+μ²α
    return NegativeBinomial(total_count=1.0 / alpha, probs=alpha * mu / (1.0 + alpha * mu))

  @staticmethod
  def scale(z_cond):
    return 1.0 + z_cond.mean(dim=1, keepdim=True)         # ν = 1 + mean of the lookback window

  def loss(self, z, x, item, t0):
    """Training: input is the true previous value. Returns the mean negative log-likelihood over all timesteps (the paper sets t0 = 0 to include the lookback window)"""
    nu = self.scale(z[:, :t0])
    z_prev = F.pad(z[:, :-1], (1, 0)) / nu                # z_{t-1}; z_0 = 0
    h, _ = self.lstm(self._inputs(z_prev, x, item))
    return -self._dist(h, nu).log_prob(z).mean()

  @torch.no_grad()
  def sample(self, z_cond, x, item, n_samples=200):
    """Prediction: read the lookback window and sample the forecast window one step at a time. Returns [n_samples, batch, forecast window length]"""
    t0, horizon = z_cond.size(1), x.size(1) - z_cond.size(1)
    nu = self.scale(z_cond)
    z_prev = F.pad(z_cond[:, :-1], (1, 0)) / nu
    _, state = self.lstm(self._inputs(z_prev, x[:, :t0], item))   # read the lookback window
    rep = lambda t: t.repeat_interleave(n_samples, dim=0)
    state = tuple(s.repeat_interleave(n_samples, dim=1) for s in state)
    last, nu_r, item_r = rep(z_cond[:, -1:]), rep(nu), rep(item)
    out = []
    for k in range(horizon):
      xk = rep(x[:, t0 + k:t0 + k + 1])
      h, state = self.lstm(self._inputs(last / nu_r, xk, item_r), state)
      last = self._dist(h, nu_r).sample()                 # feed the drawn value back as the next input
      out.append(last)
    return torch.cat(out, dim=1).view(-1, n_samples, horizon).transpose(0, 1)


# Usage (weekly sales: lookback window 52 weeks, forecast window 52 weeks, 3 covariates)
model = DeepAR(n_cov=3, n_items=1000)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

z = torch.poisson(torch.rand(64, 104) * 5)                # training windows with ground truth in both windows
x = torch.randn(64, 104, 3)                                # covariates such as age and week (standardized)
item = torch.randint(0, 1000, (64,))

model.train()
optimizer.zero_grad()
loss = model.loss(z, x, item, t0=52)
loss.backward()
optimizer.step()

model.eval()
samples = model.sample(z[:, :52], x, item)                # [200, 64, 52]
p50 = samples.quantile(0.5, dim=0)                         # median forecast
p90 = samples.quantile(0.9, dim=0)                         # 90th percentile (used for inventory decisions, etc.)

FAQ

Q. How does a "probabilistic forecast" differ from an ordinary forecast?
A.

An ordinary forecast outputs a single value, such as "12 units next week". DeepAR outputs a distribution, such as "likely around 12 units, with about a 10% chance of exceeding 20". Decisions such as setting the quantity that avoids running out of stock with 90% probability become possible only with the quantiles of a distribution. DeepAR draws hundreds of future sample paths from the distribution and expresses the forecast by their quantiles.

Q. Can it be used with only one series?
A.

It can, but its strengths are less likely to show. DeepAR's strength is learning common seasonal patterns and covariate effects from many related series. The paper says it also works on medium-sized data of a few hundred series, but with just one series, classical per-series models and pretrained models such as Chronos are also worth comparing.

Q. How does the LSTM in DeepAR differ from other LSTMs?
A.

The LSTM itself is an ordinary multi-layer LSTM. The difference is in how it is used: (1) it takes an autoregressive form that feeds the previous value as input, (2) its output is not the value itself but distribution parameters (such as μ\mu and α\alpha of the negative binomial), and (3) inputs are divided by the per-series magnitude νi\nu_i and multiplied back into the outputs.

References

  1. Salinas, D., Flunkert, V., Gasthaus, J., & Januschowski, T. (2020). DeepAR: Probabilistic forecasting with autoregressive recurrent networks. International Journal of Forecasting, 36(3), 1181–1191.
  2. Salinas, D., Flunkert, V., & Gasthaus, J. DeepAR: Probabilistic Forecasting with Autoregressive Recurrent Networks. arXiv:1704.04110.
  3. awslabs/gluonts (Amazon's time series library; PyTorch implementation of DeepAR)
  4. Hochreiter, S., & Schmidhuber, J. (1997). Long Short-Term Memory. Neural Computation, 9(8), 1735–1780.