{'fraction_non_alphanumeric': 0.03560488522894538, 'fraction_numerical': 0.012968930262163345, 'mean_word_length': 4.656615661566157, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
TENT: Tensorized Encoder Transformer for Temperature Forecasting

Reliable weather forecasting is of great importance in science, business, and society. The best performing data-driven models for weather prediction tasks rely on recurrent or convolutional neural networks, where some of which incorporate attention mechanisms. In this work, we introduce a novel model based on Transformer architecture for weather forecasting. The proposed Tensorial Encoder Transformer (TENT) model is equipped with tensorial attention and thus it exploits the spatiotemporal structure of weather data by processing it in multidimensional tensorial format. We show that compared to the classical encoder transformer, 3D convolutional neural networks, LSTM, and Convolutional LSTM, the proposed TENT model can better learn the underlying complex pattern of the weather data for the studied temperature prediction task. Experiments on two real-life weather datasets are performed. The datasets consist of historical measurements from weather stations in the USA, Canada and Europe. The first dataset contains hourly measurements of weather attributes for 30 cities in the USA and Canada from October 2012 to November 2017. The second dataset contains daily measurements of weather attributes of 18 cities across Europe from May 2005 to April 2020. Two attention scores are introduced based on the obtained tonsorial attention and are visualized in order to shed light on the decision-making process of our model and provide insight knowledge on the most important cities for the target cities.


Introduction
In various application domains, one often encounters multivariate time series data, such as stock market prices, road traffic flows or weather conditions in different cities, to name a few [1]. Predicting new trends and patterns in time series domains based on historical observations is the focus of many research studies. In particular, recent years have witnessed the development of advanced deep data-driven models and their promising results in weather forecasting applications [2,3,4,5,6,7,8,9].
Reliable weather forecasting is of great scientific, economic and social significance. Changing weather conditions impact many aspects of life, ranging from catastrophe and disaster management to many economic sectors including transport, agriculture, energy generation among others [2]. The undergoing energy transformation to renewable energy production is only one of many sources of increasing demand for future weather conditions predication such as air temperature or wind speed [10]. High-quality temperature and wind forecasts increase the precision of estimates of future energy generation through wind and solar power [10]. Even a small increase in the prediction precision can have significant implications for the maximization of power generation [11] or the planning of energy distribution and power plant dispatching [10].
In many fields such as physics, scientific computing, and deep machine learning, data appear in tensor (a multi-dimensional data structure) format. In particular, in the weather application domain, tensorial data consists of several weather variables measured at different time and space. Simply vectorizing tensor data loses useful structural information. Furthermore, higher-order correlations (correlations between the data dimensions) can only be discovered by simultaneously considering all the dimensions of the data. Tensorial machine learning based models to analyze high dimensional data have gained much attention in recent years [12,13,14].
It is the purpose of this paper to develop a Tensorized Encoder Transformer model that can preserve the spatiotemporal structure of the weather data and learn the input-output mapping by taking into account the underlying structure of the data. In particular, a new tensorial attention mechanism is designed that can provide additional insights on the explainability of the model by learning the attention weights using tensorial input data. In particular, the learned attention weights can reveal the importance of the individual weather variables as well as the combination of weather variables and weather stations on the prediction of the target variables. This paper focuses on the temperature forecasting task. Three main contributions of our work are as follows: • To develop a novel transformer architecture equipped with a new self-attention mechanism for analyzing 3D tensor input data.
• To Introduce two attention scores based on the calculated tensorial attention.
• To compare the proposed model with the classical en-coder transformer, 3D convolutional neural network, LSTM and Convolutional LSTM models for the temperature prediction task.
• To shed light on the explainability of the proposed model using data visualization techniques.
This paper is structured as follows. A brief overview of the related works for weather forecasting is given in section 2. Our tensorial self-attention and transformer architecture with tensorial input are introduced in section 3. The description of the used datasets, the obtained results and the analysis of the tensorial attention are reported in section 4. The conclusions are drawn in section 5.

Weather elements forecasting
Conventionally, weather forecasting is done by using Numerical Weather Prediction (NWP). NWP uses mathematical models to describe physical processes and weather conditions in the atmosphere or on the surface of the earth expressed by variables such as temperature, air pressure and wind [2,15,16]. However, incomplete understanding of underlying complex atmospheric processes as well as the uncertainties in the initial conditions of the governed differential equation, may limit the accuracy of weather forecast [2,17]. In addition, the computer simulation of NWP requires high computing power [3,18].
In recent years, data-driven models have emerged which have proven to significantly reduce the processing time for weather forecasting [3,19]. They rather rely on large amounts of historical weather observations that are used to extract and learn the underlying complex input-output mapping. The learned models are then used to predict future weather conditions [2,20,21].
However, the spatiotemporal nature of the underlying weather data along with its complex nonlinear behavior causes the prediction task to be nontrivial [22]. Thanks to the growing availability of weather data as well as advancements in computing power, many researchers have become motivated to explore a variety of deep data-driven models based on Artificial Neural Networks (ANN) [23]. In particular, Convolutional Neural Networks (CNN) and Recurrent Neural Networks (RNN) such as Long Short Term Memory (LSTM) neural networks have been successfully used to forecast hourly air temperature with significantly small errors for one time step ahead [17,24]. CNNbased models do not require any feature engineering; instead, they rely on feature extraction during the training of the network [10]. Mehrkanoon [2] proposed a 3d-CNN based model for temperature forecasting. Klein et al. [25] introduced the Dynamic Convolutional Layer for short-range weather prediction task. In contrast to traditional CNN approaches, in Dynamic Convolutional Layer the filters vary from input to input during testing. RNNs, on the other hand, generally perform well when dealing with time-series data [10]. In particular, LSTM networks can better model long-term dependencies [26]. Long-and Short-term Time-series network (LSTNet) [1] leverages both CNN and RNN to extract short-term local dependency patterns among variables and to discover long-term patterns for time series trends. The ConvLSTM network combines both CNN and LSTM architectures for precipitation prediction [27]. However, the sequential nature of processing elements in RNNs limits the parallelization during training, which becomes critical at longer sequence lengths [28].
Vaswani et al. [28] introduced an attention mechanism to model dependencies in sequences regardless of the distances between positions of the input elements. Often such attention mechanisms are combined with RNNs [28]. Temporal pattern attention LSTM (TPA-LSTM) [29] utilizes an attention mechanism that allows the model not only to attend to relevant previous times but also to identify interdependencies among multiple features. The dual-stage attention-based recurrent neural network (DA-RNN) [30] incorporates a dual-stage attention scheme consisting of an encoder with an input attention mechanism and a decoder with a temporal attention mechanism.

Transformer architecture
Transformer is an attention-based encoder-decoder architecture that was first introduced in 2017 [28]. It is designed to use the attention mechanism to handle sequential data by processing all input tokens at the same time. It replaces recurrent layers, commonly used in encoder-decoder architectures, with multi-headed self-attention where the dot-product attention is extended with a scaling factor of key-dimension 1 √ d k [28]. Consequently, the model does not rely on sequential processing of the data and therefore creates the possibilities for parallelization and reducing the training computational times [28]. Another commonly used attention mechanism is the additive attention, which uses a feed-forward neural network for the computation of the attention [31].
The Transformer is at the heart of many recent breakthroughs and developments in the field of sequence-to-sequence models. It has improved the state-of-the-art in many natural language processing tasks such as machine translation [28], document generation [32] as well as syntactic parsing [33]. The pretrained transformer language models, Bidirectional Encoder Representations from Transformers (BERT) and Generative Pre-trained Transformer (GPT) have already proved their effectiveness in tasks such as natural language understanding and question answering [34,35]. Generative models such as the Image Transformer [36] and Music Transformer [37] have shown their capability to generate convincingly natural images and musical compositions based on human evaluation.
Shen et al. [38] developed Multi-mask Tensorized Self-Attention (MTSA), which captures the dependency between every two tokens using the scaled dot-product self-attention and utilizes the multi-dim self-attention mechanism [39] to estimate the contribution of each token to the given NLP task on each feature dimension. Zhou et al. [40] proposed the Informer architecture, which can handle extremely long sequences efficiently with its ProbSparse attention mechanism, which generates different sparse query-key pairs for each head to avoid information loss.
Ma et al. [14] used a tensorized transformer to compress model parameters and increase performance. In particular, [14] introduced Multi-linear attention for language modeling approaches, which uses Tucker decomposition [41,42] in Singleblock attention to reconstruct the scaled dot-product attention and Block-Term Tensor Decomposition [43] for the multi-head attention mechanism. This paper proposes a Tensorized Encoder Transformer (TENT) for temperature forecasting task. The model is equipped with a new tensorial attention mechanism. As opposed to [14], our proposed TENT model receives 3-dimensional tensors as input and maintains the tensorial format in the calculation of the self-attention layer. Thanks to the introduced tensorial self-attention mechanism, TENT model is able to capture the dependencies between time steps (lags) and the weather stations by simultaneously considering all the dimensions of the data. In the subsequent sections, the proposed model will be explained in detail.

Tensorized Encoder Transformer
Here, we extend the original Transformer [28] and introduce the Tensorized Encoder Transformer (TENT) model suitable for learning complex underlying patterns of tensorial input data. In particular, the model processes weather inputs of 3D tensorial format X ∈ R T ×C×F , where T is the number of time steps, C and F represent 2D features. 2D features of size C × F represent a matrix of weather variables such as temperature, humidity, and wind speed measured at different geographical locations. More precisely, different cities are located along dimension C and the weather variables are along dimension F. The proposed model is an encoder-only Transformer architecture that consists of a positional encoding layer, encoder layer followed by a fully-connected layer with linear activation as shown in Fig. 1. The encoder layer uses the tensorial attention that will be introduced in sections 3.3 and 3.4. Subsequent to the tensorial attention are a residual connection and a normalization layer. Here a fully connected feed-forward network with two linear transformations and ReLU activations is used after the tensorial attention layer. In line with [28], it is then followed by a second residual connection and normalization layer.

Positional Encoding
We use a fixed positional encoding to equip the model with time sequence information. The positional encoding [28] is calculated for the time step T and city C axes according to Eq. (1), where, pos is the position in time step axis and i is the position in the city axis. We broadcast the obtained values along the weather variables axis F. Hence, the values of the positional encoding are identical across the F axis and differ in T and C axes. (1)

Tensorial self-attention
To formulate tensorial self-attention, see Fig. 2, the following slice notation is used. For a tensor A ∈ R X×Y×Z the x slice is the matrix (A y,z ) x ∈ R Y×Z formed from all the values of the tensor A where the first dimension is set to x. Similarly, the x, y slice of A is the vector (A z ) x,y ∈ R Z formed from the values of A where the first and second dimensions are set to x and y respectively. We denote the dimension of the slice by the small letter corresponding to the particular dimension. The input of the tensorial self-attention is a 3D tensor X ∈ R T ×C×F . In the first step of the tensorial self-attention, the 3D Query (Q), Key (K) and Value (V) tensors which all have the same dimension, i.e. R T ×C×D , are calculated by multiplying the input tensor X with weight tensors. Here D is obtained by dividing the key-dimension d k by the number of heads, which are both hyper-parameters. More precisely, three separate 3D weight tensors W Q , W K and W V ∈ R C×F×D are used. Each t, c slice of Q, K and V (i.e. (Q d ) t,c , (K d ) t,c and (V d ) t,c respectively) is calculated by multiplying the t, c slice of X, denoted by (X f ) t,c , and the c slice of W Q , W K and . . , T, c = 1, . . . , C.
In the next step, each time step t slice of Q (denoted by (Q c,d ) t ) is multiplied with the transpose of each time step t slice of K (denoted by ((K c ,d ) t ) T ). These multiplications, see Eq. (3a), result in matrices (R c,c ) t,t of shape C × C , which are slices of a tensorR ∈ R T ×T ×C×C , where T and C are the first and second dimensions of Q tensor and T and C are the first and second dimensions of K tensor. Following the lines of [28], in Eq. (3b) the tensor R is summed over the last dimension and divided element-wise by the square root of D resulting in a tensor R ∈ R T ×T ×C .
Next, we apply a softmax function over each t, t slice of R, producing the attention tensor S ∈ R T ×T ×C as follows: Lastly, the output of the tensorial self-attention, i.e. Z ∈ R T ×C×D , is calculated by taking the Hadamard product from the t, t slice of the attention weights (S c ) t,t and the t slice of V (i.e. (V c,d ) t ), and summing over the second dimension (corresponding to t ). One should note that (S c ) t,t slice is first broadcasted to shape C × D to match the shape of (V c,d ) t slice. This calculation can be seen in Eq. (5).

Tensorial multi-head attention
Here, we calculate tensorial self-attention H times, which leads to tensorial multi-head attention. We extend the calculation of the multi-head attention [28] to tensorial inputs. Each of these heads correspond to the output of the tensorial selfattention Z h , where h indicates the index of the head. The outputs are concatenated along the last dimension || H h=1 Z h , resulting in a T × C × (H × D) tensor. Next the output tensor of multi-head attention Y ∈ R T ×C×F is obtained by multiplying each time slice, ((|| H h=1 Z h ) c,h·d ) t , with a time slice of a weight tensor W o with shape T × (H × D) × F as follows: The visualization of the multiplication operation of Eq. (6) is shown in Fig. 4.

Attention Aggregation
The attention weights have been previously used for feature selection purposes as well as model explainability [44,45]. Here, the attention tensors S (see Eq. (4)) are aggregated to shed light on the model predictions. Let us denote the extracted attention tensors by S h ∈ R T ×T ×C , where h is the head index, T and T are the numbers of time steps due to the Query and the Key respectively and C is the number of cities. In order to show the correlation between heads and cities, attention scores (AS h c ) are computed as follows: S h t,t ,c , ∀h = 1, . . . , H, c = 1, . . . , C. (7) Furthermore, in order to show the contribution of each city to the prediction, we calculate the attention scores AS c for each city as follows: AS h c , ∀c = 1, . . . , C.  Figure 5: The obtained test MAE of the models for the USA and Canada datasets averaged over cities (5a) and prediction time steps (5b).

Experiments
We apply our proposed TENT model on two datasets depicted in Table 2 and compare the obtained results with four other models, i.e. classical encoder Transformer [28] (with the input tensor flattened), 3d-CNN [2], LSTM [46] and Convolutional LSTM [47]. Following the lines of [2,3], the Mean Absolute Error (MAE) and Mean Squared Error (MSE) metrics are used to evaluate the performance of the models as follows: Here, n is the number of samples,ŷ i is the model prediction and y i is the true measurement. The training is done with MSE loss function for a maximum of 300 epochs and early stopping based on validation loss with patience 20 is used. Adam optimizer [48] is employed for all models. Both TENT and Transformer use custom learning rate schedule [28] while 3d-CNN, LSTM and Convolutional LSTM use a learning rate adapted by Adam optimizer. The empirically found optimal hyperparameters for each model are tabulated in Table 1.

USA-Canada Dataset
This dataset contains hourly measurements of the weather attributes such as humidity, air pressure, temperature, weather description, wind direction and wind speed for 30 cities in the USA and Canada from October 2012 to November 2017.
The longitude and latitude information of the cities are converted to Cartesian coordinates which are then used in normalized form as three additional features [49,50] as follows: where φ and λ are the latitude and longitude, respectively. Due to the time periodicity in the dataset, the day of the year and the hour of the day are added to each sample in the dataset and scaled along with the measurements in the dataset as in  Eq. (11). The data from 2012-2016 is used as a training and validation set and the data from 2016-2017 forms the test set.
We cast the input data to a tensor with the shape T × C × F, where the first, second and third dimensions represent the time sequence, cities and the features of the cities respectively. Predictions are made for 4, 8, 12 and 16 hours into the future (prediction time step). In our conducted experiments the lag of 16 hours is used as it was empirically found to be optimal in terms of the mean squared error on the validation set. For this dataset, the target cities are Vancouver, Dallas and New York and the target feature is temperature. The obtained test MAEs and MSEs are tabulated in Table 3. Fig. 5 (a) and (b) show the averaged MAE over cities and time steps, respectively. A subset of the obtained test prediction and real measurement for Vancouver city for 4, 8, 12 and 16 hours ahead are also depicted in Fig. 6. As can be seen, the prediction accuracy decreases as the number of hours ahead increases. The obtained test MAE and MSE results exhibit consistent pattern, with the TENT model outperforming other tested models for all tested time step ahead predictions. Our model also obtained the lowest average MAE and MSE over both cities and prediction time  Figure 7: The obtained test MAE of the models for the Europe dataset averaged over cities (7a) and prediction time steps (7b). steps.

Europe Dataset
This dataset contains daily measurements of the weather attributes of 18 cities across Europe from May 2005 to April 2020. The time periodicity is added in the form of the day of the year and normalized as other features. The data from 2005-2017 is used for training and validation and the data from 2017-2020 is used as the test set.
In this dataset, we perform experiments for 2, 4 and 6 days ahead prediction. The optimal lag parameter used to construct the regressor is empirically found and is set to 8 days. The target cities are Barcelona, Maastricht and Munich and the target feature is the average temperature. The obtained MAEs and MSEs are tabulated in Table 4. Fig. 7 (a) and (b) shows the MAE of the models averaged over cities and prediction time steps respectively. In the experiments, in general, the proposed TENT model is the second best model and only outperforms the other tested models when predicting the temperature of Maastricht city for 4 and 6 days ahead. In this dataset, LSTM has the highest performance among other models, i.e. it achieved the best MAE on 5 prediction tasks (a particular city and a particular prediction time) and the best MSE in 4 of them. It has been previously reported by [51,52], that Transformer might not reach its performance capacity when dealing with the small data size. Therefore, we think that the limited data in the EU dataset potentially prevents TENT to achieve better results compared to the LSTM model.

Attention Visualization
The attention scores AS h c in Eq. (7) are used to show to which city each of the heads is paying attention to when predicting the output of the model. In particular, the analysis is provided for three target cities, i.e. Dallas, Vancouver and New York in Figs. 8, 9 and 10 (a)-(d), respectively. In addition, in order to quantify the contribution of each city to the target city  Figure 9: Attention visualization for Vancouver in USA-Canada dataset. The circular graphs shows which city each of the most important heads attends to. The thickness of the line represents the amount of attention each of the heads is paying to the cities. The size of the circles indicates the importance of each city in the temperature prediction for the target city. The target city is marked as a red circle and its size corresponds to the importance of the attention to itself.
we compute AS c from Eq. (8). The visualization of the attention for the above-mentioned target cities are shown in Figs. 8, 9 and 10 (e)-(h).
In these plots, e.g. Fig. 8 (a)-(d), one can see the name of cities and numbers, the latter represents each of the heads used in the Tensorial multi-head attention. The thickness of the connecting lines represents the amount of attention that each head gives to the city it is connected to. For the purpose of readability of the plots, we only keep the cities that receive the most attention and the heads that contributed to those cities. In   Fig 8 (e)-(h), the size of the circles indicates the importance of each city in the temperature prediction for the target city. The target city is shown as a red circle and its size indicates the importance of the attention to itself. It can be seen that in general the farther away we are predicting into the future, the distance between the target city and the most important cities for the prediction also increases. In general, a similar pattern as those of Fig. 8 can be observed for Fig. 9 and 10.  Figure 10: Attention visualization for New York in USA-Canada dataset. The circular graphs shows which city each of the most important heads attends to. The thickness of the line represents the amount of attention each of the heads is paying to the cities. The size of the circles indicates the importance of each city in the temperature prediction for the target city. The target city is marked as a red circle and its size corresponds to the importance of the attention to itself.

Conclusion
In this paper, we introduced TENT, a novel transformerbased model equipped with tensorial attention, for the temperature prediction task. The model is tested on two real-life weather datasets and the it outperforms the other examined models in USA-Canada dataset . In the EU dataset, our model is in general the second best architecture. Two attention scores are introduced to and visualized in order to provide additional insights on the model predictions. The introduced model can potentially be used for other applications with 3D tensor inputs and our code 1 is available online.