AI Logic

Architectures

TimesNet

Updated:

TimesNet architecture. Left: the overall flow, which embeds the context window, extends its length to cover the horizon, and stacks TimesBlocks to output the horizon. Right: inside a TimesBlock (find periods with the FFT, fold the 1D series into a 2D table for each period and convolve it, return to 1D, and sum the results weighted by amplitude)

Background and overview

TimesNet is a model that finds the dominant periods in a time series with the fast Fourier transform (FFT), rearranges the 1D series into "2D tables folded by period," and captures variations with 2D convolutions, just as for images. Wu, Hu, Liu, Zhou, Wang, and Long of Tsinghua University introduced it in 2022, and it was published at ICLR 2023. It is proposed as a general-purpose time-series model whose same backbone can be used not only for forecasting but also for imputation of missing values, classification, and anomaly detection.

The value of a time series at a single time step carries little meaning on its own. What carries meaning is temporal variation, which the paper divides into two kinds:

  • Intraperiod variation: Variation between adjacent time steps, such as electricity use rising from morning to noon within a day.
  • Interperiod variation: Variation seen when comparing noon today with noon yesterday or noon last week, that is, variation between values at the same phase (the same time of day).

In a 1D series, adjacent time steps sit next to each other, but "the same time yesterday" is a whole period away. TimesNet folds the series by the period length into a table with one period per row. Values running across a row then represent intraperiod variation, and values running down a column represent interperiod variation, so 2D convolutions can see both at once.

In calendar terms, this is like taking a record of daily temperatures written in a single line and rearranging it into a calendar with "one week per row." Reading across shows variation within a week, and reading down shows week-to-week variation on the same weekday at a glance. TimesNet performs this "rearrangement" automatically for each period.

Architecture

TimesNet stacks TimesBlocks with residual connections after an embedding layer. The left of the figure at the top of the article shows the overall flow for forecasting, and the right shows the inside of a TimesBlock.

Overall flow (for long-term forecasting)

  1. Normalize: For each variable, subtract the mean of the context window and divide by the standard deviation (as in the official implementation; the inverse transform is applied to the output).
  2. Embed: Each time step of the context window (length TT, CC variables) is mapped to a dmodeld_{\mathrm{model}}-dimensional feature.
  3. Extend to cover the horizon: For forecasting, a linear layer along the time axis extends the length from TT to T+T + (horizon length), producing initial values for the future part (Appendix A of the paper; all compared models also use the same embedding and this linear layer).
  4. Stack TimesBlocks: Layer ll is connected with a residual connection as X1Dl=TimesBlock(X1Dl−1)+X1Dl−1X^l_{\mathrm{1D}} = \mathrm{TimesBlock}(X^{l-1}_{\mathrm{1D}}) + X^{l-1}_{\mathrm{1D}}.
  5. Map back to the output: A linear layer maps dmodeld_{\mathrm{model}} dimensions back to the number of variables, the result is denormalized, and the final horizon portion is used as the forecast.

Inside a TimesBlock

  1. Find periods: Apply the FFT to the input and average the amplitude of each frequency over the variables (features). Select the top kk frequencies f1,…,fkf_1, \dots, f_k by amplitude and compute the period lengths pi=⌈T/fi⌉p_i = \lceil T / f_i \rceil.
  2. Rearrange into 2D tables: Zero-pad the end of the series so its length is a multiple of the period, then fold it by each period pip_i to create kk 2D tables X2DiX^i_{\mathrm{2D}} of size fi×pif_i \times p_i.
  3. Apply 2D convolutions: Apply an Inception-style block, which runs 2D convolutions of different sizes in parallel, to each of the kk tables. The block's weights are shared across the kk tables.
  4. Return to 1D: Flatten each table back into a series and trim the zero-padded part to restore the original length.
  5. Weighted sum by amplitude: Sum the kk results using weights obtained by applying softmax to the amplitudes of the corresponding frequencies.

The equation for finding periods (Eq. 1 in the paper) is:

A=Avg(Amp(FFT(X1D))),{f1,…,fk}=arg⁡Topkf∗∈{1,…,⌊T/2⌋}(A),pi=⌈Tfi⌉\mathbf{A} = \mathrm{Avg}\bigl(\mathrm{Amp}(\mathrm{FFT}(X_{\mathrm{1D}}))\bigr), \qquad \{f_1, \dots, f_k\} = \mathop{\arg\mathrm{Topk}}_{f_* \in \{1, \dots, \lfloor T/2 \rfloor\}} (\mathbf{A}), \qquad p_i = \left\lceil \frac{T}{f_i} \right\rceil

The rearrangement, convolution, and summation (Eqs. 3, 5, and 6) can be written as:

X2Di=Reshapefi×pi(Padding(X1D)),X^1Di=Trunc(Reshape1×(fi⋅pi)(Inception(X2Di)))X^{i}_{\mathrm{2D}} = \mathrm{Reshape}_{f_i \times p_i}\bigl(\mathrm{Padding}(X_{\mathrm{1D}})\bigr), \qquad \hat{X}^{i}_{\mathrm{1D}} = \mathrm{Trunc}\Bigl(\mathrm{Reshape}_{1 \times (f_i \cdot p_i)}\bigl(\mathrm{Inception}(X^{i}_{\mathrm{2D}})\bigr)\Bigr) A^f1,…,A^fk=Softmax(Af1,…,Afk),X1D←∑i=1kA^fi X^1Di\hat{A}_{f_1}, \dots, \hat{A}_{f_k} = \mathrm{Softmax}(A_{f_1}, \dots, A_{f_k}), \qquad X_{\mathrm{1D}} \leftarrow \sum_{i=1}^{k} \hat{A}_{f_i} \, \hat{X}^{i}_{\mathrm{1D}}

The paper's settings for long-term forecasting are k=5k = 5, 2 TimesBlock layers, dmodeld_{\mathrm{model}} determined from the number of variables CC as min⁡{max⁡{2⌈log⁡C⌉,32},512}\min\{\max\{2^{\lceil \log C \rceil}, 32\}, 512\}, a mean squared error loss, Adam (learning rate 10−410^{-4}), and 10 epochs.

Why it works

The paper explains why TimesNet works as follows.

Many time series have multiple periods

Electricity and traffic data contain overlapping periods such as daily, weekly, and yearly cycles. In a 1D series these appear mixed together, but extracting the dominant periods with the FFT and rearranging the series into a separate table for each period makes it possible to handle the structure of each period separately.

2D tables have two kinds of "nearness"

In the rearranged table, a horizontal neighbor is "an adjacent time step," and a vertical neighbor is "the same phase in an adjacent period." Just as neighboring pixels in an image are similar, nearby values in this table are related. As a result, 2D convolutions, proven on images, can capture intraperiod and interperiod variation simultaneously with few parameters.

Image backbones can be used as is

Once the data is a 2D table, blocks from ResNeXt (in the ResNet family), ConvNeXt, or Swin Transformer can be used instead of Inception. In the paper's additional experiments, replacing it with these improved accuracy further. The paper cites the ability of time-series analysis to benefit from advances in image backbones as an advantage.

It learns representations that are strong for classification and anomaly detection

Models with a single linear layer along the time axis, such as DLinear, were strong at forecasting but much weaker at classification (see the table below). The paper explains that TimesNet, which stacks 2D convolutions, more easily learns the hierarchical representations needed for classification.

The "weighted sum by amplitude" in TimesBlock is inspired by the auto-correlation in Autoformer (which sums the results for each candidate period weighted by the strength of the correlation). Both are mechanisms that make periods that appear strongly in the data contribute more to the result.

Experimental results

The paper evaluated TimesNet with the same backbone on five tasks: forecasting (long-term and short-term), imputation of missing values, classification, and anomaly detection.

Long-term forecasting (Context window of 96 (36 for ILI); MSE averaged over 4 horizon lengths; lower is better. Excerpt from Table 2 of the paper.)

DataTimesNetDLinearFEDformerAutoformerInformer
ETTm10.4000.4030.4480.5880.961
ETTm20.2910.3500.3050.3271.410
ETTh10.4580.4560.4400.4961.040
Electricity0.1920.2120.2140.2270.311
Traffic0.6200.6250.6100.6280.764
Weather0.2590.2650.3090.3380.634
Exchange0.4160.3540.5190.6131.550

In the full detailed table (Table 13 of the paper), it was the best in more than 80% of settings. However, on some datasets, such as ETTh1, Traffic, and Exchange, DLinear or FEDformer did better.

Short-term forecasting (M4. Forecast lengths of 6–48. SMAPE; lower is better. Table 3 of the paper.)

TimesNetN-HiTSN-BEATSFEDformerDLinear
11.82911.92711.85112.84013.639

Other tasks (Table 4, Table 5, and Figure 5 of the paper)

TaskMetricTimesNetNext best among those compared
Imputation (ETTm1, average over 4 masking ratios)MSE (lower is better)0.027Non-stationary Transformer 0.036
Classification (average over 10 UEA datasets)Accuracy (higher is better)73.6%Flowformer 73.0%, Rocket 72.5% (DLinear 67.5%)
Anomaly detection (average over 5 datasets)F1 (higher is better)85.49%FEDformer 84.97%

For anomaly detection, TimesNet with ResNeXt in place of Inception scored even higher, at 86.34%.

Practical considerations

Keep the following in mind when using TimesNet:

  • Little advantage on data without clear periods: Since finding periods with the FFT is the starting point, DLinear did better on data with weak periodicity, such as exchange rates (Exchange).
  • One set of periods per batch: The official implementation averages amplitudes over the batch and features before selecting the top kk periods, so all series in a batch are folded by the same periods. This assumption may not hold for data that mixes series with different periods.
  • Compute depends on kk and the length: Because 2D convolutions are applied to each of the kk tables, compute is roughly proportional to kk. Increasing kk does not add parameters, since the block weights are shared.
  • Comparisons with later work: In the iTransformer paper (a comparison with the context window fixed at 96), TimesNet ranked near the top on ETT and Weather, but fell far behind iTransformer (Traffic 0.428) on Traffic (0.620) and Solar-Energy, which have many variables. It does not handle relationships between variables beyond mixing them in the embedding.

Periods are found by an FFT over the full input length (in forecasting, the context window plus the initial values for the horizon). The longest period it can find is limited to that length. If you want to use weekly or yearly periods, provide a context window long enough to contain several of those periods.

Comparison with other models

Comparing time-series models from the same perspectives gives the following:

ModelHow temporal variation is capturedHandling of periodsMain componentsSupported tasks
AutoformerSeries decomposition and auto-correlationAggregates periods via auto-correlation lagsAuto-correlation in place of attentionForecasting
DLinearLinear weights per time stepImplicit in the weightsLinear layersForecasting
PatchTSTAttention between patchesNot explicitTransformerForecasting (pretraining also possible)
TimesNetConvolves 2D tables folded by periodSelects the top kk periods with the FFTInception-style 2D convolutionsForecasting, imputation, classification, anomaly detection
iTransformerFeed-forward layers per variableNot explicitTransformer (variables as tokens)Forecasting
TCNCausal 1D convolutionsNot explicitDilated convolutionsForecasting, classification, etc.

Rough guidelines for choosing:

  • Handling forecasting, imputation, classification, and anomaly detection with a single model backbone: TimesNet is a good fit. The paper reports the best results on all five tasks.
  • Series with several clear periods, such as daily and weekly: TimesNet's period folding pays off.
  • Only long-term forecasting accuracy and speed matter: Also compare DLinear and PatchTST. On data with many variables, iTransformer may have an advantage.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
A small implementation of TimesBlock (following Eqs. 1–6 of arXiv:2210.02186 and
models/TimesNet.py and layers/Conv_Blocks.py in the official thuml/Time-Series-Library)
Input x: [batch B, length T, features d_model] → output: same shape
"""


def fft_for_period(x, k=2):
  """Compute period lengths and weights from the top-k frequencies by FFT amplitude (Eq. 1)"""
  xf = torch.fft.rfft(x, dim=1)                          # FFT along the time axis
  amp = xf.abs()                                         # [B, T//2+1, d]
  freq = amp.mean(0).mean(-1)                            # Amplitude A averaged over batch and features
  freq[0] = 0                                            # Exclude the DC component (frequency 0)
  _, top = torch.topk(freq, k)                           # Top-k frequencies f_i
  periods = [x.shape[1] // int(f) for f in top]          # Period lengths (the official implementation rounds down)
  weights = amp.mean(-1)[:, top]                         # [B, k] amplitude of each frequency
  return periods, weights


class InceptionBlock(nn.Module):
  """Run 2D convolutions of different sizes (1×1, 3×3, 5×5, ...) in parallel and average them"""

  def __init__(self, c_in, c_out, num_kernels=6):
    super().__init__()
    self.kernels = nn.ModuleList(
      [nn.Conv2d(c_in, c_out, kernel_size=2 * i + 1, padding=i) for i in range(num_kernels)]
    )

  def forward(self, x):
    return torch.stack([conv(x) for conv in self.kernels], dim=-1).mean(-1)


class TimesBlock(nn.Module):
  def __init__(self, d_model=32, d_ff=32, k=5, num_kernels=6):
    super().__init__()
    self.k = k
    # Weights shared across the k 2D tables (parameter count does not depend on k)
    self.conv = nn.Sequential(
      InceptionBlock(d_model, d_ff, num_kernels), nn.GELU(), InceptionBlock(d_ff, d_model, num_kernels)
    )

  def forward(self, x):                                  # x: [B, T, d]
    B, T, d = x.shape
    periods, weights = fft_for_period(x, self.k)
    outs = []
    for p in periods:
      length = -(-T // p) * p                            # Round up to a multiple of the period
      pad = torch.zeros(B, length - T, d, device=x.device, dtype=x.dtype)
      z = torch.cat([x, pad], dim=1)                     # Zero-pad the end
      z = z.reshape(B, length // p, p, d).permute(0, 3, 1, 2)  # 2D table [B, d, number of periods, period length]
      z = self.conv(z)                                   # 2D convolution
      z = z.permute(0, 2, 3, 1).reshape(B, -1, d)[:, :T]   # Back to 1D and trim
      outs.append(z)
    outs = torch.stack(outs, dim=-1)                     # [B, T, d, k]
    w = F.softmax(weights, dim=1)[:, None, None, :]      # Weight by softmax of amplitudes (Eq. 6)
    return (outs * w).sum(-1) + x                        # Sum + residual connection (Eq. 4)


# Usage (apply 2 TimesBlock layers to embedded features)
blocks = nn.ModuleList([TimesBlock(d_model=32, d_ff=32, k=5) for _ in range(2)])
norm = nn.LayerNorm(32)
x = torch.randn(8, 192, 32)                              # Features extended to 96 past + 96 future steps

blocks.train()                                           # No dropout or batch norm, so train and eval compute the same thing
for blk in blocks:
  x = norm(blk(x))                                       # The official implementation applies layer normalization after each layer
print(x.shape)                                           # torch.Size([8, 192, 32])

FAQ

Q. Are the periods learned during training?
A.

No. The FFT is applied to the input of each TimesBlock, and period lengths are computed on the fly from the top kk frequencies by amplitude at that moment. If the input changes, the selected periods change too. What is learned are weights such as those of the 2D convolutions (the Inception-style block).

Q. Why 2D convolutions? Wouldn't 1D convolutions work?
A.

A 1D convolution sees only adjacent time steps (intraperiod variation) as nearby. To see "the same time one period ago," it needs a large window reaching a full period length away. In a 2D table folded by period, the same time one period earlier sits directly above, so even a small convolution such as 3×33 \times 3 can see intraperiod and interperiod variation simultaneously.

Q. How is it used for tasks other than forecasting?
A.

The backbone (embedding + stacked TimesBlocks) is shared, and only the last layer is adapted to the task. For imputation and anomaly detection, it outputs a series of the same length as the input and compares it with the original (for anomaly detection, the reconstruction error is used as the anomaly score); for classification, the features of all time steps are flattened and a linear layer outputs the class. For forecasting, a linear layer along the time axis extends the length to cover the horizon before the input enters the TimesBlocks.

References

  1. Wu, H., Hu, T., Liu, Y., Zhou, H., Wang, J., & Long, M. (2023). TimesNet: Temporal 2D-Variation Modeling for General Time Series Analysis. ICLR 2023.
  2. thuml/Time-Series-Library (a library that includes the official implementation; PyTorch)
  3. Szegedy, C., Liu, W., Jia, Y., et al. (2015). Going Deeper with Convolutions. CVPR 2015.
  4. Wu, H., Xu, J., Wang, J., & Long, M. (2021). Autoformer: Decomposition Transformers with Auto-Correlation for Long-Term Series Forecasting. NeurIPS 2021.
  5. Liu, Y., Hu, T., Zhang, H., Wu, H., Wang, S., Ma, L., & Long, M. (2024). iTransformer: Inverted Transformers Are Effective for Time Series Forecasting. ICLR 2024.