scieee AI-readable full text Open interactive document viewer

Energy load forecast in smart buildings with deep learning techniques

Barón García, Alejandro

Abstract

Grado en Ingeniería Informática

Full text

Grado en Ingenier´ıa Inform´atica Final Degree Project Energy Load Forecast in Smart Buildings with Deep Learning Techniques Author Alejandro Bar´on Garc´ıa Supervisors Carlos Javier Alonso Gonz´alez Jos´e Belarmino Pulido Junquera ACADEMIC YEAR 2019-2020 Abstract Predicting energy load is a growing problem these days. The need to study in advance how electricity consumption will behave is key to resource management. Especially interesting is the case of the so-called Smart Buildings, buildings born from the trend towards sustainable development and consumption which is increasingly in vogue, becoming mandatory by law in many countries. One type of model that constitutes an important part of the state of the art are the models based on Deep Learning. These models represented great advances in Artificial Intelligence recently, since although they were born in the 20th century, it has not been until 10 years ago that they have re-emerged thanks to the computational advances that allow them to be trained by the general public. In this Final Degree Project, advanced Deep Learning techniques applied to the problem of load prediction in Smart Buildings are presented, mainly basing the development on the data from the Alice Perry building of the National University of Ireland Galway, in collaboration with the Informatics Research Unit for Sustainable Engineering of the same university. The datasets used were obtained from the time series of aggregated electricity consumption of the air handling units (AHUs) in the Alice Perry building. Along with this information, historical weather data were also collected from the weather station in the same building in order to study if these climatic variables help to a better prediction in the models. Time series prediction on this energy load data will be made in two different ways with hourly granularity: one-step prediction in which studying the previous observations an estimate of the value of the load in the next hour is obtained and sequence prediction, in which we will try to predict the behaviour of the series in the next hours from the previous values. 1 Resumen La predicci´on de carga energ´etica es un problema al alza actualmente. La necesidad de estudiar con antelaci´on c´omo se va a comportar el consumo el´ectrico es clave para la gesti´on de recursos. Especialmente interesante es el caso de los llamados Smart Buildings, edificios nacidos por la tendencia hacia un desarrollo y consumo sostenible el cual cada vez est´a m´as en boga, llegando a ser obligatorio por ley en muchos pa´ıses. Un tipo de modelos que constituyen una parte importante del estado del arte son los modelos basados en Deep Learning. Estos modelos supusieron grandes avances en la Inteligencia Artificial recientemente, ya que aunque nacidos en el Siglo XX, no ha sido hasta escasos 10 a˜nos cuando han resurgido gracias a los avances computacionales que permiten entrenarlos por el p´ublico general. En este trabajo de fin de grado se presentan t´ecnicas avanzadas de Deep Learning aplicadas al problema de la predicci´on de carga en Smart Buildings, principalmente basando el desarrollo en los datos del edificio Alice Perry de la National University of Ireland Galway, en colaboraci´on con el grupo Informatics Research Unit for Sustainable Engineering de la misma universidad. Los conjuntos de datos utilizados se obtuvieron datos sobre la serie temporal de consumo el´ectrico agregado de los aires acondicionados en el edificio Alice Perry. Junto a esta informaci´on, se recopilaron tambi´en datos meteorol´ogicos hist´oricos de la estaci´on meteorol´ogica en el mismo edificiocon el objetivo de estudiar si estas variables clim´aticas ayudan a una mejor predicci´on en los modelos. La predicci´on de series temporales sobre estos datos de carga energ´etica se realizar´a en dos modos con granularidad horaria: La predicci´on a un paso en la que estudiando las observaciones anteriores se obtiene una estimaci´on del valor de la carga en la pr´oxima hora y predicci´on de secuencias, en la que se intentar´a predecir el comportamiento de la serie en las pr´oximas horas a partir de los valores anteriores. 2 For life is quite absurd And death’s the final word You must always face the curtain with a bow Forget about your sin Give the audience a grin Enjoy it, it’s your last chance anyhow Always look on the bright side of life - Eric Idle, Monty Python Acknowledgements To my two supervisors, Carlos & Belarmino for the humongous effort and help that they put into this final degree project and their trust in my work. To Desir´ee for helping me in Galway and helping me getting into the research scene. To the IRUSE group, I want to thank everyone specially Marcus Keane for accepting me, guiding me and treating me like another member of the group. To my friends, who whenever I felt down or needed to get away, they were always there to cheer me up, specially in these last hard months. Some of you have been with me since we were 6, some of you we started university and some of you just came a couple years ago when sport brought us together. It’s been (and will be) a pleasure to walk with you by my side. Last, but not least, to my parents, Edith & Juan Luis for helping me getting through these difficult times during my university degree. You have helped me to push through my studies and wouldn’t have been able to complete them without your encouragement. I love you. 3 Contents 1 Introduction 7 1.1 Motivation....................................... 7 1.2 ProblemClassification ................................ 7 2 Planning 9 2.1 Objectives....................................... 9 2.1.1 Tasks...................................... 9 2.2 Research Process Planning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 2.2.1 Costestimation................................ 11 2.2.2 RiskIdentification .............................. 12 2.2.3 RevisitingPlanning.............................. 13 3 Deep Learning 15 3.1 Deep Learning & Artificial Neural Networks . . . . . . . . . . . . . . . . . . . . 15 3.1.1 Perceptron................................... 16 3.1.2 ActivationFunctions ............................. 17 3.1.3 Feed Forward Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 3.1.4 Convolutional Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 3.1.5 Recurrent Neural Networks . . . . . . . . . . . . . . . . . . . . . . . . . 23 3.1.6 Otherlayers.................................. 25 3.1.7 Trainingprocess................................ 26 3.1.8 Training Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 3.1.9 Validation methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 4 Case study 33 4.1 AvailableDatasets .................................. 33 4.2 Techniquesreview................................... 35 4.3 NUIG Alice Perry dataset exploration . . . . . . . . . . . . . . . . . . . . . . . . 36 4.3.1 Cleaningthedataset ............................. 38 4.3.2 Weather NAs imputation . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 4 4.3.3 Timecodification............................... 42 4.3.4 TrainTestSplit................................ 44 4.3.5 Normalization................................. 45 4.4 Testing on Benchmark: The Building Genome Project 2 . . . . . . . . . . . . . 46 5 Models for One-Step ahead prediction 48 5.1 Proposed models for one step ahead estimation . . . . . . . . . . . . . . . . . . 48 5.1.1 Model 1: Feed Forward Network . . . . . . . . . . . . . . . . . . . . . . . 48 5.1.2 Model2:LSTM................................ 49 5.1.3 Model3:CNN ................................ 49 5.1.4 Model 4: Hybrid LSTM+FFN . . . . . . . . . . . . . . . . . . . . . . . 50 5.1.5 Model 5: Hybrid CNN-LSTM + FFN . . . . . . . . . . . . . . . . . . . . 50 5.1.6 Model 6: Time Distributed CNN + FFN . . . . . . . . . . . . . . . . . . 51 6 Models for Sequence Prediction 53 6.1 TheMany-to-Onemodel............................... 53 6.2 TheSeq2Seqmodel.................................. 54 6.2.1 Encoder .................................... 55 6.2.2 Decoder .................................... 55 6.2.3 Training.................................... 55 7 Results for One-Step prediction 58 7.1 ExperimentSetup................................... 58 7.2 Predictions using Load and Timestamp as predictors . . . . . . . . . . . . . . . 59 7.3 Predictions using Load, Weather Variables and Timestamp as predictors . . . . 61 7.4 FinalRepetitions ................................... 63 7.5 Testing the best architecture on the Building Genome 2 data . . . . . . . . . . . 64 8 Results for Sequence prediction 66 8.1 ExperimentSetup................................... 66 8.2 Results......................................... 66 8.3 Testing the best architecture on the Building Genome 2 data . . . . . . . . . . . 69 9 Conclusions & Further Work 73 9.1 Conclusions on Deep Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 9.2 Conclusions on One-step models . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 9.3 Conclusions on Sequence models . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 9.4 Conclusions on the datasets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 9.4.1 AlicePerrydataset.............................. 74 9.4.2 BuildingGenome2.............................. 75 9.5 FurtherWork ..................................... 75 5 A Appendix 76 A.1 KerasKeyparameters ................................ 76 A.1.1 Compileparameters ............................. 76 A.1.2 Fitparameters ................................ 76 A.2 KerasLayers ..................................... 76 A.2.1 LeakyReLU .................................. 76 A.2.2 Dense ..................................... 77 A.2.3 LSTM ..................................... 77 A.2.4 Convolutional................................. 78 A.2.5 Pooling .................................... 78 A.2.6 Dropout.................................... 78 A.2.7 Concatenate.................................. 78 A.3 Code.......................................... 79 A.4 Alice Perry Data Preprocessing . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 A.4.1 AuxiliarFunctions .............................. 79 A.4.2 Loadreading ................................. 81 A.4.3 Removing cooling and holidays periods . . . . . . . . . . . . . . . . . . . 82 A.4.4 Reading Met ´ Eireann............................. 82 A.4.5 Imputing NAs with Met ´ Eireann ...................... 83 6 1. Introduction 1.1 Motivation Wang et al. [1] state that ”In recent years, the power industry has witnessed considerable developments of data analytics in the processes of generation, transmission, equipment, and consumption”. They also showed that number of publications growed from 2010 to 2017, rapidly increasing from 2012. The availability of data, smart meters and the development of new Machine Learning techniques made it possible to create data-driven models for the energy consumption field. From the perspective of the Degree in Computer Engineering, the interest relies in continuing learning the Deep Learning techniques introduced in the Machine Learning Techniques and Data Mining subjects, deepening the baseline knowledge taught in them. This final degree project will be a first step into the research scene, motivating a literature review that will help extend and strengthen not only the domain knowledge gained while doing the project but researching competences. The main idea behind the definition of this project is to study the performance of different deep learning architectures for time series forecast, more specifically applied to energy load forecast in smart buildings. 1.2 Problem Classification In their review, Hamad et al. [2] propose four classes attending to the range of the load forecast: •Long-term load forecasting (LTLF): for one year or more ahead, usually carried by strategic planning projects. •Medium-term load forecasting (MTLF): from one week to a year, this range is mainly used for applications like maintenance schedule and fuel purchase planning. 7 •Short-term load forecasting (STLF): from one hour to one week, allowing to carry day-to-day applications. •Ultra/very short-term load forecasting (VSTLF): from minutes to an hour ahead, usually needed for real-time control. According to Lin et al. ([3] trough [2]) there are two main families of models for load prediction •Multi-factor forecasting methods: which focus on creating models that portray the relationship between significant factors and the energy load in the system. •Time series forecasting methods: which focus on using existing historical data to build data-driven models. Within these models we can find three main families: –Statistical models (SM): These methods assume independence and normality of the residuals (there is an underlying probability distribution in the whole process). This forces strong assumptions on the data which can result in a weaker predictive power, but have great interpretability –Machine learning models (ML) : Which do not assume any probability distribution, thus their predictive power can be better than SMs. However, these methods can lack interpretability (i.e. ensemble methods, neural networks). –Hybrid models (HM): These methods present a mixture of the above mentioned, using them together to model the data. This Final Degree Project focuses on ML models, more precisely Deep Learning (DL) models applied to short-term forecasting. 8 3. Deep Learning 3.1 Deep Learning & Artificial Neural Networks Deep Learning models, are part of the family of ML methods. These methods are widely used in Regression and Classification problems. Although there are many DL approaches, the focus of this project will be Artificial Neural Networks (ANNs). The first Artificial Neural Network model was proposed in 1943 by Warren S. McCulloch & Walter Pitts [4] as a mathematical model to represent neural/mental activity. Further work was carried by Alexey Ivakhnenko and Lapa [5] in 1967 when they proposed supervised feed-forward multilayer neural network. However, it wasn’t until recent times when Deep Learning got a place in the State of the Art in multiple applications. In 1986, David E. Rumelhart, Geoffrey E. Hinton & Ronald J. Williams [6] presented the backpropagation algorithm applied to ANN which allowed to train the neurons that make up the network weights based on the error they made when predicting an observation. This work proved that it was possible to train multiple layer perceptrons (MLP) with a fast, simple and no hyperparameter dependant algorithm like backpropagation. However, computational power still fell short. These multiple layer architectures are also referred as Deep Neural Networks or DNNs. When talking about the breaktrough that caused the comeback of Deep Learning people usually refer to AlexNet [7]. In this 2012 project, Alex Krizhevsky, Ilya Sutskever & Geoffrey E. Hinton trained a Convolutional Neural Network (CNN) with a multipleGPU implementation in CUDA. They also included new features such as using the Rectified Linear Unit or ReLU [8] as the activation function instead of the sigmoid function. They used their model for the ImageNet 2012 contest, in which it achieved top-1 and top-5 test set error rates of 37.5 % and 17.0 %5 while the best performance achieved during the previous edition was 47.1% and 28.2% . This motivated more work in the field due to the fact that they used a supervised approach only training with backpropagation. Nevertheless, in this Final Degree Project the main objective is to work with Time Series. Many 15 models have been applied to this particular kind of data, but the Recurrent Neural Network (RNN) architecture is the most popular one. RNNs were popularized by Hopfield in 1982. However, RNNs architectures suffered from the vanishing gradient problem [9](where the gradients calculated for updating the network’s weights went towards small values, preventing the network from being further trained). It was in 1997 when Sepp Hochreiter and J¨urgen Schmidhuber proposed a novel RNN achitecture, Long Short-Term Memory (LSTM) cells [10]. This architecture solved the problem of vanishing gradients by introducing an internal state into the cells, where important information is stored and kept through time. LSTMs can reset this internal state and update it with relevant new information. In the following sections, further theoretical explanation on the main three architectures used in this Final Degree Project and their foundations will be carried out. 3.1.1 Perceptron The basic unit of a neural network is the simple perceptron or neuron. Figure 3.1: Diagram of a Neuron with three inputs which contains a set of weights W, one for each input Xand an activation function Ffor outputing its value A neuron is a simple unit representing a mathematical function based on the McCulloch-Pitts model [4]. It consists on a set of weights W, one for each input in X. The idea is to make a basic calculation by adding each input multiplied by its corresponding weight and then output a value by applying an activation function to that sum. The original activation function was the binary activation, trying to emulate the biological neurons excitation and information exchange. F(x) = (1, x ≥0 0, x < 0(3.1) 16 3.1.2 Activation Functions In this section, the considered Activation Functions (AFs) for the project are explained alongside the reasons to finally using them or not. Sigmoid Figure 3.2: Sigmoid activation function The sigmoid function is a non-linear AF used in neural networks. It’s a non linear activation, derivable continuous with a positive derivative in any point. It’s defined by the following formula: σ(x) = 1 1 + e−x(3.2) Neal ([11] trough [12] ) highlights the main advantages of the sigmoid functions as, being easy to understand and are used mostly in shallow networks. However, according to Nwankpa [12]: ”the Sigmoid AF suffers major drawbacks which include sharp damp gradients during backpropagation from deeper hidden layers to the input layers, gradient saturation, slow convergence and non-zero centred output thereby causing the gradient updates to propagate in different directions. Other forms of AF including the hyperbolic tangent function was proposed to remedy some of these drawbacks suffered by the Sigmoid AF”. Despite the fact that this AF used to be one of the most if not the most popular, these drawbacks alongside the existence of new and better approaches make it not suitable for practical use. Hyperbolic Tangent Hyperbolic tangent is usually applied over the output of LSTMs, as further sections show (see Figure 3.10), in order to limit their output between 1 and -1. It arose as a solution for the 17 drawbacks for the sigmoid AF. Figure 3.3: Hyperbolic tangent (tanh) function This is a trigonometric function, and is not usually expressed with another formula, however, it’s defined as follows: tanh(x) = ex−e−x ex+e−x(3.3) Rectified Linear Unit The Rectified Linear Unit (commonly known as ReLU) was an activation function proposed by Hahnloser in [8]. Dahl et al. [13] showed that usung the ReLU function improves the error rate when using ReLUs instead of sigmoids as activation functions. 18 Figure 3.4: Rectified Linear Unit activation function It’s defined as follows: F(x) = (x, x ≥0 0, x < 0(3.4) According to [12], this function rectifies the values of the inputs less than zero thereby forcing them to zero and eliminating the vanishing gradient problem observed in the sigmoid AFs. But the main advantage of ReLU comes also from a computational cost perspective, since it does not make any calculations (i.e. divisions or exponentials) ([14] through [12]). LeakyReLU However, ReLUs suffer the problem known as Dying ReLUs. The hard 0 activation value in the ReLU makes the gradient 0 whenever the neuron is not activated. According to Maas et al. [15] if the neuron is not initially activated, its weight might not get updated due to the zero gradient, so the weights value get stuck and the network can’t improve its predictions. In the same paper,Leaky ReLU was proposed as a way of overcoming this problem. Instead of forcing a 0 value when the input is negative, a small value is returned, controlled by the leaking parameter α. This makes the gradient not 0 in the entire AF domain. 19 Figure 3.5: Leaky ReLU activation function with α= 0.03 It’s defined by the following equation: F(x) = (x, x ≥0 x∗α, x < 0(3.5) 3.1.3 Feed Forward Networks Feed Forward Networks or FFNs are ANNs composed by Dense layers (Figure 3.6) of simple perceptrons or neurons, which propagate the information forward into the next layer (each neuron outputs its value to all neurons in the next layer). We talk about Dense or Fully Connected layers where all neurons are mapped to all neurons in the next layer. The layers between the first and the output layers are called hidden layers, and they are not always included (this is known as a single layer network) in the ANN. Although they showed good performance for tabular data, FFNs fell short for other problems, like pattern recognition in handwritten Zip codes. That’s why in 1980, Fukushima [16] proposed his Neocognitron as a primitive Convolutional Neural Network, and in 1989, Waibel et al. released their Time-Delay Neural Network (TDNN) used for phoneme recognition, as a way to capture the time-dependant structure of the data. 20 Figure 3.6: Example of a Dense or Fully connected Layer Figure 3.7: Diagram of a 2 Dense Layers DNN 3.1.4 Convolutional Networks Convolutional Neural Networks or CNNs [17] are special type of Neural Networks, which has shown exemplary performance on several competitions related to Computer Vision and Image Processing. Some of the exciting application areas of CNN include Image Classification and Segmentation, Object Detection, Video Processing, Natural Language Processing, and Speech Recognition. The motivations behind convolutions in ANNs are many. But the two most important ones,as 21 LeCun exposed in the LeNet paper [18] considered by many as the first CNN, FFNs present too many parameters when analizing images with hundreds of pixels, and they can’t analyse the structure of the data (when flattening an image input, the structure of the original pixels and their distribution gets lost). However, LeCun in the same paper claims that the main deficiency of unstructured nets for image or speech recognition applications is that hey have no built-in invariance with respect to relocations or local distortions of the input (see [18] for further details). Convolutions In Convolutional layers the input is a tensor with any dimension (1D,2D,3D...). The idea of convolutions is to apply a filter to extract features from the input data. Since we are working with time series data, 1D convolutions will be applied. Figure 3.8 shows an example of a 1D convolution. Figure 3.8: 1D-Convolution example over a 1D vector The values of the convolution (-1 and 1 in the example) are learnt by the network through backpropagation. Pooling After applying convolutions and extracting features, pooling layers are applied to make a summary of those features and reduce the dimensionality. These two layers are usually applied one after another, concatenating them and finally feeding the input into a FFN by flattening the last layer. Figure 3.9 shows an example of Max Pooling, the choice for this Final Degree Project. 22 Figure 3.9: Max Pooling example over a 1D vector 3.1.5 Recurrent Neural Networks Recurrent Neural Networks (RNNs) are a class of ANN where connections between neurons are not only in a forward direction but also backward, making cycles in the ANN graph. This allows to return information to previous layers for future inputs, allowing for a time-distributed architecture. RNNs started with Rumerlhart’s 1986 [6] work, leading to Elman nets [19] y Jordan nets [20]. However, the most popular architectures are the Long Short-Term Memories and the Gate Recurrent Units. In this project, Long Short-Term memories will be the core architecture, due to the time series nature of the energy load data. Long Short-Term Memory Networks Long Short-Term memories [10] came up as a solution for the vanishing gradient in neural networks. Their solution was to include a memory cell cand a hidden state hthat kept important information throughout the training process and enabling transmission during the sequence chain, making it able to reset it aswell if more relevant information showed up. To achieve this, the forget gate outputs a 1 or a 0 thanks to the sigmoid function σdepending on if the information on the cell state is decided to be kept or not. The next output is provided by σin the update gate and tanh in the candidate gate. Using the product of these two values, and then adding it with the product of the forget gate output and the previous cell state, we get the updated memory cell value. The last step is to calculate the hidden state, by applying the tanh over the cell state and multiplying the resulting value by the output from the output gate. Figure 3.10 shows the pipeline for this process. Every time a σor tanh function is going to be applied as an AF, a different set of weights and bias is applied to the input before the AF. 23 Figure 3.10: LSTM Cell pipeline. Figure adapted from https://en.wikipedia.org/wiki/ Long short-term memory The LSTM pipeline can be described by the following equations: ft=σ(Wfxt+Ufht−1+bf) it=σ(Wixt+Uiht−1+bi) ot=σ(Woxt+Uoht−1+bo) ˜ct=tanh (Wcxt+Ucht−1+bc) ct=ftxct−1+itx ˜ct ht=otxtanh (ct) ˆyt=ht Figure 3.11 shows an unrolled version of the diagram in figure 3.10. The hidden state is fed into the next into the next timestamp, and the cell state is transferred in a kind of conveyor belt, updated only when the forget gate decides that new information is more important to be kept. 24 Figure 3.20: Unrolling graph The iterative process goes as follows 1. Get the sequence of input values and the corresponding sequence of output values 2. Unroll the network and calculate errors in each timestep, accumulate them and calculate gradients. 3. Roll up the network 4. Update weights However, this approach has its drawbacks. The longer the sequence, the higher the computational cost. This also can cause vanishing/exploding gradients, since a long unrolling is like having a neural network with many layers, thus calculating many derivatives falls into the same faults as the very deep neural networks. Truncated Backpropagation Through time Truncated Backpropagation Through Time, or TBPTT, addreses the problem of too long sequences in BPTT. The idea is to process the sequence by lots, calculating the gradient for subsequences of the input sequence instead of doing it as a whole. It’s ruled by two parameters, k1for the input sequence size and k2for the accumulated steps for BPTT. It goes as follows: 1. Get the sequence of k1input values and the corresponding sequence of output values 2. Unroll the network and calculate errors in each timestep, accumulating them for k2steps 3. Roll up the network and calculate gradient of the error 4. Update weights All k1, k2∈Nvalue combinations restricted to k1, k2< n are possible. However, Keras implementation forces k1=k2=k, where kis equal to the choice of window size for previous values to use as predictors. 31 3.1.9 Validation methodology In order to test model performance, the following metrics will be used: Error measurements for one-step ahead prediction RMSE: v u u t 1 N N X i=0 (yt−ˆyt)2(3.7) CVRMSE: 1 ¯yv u u t 1 N N X i=0 (yt−ˆyt)2(3.8) CVRMSE provides an indication on how much does the errors variate with respect to the mean over one (if multiplied by 100, the percentage of deviation would be obtained). This allows for comparison between datasets, since dividing by the mean gets the scale of the data out of the statistic value. Error measurements for sequence prediction Time-RMSE (as proposed by [25]): v u u t 1 N N X t=0 1 scope scope X i=0 (yt[i]−ˆyt[i])2(3.9) Time-CV(RMSE) (as a proposal for CV(RMSE) adaptation): v u u t 1 N N X t=0 1 scope scope X i=0 (yt[i]−ˆyt[i])2 ¯y2 t (3.10) 32 4. Case study 4.1 Available Datasets According to Wang et al., due to the private nature of Energy Load data, many companies are hesitant to release their data [1]. In the same paper, they showcased a table with Open Load Datasets. Table 4.1 shows the information they gathered about the most popular open energy load datasets Name Brief Description Frequency Duration Custom Behavior Trials Smart meter read data Pre- and post-trial survey data Every 30 min 2009/9-2011/1 Low Carbon London Smart meter read data Electricity price data Appliance and attitude survey data Every 30 min 2013/1-2013/12 PecanStreet Residential electricity consumption data Electric vehicle charging data Every 1 min 2005/5-2017/5 Building Data Genome Non-residential building smart meter data Area,weather and primary use type data Every 1 hour 2014/12-2015/11 UMass Smart Residential electricity consumption data Every 1 min One day Ausgrid Residents General consumption data Controlled load consumption data PV output data Every 30 min 2010/7-2013/6 Ausgrid Substation Substation metering data Every 15 min 2005/5- GEFCom 2012 Zonal load data Temperature data Hourly 2003/1-2008/6 GEFCom 2014 Zonal load data 25 weather station data Hourly 2005/1-2010/9 ISO New England System load data Temperature data Locational marginal pricing data Hourly 2003/1- NUIG Alice Perry Air Handling Units load data Weather Station data Hourly 2018/5-2020/2 Tucson Electrical Power Tucson (Texas) Area Load Data Tucson Airport Weather station Hourly 2015/07-2018/07 Table 4.1: Open Energy Load datasets from the Wang et al. [1] review 33 For this project, in table 4.1 a basic description on how they used the datasets and two key points that were needed for this project; the existance of weather data in the dataset and if it was a residential building or not. Name Type of forecast in references Weather Data? Residential Building? Custom Behavior Trials Short term No Yes Low Carbon London Short term No Yes PecanStreet No references No Yes Building Data Genome No references Yes No UMass Smart Ultra short term No* Yes Ausgrid Residents No references No Yes Ausgrid Substation No references No Not a Building GEFCom 2012 Short & Medium Term Yes US Utility with 20 zones GEFCom 2014 Short & Medium Term Yes AUS Utility with 10 zones ISO New England Short Term Yes Not a Building (Zones) NUIG Alice Perry Short Term Yes No Tucson Electrical Power Short Term Yes Not a Building (Zones) *There is a new version of the dataset Table 4.2: Information available in each dataset and type of source 34 4.2 Techniques review Name Techniques used in references Custom Behavior Trials Thefting detection with customer clustering & SVM [28] Pattern extraction and customer classification with K-SVD and SVM [29] Deep Learning household load prediction using pools of neighbours [30] Clustering customer behaviour, reducing dimensionality with Markov models [31] Load forecast with a non-parametric approach [32] Load forecast with Clustering+MLP [33] Load forecast with Boosted Quantile Regression [34] Behavior indicators through a cross-domain feature selection and coding approach [35] Load profiling with Clustering [36] Household characteristic extraction with Unsupervised learning and regression [37] Household Load data compression and reconstruction [38] Socio-demographic Information Identification from Load data with Convolutional Networks [39] Low Carbon London Costumer clustering with C-Vine Copula Mixture Model [40] Peak Load Estimation with clustering and quantile-based probabilistic approach [41] PecanStreet X Building Data Genome X UMass Smart* Power Consumption Profiling with Time-Frequency (TF) based clustering [42] Layered clustering for load profiling (local clusters into global) [43] Ausgrid Residents X Ausgrid Substation X GEFCom 2012 Load forecast with ARX,Echo State Networks and Wavelets while tuning with genetic algorithms [44] Load Forecast via quantile regression averaging on sister models [45] Load forecast with parametric models [46] Load forecast in two stages using nonlinear Lasso and Splines [47] Hierarchical load forecasting with Gradient boosting machines and Gaussian processes [48] Electric load forecasting and backcasting with Kernel regression, random forests and splines [49] Load forecast with Gradient Boosting based splines [50] Weather station selection with GEFCom benchmark model [51] GEFCom 2014 Probabilistic load forecasting using kernel density estimation (KDE) and quantile regression [52] Probabilistic load forecasting semi-parametric regression, simulation and quantiles [53] Probabilistic load forecasting with forecast combination and residual simulation [54] Probabilistic load forecasting with a hybrid model of kernel density estimation and quantile regression [55] Probabilistic load forecasting with non parametric Nadaraya–Watson estimators [56] Probabilistic load forecasting with Lasso [57] Probabilistic load forecasting with Generalized additive models and Quantile regression [58] Load forecasting with Tao’s benchmark model** incorporating recency effect through moving averages [59] ISO New England Paper cited [59][60] [61] but none of those papers used the dataset. North Carolina Electric Membership Corporation (NCEMC) Incorporating Rel.Humidity info into Tao’s benchmark model [60] Incorporating Wind info into Tao’s benchmark model [62] Temperature scenario generating with bootstraping,date shifting, fourier transformations among ohters [61] NUIG Alice Perry (private dataset) Load prediction with LSTM and seasonal clustering [63] Tucson Electrical Power LSTM for short term load forecast [64] *There is a new version of the dataset ** Tao’s benchmark model was used as basic model for the GEFCom 2014, a vanilla linear model Table 4.3: Techniques review Table 4.2 represents a paper review in which a short summary on what techniques were used in each paper from [1] and dataset and for what purpose is shown. As it can be seen,at the time of these papers, Deep Learning is still emerging in the Load Forecast field and there are not many approaches using these models. 35 However, later work from authors like Marino et al.[65], Wilms et al.[66] or Gasparin et al. [25] shows that DNNs, specifically RNNs have remarkable performance in the Load Forecast field, even outperforming some of the methods listed in Table 4.2. In this project DNNs architectures will be presented an tested on a real world problem, the NUIG Alice Perry dataset. 4.3 NUIG Alice Perry dataset exploration In this dataset there are 824338 observations in minutely format corresponding to the aggregated load of the NUIG’s Alice Perry building Air Handling Units (AHUs) heating energy load. A weather station in the same building provides 16731 observations in hourly data for ten variables (’Batt [V]’, ’PTemp [oC]’, ’AirTemp [oC]’, ’RH [%]’, ’Slr [kW/m2]’, ’Slr [kJ/m2] Tot’, ’WindSpeed [m/s]’,’WindDir [deg]’, ’Gust 3s Avg [m/s]’, ’BP [mBar]’). A group of sparse observations corresponding to a 2016 day were discarded. Figure 4.1: Load data in the original scale (minutely data). Gaps represent missing values The AHUs load data, in kWh, is aggregated into hourly data using the mean. Afterwards, it is merged (outer merge) with the weather station data, making the final dataset with 15270 hourly observations, which presents missing values or NAs in the distribution indicated by Table 4.3. Figure 4.2 shows a time series plot portraying the location of the NAs. Figure 4.3 shows the time series for weather variables. 36 Varaible Mean σMinimum Maximum Timestamp 2018-05-24 15:00:00 2020-02-19 20:00:00 Load 4.111483 4.373992 -4.65141 22.7941 AirTemp [oC] 9.973651 4.880410 -3.1177 29.4605 BP [mBar] 1010.784819 12.828838 946.091 1045 Batt [V] 13.538727 0.392777 8.82636 13.9718 Gust 3s Avg [m/s] 4.267261 2.268860 0 16.8267 PTemp [oC] 14.522938 5.307262 0.785 37.2435 RH [%] 83.855687 12.643092 26.2922 100 Slr [kJ/m2] Tot 5.752758 9.602083 0 54.2645 Slr [kW/m2] 0.095862 0.160034 0 0.9065 WindDir [deg] 199.253634 89.598314 0 350.942 WindSpeed [m/s] 2.651774 1.435264 0 10.1618 Table 4.4: Statistics for variables in the hourly dataframe Varaible Number of NAs Timestamp 0 Load 1500 Record 789 Batt [V] 811 PTemp [oC] 811 AirTemp [oC] 811 RH [%] 811 Slr [kW/m2] 811 Slr [kJ/m2] Tot 811 WindSpeed [m/s] 811 WindDir [deg] 811 Gust 3s Avg [m/s] 811 BP [mBar] 811 Table 4.5: NAs by variable after merging datasets and aggregating by hourr As it can be seen in Figure 4.3, there are negative values for load. According to data providers, the load is estimated with the following formula: ∆T= Maximum Airflow ∗Valve % (4.1) Where ∆T=Tflow −Treturn. Due to Load being estimated, then it maybe the case that Tflow −Treturn inverts when the heating valve is closed so what should be warmer/colder is the other way round (and this depends on the design of the hydronics network). 37 Figure 4.2: Full Hourly data series for load data. Blank spaces represent NAs in load data, and red values represent missing values in the weather data 4.3.1 Cleaning the dataset As seen in Figure 4.2, between May and September both in 2018 and 2019 the time series takes very small values. These months are the warmer ones, and the time series represent energy consumption from the AHUs in heating mode. Therefore it doesn’t make sense to study the heating load in these months, thus they will be removed. There are also some dates that will be removed. These weeks correspond to the periods the Alice Perry building is closed during winter holidays. Therefore, removing this weeks with a different behaviour should improve the overall performance. Figure 4.4 shows, in purple, the removed periods from the dataset. Figure 4.5 shows the final data with these periods removed. 38 Figure 4.3: Full Hourly data series for weather data. Blank spaces represent NAs in the series 39 Figure 4.4: Full Hourly data series for load data. Purple shows the dates that will be dismissed due to their different behaviour from what the main series represents Figure 4.5: Final full Hourly data series for load data after preprocessing 4.3.2 Weather NAs imputation In order to fill the gaps in Figure 4.3, information from a nearby weather station placed in Atherny, 25km to the east from Galway city. Data is provided by Met ´ Eireann and available at their official website. 40 Figure 4.11: Load series for the Wolf education Tammie building Figure 4.12: Train Test split for the Wolf education Tammie building 47 5. Models for One-Step ahead prediction The main purpose of this chapter is to showcase some DNN architectures in order to see which one performs the best in the data. 5.1 Proposed models for one step ahead estimation 5.1.1 Model 1: Feed Forward Network As Wang et al. [68] state, MLPs are often used as baseline models. However, these models incorporate modern techniques like Dropout or ReLUs as activation functions. The baseline model will be a two layered MLP, as seen in Figure 5.1. Figure 5.1: Model 1 scheme 48 5.1.2 Model 2: LSTM LSTMs are the most popular architecture when it comes to time series data. Many load forecast projects use LSTMs as the core of their proposal [64] [65]. In this project a basic LSTM model will be used in order to see if it improves the FFN predictions, and check if more complex approaches (presented in the following sections) improve this model. Figure 5.2 shows the two layered LSTM network used in this project. Figure 5.2: Model 2 scheme 5.1.3 Model 3: CNN According to Ismail et al. [69], complex CNN based architectures like ResNet have been applied to Time series data. In fact, Gamboa ([70] through [69]) states that motivated by the success of these CNN architectures in these various domains, researchers have started adopting them for time series analysis. Figure 5.3 shows a two CNN-Pool block neural network, which are fed into a hidden fully conected layer before the final output. Figure 5.3: Model 3 scheme 49 5.1.4 Model 4: Hybrid LSTM+FFN This architecture was proposed by Andrew Loder and Mark C. Lewis [64], which proved to outperform the FFN and the LSTM architectures in particular subsets of the data, like Winter periods. However, when working with many variables as this project’s datasets have, the Dying ReLUs phenomenon showed up, so instead of using the ReLU activation, the Leaky ReLU is incorporated into the model. Figure 5.4 shows the architecture of this model. Figure 5.4: Model 4 scheme In this architecture, the left input in Figure 5.4 takes the continuous historical values such as past Load data or weather information, which are fed into a LSTM network. On the right input, the timestamp encoding is fed into a dense layer. Both outputs are then concatenated and fed into a dense layer, which will then be fed into the final output layer. 5.1.5 Model 5: Hybrid CNN-LSTM + FFN In order to try to improve Model 4, a convolutional layer and a pooling layer will be added in this architecture, applied over the outputs of the LSTM layers. 50 Figure 5.5: Model 5 scheme The idea is to combine both CNNs and LSTM trying to exploit the best characteristics of each architecture. 5.1.6 Model 6: Time Distributed CNN + FFN As an alternative to the addition of convolutions after the LSTM layers in Model 5, Model 6 is a new proposal inspired by an architecture used to process video data. A similar architecture was successfully tested by authors in [71]. Figure 5.6: Model 6 scheme Figure 5.7 shows how the Time Distributed CNN works. Input data is split into subsequences of 8 hours, so each day is composed of 3 subsequences. Convolutions are applied to each subsequence, and their output is then fed to a LSTM layer. 51 Figure 5.7: Representation of Time Distributed CNN workflow 52 6. Models for Sequence Prediction In the previous chapter, models for one-step ahead prediction were showcased. However, sometimes a sequence prediction is required, in order to get an idea of how the behaviour will be for the next several hours, not just the following one. In this chapter, two main architectures are explained and tested to see what performance they give in the problem we are facing 6.1 The Many-to-One model This architecture takes a sequence (in our case a sequence of two variables, Fand Y, [y0, y1, . . . , yt−1] as the last 60 previous load values and [f1, f2, . . . , ft] as the codification for the dates) as input and outputs one single value as output. However, this can be adapted to sequence prediction as figure 6.1 shows. In fact, the previous chapter models were many to one, but in order to achieve a finer tuning, exclusively LSTM based architecture will be considered. The advantage of this approach against the One-to-One model is that the input is a full sequence of values, thus the network is able to capture the pattern in the input sequence. 53 Figure 6.1: Many to one architecture and its adaptation to sequence prediction Nevertheless, as seen in figure 6.1, this architecture is only able to output one value. In order to predict a sequence, the prediction for the previous step must be reinjected as the latest value for the sequence. This creates a very challenging scenario, since predictions will be based on predictions. In order to solve this problem, Seq2Seq models can be applied. 6.2 The Seq2Seq model The Secuence to Secuence Model, usually referred as seq2seq was introduced in 2014 by Sutskever et al. [72] in the Machine Translation context. The idea is to be able to generate outputs of flexible length given a set of previous values with a different length. This approach is also known as Many to Many. Previous work [65] [66] has proven the viability of this approach The baseline model will be the Encoder-Decoder model. This model consists of two submodels, the encoder and the decoder. 54 6.2.1 Encoder The Encoder model takes any sequence of a fixed length and learns a hidden representation of this vector as its output. Later on, this output is fed into the decoder model, conditioning its output. 6.2.2 Decoder The function of the decoder is to output the predictions based on the encoder representation of the input vector. This is known as conditional output; given a learned representation of the input vector, the outputs are retrieved. Figure 6.2 shows the scheme of this model. Figure 6.2: Encoder-Decoder model, showing the conditional output ˆygiven the Encoder Input 6.2.3 Training Training the Encoder first In [65], authors claim that pretraining the encoder first can improve model performance . The way of training it is through teacher enforcing, treating it like a One-to-one model. Figure 6.3 shows this process 55 Figure 6.3: Encoder pretraining Training the Encoder-Decoder together Once the encoder is trained, it’s plugged into the decoder for a combined training. The sequence input, consisting on both the series yand the time codification f, are fed into the encoder, which outputs its LSTM layers hidden and cell states into the decoder. The decoder takes the date codification as input and outputs the load prediction for that date given the encoder representation. Then the errors of the decoder output are backpropagated through the decoder and the encoder, tuning both at the same time. Figure 6.4 shows how this model is structured. Figure 6.4: Example of a 3 layered Encoder-Decoder Keras graph 56 Epochs Batch Size RMSE CVRMSE Execution Time Model Timecod CNN cyclical one-hot 47.0 89.6 2.253633 0.250404 258.794594 FFN cyclical 39.0 64.0 3.714221 0.412691 100.036803 one-hot 45.0 76.8 3.718279 0.413142 103.913929 Hybrid cyclical 43.0 76.8 2.245731 0.249526 1594.831875 one-hot 45.0 64.0 1.970037 0.218893 1606.658120 HybridCNN cyclical 51.0 64.0 2.533662 0.281518 1662.550046 one-hot 49.0 76.8 2.384882 0.264987 1608.775339 LSTM cyclical one-hot 49.0 128.0 2.537884 0.281987 1125.982756 TDCNN cyclical one-hot Table 7.8: Average RMSE for each combination of Model and Time codification. Blank spaces represent combinations that were not trainable due to the lack of power in the computer the experiments were carried with 7.4 Final Repetitions As Table 7.2 indicates, the best model is the LSTM with one-hot encoding, training for 65 epochs and a batch size of 128. This set of parameters will be used in 5 final repetitions to try to get the minimum RMSE possible The minimum achieved was an RMSE of 1.593951 and a CVRMSE of 0.1772. Figure 7.1 shows the predicted time series vs the real time series for the test data. 63 Figure 7.1: Time series prediction for the test data with the best model 7.5 Testing the best architecture on the Building Genome 2 data The same model was trained and tested on the Wolf education Tammie building only using Load and Timestamp as predictors, achieving an RMSE of 3.46 (in the original scale) and a CVRMSE of 0.0401. Figure 7.2 presents the predicted values for this building, achieving a much better prediction than for the Alice Perry data. This low CVRMSE when using the same model reflects that the NUIG dataset is much more challenging than the available datasets, due to the big variation in the data, having a lot of outliers and many missing values. Figure 7.2 shows how much better fitting was provided with the same model for the Building Genome 2 data than the fitting obtained in Figure 7.1. 64 Figure 7.2: Real (blue) vs Predicted (orange) for the Wolf education Tammie building with the best model 65 8. Results for Sequence prediction 8.1 Experiment Setup Multiple layered LSTM models were tested for each architecture. All models were trained using the hyperbolic tangent as an activation function. Every model was trained at 30 epochs and using a batch size of 64 for the MTO and a batch size of 128 for the Seq2Seq model. Every combination of hyperparameters was tested 5 times, due to the stochastic nature of the weight updating process, and then averaged to get an estimator of the RMSE. The networks were tested to predict using the 60 previous observations the 60 following ones. 8.2 Results Figure 8.1 shows the results for the five repetitions of each combination of hyperparameters. As we can see, Many-to-One models are much more stable in terms of weight calculation, having much less dispersion in the repetitions. This is probably due to the fact that the Seq2Seq model is bigger by definition, since it’s composed of two submodels (although the encoder was pretrained, but by definition the seq2seq model will have more parameters). 66 Figure 8.1: Encoder-Decoder different models Time-RMSE on Test. X-axis ticks represent the combinations for Algorithm-Batch Size-Epochs-Number of layers-Neurons per layer-Timestamp codification 67 Time-RMSE CVRMSE Execution Time Algo. Batch Size Epochs NoLayers Neurons Time Cod. MTO 64 30 2 128 64 cyclical 7.725562 0.818659 1152.657166 one-hot 7.039355 0.750309 1146.410642 16 8 cyclical 4.255968 0.469146 644.930541 one-hot 4.518206 0.488365 634.186083 32 16 cyclical 7.817810 0.853784 686.002445 one-hot 6.935232 0.760880 678.409734 64 32 cyclical 5.852846 0.663232 822.437546 one-hot 5.875786 0.647162 806.877860 3 16 8 4 cyclical 5.917021 0.654249 914.205121 one-hot 5.870928 0.644215 912.040296 32 16 8 cyclical 6.842274 0.740326 962.612950 one-hot 6.626617 0.714234 964.576747 S2S 128 30 2 128 64 cyclical 6.960216 0.708390 1421.530302 one-hot 6.811868 0.695569 1410.228048 16 8 cyclical 7.771836 0.798580 626.538593 one-hot 7.752938 0.789764 640.614926 32 16 cyclical 7.393806 0.753349 653.313766 one-hot 7.224111 0.738680 660.806733 64 32 cyclical 7.540910 0.770091 893.147289 one-hot 6.965215 0.709630 905.810530 3 16 8 4 cyclical 8.016221 0.820358 850.189411 one-hot 7.235989 0.739930 847.862240 32 16 8 cyclical 7.525386 0.770729 902.373420 one-hot 7.222317 0.743517 936.223573 Table 8.1: Average RMSE over 5 repetitions for combinations showed in Figure 8.1, with the minimums highlighted in black As it can be seen, the best combination of hyperparameters (on average and on minimum) is the Many-to-One two layered model with 16 and 8 neurons, with a batch size of 64, trained for 30 epochs and using cyclical encoding for the date codification. This is, in fact, the smallest network in terms of parameters, since the cyclical encoding uses only four variables to code the timestamps. Final Repetitions Using the best combination of hyperparameters, 5 repetitions were made in order to look for the best weight tuning. Figure 8.2 shows the sequence prediction skipping 60 observations for the best model after repetitions, which had a RMSE of 3.45 and a CVRMSE of 0.35. Figure 8.3 shows 4 different close-up day load predictions graphs. As it can be seen, the curve fitting captures the general behaviour of the series, however, when it comes to estimate the load peaks and drops the net doesn’t capture the information. The main reason for this problem could be that these peaks and drops do not correspond to a pattern and are influenced by external factors of which no record is kept or known. Another possible reason is that as seen in Figure 4.9 the test split has a different distribution from the majority of the 68 train split, reaching higher peaks. Therefore, in order to palliate this effect more data needs to be recollected in 2020 (thus waiting until its generated) and then train with more recent data. However, it must be taken into account that this chapter was based on predicting with predictions, which is vastly challenging compared to the previous chapter but LSTMs still managed to get a good prediction. Figure 8.2: Sequence Prediction for MTO 8.3 Testing the best architecture on the Building Genome 2 data Just as it was tested in section 4.4, the best architecture was applied to the Wolf education Tammie building data, but this time for sequence prediction. This time the model achieved a RMSE of 12.802 (in the original scale) and a CVRMSE of 0.1436. Figure 8.4 using sequences but skipping the 60 intermediates so that there is a possible comparison with the original series & 8.5 shows sequence prediction closeup for 4 different sequences. Prediction according to de CVRMSE is much better for this data too when it comes to sequence prediction. 69 Figure 8.3: Sequence Prediction for 4 different days 70 Figure 8.4: Sequence Prediction for MTO for the Wolf education Tammie building 71 Figure 8.5: Sequence Prediction for 4 different days for Wolf education Tammie building 72 A.3 Code Code is available at the following repositories : Link to Repository 1 Link to Repository 2 in jupyter-notebook format. However, the Alice perry data is not of public domain, so only examples using the Building Genome data will be available there, although the code is the same except for the df (dataframe) assignation. In case the repository is not available please contact any of the authors. A.4 Alice Perry Data Preprocessing A.4.1 Auxiliar Functions import pandas as pd import numpy as np import datetime as dt import matplotlib.pyplot as plt import time as clock plt.rcParams["figure.figsize"]=(20,10) # Aggregates data into hourly granularity. def aggregate_by_hour(df,timecol="Timestamp"): df[timecol] = pd.to_datetime(df[timecol]) time = df.Timestamp.dt group= df.groupby([time.year,time.month,time.day,time.hour]).mean() grouptime= pd.to_datetime([dt.datetime(year=k[0],month=k[1],day=k[2],hour=k[3]) for k in group.index]) group= group.reset_index(drop="True") group[timecol] = grouptime return(group) # Places NaN values in the negative values of the dataframe def negative_to_na(df,feature): index=df["AHUs_Heating_LPHW_energy_kWh"]<0 df[feature].loc[index]=np.nan return(df) # Fills the dataset with NaN between non consecutive observations def na_in_gaps(df,freq="H"): dates = pd.DataFrame() 79 dates["Timestamp"] = pd.date_range(start=df["Timestamp"].iloc[0],end=df["Timestamp"].iloc[-1],freq=freq) return(pd.merge(dates,df,on="Timestamp",how="left")) # Gets the time codification for the Timestamp def get_time_codification(df,variables=["weekday","hour"],mode="cyclical"): if mode=="one-hot": weekday_oh = pd.get_dummies(df["Timestamp"].dt.weekday,prefix="Weekday_") hour_oh = pd.get_dummies(df["Timestamp"].dt.hour,prefix="Hour_") month_oh = pd.get_dummies(df["Timestamp"].dt.month,prefix="Month_") dict_oh = {"weekday":weekday_oh,"hour":hour_oh,"month":month_oh} output = pd.concat([dict_oh[v] for vin variables],axis=1) output.insert(0,"Timestamp",df["Timestamp"]) return output elif mode=="cyclical": weekday_cos = pd.Series(np.cos(df["Timestamp"].dt.weekday*2*np.pi/6),name="weekday_cos") weekday_sin = pd.Series(np.sin(df["Timestamp"].dt.weekday*2*np.pi/6),name="weekday_sin") hour_cos = pd.Series(np.cos(df["Timestamp"].dt.hour*2*np.pi/23),name="hour_cos") hour_sin = pd.Series(np.sin(df["Timestamp"].dt.hour*2*np.pi/23),name="hour_sin") month_cos = pd.Series(np.cos((df["Timestamp"].dt.month-1)*2*np.pi/11),name="month_cos") month_sin = pd.Series(np.sin((df["Timestamp"].dt.month-1)*2*np.pi/11),name="month_sin") dict_sin = {"weekday":weekday_sin,"hour":hour_sin,"month":month_sin} dict_cos = {"weekday":weekday_cos,"hour":hour_cos,"month":month_cos} 80 output = pd.concat([dict_sin[v] for vin variables]+[dict_cos[v] for v in variables],axis=1) output.insert(0,"Timestamp",df["Timestamp"]) return output # Plots in two colors the chosen variable according to a boolean mask def plot_masked_var(df,mask,var="Load",color="red",colorbase="#1f77b4",output=plt): dfcopy=df.copy() dfcopy[var][mask==0]=np.nan output.plot(df["Timestamp"],df[var],color=colorbase) output.plot(dfcopy["Timestamp"],dfcopy[var],color=color) A.4.2 Load reading #Dataset with AHUs information df_load=pd.read_csv("../data/AlicePerry/ahusHeating.csv") #Dataset with weather information df_weather=pd.read_csv("../data/AlicePerry/weather/weather_station_processed2020.csv", sep=";").drop(["Unnamed: 0","Record"],axis=1) df_weather["Timestamp"]=pd.to_datetime(df_weather["Timestamp"]) #Joining both datasets df=pd.merge(df_load,df_weather,on="Timestamp",how="left") df=df.rename(columns={df.columns[1]:"Load"}) df_with_nas=df.copy() #Checking Nas print(df.isna().sum()) # Plotting the load variable plt.plot(df["Timestamp"],df["Load"]) nas=df.isna()["Batt [V]"] plot_masked_var(df,nas) #Plot weather variables 81 fig, axes = plt.subplots(10,figsize=(20,20)) for sin range(len(axes)): axes[s].set_ylabel(df.columns[s+2]) axes[s].plot(df["Timestamp"],df.iloc[:,s+2],color="darkgreen") A.4.3 Removing cooling and holidays periods time=df["Timestamp"] #Holiday period mask closed=(df["Timestamp"]>dt.datetime(2018,12,25)) & (df["Timestamp"]<dt.datetime(2019,1,2)) | (df["Timestamp"]>dt.datetime(2019,12,25)) & (df["Timestamp"]<dt.datetime(2020,1,2)) #Cooling period (mostly summer) mask cooling=((df["Timestamp"]<dt.datetime(2018,9,15))) | (df["Timestamp"]>dt.datetime(2019,5,5)) & (df["Timestamp"]<dt.datetime(2019,8,13)) mask=closed | cooling plot_masked_var(df,mask,color="purple") df["Load"].loc[mask]=np.nan A.4.4 Reading Met ´ Eireann df_met_or=pd.read_csv("../data/AlicePerry/hly1875.csv").rename({"date":"Timestamp"} ,axis="columns") df_met=df_met_or.copy() #making a copy to save original data df_met=df_met.replace(r’^\s*$’, np.nan, regex=True) # Fixing some wrong values for col in df_met.columns[1:]: df_met[col] = df_met[col].astype(float)#From string to float df_met["Timestamp"]=pd.to_datetime(df_met["Timestamp"]) # Datetime to pandas time class matchmask=(df_met["Timestamp"]>=df["Timestamp"].iloc[0]) & (df_met["Timestamp"]<=df["Timestamp"].iloc[-1]) #Getting the same dates as our dataframe 82 df_met=df_met.loc[matchmask] A.4.5 Imputing NAs with Met ´ Eireann Barometric Pressure pressure_dif=1010.73-1013.25 #Difference of pressure between 21meters and 0meters, since NUIG is measured at 21 df.loc[fillingindex,"BP [mBar]"]=df_met["msl"].loc[fillingindex].values+pressure_dif #Sudden drop fix in one single observation df["BP [mBar]"].iloc[5206]=df_met["msl"].iloc[5206]+pressure_dif Relative Humidity df.loc[fillingindex,"RH [%]"]=df_met["rhum"].loc[fillingindex].values Wind Speed knots_to_ms=0.514444 df.loc[fillingindex,"WindSpeed [m/s]"]=df_met["wdsp"].loc[fillingindex].values*knots_to_ms Air Temperature df.loc[fillingindex,"AirTemp [oC]"]=df_met["temp"].loc[fillingindex].values df["AirTemp [oC]"]=df["AirTemp [oC]"]+3.5 #Error in the meter Solar Radiation datestofill=df["Timestamp"].loc[fillingindex] fillingdates=datestofill+dt.timedelta(days=365) #Same period from the next year df_weather.index=df_weather["Timestamp"] df.loc[fillingindex,"Slr [kW/m2]"]=df_weather.loc[fillingdates,"Slr [kW/m2]"].values plot_masked_var(df[4000:7000],fillingindex[4000:7000],"Slr [kW/m2]") 83 Plotting after filling clean=df.isna().sum()==0 cleancols=list(df.columns[clean][1:]) fig, axes = plt.subplots(len(cleancols),figsize=(20,20)) print(cleancols) for sin range(len(cleancols)): axes[s].set_ylabel(cleancols[s]) plot_masked_var(df,fillingindex,cleancols[s],output=axes[s],color="#A70961" ,colorbase="darkgreen") 84 List of Figures 2.1 CRISP-DMcycle ................................... 10 2.2 Gantt diagram for the project . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 3.1 Diagram of a Neuron with three inputs which contains a set of weights W, one for each input Xand an activation function Ffor outputing its value . . . . . . 16 3.2 Sigmoid activation function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.3 Hyperbolic tangent (tanh) function . . . . . . . . . . . . . . . . . . . . . . . . . 18 3.4 Rectified Linear Unit activation function . . . . . . . . . . . . . . . . . . . . . . 19 3.5 Leaky ReLU activation function with α= 0.03................... 20 3.6 Example of a Dense or Fully connected Layer . . . . . . . . . . . . . . . . . . . 21 3.7 Diagram of a 2 Dense Layers DNN . . . . . . . . . . . . . . . . . . . . . . . . . 21 3.8 1D-Convolution example over a 1D vector . . . . . . . . . . . . . . . . . . . . . 22 3.9 Max Pooling example over a 1D vector . . . . . . . . . . . . . . . . . . . . . . . 23 3.10 LSTM Cell pipeline. Figure adapted from https://en.wikipedia.org/wiki/ Long shorttermmemory ..................................... 24 3.11 LSTM Unrolled Graph. Adaptation from Figure 6.13 from [21] ......... 25 3.12DropoutExample................................... 25 3.13 Concatenate Layer example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 3.14FlattenLayerexample ................................ 26 3.15 Train sample division in batches and epoch representation . . . . . . . . . . . . 27 3.16 Original adam algorithm (extracted from [24])................... 28 3.17 Computational Graph for a two layer FFN . . . . . . . . . . . . . . . . . . . . . 29 3.18 Sigmoid function and its derivative . . . . . . . . . . . . . . . . . . . . . . . . . 30 3.19 Computational graph for a Deep neural network . . . . . . . . . . . . . . . . . . 30 3.20Unrollinggraph.................................... 31 4.1 Load data in the original scale (minutely data). Gaps represent missing values . 36 4.2 Full Hourly data series for load data. Blank spaces represent NAs in load data, and red values represent missing values in the weather data . . . . . . . . . . . . 38 4.3 Full Hourly data series for weather data. Blank spaces represent NAs in the series 39 85 4.4 Full Hourly data series for load data. Purple shows the dates that will be dismissed due to their different behaviour from what the main series represents . . 40 4.5 Final full Hourly data series for load data after preprocessing . . . . . . . . . . . 40 4.6 Weather data after imputation. Maroon colour indicates the filled values . . . . 42 4.7 HourCodification................................... 43 4.8 WeekdayCodification................................. 44 4.9 Train (blue) and Test (orange) split . . . . . . . . . . . . . . . . . . . . . . . . 45 4.10 Train (blue) and Test (orange) split normalized . . . . . . . . . . . . . . . . . . 45 4.11 Load series for the Wolf education Tammie building ............... 47 4.12 Train Test split for the Wolf education Tammie building............. 47 5.1 Model1scheme.................................... 48 5.2 Model2scheme.................................... 49 5.3 Model3scheme.................................... 49 5.4 Model4scheme.................................... 50 5.5 Model5scheme.................................... 51 5.6 Model6scheme.................................... 51 5.7 Representation of Time Distributed CNN workflow . . . . . . . . . . . . . . . . 52 6.1 Many to one architecture and its adaptation to sequence prediction . . . . . . . 54 6.2 Encoder-Decoder model, showing the conditional output ˆygiven the Encoder Input.......................................... 55 6.3 Encoderpretraining.................................. 56 6.4 Example of a 3 layered Encoder-Decoder Keras graph . . . . . . . . . . . . . . . 56 6.5 Encoder-Decoder combined training and inference . . . . . . . . . . . . . . . . . 57 7.1 Time series prediction for the test data with the best model . . . . . . . . . . . 64 7.2 Real (blue) vs Predicted (orange) for the Wolf education Tammie building with thebestmodel .................................... 65 8.1 Encoder-Decoder different models Time-RMSE on Test. X-axis ticks represent the combinations for Algorithm-Batch Size-Epochs-Number of layers-Neurons per layer-Timestamp codification . . . . . . . . . . . . . . . . . . . . . . . . . . 67 8.2 Sequence Prediction for MTO . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 8.3 Sequence Prediction for 4 different days . . . . . . . . . . . . . . . . . . . . . . . 70 8.4 Sequence Prediction for MTO for the Wolf education Tammie building . . . . . 71 8.5 Sequence Prediction for 4 different days for Wolf education Tammie building . . 72 A.1 LSTMtensorshape.................................. 78 86 List of Tables 2.1 Hour estimation for each subtask . . . . . . . . . . . . . . . . . . . . . . . . . . 12 2.2 Riskidentification................................... 13 2.3 Risk identification revisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 4.1 Open Energy Load datasets from the Wang et al. [1] review . . . . . . . . . . . 33 4.2 Information available in each dataset and type of source . . . . . . . . . . . . . 34 4.3 Techniquesreview................................... 35 4.4 Statistics for variables in the hourly dataframe . . . . . . . . . . . . . . . . . . . 37 4.5 NAs by variable after merging datasets and aggregating by hourr . . . . . . . . 37 4.6 Table of correspondence between NUIG dataset and Met.ie dataset . . . . . . . 41 4.7 Example of One-Hot encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 4.8 Main statistics for the Wolf education Tammie building ............. 46 7.1 Information Input for the models . . . . . . . . . . . . . . . . . . . . . . . . . . 59 7.2 Results for the best model (minimum RMSE) in 5 repetitions for each combination of Model and Time codification when Normalizing . . . . . . . . . . . . . . 60 7.3 Results for the best model (minimum RMSE) in 5 repetitions for each combination of Model and Time codification without Normalizing . . . . . . . . . . . . . 60 7.4 Results for the average RMSE for each combination of Model and Time codificationwhenNormalizing............................... 61 7.5 Results for the average RMSE for each combination of Model and Time codificationwithoutNormalizing ............................. 61 7.6 Information Input for the models with weather variables . . . . . . . . . . . . . 62 7.7 Minimum RMSE achieved for each combination of Model and Time codification. Blank spaces represent combinations that were not trainable due to the lack of power in the computer the experiments were carried with . . . . . . . . . . . . . 62 7.8 Average RMSE for each combination of Model and Time codification. Blank spaces represent combinations that were not trainable due to the lack of power in the computer the experiments were carried with . . . . . . . . . . . . . . . . 63 87 8.1 Average RMSE over 5 repetitions for combinations showed in Figure 8.1, with the minimums highlighted in black . . . . . . . . . . . . . . . . . . . . . . . . . 68 88