|
8 | 8 | "source": [
|
9 | 9 | "# TFT Model for Energy Price in Spain\n",
|
10 | 10 | "\n",
|
11 |
| - "TFT (Temporal Fusion Transformer)\n", |
12 |
| - "N-BeatsX (N-Beats with Exogenous Variables)\n", |
13 |
| - "N-HiTS (Neural Hierarchical Interpolation for Time Series Forecasting)\n", |
| 11 | + "## Model Comparison\n", |
14 | 12 | "\n",
|
15 |
| - "## Why Transformers\n", |
| 13 | + "In this section, I will compare three standout models for time-series forecasting: `TFTs` (Temporal Fusion Transformers), `N-BeatsX`, and `N-HiTS`. \n", |
16 | 14 | "\n",
|
17 |
| - "Transformers, originally developed for natural language processing, have become a powerful tool for time series forecasting. Transformers take a matrix of features x timesteps as input, with each timestep encoded individually using position encoding and the self-attention mechanism. These techniques allow the model to capture both short- and long-range dependencies in the data whilst the temporal and sequential structure is maintained, unlike in FNNs (Feedforward Neural Networks), which collapse the data into a single column before encoding.\n", |
| 15 | + "They are all state-of-the-art models, widely recognized for their effectiveness in handling complex time-series data, capturing both short-term and long-term dependencies. These models are supported by strong research and practical applications, making them top choices for many forecasting tasks across different industries, including energy price prediction.\n", |
18 | 16 | "\n",
|
19 |
| - "For energy demand forecasting, transformers can process multiple input features simultaneously, including lagged demand values, weather conditions, calendar effects, and other exogenous variables, without relying on manually defined temporal dependencies. \n", |
| 17 | + "**TFT (Temporal Fusion Transformer)**\n", |
20 | 18 | "\n",
|
21 |
| - "The table below highlights how a Transformer is well-suited to predicting energy demand compared with other neural-network-based machine learning methods:\n", |
| 19 | + "TFTs adapt and extend the transformer design specifically for time series forecasting. They combine the strengths of sequence models and attention mechanisms, enabling accurate and interpretable multi-horizon forecasting.\n", |
22 | 20 | "\n",
|
23 |
| - "| Feature | Transformer | RNN/LSTM/GRU | FNN (Feedforward Neural Network) | CNN (Convolutional Neural Network) |\n", |
24 |
| - "|------------------------------------|---------------------------------------------|------------------------------------------|------------------------------------------|------------------------------------------|\n", |
25 |
| - "| **Architecture Type** | Attention-based (self-attention) | Sequential (recurrence-based) | Fully connected layers (no recurrence) | Convolutional layers (local receptive fields) |\n", |
26 |
| - "| **Handling of Long-Term Dependencies** | Excellent (self-attention) | Limited (vanishing/exploding gradients) | None (treats all inputs as independent) | Limited (focuses on local features) |\n", |
27 |
| - "| **Scalability** | High (parallel processing of large data) | Low (sequential processing) | High (processing all features in parallel)| High (parallel processing of convolutions) |\n", |
28 |
| - "| **Training Time** | Faster (due to parallelisation) | Slower (sequential training) | Fast (simple architecture) | Moderate (depends on depth of network) |\n", |
29 |
| - "| **Multi-Output Prediction** | Very effective for multi-output tasks | Challenging (often requires multiple models or complex architectures) | Challenging (often requires separate models) | Effective (can use same model for multiple outputs) |\n", |
30 |
| - "| **Handling Complex Temporal Relationships** | Good (learns relationships with long-range dependencies) | Poor for long sequences due to vanishing gradients | Poor (no temporal awareness) | Limited (focuses on local patterns, not temporal) |\n", |
| 21 | + "The TFT encoder is designed to handle the unique structure of time series data by separating inputs into static features, past observed variables, and known future inputs. Each of these is passed through embedding layers and processed by Variable Selection Networks, which use Gated Residual Networks (GRNs) to dynamically weight the importance of each input feature at every timestep. This allows the model to focus only on the most relevant information. The selected inputs are then passed through a sequence of LSTM layers, which capture temporal dependencies and preserve the ordering of events.\n", |
31 | 22 | "\n",
|
| 23 | + "In the decoder, TFTs leverage multi-head attention to identify and focus on the most relevant timesteps from the encoded historical data for each forecasting horizon. \n", |
32 | 24 | "\n",
|
| 25 | + "**N-BeatsX (N-Beats with Exogenous Variables)**\n", |
33 | 26 | "\n",
|
| 27 | + "N-BeatsX is an extension of the N-BEATS model designed for time series forecasting that incorporates exogenous variables. The model consists of two main blocks which are fully connected feedforward networks (FFNs): the backcast block and the forecast block.\n", |
34 | 28 | "\n",
|
35 |
| - "## Choosing a Transformer Architecture\n", |
| 29 | + "- **Backcast Block:** This block aims to model the historical data by reconstructing past values. It learns the patterns and underlying structure of the time series data, helping the model capture long-term trends and seasonality.\n", |
36 | 30 | "\n",
|
37 |
| - "The model needs to generate 24 hourly predictions for the next day at noon, meaning it must capture sequential dependencies effectively. There are two main transformer architectures to consider:\n", |
| 31 | + "- **Forecast Block:** The forecast block predicts future values based on the patterns learned in the backcast block. It decomposes the forecast into components like trend and seasonality, making the model interpretable.\n", |
38 | 32 | "\n",
|
39 |
| - "- **Sequence-to-Sequence (Seq2Seq) Transformer** : This approach uses both an encoder and a decoder. The encoder processes historical data (past demand, weather, etc), extracting meaningful representations. The decoder autoregressively generates each hour’s demand forecast while attending to both the encoder’s outputs and known future data (weather forecasts, calendar effects, etc).\n", |
40 |
| - " - Pros : Naturally handles multi-step forecasting by generating predictions one at a time. Can incorporate past predictions dynamically in an autoregressive manner.\n", |
41 |
| - " - Cons : Requires masking to ensure predictions don’t leak future information. More computationally expensive due to the decoder’s sequential nature.\n", |
42 |
| - "- **Encoder-Only Transformer** : This approach uses only an encoder (like BERT-style transformers) to map historical and exogenous features directly to all 24 future hourly predictions in a single forward pass.\n", |
43 |
| - " - Pros : Faster and more efficient since it doesn’t require iterative decoding. Avoids error accumulation from autoregressive predictions.\n", |
44 |
| - " - Cons : Can struggle with capturing temporal dependencies between consecutive predicted hours. Less flexible in handling exogenous variables that evolve dynamically.\n", |
| 33 | + "**N-HiTS (Neural Hierarchical Interpolation for Time Series Forecasting)**\n", |
45 | 34 | "\n",
|
46 |
| - "For this task, an encoder-only transformer will be used since it efficiently predicts all 24 future time steps in one forward pass. While Seq2Seq models better capture sequential dependencies, their computational cost and risk of accumulating errors make them less suitable for predicting 36 hours ahead (12 historical + 24 future time steps)." |
| 35 | + "N-HiTS uses hierarchical decomposition and interpolation to efficiently capture both short-term and long-term temporal dependencies in time series data.\n", |
| 36 | + "\n", |
| 37 | + "N-HiTS works by processing the time series data through multiple hierarchical levels, each focused on a different temporal resolution. The model starts with coarse, long-term trends and progressively refines the forecast using interpolation layers, which help generate more fine-grained predictions at each level. This hierarchical approach allows N-HiTS to capture patterns across multiple temporal scales, making it effective for both long-term trends and short-term fluctuations.\n", |
| 38 | + "\n", |
| 39 | + "**Why TFTs**\n", |
| 40 | + "\n", |
| 41 | + "For energy price prediction, where exogenous variables like energy demand and weather forecasts play a critical role, TFTs stand out. Their ability to handle mixed inputs, including historical data and known future inputs, makes them the ideal choice. Additionally, Variable Selection Networks (VSNs) in TFTs ensure that only the most relevant factors influence the predictions. While N-BeatsX and N-HiTS can handle exogenous variables, they lack the flexibility to incorporate known future inputs, making TFTs the better fit for this task." |
47 | 42 | ]
|
48 | 43 | },
|
49 | 44 | {
|
|
71 | 66 | "source": [
|
72 | 67 | "## Feature Engineering\n",
|
73 | 68 | "\n",
|
74 |
| - "The pre-cleaned dataset from [xgboost_demand.ipynb](xgboost_demand.ipynb) can be reused for the transformer model, but adjustments are needed in the feature engineering step. Unlike XGBoost, which treated each time step as a separate row with extracted lag-based features, the transformer model requires the data to be structured as a sequence. This means that instead of having a single feature vector per prediction (num_features), the input to the transformer will be a (24, num_features) matrix, preserving the temporal relationships within each 24-hour window." |
| 69 | + "The pre-cleaned dataset from [xgboost_price.ipynb](xgboost_price.ipynb) can be reused for the TFT model, but adjustments are needed in the feature engineering step. Unlike XGBoost, which treated each time step as a separate row with extracted lag-based features, the TFT model requires the data to be structured as a time series dataset, with the data split into different parts, such as known features (future inputs), observed features (historical data), and target variables. This means the input to the TFT model must be organized as sequences, where each sequence corresponds to a 1-week window that preserves the temporal relationships across time steps. `pytorch_forecasting` has a `TimeSeriesDataSet` which can handle this.\n", |
| 70 | + "\n", |
| 71 | + "The TFT model requires more training data than XGBoost, so using one data point per day is insufficient. To address this, we will create one data point for each hour of the day, increasing the amount of training data and allowing the model to learn richer temporal patterns. While the TFT will still only make predictions for each hour (0-23) of the following day at noon, using data for other hours can still provide valuable context. This extra data can help the model capture long-term trends, making it more generalised and improving its overall forecasting accuracy." |
75 | 72 | ]
|
76 | 73 | },
|
77 | 74 | {
|
|
245 | 242 | "print(f'Test Batches: {len(test_dataloader)}')"
|
246 | 243 | ]
|
247 | 244 | },
|
| 245 | + { |
| 246 | + "cell_type": "markdown", |
| 247 | + "metadata": {}, |
| 248 | + "source": [ |
| 249 | + "## Model Training" |
| 250 | + ] |
| 251 | + }, |
248 | 252 | {
|
249 | 253 | "cell_type": "code",
|
250 | 254 | "execution_count": 4,
|
|
330 | 334 | "name": "stdout",
|
331 | 335 | "output_type": "stream",
|
332 | 336 | "text": [
|
333 |
| - "Epoch 0: 100%|██████████| 542/542 [02:53<00:00, 3.12it/s, v_num=3, train_loss_step=944.0, val_loss=467.0, train_loss_epoch=371.0]\n" |
| 337 | + "Epoch 20: 100%|██████████| 542/542 [02:53<00:00, 3.12it/s, v_num=3, train_loss_step=944.0, val_loss=467.0, train_loss_epoch=371.0]\n" |
334 | 338 | ]
|
335 | 339 | }
|
336 | 340 | ],
|
|
364 | 368 | ")"
|
365 | 369 | ]
|
366 | 370 | },
|
| 371 | + { |
| 372 | + "cell_type": "markdown", |
| 373 | + "metadata": {}, |
| 374 | + "source": [ |
| 375 | + "The model output is a 35-vector, with predictions for each hour from 1pm the day before to 11pm on the day being predicted. Therefore, the prediction needs to be sliced to only include the last 24 hours of the prediction." |
| 376 | + ] |
| 377 | + }, |
367 | 378 | {
|
368 | 379 | "cell_type": "code",
|
369 | 380 | "execution_count": 7,
|
|
422 | 433 | "plt.show()"
|
423 | 434 | ]
|
424 | 435 | },
|
425 |
| - { |
426 |
| - "cell_type": "markdown", |
427 |
| - "metadata": {}, |
428 |
| - "source": [ |
429 |
| - "The transformer model requires more training data than XGBoost, so using one data point per day is insufficient. To address this, we will create one data point for each hour of the day, increasing the amount of training data and allowing the model to learn richer temporal patterns. While the transformer will still only make predictions for each hour (0-23) of the following day at noon, using data for other hours can still provide valuable context. This extra data can help the model capture long-term trends, making it more generalised and improving its overall forecasting accuracy." |
430 |
| - ] |
431 |
| - }, |
432 | 436 | {
|
433 | 437 | "cell_type": "code",
|
434 | 438 | "execution_count": 8,
|
|
465 | 469 | "source": [
|
466 | 470 | "## Summary\n",
|
467 | 471 | "\n",
|
468 |
| - "The Transformer model achieved a Root Mean Squared Error (RMSE) of 899.11 MW, a Mean Absolute Error (MAE) of 681.94 MW, and a Mean Absolute Percentage Error (MAPE) of 2.57%. Therefore, the model is 97.43% accurate. This is significantly better that the benchmark model, however it was still outperformed by the XGBoost model with RMSE of 851.66 MW, MAE of 632.62 MW, and MAPE of 2.39%.\n", |
469 |
| - "\n", |
470 |
| - "The XGBoost model outperformed the Transformer model primarily due to the limited dataset size. The XGBoost model benefits from handcrafted lag-based features, which explicitly encode temporal dependencies. In contrast, the transformer model relies on self-attention to learn these relationships, which requires significantly more data to generalise effectively. Additionally, Transformers have higher model complexity, making them more prone to overfitting on small datasets, whereas XGBoost’s built-in regularisation techniques help maintain robust performance.\n", |
| 472 | + "The TFT model achieved a Root Mean Squared Error (RMSE) of 22.23 EUR/MWh, and a Mean Absolute Error (MAE) of 16.52 EUR/MWh. This is significantly better that the benchmark model, and similar performance to the XGBoost model with RMSE of 21.57 EUR/MWh, MAE of 16.57 EUR/MWh. The TFT's RMSE was 0.66 EUR/MWh (3%) worse, however its MAE was marginally (0.05 EUR/MWh) better than the XGBoost model.\n", |
471 | 473 | "\n",
|
472 |
| - "The histogram of residuals indicates that the Transformer model systematically overpredicts energy demand more often than it underpredicts. Since this effect was not observed in the XGBoost model, it is unlikely to be caused by bias in the training data. Instead, it may be a consequence of the Transformer being trained on a more generalised dataset, where predictions were made at every hour rather than specifically at noon each day, potentially reducing its ability to capture noon-specific demand patterns accurately." |
| 474 | + "Despite the limited dataset size, the TFT model achieved performance comparable to XGBoost, highlighting the advantage of using architectures specifically designed for time-series forecasting. Previously, a general-purpose Transformer struggled in predicting energy demand due to its complexity and data requirements, but the TFT’s tailored design, incorporating components like LSTMs for short-term patterns, attention for long-term dependencies, and variable selection networks for feature relevance, allowed it to make effective use of the available data. Its ability to handle both known future inputs and exogenous variables in a structured way also contributed to its strong performance, even in a data-constrained setting." |
473 | 475 | ]
|
474 | 476 | }
|
475 | 477 | ],
|
|
0 commit comments