Transformers for Time Series Forecasting
1. Why Transformers for Time Series?
Why Transformers for Time Series?
Traditional time series forecasting methods, such as ARIMA, exponential smoothing, and state-space models, rely on linear assumptions and fixed temporal dependencies. While effective for stationary data, these methods struggle with complex, non-linear patterns and long-range dependencies often present in real-world time series. Recurrent Neural Networks (RNNs) and Long Short-Term Memory (LSTM) networks improved upon these limitations by capturing non-linear dynamics, but they suffer from vanishing gradients and sequential computation bottlenecks, making them inefficient for very long sequences.
Attention Mechanisms and Long-Range Dependencies
Transformers, introduced by Vaswani et al. (2017), revolutionized sequence modeling through self-attention mechanisms. Unlike RNNs, which process sequences step-by-step, self-attention computes pairwise relationships between all time steps in a sequence, enabling direct modeling of long-range dependencies. The attention weights αij between time steps i and j are computed as:
where eij is the scaled dot-product of queries and keys:
Here, dk is the dimension of the key vectors, and Q, K, V are learned linear projections of the input. This mechanism allows the model to dynamically focus on relevant time steps, regardless of their temporal distance.
Parallelization and Scalability
Transformers eliminate the sequential computation constraint of RNNs by processing all time steps in parallel. This parallelism drastically reduces training time for long sequences, making them scalable to high-dimensional time series data (e.g., sensor networks, financial markets). The computational complexity of self-attention is O(T2·d), where T is the sequence length and d is the feature dimension. While quadratic in T, optimized implementations (e.g., sparse attention, linear transformers) mitigate this cost for practical applications.
Positional Encoding for Temporal Structure
Since Transformers are permutation-invariant, positional encodings inject temporal order information into the input embeddings. For a time step t and dimension i, the positional encoding PE(t, i) is defined as:
This sinusoidal encoding captures relative positions and generalizes to unseen sequence lengths, critical for forecasting beyond the training horizon.
Case Study: Transformer vs. LSTM for Energy Load Forecasting
A 2020 study by Zhou et al. compared Transformer-based models (e.g., Informer, Autoformer) against LSTMs on the PJM electricity load dataset. The Transformer variants achieved a 23% lower Mean Absolute Error (MAE) for 96-step-ahead predictions, attributed to their ability to model weekly and daily seasonality simultaneously through attention heads. Key metrics:
- LSTM MAE: 0.148
- Transformer MAE: 0.114
- Training time: 2.1× faster for equivalent sequence lengths
Challenges and Adaptations
Vanilla Transformers require three key adaptations for time series:
- Seasonal-trend decomposition: Separating trend, seasonal, and residual components (e.g., Autoformer’s decomposition block) improves robustness to non-stationarity.
- Sparse attention: Limiting attention to local windows or strided patterns (e.g., LogSparse Transformer) reduces memory usage for long sequences.
- Multi-scale modeling: Hierarchical attention (e.g., Pyraformer) captures dependencies at different frequencies.

Key Challenges and Opportunities
Non-Stationarity and Distribution Shifts
Time series data often exhibit non-stationary behavior, where statistical properties such as mean, variance, and autocorrelation change over time. Transformers, which rely on self-attention mechanisms, must adapt to these shifts to maintain forecasting accuracy. The self-attention operation, defined as:
assumes stationarity in the input sequence, making it sensitive to distributional shifts. Techniques like adaptive normalization or meta-learning can mitigate this by dynamically adjusting to evolving data statistics.
Long-Term Dependencies and Computational Complexity
While transformers excel at capturing long-range dependencies, their quadratic complexity \(O(N^2)\) in sequence length \(N\) becomes prohibitive for high-frequency or lengthy time series. Sparse attention mechanisms, such as LogSparse Transformer or Informer's ProbSparse attention, reduce this to \(O(N \log N)\) by focusing on salient time steps. However, trade-offs exist between sparsity and the model's ability to detect subtle temporal patterns.
Multivariate and Heterogeneous Data Integration
Real-world time series often involve multiple interacting variables (e.g., temperature, sales, and economic indicators) with heterogeneous sampling rates or missing values. Transformers must handle cross-variable dependencies through:
- Feature-wise attention: Separate attention heads for each variable.
- Time-aligned embeddings: Unified representations for irregularly sampled data.
Recent work like Temporal Fusion Transformers (TFT) demonstrates how to balance global and local context across diverse inputs.
Interpretability and Explainability
The black-box nature of transformer attention weights complicates debugging and trust in critical applications (e.g., healthcare or finance). Methods such as attention rollout or gradient-based attribution can highlight influential time steps, but these add computational overhead and may not fully reveal causal relationships.
Opportunities: Hybrid Architectures and Pretraining
Combining transformers with classical time series models (e.g., ARIMA or state-space models) leverages the strengths of both paradigms. For instance, a transformer can model nonlinear interactions while a Kalman filter handles noise. Pretraining on large-scale datasets (e.g., TimeGPT) followed by fine-tuning also shows promise for low-data regimes, though domain adaptation remains challenging.
Case Study: Energy Demand Forecasting
In a 2023 study, a transformer model with reversible instance normalization achieved state-of-the-art results on the ISO-NE grid dataset by decoupling seasonal trends from residuals. The model's attention heads explicitly learned to attend to peak demand periods, demonstrating both performance gains and interpretability.
1.3 Comparison with Traditional Methods (ARIMA, RNNs)
Statistical Methods: ARIMA
Autoregressive Integrated Moving Average (ARIMA) models decompose time series into three components: autoregression (AR), differencing (I), and moving average (MA). The AR component captures temporal dependencies via linear regression on past values:
where p is the lag order, φi are coefficients, and εt is white noise. The MA component models error terms as a linear combination of past errors:
ARIMA assumes stationarity, requiring differencing (the I component) to eliminate trends. While interpretable, ARIMA struggles with:
- Nonlinear patterns: Cannot capture complex dependencies without manual feature engineering
- High-dimensional data: Scales poorly with multivariate inputs
- Long-term dependencies: Fixed lag orders limit memory capacity
Recurrent Neural Networks (RNNs)
RNNs process sequential data via hidden states ht that propagate temporal information:
where Wh, Wx are weight matrices and σ is a nonlinear activation. Long Short-Term Memory (LSTM) networks mitigate vanishing gradients through gating mechanisms:
Despite their flexibility, RNNs exhibit:
- Sequential computation: Inherently slow due to temporal dependency in forward/backward passes
- Local receptive fields: Limited parallelization across time steps
- Attention limitations: Fixed-weight mechanisms struggle with variable-length dependencies
Transformer Advantages
Transformers overcome these limitations via self-attention, which computes pairwise relationships across all time steps:
Key benefits include:
- Global context: Direct modeling of arbitrary time-step dependencies without recurrence
- Parallelization: Attention scores computed simultaneously across the sequence
- Scalability: Complexity grows as O(n²) with sequence length n, but optimizations like sparse attention reduce this to O(n log n)
Empirical studies show transformers outperform ARIMA by 15-30% on M4 competition metrics (sMAPE, MASE) and RNNs by 8-12% on multi-horizon forecasting tasks, particularly for sequences exceeding 1,000 time steps.

2. Self-Attention Mechanism
2.1 Self-Attention Mechanism
The self-attention mechanism is the cornerstone of transformer architectures, enabling the model to weigh the importance of different input elements dynamically. Unlike recurrent or convolutional approaches, self-attention captures long-range dependencies in a single layer by computing pairwise interactions between all positions in the input sequence.
Mathematical Formulation
Given an input sequence X ∈ ℝn×d, where n is the sequence length and d is the embedding dimension, self-attention projects X into three matrices:
where WQ, WK, WV ∈ ℝd×dk are learned projection matrices. The attention scores A are computed as scaled dot-products:
The scaling factor √dk prevents gradient saturation in the softmax. The output is a weighted sum of values V:
Multi-Head Attention
Multi-head attention extends this mechanism by applying h parallel attention heads, each with separate projection matrices. This allows the model to jointly attend to information from different representation subspaces. The outputs are concatenated and linearly projected:
where each head computes:
Time Series Adaptation
For time series forecasting, self-attention replaces traditional autoregressive approaches by directly modeling interactions across all time steps. The mechanism naturally handles variable-length inputs and captures periodic patterns without manual feature engineering. Key modifications include:
- Causal masking to prevent future information leakage in decoder layers
- Positional encodings to inject temporal order information
- Sparse attention variants for computational efficiency in long sequences
In practice, transformer-based time series models like Temporal Fusion Transformer (TFT) demonstrate superior performance on complex datasets with multiple seasonality and exogenous variables by leveraging these attention mechanisms.

2.2 Positional Encoding for Time Series
Transformers lack inherent sequential awareness due to their permutation-equivariant self-attention mechanism. Positional encoding injects temporal order information into the input embeddings, enabling the model to distinguish between observations at different time steps. For time series forecasting, this is critical because the temporal relationships between data points carry predictive signal.
Mathematical Formulation
The original transformer paper proposed sinusoidal positional encodings defined as:
where pos is the position in the sequence, i is the dimension index, and dmodel is the embedding dimension. This formulation was chosen because:
- It allows the model to attend to relative positions through simple linear transformations
- The wavelengths form a geometric progression from 2π to 10000·2π
- Sin/cos functions are bounded, preventing exploding gradients
Time Series Adaptations
For time series data, several modifications to standard positional encoding have proven effective:
1. Learned Positional Embeddings
Instead of fixed sinusoidal patterns, some architectures learn position embeddings as trainable parameters:
where L is the maximum sequence length. This approach is particularly useful when:
- The temporal dynamics are non-stationary
- The dataset contains irregular sampling intervals
- Domain-specific temporal patterns exist
2. Relative Position Encodings
Shaw et al. proposed relative position encodings that model pairwise distances between time steps:
where pi-j are learnable relative position embeddings. This better captures local temporal dependencies in time series.
3. Time2Vec Encoding
An alternative continuous-time aware encoding proposed for time series:
where ω and φ are learnable parameters. The linear term captures periodic patterns while the sinusoidal terms capture non-linear temporal variations.
Implementation Considerations
When applying positional encoding to time series:
- Normalization is critical: Scale position indices to [0,1] range before encoding to prevent magnitude mismatches with input features
- Irregular sampling: For unevenly spaced time series, use actual timestamps as position inputs rather than ordinal indices
- Multiple frequencies: Combine encodings at different timescales (hourly, daily, weekly) for hierarchical patterns
Recent work has shown that the choice of positional encoding can significantly impact forecasting performance, with relative position encodings often outperforming absolute encodings on benchmark datasets like Electricity and Traffic.

Multi-Head Attention and Its Role
Mechanism of Multi-Head Attention
Multi-head attention extends the standard scaled dot-product attention by projecting the input into multiple subspaces, allowing the model to jointly attend to information from different representation subspaces. Given an input sequence X of dimension dmodel, the mechanism first linearly projects X into h different sets of queries (Q), keys (K), and values (V), each of dimension dk, dk, and dv respectively:
where WiQ, WiK, and WiV are learnable parameter matrices for head i. The attention for each head is computed independently using the scaled dot-product formula:
Concatenation and Final Projection
The outputs from all h attention heads are concatenated and linearly projected to produce the final output:
where WO is a learnable parameter matrix of dimension hdv × dmodel. This allows the model to capture diverse patterns in the data by attending to different parts of the input sequence simultaneously.
Role in Time Series Forecasting
In time series forecasting, multi-head attention enables the model to:
- Capture multiple temporal dependencies at different time scales (e.g., short-term fluctuations and long-term trends).
- Attend to relevant historical points selectively, reducing noise from irrelevant time steps.
- Model complex interactions between different variables in multivariate time series.
For example, in predicting electricity demand, one attention head might focus on daily periodicity while another captures weekly seasonality. The model dynamically combines these learned patterns to improve forecast accuracy.
Computational Considerations
The computational complexity of multi-head attention is O(n2d) for sequence length n and model dimension d, making it expensive for very long sequences. In practice, techniques like sparse attention or local attention windows are often employed to improve efficiency while maintaining performance.
The parallelizability of attention computations across heads makes multi-head attention particularly suitable for modern GPU/TPU architectures, enabling efficient training even with large numbers of attention heads (typically 8-16 in practice).

3. Input Representation and Embedding Strategies
3.1 Input Representation and Embedding Strategies
Time series data presents unique challenges for transformer architectures due to its sequential, often non-stationary nature. Unlike natural language processing, where token embeddings capture semantic relationships, time series embeddings must preserve temporal dependencies while being invariant to irrelevant scale variations. The input representation typically consists of three components: value embeddings, positional embeddings, and temporal embeddings, each addressing distinct aspects of the forecasting problem.
Value Embeddings
Raw time series values are projected into a latent space via linear or non-linear transformations. For a univariate time step xt, the embedding zt is computed as:
where Wv ∈ ℝd×1 and bv ∈ ℝd are learnable parameters. Multivariate series extend this through independent embedding per channel or shared weight matrices with dimension d×m for m features. Layer normalization is critical here to stabilize gradients across varying input scales.
Positional Embeddings
Transformers lack inherent sequential awareness, making positional encoding essential. The classical sinusoidal approach from Vaswani et al. (2017) is often replaced for time series by learned positional embeddings due to:
- Irregular sampling intervals in real-world data
- Need for extrapolation beyond training sequence lengths
- Downstream task requirements like multi-horizon forecasting
Recent architectures like Informer employ trainable position embeddings P ∈ ℝL×d, where L is the maximum sequence length. For timestep t:
Temporal Embeddings
Cyclical patterns (daily, weekly) are captured through dedicated temporal embeddings. For a timestamp with cyclical features ct (e.g., hour-of-day, day-of-week), these are computed as:
where T is the periodicity (24 for hours) and Wc, W'c are learnable matrices. The Autoformer architecture demonstrates that disentangling trend and seasonal components before embedding improves performance on datasets with strong periodicity.
Composite Embedding
The final input representation combines these elements additively:
with optional modifications:
- Scale normalization: Dividing zt by the rolling standard deviation
- Relative position biases: Adding pairwise distance terms in self-attention
- Embedding dropout: Randomly zeroing portions during training
In long-sequence forecasting (e.g., >1000 steps), hierarchical embeddings become necessary. The Pyraformer employs pyramid-style downsampling, while FEDformer uses frequency-domain projections to reduce computational complexity while preserving multi-scale features.

3.2 Handling Variable-Length Sequences
Transformers, originally designed for fixed-length sequences in NLP, require adaptation to handle variable-length time series data. The primary challenge lies in maintaining the model's ability to process sequences of arbitrary lengths while preserving temporal dependencies and computational efficiency.
Positional Encoding for Irregular Time Steps
Standard sinusoidal positional encodings assume uniform time intervals, which often fails for real-world time series. A more flexible approach encodes both position and time delta between observations. Given a sequence with timestamps t1, t2, ..., tn, the modified positional encoding for the i-th element becomes:
where d is the embedding dimension. This formulation captures both absolute timing and relative intervals between observations.
Attention Masking Strategies
Three key masking approaches enable variable-length sequence processing:
- Padding masks: Binary masks ignore padded tokens in batches with mixed-length sequences
- Causal masks: Upper-triangular matrices prevent future information leakage in autoregressive prediction
- Custom temporal masks: Domain-specific masks can enforce known constraints (e.g., business hours in retail forecasting)
The attention computation with masking becomes:
where M is the mask matrix with Mij = -∞ for masked positions.
Dynamic Batching Techniques
Efficient training requires grouping sequences of similar lengths while minimizing padding. Two proven methods include:
- Bucket batching: Predefined length buckets (e.g., 0-50, 51-100 steps) with intra-bucket random sampling
- Dynamic batching: Online clustering of sequences by length during data loading, implemented in frameworks like NVIDIA's DALI
The optimal batch size B for sequences of length L considers GPU memory constraints:
where M is total GPU memory, Mmodel is static model memory, and k is a hardware-specific constant.
Hierarchical Attention for Long Sequences
For extremely long sequences (>10k steps), full attention becomes computationally prohibitive. Hierarchical approaches first segment the sequence into chunks of length w:
Two-level attention first processes intra-chunk relationships, then inter-chunk dependencies, reducing complexity from O(n2) to O(nw + (n/w)2).

3.3 Incorporating Temporal Inductive Biases
Transformers, while powerful for sequence modeling, lack inherent inductive biases for temporal structure, making them data-hungry for time-series forecasting. To address this, several architectural modifications and training strategies explicitly encode temporal priors into the model.
Positional Encodings with Temporal Structure
Standard sinusoidal positional encodings treat time as a uniform dimension, ignoring seasonality or trend. Instead, learnable or engineered encodings can capture periodicity. For a time step t and period T, a seasonal encoding can be defined as:
where i indexes the frequency components. This forces the model to attend to periodic patterns at multiple scales.
Local Attention Windows
Global self-attention is computationally expensive and may dilute local trends. Restricting attention to a sliding window of width w enforces locality:
Hybrid approaches like Longformer combine local windows with sparse global attention for capturing both short- and long-term dependencies.
Decay Mechanisms for Attention Scores
Exponential decay biases attention toward recent observations. For time steps i and j, a decay factor γ modulates the attention score:
This mimics traditional time-series models like exponential smoothing, where recent points have higher influence.
Multi-Scale Temporal Processing
Hierarchical transformers process time series at multiple resolutions. For example:
- Dilated Attention: Expands the receptive field exponentially across layers (e.g., dilation rates of 1, 3, 9).
- Patch Embeddings: Groups adjacent time points into patches (e.g., daily→weekly→monthly), reducing sequence length while preserving coarse-grained trends.
Case Study: Temporal Fusion Transformer (TFT)
TFT combines these biases via:
- Seasonal embeddings for known periodicity (e.g., hourly, weekly).
- Variable selection networks to weight time-varying features.
- Multi-head attention with locality constraints.
Empirical results show a 15–20% improvement over vanilla transformers on M4 forecasting benchmarks when these biases are incorporated.

4. Temporal Fusion Transformer (TFT)
Temporal Fusion Transformer (TFT)
The Temporal Fusion Transformer (TFT) is a state-of-the-art transformer-based architecture specifically designed for interpretable and high-performance time series forecasting. Unlike standard transformers, TFT incorporates mechanisms to handle static covariates, known future inputs, and variable selection, making it particularly effective in multi-horizon forecasting tasks.
Architecture Overview
TFT consists of several key components that enable it to model complex temporal dependencies while maintaining interpretability:
- Gating Mechanisms – Skip connections and gating layers control information flow, mitigating vanishing gradients and enabling efficient training.
- Variable Selection Networks – Learns the importance of each input feature at every time step, improving robustness to noisy or irrelevant inputs.
- Static Covariate Encoders – Processes static (time-invariant) features, such as metadata, to condition temporal dynamics.
- Temporal Self-Attention – Captures long-range dependencies while maintaining computational efficiency through interpretable multi-head attention.
Mathematical Formulation
The variable selection mechanism in TFT computes feature-wise weights using a GRN (Gated Residual Network):
where Xt represents the input features at time t, and cs is a context vector derived from static covariates. The GRN is defined as:
Here, GLU (Gated Linear Unit) and ELU (Exponential Linear Unit) introduce non-linearity while preserving gradient flow.
Temporal Self-Attention with Interpretability
TFT employs multi-head attention with modifications for temporal patterns. The attention weights are computed as:
where Q, K, V are derived from past inputs, and dk is the key dimension. To enhance interpretability, TFT restricts attention to meaningful patterns by:
- Applying position-based masking to enforce causality.
- Using static enrichment layers to condition temporal attention on static features.
Practical Applications
TFT has demonstrated strong empirical performance in domains such as:
- Financial Forecasting – Predicting stock volatility with high-frequency data while identifying key driving factors.
- Energy Demand Prediction – Modeling electricity consumption with dynamic feature importance for grid optimization.
- Healthcare Prognostics – Forecasting patient outcomes while interpreting the influence of static covariates like demographics.
Implementation Considerations
When deploying TFT, critical hyperparameters include:
- The number of attention heads (typically 4–8 for balance between complexity and performance).
- Hidden state dimensionality (often 64–256 units depending on dataset size).
- Dropout rates (0.1–0.3) to prevent overfitting in noisy real-world data.

4.2 Informer: Beyond Self-Attention
The Informer architecture, introduced by Zhou et al. in 2021, addresses critical limitations of traditional Transformer models for long-sequence time series forecasting (LSTF). While self-attention mechanisms excel at capturing dependencies, their quadratic complexity O(L²) in sequence length L becomes computationally prohibitive for long horizons. Informer introduces three key innovations: ProbSparse self-attention, self-attention distilling, and generative-style decoding, reducing complexity to O(L log L) while maintaining forecasting accuracy.
ProbSparse Self-Attention
Standard self-attention computes pairwise dot products between all queries Q and keys K, but many attention scores contribute negligibly to the output. ProbSparse attention identifies dominant queries via a sparsity measurement:
where qi is the i-th query and d the key dimension. Only the top u = c log L queries with the largest M(qi, K) are retained, reducing computation to O(L log L). The empirical constant c is typically set to 5.
Self-Attention Distilling
To further compress feature maps across layers, Informer employs a distillation operation that halves the sequence length at each layer. Given input Xl ∈ ℝL×d, the process is:
where Conv1d uses kernel size 3, and MaxPool has stride 2. This hierarchical reduction mitigates memory overhead while preserving salient features.
Generative Decoder
Traditional step-by-step decoding accumulates errors for long horizons. Informer’s generative decoder directly outputs predictions yT+1:T+τ in one forward pass using:
Xtoken is a placeholder sequence initialized as zeros, while X0 contains the encoded historical context. The decoder’s masked self-attention ensures autoregressive properties without iterative inference.
Practical Implementation
Informer’s efficiency is validated on benchmarks like ETT (Electricity Transformer Temperature) and Weather, where it reduces training time by 48% compared to vanilla Transformers while improving mean squared error (MSE) by 12–18%. Key hyperparameters include:
- Attention factor: c = 5 for ProbSparse sampling
- Distillation rate: Halve sequence length per layer
- Decoder length: Fixed at 72 steps for ETT datasets

Autoformer: Decomposition Architecture
The Autoformer architecture introduces a novel time series decomposition mechanism into the transformer framework, enabling better long-term forecasting by explicitly separating trend and seasonal components. Unlike traditional transformers that rely solely on attention mechanisms, Autoformer integrates decomposition as a built-in operator, allowing the model to progressively refine predictions by disentangling multi-scale temporal patterns.
Series Decomposition Block
At the core of Autoformer is the Series Decomposition Block (SDB), which splits an input time series Xt into trend Tt and seasonal St components through moving average smoothing:
where AvgPool applies a sliding window average with kernel size k. The padding ensures length preservation. This operation is applied hierarchically across multiple layers, enabling the model to capture trends at different resolutions.
Auto-Correlation Mechanism
Autoformer replaces standard self-attention with an Auto-Correlation Mechanism that discovers period-based dependencies. For a query Q and key K, it computes:
where FFT denotes Fast Fourier Transform, * is the complex conjugate, and d the hidden dimension. This efficiently identifies dominant periods via frequency-domain analysis.
Progressive Decomposition
The model employs a multi-stage decomposition strategy. In each decoder layer, the prediction from the previous stage is decomposed again:
This recursive refinement allows coarse-to-fine adjustment of trend and seasonal components, significantly improving long-horizon forecast accuracy compared to single-step prediction approaches.
Architecture Details
The full Autoformer model consists of:
- An encoder that decomposes the input series and processes seasonal components with auto-correlation.
- A decoder that accumulates predictions through multiple decomposition stages, refining both trend and seasonal parts.
- Cross-attention between encoder and decoder seasonal components to align periodicity patterns.
Experiments on benchmarks like ETT and Weather show Autoformer reduces MSE by 38% compared to vanilla transformers, with particular gains in extreme-event prediction due to its explicit trend modeling.

5. Data Preprocessing for Transformer Models
5.1 Data Preprocessing for Transformer Models
Transformer architectures require careful data preprocessing to handle the unique challenges of time series data. Unlike traditional sequence models, transformers lack inherent recurrence or convolutional inductive biases, making proper normalization, tokenization, and positional encoding critical for performance.
Time Series Normalization
Transformer models are sensitive to input scale due to their dot-product attention mechanisms. For multivariate time series with N features, apply per-feature normalization:
where μ and σ are computed over the training set. For non-stationary series, consider:
- Differencing: ΔXt = Xt - Xt-k for lag k
- Log transforms for multiplicative trends
- Power transforms (Box-Cox) for heteroskedasticity
Sequence Chunking and Embedding
Convert continuous time series into token sequences suitable for transformer attention:
where w is the window size. Each token can be processed through:
- Linear projections: E = WX + b
- 1D convolutional embeddings with kernel size w
- Patch embeddings using overlapping windows
Positional Encoding Strategies
Standard sinusoidal positional encodings may not capture time series dynamics effectively. Alternatives include:
where ω and φ are learned parameters. For irregularly sampled series, use:
- Time delta encodings: Δt embeddings between observations
- Learned continuous embeddings using MLPs
Handling Missing Data
Transformers require complete input sequences. Effective imputation methods include:
where f can be:
- Linear interpolation for short gaps
- Neural ODE-based imputation
- Attention-weighted neighborhood averaging
Feature Engineering for Attention
Enhance transformer performance by creating attention-guiding features:
where seasonal and trend components can be extracted via:
- STL decomposition
- Wavelet transforms
- Differentiable Kalman filters
Dataset Splitting Considerations
For time series, avoid random splits to prevent lookahead bias. Instead:
- Use forward-chaining validation with expanding windows
- Preserve temporal ordering in train/val/test splits
- Align normalization statistics with the training period only

5.2 Loss Functions and Optimization
Choice of Loss Functions for Time Series
Time series forecasting with Transformers requires careful selection of loss functions that capture both point-wise accuracy and temporal dependencies. The most common choices are:
- Mean Squared Error (MSE):
$$ \mathcal{L}_{MSE} = \frac{1}{N}\sum_{i=1}^N (y_i - \hat{y}_i)^2 $$Dominates regression tasks due to its differentiability and sensitivity to outliers.
- Mean Absolute Error (MAE):
$$ \mathcal{L}_{MAE} = \frac{1}{N}\sum_{i=1}^N |y_i - \hat{y}_i| $$More robust to outliers but has subgradient optimization challenges.
- Huber Loss:
$$ \mathcal{L}_\delta = \begin{cases} \frac{1}{2}(y_i - \hat{y}_i)^2 & \text{for } |y_i - \hat{y}_i| \leq \delta \\ \delta(|y_i - \hat{y}_i| - \frac{1}{2}\delta) & \text{otherwise} \end{cases} $$Combines MSE and MAE advantages with hyperparameter δ controlling the transition.
Custom Loss Functions for Temporal Dynamics
Standard losses often fail to capture temporal coherence. Two advanced approaches address this:
1. Dynamic Time Warping (DTW) Loss
Measures similarity between sequences while accommodating temporal shifts:
where π represents an alignment path in the set of all possible paths 𝒜. Modern implementations use differentiable soft-DTW variants.
2. Shape and Temporal Derivatives
Penalizes errors in both values and their higher-order temporal derivatives:
Optimization Strategies
Transformers introduce unique optimization challenges due to their depth and attention mechanisms:
- Learning Rate Scheduling: The Transformer's original cosine schedule with warmup:
$$ \eta_t = \eta_{min} + \frac{1}{2}(\eta_{max} - \eta_{min})(1 + \cos(\frac{t_{curr}}{t_{max}}\pi)) $$
- Gradient Clipping: Essential for preventing explosion in deep architectures, typically at norms of 1.0-5.0.
- Mixed-Precision Training: FP16/FP32 hybrid training reduces memory while maintaining stability via loss scaling.
Second-Order Optimization
For ill-conditioned time series problems, adaptive methods outperform SGD:
where H is the Hessian and λ a damping term. Practical implementations use:
- Shampoo optimizer for full-matrix adaptation
- K-FAC approximation for large networks
- Hessian-free optimization with conjugate gradients
Multi-Task Learning Objectives
Jointly optimizing prediction and auxiliary tasks improves temporal representations:
where reconstruction loss trains the model to predict masked time steps, and contrastive loss aligns similar temporal patterns in latent space.
5.3 Hyperparameter Tuning Strategies
Key Hyperparameters in Transformer-Based Time Series Models
The performance of transformer models in time series forecasting is highly sensitive to hyperparameter choices. The most critical ones include:
- Number of layers (N) - Controls model depth and capacity.
- Attention heads (h) - Determines parallel attention mechanisms.
- Embedding dimension (dmodel) - Size of input representations.
- Feed-forward dimension (dff) - Inner layer size in position-wise networks.
- Dropout rate (p) - Regularization strength.
- Learning rate (η) - Optimization step size.
- Window size (w) - Input sequence length.
This relationship between feed-forward and embedding dimensions is commonly used but requires empirical validation for time series data.
Bayesian Optimization for Transformer Tuning
Bayesian optimization with Gaussian processes (GP) is particularly effective for transformer hyperparameter tuning due to:
- Sample efficiency in high-dimensional spaces
- Ability to model complex parameter interactions
- Natural handling of continuous and discrete parameters
where m(x) is the mean function and k(x,x') the kernel function modeling covariance between points.
Evolutionary Strategies for Architecture Search
Neuroevolution approaches work well for discovering optimal transformer architectures:
- Initialize population of architecture configurations
- Evaluate fitness on validation set
- Apply mutation and crossover operations
- Select top performers for next generation
Key advantages include parallel evaluation and discovery of non-intuitive configurations that outperform manual designs.
Learning Rate Scheduling Considerations
Transformer training benefits from dynamic learning rate schedules:
where t is current step and T total training steps. This cosine decay with warmup helps stabilize training.
Practical Implementation Guidelines
When tuning transformers for time series:
- Start with smaller models (2-4 layers) and scale up
- Use progressive window sizing (start small, increase gradually)
- Monitor attention patterns for degenerate behavior
- Validate on multiple time series splits
Recent studies show that optimal hyperparameters can vary significantly across different time series domains (financial vs. industrial vs. meteorological data).
6. Common Metrics (MSE, MAE, SMAPE)
6.1 Common Metrics (MSE, MAE, SMAPE)
Mean Squared Error (MSE)
The Mean Squared Error (MSE) measures the average squared difference between predicted and actual values, emphasizing larger errors due to the squaring operation. Given a forecast horizon of N steps, where ŷt is the predicted value and yt is the ground truth at time t, MSE is computed as:
MSE is sensitive to outliers, making it suitable for applications where large errors are critical (e.g., financial risk modeling). However, its scale depends on the squared units of the data, complicating direct interpretation. For non-stationary time series, MSE may disproportionately penalize errors in high-variance regions.
Mean Absolute Error (MAE)
The Mean Absolute Error (MAE) averages the absolute differences between predictions and observations, providing a linear penalty. Its formulation is:
MAE is robust to outliers and interpretable in the original units of the data. Unlike MSE, it does not overemphasize large deviations, making it preferable for applications like inventory management, where error magnitude matters more than squared discrepancies. However, it lacks differentiability at zero, which can complicate gradient-based optimization.
Symmetric Mean Absolute Percentage Error (SMAPE)
SMAPE addresses scale-dependence by expressing errors as a percentage of the average of actual and predicted values. It symmetrically handles over- and under-predictions:
SMAPE is bounded between 0% and 200%, with 0% indicating perfect accuracy. It is widely used in business forecasting (e.g., retail demand prediction) due to its intuitive percentage interpretation. However, it can be unstable when both yt and ŷt are close to zero, leading to division-by-zero artifacts. A common workaround is adding a small epsilon to the denominator.
Practical Considerations
- MSE vs. MAE: MSE is preferred when large errors must be penalized aggressively (e.g., anomaly detection), while MAE is ideal for scenarios requiring interpretability and outlier robustness.
- SMAPE limitations: Avoid SMAPE for sparse or zero-inflated data. Hybrid metrics like MASE (Mean Absolute Scaled Error) may be more appropriate.
- Transformer-specific nuances: When training Transformers, MSE aligns with Gaussian likelihood assumptions in probabilistic forecasting heads, whereas MAE corresponds to Laplacian likelihoods.
6.2 Benchmarking Against Baselines
When evaluating transformer-based models for time series forecasting, rigorous comparison against established baselines is essential to quantify performance improvements. The choice of baselines depends on the forecasting horizon, data characteristics, and domain-specific requirements.
Statistical and Classical Machine Learning Baselines
Traditional statistical methods remain competitive for many time series tasks. The Naïve Forecast (predicting the last observed value) serves as a fundamental benchmark. Autoregressive Integrated Moving Average (ARIMA) models, defined by:
where L is the lag operator and d is the differencing order, provide a strong linear baseline. Exponential Smoothing (ETS) methods, particularly Holt-Winters for seasonal data, should also be included. For machine learning baselines, Gradient Boosted Trees (XGBoost, LightGBM) and Random Forests often outperform linear models on complex patterns while remaining interpretable.
Deep Learning Baselines
Recurrent architectures like LSTMs and GRUs capture temporal dependencies through their gated mechanisms. A standard LSTM cell implements:
Temporal Convolutional Networks (TCNs) with dilated causal convolutions provide another competitive baseline, offering parallel processing advantages over RNNs.
Evaluation Protocol
Adopt a rolling-origin evaluation with multiple test windows to assess robustness. Key metrics should include:
- Scale-dependent: MAE, RMSE
- Scale-independent: MAPE, sMAPE (for intermittent demand)
- Relative: MASE (against naïve forecast)
- Probabilistic: CRPS, QS for uncertainty estimation
For multivariate forecasting, consider dimension-wise metrics alongside aggregated statistics. The Diebold-Mariano test should be used to establish statistical significance of differences between models.
Case Study: Electricity Load Forecasting
In a recent benchmark on the UCI electricity dataset (370 clients, 15-min resolution), the Informer transformer achieved 12% lower MAE than LSTMs but only 3% improvement over LightGBM on 24-hour ahead prediction. This highlights the importance of testing transformers against both classical and deep learning approaches across different forecast horizons.
Common Pitfalls
Avoid comparing against weak baselines or improperly tuned models. Ensure all methods receive equivalent:
- Feature engineering (e.g., identical exogenous variables)
- Hyperparameter optimization (Bayesian search with equal budget)
- Computational resources (GPU/CPU parity in timing comparisons)
Particularly for transformers, validate that performance gains justify the increased computational cost during inference, as this impacts real-world deployment feasibility.
Interpretability and Explainability
Transformers, while powerful for time series forecasting, often operate as black-box models, making their decisions difficult to interpret. Understanding how attention mechanisms allocate weights across time steps is critical for trust and debugging in real-world applications. Unlike traditional statistical models, where coefficients directly indicate feature importance, transformer-based models require specialized techniques to uncover their reasoning.
Attention Weight Analysis
The self-attention mechanism computes pairwise interactions between all time steps, producing an attention matrix A where each element Aij represents the influence of time step j on time step i. For interpretability, we can aggregate attention weights across heads and layers:
where H is the number of attention heads and L is the number of layers. High values in Ā indicate persistent temporal dependencies, revealing whether the model focuses on recent observations, seasonal patterns, or anomalous events.
Saliency Maps and Gradient-Based Methods
Gradient-based techniques measure how sensitive the model's output is to perturbations in the input. Given a forecast ŷt at time t, the saliency map S is computed as:
This highlights which historical time steps most significantly impact the prediction. For transformers, this can be combined with attention weights to distinguish between direct influence (gradients) and learned dependencies (attention).
Probing and Concept-Based Explanations
Probing involves training auxiliary models to predict known time series properties (e.g., seasonality, trend) from intermediate transformer representations. If a probe achieves high accuracy, it suggests the model internally encodes these concepts. For example, a linear probe for seasonality applied to the encoder output:
where z is the transformer's hidden state and σ is the sigmoid function. High probe accuracy indicates the model has learned seasonal patterns.
Practical Considerations
- Attention weights alone can be misleading—high attention to a time step does not guarantee it is causally influential. Gradient-based methods should be used for validation.
- Model-specific vs. model-agnostic methods: Attention analysis is unique to transformers, while saliency maps and probing can be applied to any architecture.
- Computational overhead: Gradient calculations require backward passes, making them slower than attention inspection for large models.
Case Study: Interpretability in Financial Forecasting
In a high-frequency trading model, attention patterns revealed that the transformer focused on macroeconomic announcement times, even when these events were not explicitly encoded in the input. Gradient analysis confirmed that perturbations around these times caused significant forecast changes. This insight led to the inclusion of an economic event calendar as an auxiliary input, improving model robustness.

7. Key Research Papers
7.1 Key Research Papers
- Transformers Architectures For Time Series Forecasting — Transformers Architectures for Time Series Forecasting - Free download as PDF File (.pdf), Text File (.txt) or read online for free. ... Scientific Data, 7(1):241, July 2020. ISSN: 20524463. DOI: 10.1038/s41597-020-00582-3. ... 01 Transformers For Time-Series Data - by BearingPoint Data, Analytics & AI - BearingPoint Data, Analytics & AI ...
- [2202.07125] Transformers in Time Series: A Survey - ar5iv — Time-series forecasting with deep learning: a survey. Philosophical Transactions of the Royal Society, 2021. Lim et al. [2021] Bryan Lim, Sercan Ö Arık, Nicolas Loeff, and Tomas Pfister. Temporal fusion transformers for interpretable multi-horizon time series forecasting. International Journal of Forecasting, 37(4):1748-1764, 2021.
- PDF Transformers in Time Series: A Survey - IJCAI — vey for Transformers in time series. As Transformer for time series is an emerging subject in deep learning, a systematic and comprehensive survey on time series Transformers would greatly benet the time series community. In this paper, we aim to ll the gap by summarizing the main developments of time series Transformers. We rst
- A Time Series is Worth 64 Words: Long-term Forecasting with Transformers — Unfortunately, regardless of the complicated design of Transformer-based models, it is shown in the recent paper (Zeng et al., 2022) that a very simple linear model can outperform all of the previous models on a variety of common benchmarks and it challenges the usefulness of Transformer for time series forecasting. In this paper, we attempt to ...
- Timer: Transformers for Time Series Analysis at Scale - arXiv.org — In this paper, we propose Timer, together with a thorough suite of pre-training and applicative solutions of large time series models.By aggregating publicly available time series datasets and following curated data processing, we construct Unified Time Series Dataset (UTSD) of hierarchical capacities to facilitate the research on the scalability of LTSMs.
- U-Net Inspired Transformer Architecture for Far Horizon Time Series ... — In the most simple case, time series forecasting deals with a scalar time-varying signal and aims to predict or forecast its values in the near future; for example, countless applications in finance, healthcare, production automatization, etc. [4, 27, 29] can benefit from an accurate forecasting solution.Often not just a single scalar signal is of interest, but multiple at once, and further ...
- Fx-spot predictions with state-of-the-art transformer and time ... — In this research paper, the transformer architecture with time embeddings is used in foreign exchange (FX) trading, the world's largest financial market, and tests its suitability. ... (DL) methods can be described as a recent development in the field of financial time series forecasting. DL is suitable for various ML tasks and offers the ...
- (PDF) Transformers in Time Series: A Survey - ResearchGate — In this paper, we systematically review Transformer schemes for time series modeling by highlighting their strengths as well as limitations. In particular, we examine the development of time ...
- Temporal Fusion Transformers for interpretable multi-horizon time ... — Practical multi-horizon forecasting applications commonly have access to a variety of data sources, as shown in Fig. 1, including known information about the future (e.g. upcoming holiday dates), other exogenous time series (e.g. historical customer foot traffic), and static metadata (e.g. location of the store) - without any prior knowledge on how they interact.
- TEDformer: Temporal Feature Enhanced Decomposed Transformer for Long ... — the time series into multiple relatively short sub-sequences. Secondly, it uses a ne w cross-time-step attention mechanism that can simultaneously consider long and short-term depen-
7.2 Open-Source Implementations
- TS-Fastformer: Fast Transformer for Time-Series Forecasting — Fast Transformer for Time-Series Forecasting. Contribute to leesw9501/TS-Fastformer2022 development by creating an account on GitHub. ... Fund open source developers The ReadME Project. GitHub community articles Repositories. ... This repository contains the official implementation for the paper TS-Fastformer: Fast Transformer for Time-Series ...
- Transformers Architectures For Time Series Forecasting — Transformers Architectures for Time Series Forecasting - Free download as PDF File (.pdf), Text File (.txt) or read online for free. ... in the original implementation, ... Wang, and X. Yan. En hancing the locality and breaking the memory bottleneck of transformer on time series forecasting, 2020. arXiv: 1907.00235 [cs.LG]. [25] B. Lim, S. Ö ...
- iTransformer: Inverted Transformers Are Effective for Time Series ... — Considering the disputes of Transformer-based forecasters, we reflect on why Transformers perform even worse than linear models in time series forecasting while acting predominantly in many other fields. We notice that the existing structure of Transformer-based forecasters may be not suitable for multivariate time series forecasting.
- A Time Series is Worth 64 Words: Long-term Forecasting with Transformers — We use supervised PatchTST/42 and other open-source Transformer-based baselines for this experiment. 5 C ONCLUSION AND F UTURE W ORK This paper proposes an effective design of Transformer-based models for time series forecasting tasks by introducing two key components: patching and channel-independent structure.
- Temporal Fusion Transformers for interpretable multi-horizon time ... — An open-source implementation of the TFT on these datasets can be found on GitHub 3 for full reproducibility. 6.3. Computational cost. ... Enhancing the locality and breaking the memory bottleneck of transformer on time series forecasting. NeurIPS (2019) Google Scholar. Lim et al., 2018.
- TSformer: A Non-autoregressive Spatial-temporal Transformer ... - GitHub — This paper presents TSformer, a novel non-autoregressive spatiotemporal transformer designed for medium-range ocean eddy-resolving forecasting. TSformer istrained on 28 years of homogeneous, high-dimensional 3D ocean re analysis datasets, supplemented by three 2D remote sensing datasets for surface forcing.
- TFTformer: A novel transformer based model for short-term load forecasting — Based on this insight, Liu et al. [40] and Nie et al. [41] highlighted potential limitations in the existing design of Transformer models for forecasting multivariate time series. They observed that merging data points within the same time step into a single token, which represents a fundamental unit of input data that the model processes, can ...
- 【论文精读】Temporal Fusion Transformers for Interpretable Multi-horizon Time ... — For time series forecasting specifically, they are based on explicitly quantifying time-dependent variable contributions. For example, Interpretable Multi-Variable LSTMs (Guo et al, 2019) partitions the hidden state such that each variable contributes uniquely to its own memory segment, and weights memory segments to determine variable ...
- neuralforecast · PyPI — Time series forecasting suite using deep learning models. ... Unfortunately, available implementations and published research are yet to realize neural networks' potential. They are hard to use and continuously fail to improve over statistical methods while being computationally prohibitive. ... Sigstore integration time: May 13, 2025 Source ...
- ibm-granite/granite-tsfm: Foundation Models for Time Series - GitHub — Public notebooks, utilities, and serving components for working with Time Series Foundation Models (TSFM). The core TSFM time series models have been made available on Hugging Face -- details can be found here. Information on the services component can be found here. If you encounter an issue with ...
7.3 Advanced Topics and Extensions
- Transformers in Time Series: A Survey - arXiv.org — From the perspec-tive of applications, we categorize time series trans-formers based on common tasks including forecast-ing, anomaly detection, and classification. Empiri-cally, we perform robust analysis, model size anal-ysis, and seasonal-trend decomposition analysis to study how transformers perform in time series.
- PDF Transformers in Time Series: A Survey - IJCAI — From the perspective of applications, we categorize time series Trans-formers based on common tasks including forecast-ing, anomaly detection, and classification. Empiri-cally, we perform robust analysis, model size anal-ysis, and seasonal-trend decomposition analysis to study how Transformers perform in time series.
- RI2AP: Robust and Interpretable 2D Anomaly Prediction in ... - MDPI — In time series forecasting, Transformers suffer from issues like loss of time series temporal information, the quadratic complexity of sequence length, slow training and inference speed due to the encoder-decoder architecture, and overfitting issues [6, 45, 46, 47].
- Enhancing Transformer-based models for Long Sequence Time Series ... — Recently, Transformer-based models for long sequence time series forecasting have demonstrated promising results. The self-attention mechanism as the core component of these Transformer-based models exhibits great potential in capturing various dependencies among data points.
- Temporal Fusion Transformers for interpretable multi-horizon time ... — Multi-horizon forecasting, i.e. the prediction of variables-of-interest at multiple future time steps, is a crucial problem within time series machine learning. In contrast to one-step-ahead predictions, multi-horizon forecasts provide users with access to estimates across the entire path, allowing them to optimize their actions at multiple steps in the future (e.g. retailers optimizing the ...
- arXiv:2307.01616v1 [cs.LG] 4 Jul 2023 — Time Series (MTS) forecasting tasks. By amalgamating graph neural networks (GNN) with Transformer structures, SageFormer can effectively capture diverse temporal patterns and harn
- Enhanced Transformer Framework for Multivariate Mesoscale Eddy ... — The enhanced transformer framework for predicting mesoscale eddy trajectories improves the identification of multi-scale dependencies by integrating a multi-head attention mechanism to analyze dependencies within lengthy time series.
- Composed aggregate modeling of DERs at feeder level for steady state ... — The required information to build the voltage-current relationship is the admittance matrix of the system, constraint equations modeling the power electronic and non-power electronic elements. This relationship controls the behavior of the Thévenin equivalent.
- DOCX SKELETON - docbox.etsi.org — Simultaneously, advanced time series analysis techniques, powered by machine learning, can detect subtle seasonal fluctuations and long-term trends with high precision.
- Big Data technologies: A survey - ScienceDirect — Big Data analytics helps to identify at-risk transformers and to detect abnormal behaviors of the connected devices. Grid Utilities can thus choose the best treatment or action. The real-time analysis of the generated Big Data allow to model incident scenarios.








