Full text
i Dominika Leszko Internship report presented as partial requirement for obtaining the Master’s degree in Data Science and Advanced Analytics Time Series Forecasting for a Call Center in a Warsaw Holding Company Time Series Forecasting for a Call Center in a Warsaw Holding Company
2 NOVA Information Management School Instituto Superior de Estatística e Gestão de Informação Universidade Nova de Lisboa TIME SERIES FORECASTING FOR A CALL CENTER IN A WARSAW HOLDING COMPANY by Dominika Leszko Internship report presented as partial requirement for obtaining the Master’s degree in Data Science and Advanced Analytics Supervisor: Flavio Pinheiro External Supervisor: Pawel Brach April 2020
3 ABSTRACT In recent years, artificial intelligence and cognitive technologies are actively being adopted in industries that use conversational marketing. Workforce managers face the constant challenge of balancing the priorities of service levels and related service costs. This problem is especially common when inaccurate forecasts lead to inefficient scheduling decisions and in turn result in dramatic impact on the customer engagement and experience and thus call center’s profitability. The main trigger of this project development was the Company X’s struggle to estimate the number of inbound phone calls expected in the upcoming 40 days. Accurate phone call volume forecast could significantly improve consultants’ time management, as well as, service quality. Keeping this goal in mind, the main focus of this internship is to conduct a set of experiments with various types of predictive models and identify the best performing for the analyzed use case. After a thorough review of literature covering work related to time series analysis, the empirical part of the internship follows which describes the process of developing both, univariate and multivariate statistical models. The methods used in the report also include two types of recurrent neural networks which are commonly used for time series prediction. The exogenous variables used in multivariate models are derived from the Media Planning department of the company which stores information about the ads being published in the newspapers. The outcome of the research shows that statistical models outperformed the neural networks in this specific application. This report covers the overview of statistical and neural network models used. After that, a comparative study of all tested models is conducted and one best performing model is selected. Evidently, the experiments showed that SARIMAX model yields best predictions for the analyzed use-case and thus it is recommended for the company to be used for a better staff management driving a more pleasant customer experience of the call center. KEYWORDS Machine learning; Time Series Analysis; ARIMA; Forecasting; Supervised Learning; Predictive Models; Artificial Neural Networks; Recurrent Neural Networks; Gated Recurrent Unit; Long Short Term Memory;
4 CONTENTS 1. Introduction .................................................................................................................. 8 1.1. Project description ................................................................................................. 8 1.2. Business contextualization .................................................................................... 9 1.3. Structure of the present report ............................................................................. 10 2. Theoretical framework ............................................................................................... 11 2.1. Time series analysis ............................................................................................. 11 2.1.1. Introduction to Time Series .......................................................................... 11 2.1.2. Time Series Classification Types ................................................................. 11 2.1.3. Time Series Components .............................................................................. 12 2.1.4. Types of Time Series Models ....................................................................... 14 2.1.5. Autocorrelation and Partial Autocorrelation ................................................ 15 2.1.6. Types of Time Series Forecasting ................................................................ 17 2.1.7. Forecast Error Metrics .................................................................................. 17 2.1.8. Cross-validation for Time Series .................................................................. 19 2.1.9. Data Preprocessing ....................................................................................... 21 2.2. Time series forecasting methods overview ......................................................... 23 2.2.1. Evolution of time series analysis .................................................................. 23 2.2.2. Time series forecasting methods .................................................................. 23 2.2.3. Autoregressive Models ................................................................................. 24 2.2.4. Moving Average Models .............................................................................. 26 2.2.5. ARIMA Models ............................................................................................ 26 2.2.6. ARIMAX Models ......................................................................................... 27 2.2.7. SARIMA Models ......................................................................................... 28 2.2.8. ARFIMA Models ......................................................................................... 28 2.2.9. Artificial Neural Networks ........................................................................... 29 2.2.10.Recurrent Neural Networks ........................................................................ 30 2.2.11.Long Short-Term Memory Network ........................................................... 32 2.2.12.Gated Recurrent Units ................................................................................ 33 3. Related work ............................................................................................................... 34 3.1. Possible Time Series Applications ...................................................................... 34 3.2. Time series comparative studies .......................................................................... 34 4. Experiments and discussion ....................................................................................... 37 4.1. Dataset explanation ............................................................................................. 37 4.2. Data exploration .................................................................................................. 39
5 4.2.1. Time series stationarity ................................................................................ 40 4.3. ARIMA Univariate Modelling ............................................................................ 45 4.3.1. Model identification ..................................................................................... 45 4.3.2. Model evaluation .......................................................................................... 47 4.3.3. Model diagnostics ......................................................................................... 49 4.4. SARIMAX Multivariate Modelling .................................................................... 50 4.4.1. Multivariate dataset ...................................................................................... 50 4.4.2. Feature selection ........................................................................................... 51 4.4.3. SARIMAX results ........................................................................................ 52 4.5. Gated Recurrent unit experiment ......................................................................... 55 4.5.1. GRU Base Model Setup ............................................................................... 55 4.5.2. Parameter tuning ........................................................................................... 58 4.5.3. Final GRU model ......................................................................................... 62 4.6. Long-Short term memory experiment ................................................................. 63 4.6.1. LSTM Base Model Setup ............................................................................. 64 4.6.2. LSTM nodes ................................................................................................. 64 4.6.3. Batch size ..................................................................................................... 65 4.6.4. Sequence length ............................................................................................ 65 4.6.5. Learning rate ................................................................................................. 66 4.6.6. Layer setup ................................................................................................... 66 4.6.7. Final LSTM Model ....................................................................................... 67 5. Conclusion .................................................................................................................. 68 5.1. Limitations and future work ................................................................................ 69 5.2. Final thoughts ...................................................................................................... 69 6. Bibliography ............................................................................................................... 71
6 LIST OF FIGURES Figure 1: Trend Component of Time Series ............................................................................. 13 Figure 2: Cyclical Component of Time Series. ........................................................................ 13 Figure 3: Seasonal Component of Time Series. ....................................................................... 14 Figure 4: Additive and Multiplicative Seasonality. ................................................................. 15 Figure 5: Examples of ACF and PACF plots and interpretations. ........................................... 16 Figure 6: Model Complexity Bias-Variance Tradeoff. ............................................................ 19 Figure 7: Walk forward cross-validation technique with window size of one and four .......... 21 Figure 8: Examples of data from autoregressive models with different parameters. ............... 25 Figure 9: Examples of data from autoregressive models with different parameters ................ 26 Figure 10: Recurrent Neural Network Loop ............................................................................ 31 Figure 11: LSTM Memory Cell ............................................................................................... 32 Figure 12: Gated Recurrent Unit Cell ...................................................................................... 33 Figure 13: Univariate Dataset Distribution. ............................................................................. 39 Figure 14: Time Series Component Decomposition. .............................................................. 40 Figure 15: Residuals of original time series. ........................................................................... 41 Figure 16: Residuals of log-transformed time series. ............................................................. 41 Figure 17: Residuals of Square Root-transformed time series. ............................................... 41 Figure 18: Residuals of Box Cox-transformed time series. .................................................... 42 Figure 19: Rolling Mean and Standard Deviation over raw data series. ................................. 42 Figure 20: Rolling Mean and Standard Deviation over transformed data series. .................... 43 Figure 21: Autocorrelation and Partial Autocorrelation plots. ................................................ 46 Figure 22: Autocorrelation and Partial Autocorrelation plots on 1st order differenced data. .. 47 Figure 23: Manually defined model summary. ....................................................................... 48 Figure 24: Automatically defined model summary. ................................................................ 48 Figure 25: Model diagnostics plots. ........................................................................................ 49 Figure 26: Gini feature importance bar plot. ........................................................................... 52 Figure 27: Predictive accuracy of univariate and multivariate SARIMA(X) models. ............. 54 Figure 28: GRU Base model architecture visualization. .......................................................... 57 Figure 29: GRU Base Model predictions over real data for train and test sets. ....................... 57 Figure 30: GRU Final Model predictions over real data for train and test sets. ...................... 63 Figure 31: LSTM Base and Final Model predictions over real data for train and test sets. ..... 64
7 LIST OF TABLES Table 1: Results of Dickey-Fuller test on raw data. ................................................................ 44 Table 2: Results of Dickey-Fuller test on log-transformed data. ............................................ 44 Table 3: Backward elimination results for SARIMAX vs Base Model. .................................. 53 Table 4: GRU parameter tuning: GRU nodes. ......................................................................... 59 Table 5: GRU parameter tuning: Batch Size. ........................................................................... 60 Table 6: GRU parameter tuning: Sequence length. .................................................................. 60 Table 7: GRU parameter tuning: Learning Rate. ..................................................................... 61 Table 8: GRU parameter tuning: Layer Setup. ........................................................................ 62 Table 9: LSTM parameter tuning: LSTM nodes. ..................................................................... 65 Table 10: LSTM parameter tuning: Batch Size. ...................................................................... 65 Table 11: LSTM parameter tuning: Sequence Length. ............................................................ 66 Table 12: LSTM parameter tuning: Learning Rate. ................................................................. 66 Table 13: LSTM parameter tuning: Layer Setup. .................................................................... 67
8 1. INTRODUCTION In recent years, call centers have been revolutionized by the data. Even though some static onesize-fits-all strategies, as well as, static call scripts still remain, technology has changed significantly the way that call centers are functioning. The power of call centers remains in the huge amounts of data that such institutions gather when interacting with customers. It is possible for call center agents to know yet before receiving the call many crucial characteristics of the customer, such as which advertisement he has seen, what age range he falls into and what is his expenditure tendency. Naturally, as the time passes by, the customer database becomes larger and finally powerful enough to enable the call center to leverage all available data and drive appropriate interaction with each customer. American Express proved that 78 % of consumers have resigned from making an intended purchase due to poor customer service experience (2017, American Express Barometer). This is a clear sign that call centers must direct their focus onto a seamless and convenient experience for customers, unless they are ready to risk losing out on a competitor. To ensure that such scenario does not happen, more and more call centers are turning to technologies, such as Artificial Intelligence, Machine Learning and Time Series Analysis in order to provide them with useful insights. Layering in AI can include call volume forecast for better resource management or customer churn to determine appropriate marketing strategies, next best action, and more. Below report will present one of many possible applications of Statistical and Machine Learning methodologies aiming at improvement of operational efficiency in the life cycle of a Call Center. 1.1. PROJECT DESCRIPTION At the second year of the NOVA IMS master program in Data Science and Advanced Analytics, I have enrolled in the internship program at a Holding Company (Company X) in Warsaw, Poland. The below report is a summary of the analytic activities developed by me as an intern during that period. During the internship, I joined the analytical team, which was mainly in charge of providing data visualizations in the form of BI dashboards, performing ETL processes and building a reliable Data Warehouse. The main focus of my work was to identify Machine Learning opportunities within the umbrella of organizations to improve and automate the decision making processes. After throughout analysis of possible AI implementations and a number of discussions with business decision makers within the company, it has been agreed that the biggest need for automated optimization is currently laying in the subsidiary company providing Call Center service. More
9 specifically, the main challenge that the Call Center is currently facing is the consultants’ inefficient time management. Since the number of inbound phone calls is very unexpected, current call load balancing proves to be inefficient, often leading to either inactive at work agents as phone call frequency drops, or, on the other hand, insufficient number of calling agents at peak times. The latter often leads to dissatisfaction of customers caused by extended waiting time to be served by the consultant. This problem was previously attempted to be tackled within the company by means of a simple estimation that the phone call volume at the X following time steps would be equal to its average of X proceeding days. This solution did not result in a satisfactory accuracy, neither did it take advantage of the data stored at the Media Planning section of the company. This being said, the company’s solution leaves a lot of room for improvement given the relatively poor prediction quality. Last but not least, it is worth mentioning that accurate predictions of the inbound phone calls will bring value to not only the Call Center itself, but also, to the Supply Stock Management, as well as, Delivery Management Teams, which will have a better idea on which days more products will need to be available in stock for shipping. Finally, in the work reported in this document, we aimed to combine business knowhow and data engineering practices to gain the best prediction possible of the number of inbound phone calls for each of the next upcoming 40 days. Ultimately, we aimed to generate a series of predictions of customers’ responses to press-published advertisements of dietary supplements with the use of provided data that was collected by the company in the last 2 years. As aforementioned, accurate predictions would help in different areas of company’s activities, such as Delivery, Supply Stock Management and foremost in the Call Center’s staff time management, ultimately leading to a better Customer Experience and to a better company’s image in the market. Last but not least, another objective of the internship was to make a thorough and diversified research of the most optimal model for the analyzed use-case, including univariate and multivariate models, statistical models and recurrent neural networks. 1.2. BUSINESS CONTEXTUALIZATION The work described in this report was developed during an internship in a Holding Company (Company X), consisting of an umbrella of brands, such as marketing agency, call center agency, logistics provider, software house, financial services provider, beauty service and employment agency.
16 Below figure (Figure 5) represents a set of ACF and PACF plots for a sample series of data. The description of each scenario, as well as, possible interpretations of autoregressive and moving average terms has been presented below. Figure 5: Examples of ACF and PACF plots and interpretations. (Robert Nau, 2019) The visualization in the top left panel is an autocorrelation plot of the raw data. The autocorrelations look highly significant up to the 13th lag, which may be caused by the previously described propagation of autocorrelation at lag 1 (chaining effect). That is why, the top right panel of the Figure 5 represents a partial autocorrelation plot of the same series. Looking at the PACF plot, it is clear that lag-1 autocorrelation explains all remaining autocorrelations at the higher lags which are below the red line of significance level. This being said, it is safe to conclude that AR(1) model would be appropriate for the above series. Another possible approach to modelling above series is to perform a 1st order of non-seasonal differencing as a pre-processing step. The ACF and PACF plot of differenced data has been plotted in the bottom left and right panel of the Figure 5, respectively. Comparing the two graphs, it is clear that autocorrelations decay slower in the ACF plot, where all spikes up to 4 are significant, while in the PACF only the 2 initial spikes appear to be significant and then they shut off. This being said, the analysis of ACF and PACF plots on differenced data suggests modelling the series by means of the ARIMA(2,1,0) model, where 2 stands for the
17 autoregressive term, 1 indicated the order of differencing, and 0 means no moving average term used. 2.1.6. Types of Time Series Forecasting Time series forecasting refers to predicting the future the most accurately as possible based on the information recorded at previous time steps. Based on the dimensionality of the analyzed data, Time Series Forecasting can be divided into two types: - Univariate Modelling - Such forecasting methods use only the time and target value as inputs for modelling. An example of Univariate Modelling can be forecasting of the sales volume based on sales volumes recorded in the past. - Multivariate Modelling – often a more efficient way of predicting a series of future values thanks to the advantage of using any additional information, such as knowledge of any future events which may impact the forecasts. Such models, where other than only time features are also used, can often make up for some fluctuations caused by some external factors, which could not be explained by regular trend, cycle or seasonal time components. An example of a multivariate modelling use-case can be a forecast of the air temperature based on not only air temperatures recorded in the past, but also, using the information about the rainfall, air humidity and the sunlight. 2.1.7. Forecast Error Metrics The common goal of statistical predictions is to minimize the error of the predictions. The error can be defined as the difference between the forecast and its observed value. In time series, we should not understand the “error” as a mistake, but rather as a part of the observation, which is unpredictable. The formula for error calculation can be found below, where {y1, … ,yT} are the train data, while {yT+1, yT+2,…} are the test data. 𝑒𝑇+ℎ=𝑦𝑇+ℎ|𝑇− 𝑦𝑇+ℎ|𝑇 (3) The errors differ from previously described residuals in two aspects. First of all, while residuals are calculated on the training set, the error is calculated on the validation set. Additionally, forecast errors can involve multi-step forecasts, which is not the case for residuals, as these are based on one-step forecast only. There is a number of forecast error metrics which vary in different kinds of information used to identify the prediction accuracy. These can be classified into 3 categories:
18 - Scale-dependent errors As the name suggests, scale-dependent errors cannot be used to compare between series involving different units, as they are scale dependent and expressed in some particular units. The most commonly used scale-dependent accuracy measures are based on absolute errors or squared errors, such as: 1. Mean Absolute Error (MAE) – an easily interpretable metric which treats errors in absolute terms, i.e. error of 10 is treated twice as bad as error of 5. 𝑀𝐴𝐸=1𝑁∑|𝑍(𝑡)−𝑍(𝑡)| 𝑁 𝑡=1 (4) 2. Root Mean Squared Error (RMSE) – gives a higher weight to large errors, penalizing them when they are very undesirable. 𝑅𝑀𝑆𝐸=√1𝑁∑(𝑍(𝑡)−𝑍(𝑡)) 𝑁 𝑡=1 2 (5) - Percentage errors Percentage errors solve the problem of being scale-dependent, making a comparison of various time series possible, regardless of the units expressed in the time series. On the other hand, percentage errors’ downside is the fact that they are infinite or undefined if the true value that we are trying to predict equals zero. This being said, intermittentdemand data predictions should not be measured with the use of percentage errors due to zero demand values present in the series. Additionally, in case actual values oscillate around zero, the distribution of percentage errors can be very skewed. The two most commonly used percentage errors involve: 1. Mean Absolute Percentage Error (MAPE) – an easily interpretable metric with a drawback of more heavy penalization on negative forecasting errors as compared to the positive forecasting errors. 𝑀𝐴𝑃𝐸=1𝑁∑|𝑍(𝑡)−𝑍(𝑡)| 𝑍(𝑡) 𝑁 𝑡=1 ∙100% (6)
19 2. Symmetric Mean Absolute Percentage Error (sMAPE) – a modified version of MAPE, created in the M3-competition (Makridakis & Hibon, 2000). The motivation behind this metric is to cancel the heavy penalization on negative forecasting errors, which is present in the classic MAPE metric. The downside of sMAPE is the fact that it does not eliminate the problem of division by a number close to zero, as a result it may lead to infinite error values for certain predictions. Finally, it is negative sMAPE values are possible making the interpretation ambiguous. 𝑆𝑀𝐴𝑃𝐸=1𝑁∑|𝑍(𝑡)−𝑍(𝑡)| (𝑍(𝑡)+𝑍(𝑡)) 𝑁 𝑡=1 ∙200 (7) 2.1.8. Cross-validation for Time Series “It can not be emphasized enough that no claim whatsoever is being made in this paper that all algorithms are equivalent in practice in the real world. In particular no claim is being made that one should not use cross-validation in the real world.” - Wolpert (1994a) It is important to appropriately estimate the accuracy of a model not only to predict the future prediction accuracy but also for choosing the best of the analyzed models (aka model selection) (Wolpert). The goal is to create a model yielding predictions with low bias and low variance. In order to correctly assess the results of statistical analysis or model-generated predictions, we need to ensure that our model will generalize to an independent data set. One way to achieve this is by applying cross-validation methodology. The motivation to use crossvalidation techniques is to verify how well the model will perform in practice, i.e. outside of a training set (in-sample data). Finally, cross-validation can also give us insights about potential underfitting (high bias, low variance) or overfitting (low bias, high variance) of the model. Figure 6: Model Complexity Bias-Variance Tradeoff. (Scott Fortmann-Roe, 2016)
20 The two most common cross-validation techniques involve leave p out and K-fold crossvalidation. The former randomly selects p samples as the validation set, using the rest of the samples as the training set. The latter creates random K equal-size partitions of the data, each of which is in turn used as a validation set, while the remaining K-1 subsets constitute for the training set. Unfortunately, there is a number of problems arising from applying these methods for Time Series Predictions: - Autocorrelation along the time axis is a common component of a time series data. An example of such autocorrelation is car traffic, which affects all drivers on the route across consecutive time points. The randomization will most likely lead to presence of strong correlation of data samples from validation set and from the training set. Such phenomena breaks the purpose of validation set, which should be previously unseen by the model. In such case, the model virtually ‘knows’ about the validation set apriori, leading to the artificially good prediction accuracy, which is a sign of overfitting. - Time series is a time-ordered series of data, in which past observations are used to predict the future. Standard cross-validation techniques involve randomization, which does not preserve the time ordering. A negative side-effect of traditional crossvalidation for time series would be generating predictions for some samples using a model trained on posterior data points. In the answer to above issues, a new cross-validation approach has been created for Time Series Predictions. One such methodology is known as Walk-Forward Cross Validation. This cross-validation technique involves arranging the data from past to present and splitting it to k equal blocks of contiguous samples, deciding that first p blocks will constitute a train set. This way, the training set consists of the blocks from 1 to p, while block p+1 is the validation set. After, the splits successively shift to the right, making the following split’s training set consist of blocks from 2 to p+1 and the validation set p+2, and so on. In this way, the ‘walking forward’ methodology leads to k-p splits. The visual representation of this methodology is presented at the Figure 7 below with the blue points representing training data and red points representing the validation data. For the final prediction accuracy, the chosen performance metric is averaged across the different folds. Of course, walk-forward cross validation allows to expand the validation period by more than one, i.e. it is possible to perform cross-validation
21 for weekly or monthly prediction (expanding the validation window by 7 or 30 data points, respectively and considering daily data). Figure 7: Walk forward cross-validation technique with window size of one and four (Hyndman, R.J., & Athanasopoulos, G., 2018) 2.1.9. Data Preprocessing 2.1.9.1. Data Transformation The main focus of time series data preprocessing lays in the data transformation methods. The most commonly used four data transformation methods for time series predictions include: - Power Transform – makes the distribution more similar to Gaussian by removing a shift from data. In a time series dataset, it can be seen as a stabilization of variance over time. Some common examples of power transform methods include square root, cube root and log transformations. - Difference Transform – this transformation is commonly used in order to make the mean, variance and covariance of a time series constant across time, i.e. in other words, stationary which is a prerequisite of some popular forecasting models (e.g. ARIMA). The 1st order differencing often helps to remove trend from a series of data, while kth differencing on a series with seasonality of length k should help remove the seasonal fluctuations. Difference transform methods are usually applied iteratively until the time series becomes stationary. - Standardization – makes the distribution of the data similar to Gaussian. Standardization primarily consists of subtracting the mean and then dividing the result by a standard deviation of the data sample. As a result, transformed data has a mean of 0 and a standard deviation of 1, making it a standard Gaussian distribution.
22 - Normalization – a very common in Machine Learning transformation method leading to a scale adjustment within some boundaries (usually <0,1>). Such transformed time series is easier to be predicted by a forecasting model and often provides a better accuracy. 2.1.9.2. Missing Values Imputation Missing values in a time series can be a result of a natural process, e.g. in the in-store sales time series there is no sales recorded on public holidays. Introducing a dummy variable indicating whether a given day is a public holiday is a possible way to approach such problem, avoiding the sales underestimation on the first day after the public holiday and then overestimations in the following days. However, in real-life dataset, the missing values are often not the result of a natural process but appear to be rather random. In such cases, the cause of missing values may be simply a device malfunction which did not record the data when needed or a human error in case the data is entered manually. In such scenarios, we can either take advantage of the models which work flawlessly even with missing data (e.g. Naïve Forecast) or make use of missing values imputation methods. One way the null values in a time series may be imputed is by taking the series of data after the last missing value and generate a forecast of the next missing value, in effect replacing it with that prediction. Alternatively, it is possible to use simple computation methods like mean, median or mode imputation. In case of time series, however, there is also some special imputation methods, which include: Last Observation Carried Forward (LOCF), Next Observation Carried Backward (NOCB) and Linear Interpolation. The latter imputation methods rely on the assumption that adjacent observations are similar to each other, thus they do not work well when this assumption is not satisfied, especially in the presence of strong seasonality. 2.1.9.3. Outlier Imputation Outliers are defined as observations that are very different from the majority of time series’ observations and can be seen on time series plots as sudden spikes or falls. As in the case of missing values, they can be simply erroneous data caused by e.g. a human error who entered the data manually or by a device malfunction. A common practice is to replace outliers with imputation methods described above in order to force the data to be more consistent with the majority of the series. One needs to be careful about replacing outliers without making sure that
23 these are in fact erroneous data, as they may often provide useful information about the underlying process which should be taken into consideration in the forecasting process. 2.2. TIME SERIES FORECASTING METHODS OVERVIEW 2.2.1. Evolution of time series analysis In the nineteenth century early attempts to study time series were mostly based on the idea of a deterministic world until 1927, when the first major breakthrough in the area of time series forecasting took place essentially thanks to the contribution of Yule who introduced the notion of stochasticity in the time series. Simply put, Yule stated that every sequence of such data can be considered as the realization of a stochastic process, making this simple idea the base of further developed time series concepts over the years. More innovative forecasting concepts include the concept of autoregressive (AR) and moving average (MA) models formulated by Slutsky, Walker, Yaglom and Yule. Further, Kolmogorov (1941) proposed a solution to the linear forecasting problem relying on the idea of Wold’s decomposition theorem. After that, a vast research about time series parameter estimation, identification, model diagnosis and forecasting has been developed until a crucial revelation in the area of time series development was included in the publication by Box & Jenkins (1970, 1976) which was a vital integration of so-far existing knowledge. The book, making an enormous impact on the theory and practice of modern time series analysis and forecasting is also known for introducing a concept of Box- Jenkins approach, which is essentially a coherent, versatile three-stage iterative cycle for time series identification, estimation and verification. Investigation of time series forecasting methodology is remaining active until today with new approaches and extensions are being tested. 2.2.2. Time series forecasting methods Time series forecasting falls onto a category of quantitative forecasting methods and serves a purpose to predict the manner in which the sequence of observations will continue into the future, using the series of past data collected at regular intervals of time (hourly, daily, weekly etc.). Since there is a number of time series forecasting methods and none can be objectively indicated as better than other, an appropriate model selection needs to be made. Before deciding on the model type to be used, one needs to take into consideration both, time and computation resources, the data available, the accuracy of the competing models, as well as, the manner in which the forecasting model will be used. It is important to notice that time series forecasting
24 methods vary significantly in complexity. Some time series forecasting methods are as simple as a Naïve Forecast, which simply put, sets the all forecasts to be equal to the value of proceeding observation. This method is appropriate for data, which follows a random walk, such as economic or financial time series data, and is also known as a Random Walk Forecast. 𝑦𝑇+ℎ|𝑇=𝑦𝑇 (8) Naïve Forecast can also be applied to a seasonal time series, where the forecast values are set as the last observed value of the same season of the year (e.g. the same day of previous week). 𝑦𝑇+ℎ|𝑇=𝑦𝑇+ℎ−𝑚(𝑘+1) (9) Finally, another variation of the simplest forecasting methods has been created and named as Drift Method. Drift forecast model allows the forecasts to fluctuate up and down over time and sets the drift (i.e. change over time) to the average change recorded in the historical data. These models do capture the trend component but fail to do so with the seasonal component. 𝑦𝑇+ℎ|𝑇=𝑦𝑇+ℎ 𝑇−1∑(𝑦𝑡−𝑦𝑡−1) 𝑇 𝑡=2 =𝑦𝑇+ℎ(𝑦𝑇−𝑦1 𝑇−1)(10) In addition to the above extremely simple and surprisingly effective time series forecasting methods, more advanced and widely used nowadays methods will be described and studied in the sections below. 2.2.3. Autoregressive Models Similarly to multiple linear regression, where variable of interest is forecasted with use of a linear combination of predictors, the autoregressive models (AR) uses a linear combination of past values of target variable in order to predict the next values in the series. Thus, the autoregression term indicating that it is a regression of the target variable against itself. This model is suitable for a time series not exhibiting any trend nor seasonal components (stationary time series). An autoregressive model of order p AR(p) can be written as: 𝑍𝑡=𝜙1𝑍𝑡−1+𝜙2𝑍𝑡−2+⋯+𝜙𝑝𝑍𝑡−𝑝+𝑎𝑡 (11) , where at represents white noise, putting an assumption that any element in a time series can be represented as a random draw from a population distribution with constant variance and mean centered at 0.
25 Another possible notation for the AR(p) is following: 𝜙(𝐵)𝑍𝑡=𝑎𝑡 (12) with a backshift operator defined as: 𝜙(𝐵)=1−𝜙1𝐵−𝜙2𝐵2−⋯−𝜙𝑝𝐵𝑝 (13) The effect of backshift (aka Lag) operator is shifting the data back by one period. One single application of a backshift operator results in one backward shift of the data, while two such applications lead to shifting the data twice. In case the underlying process units are months and we wish to look at the data “same month last year”, then the appropriate notation looks as following B12yt=yt-12. Backshift operator is very useful when expressing the order of differencing applied in the time series data preprocessing phase. Finally, the variance of a white noise process is estimated from the data. There is no one best method to determine the correct order of autoregressive term for underlying process. Obtaining the right model should be the effect of trial and error supported with the guidance of Autocorrelation and Partial Autocorrelation Plots analysis. Optionally, one can use built-in functions provided by many data analysis softwares, such as auto.arima in pmdarima Python package, which conduct a search of all possible models, returning the one with the highest accuracy according to AIC, AICc or BIC criteria. It is worth noticing that models returned by such built-in functions will not always result in the highest possible accuracy, as criteria used in the search penalize for a number of parameters in the model for a lower model complexity. Below figure (Figure 8) illustrates two examples of Autoregressive Models. Figure 8: Examples of data from autoregressive models with different parameters. (Hyndman, R.J., & Athanasopoulos, G., 2018)
32 the data sequence is, the further the gradients need to carry the information used in the RNN parameter update, making these updates become extremely small, in effect not learning at all. According to (Xavier et al 2011) ReLU activation function slows down the vanishing gradient problem, as compared to the sigmoid function. 2.2.11. Long Short-Term Memory Network Long Short Term Memory networks are a special kind of recurrent neural networks, which can deal better with the gradient vanishing problem, making LSTMs capable of learning long-term dependencies. Hochreiter & Schmidhuber (1997) were the ones to introduce and popularize this algorithm. LSTMs are known for their outstanding accuracy, when its parameters are carefully set-up. Additionally, remembering long-term dependencies is something that they are cut out for. The structure of this powerful algorithm has been presented below: Figure 11: LSTM Memory Cell (Christopher, 2015) LSTMs, just like standard RNNs, are in the form of a chain of repeating modules. What differs them however, is the structure of these modules, as instead of having a single neural network layer in each as classical RNNs do, they consist of four layers interacting with each other in a precise way. The horizontal line running across above part of the diagram presents the core idea behind LSTM and is known as the cell state. The main role of the cell state is to propagate the information, leaving it unchanged, adding relevant and removing irrelevant pieces of information which is structured by the gates. The forget gates are composed of a sigmoid layer and a point-wise multiplication operation. The output of the sigmoid layer is a value between zero and one, determining how much information should be let through (and forgotten) into the cell state. The next step is the input gate, which is essentially a hidden layer of sigmoid activated nodes, outputting values between 0 and 1 that are able to control the amount of input which will flow into the unit. The tanh layer creates a vector of new candidate values which can be added
33 to the state. Finally, the output gate determines with the use of a sigmoid function which values of the state will serve as the output from the cell. The flexibility of LSTM is provided thanks the number of gating functions controlling what needs to be forgotten and remembered by the network. However, as Machine Learning is known to be a science of trade-offs, here is no exception made, and thus the flexibility of LSTM also comes with the cost of a big number of parameters that need to be fine-tuned for the network to perform efficiently, making it computationally expensive to train. 2.2.12. Gated Recurrent Units A gated recurrent unit has been introduced by Cho, et al. (2014) as a newer generation of RNNs. It works similarly to LSTMs with two main differences: instead of a cell state, GRU uses a hidden state in order to propagate the information. Additionally, GRU has only two gates: a reset and update gate. Gated recurrent unit has been introduced as an alternative to LSTMs, which would be still able to avoid the vanishing gradient problem, but would not have such a big number of parameters to tune and would be less computationally complex. In addition, according to the research of Tang, et al. (2017), GRU is more robust to noise as compared to LSTM and it tends to outperform LSTM in several applications. The GRU unit architecture has been presented in the diagram below: Figure 12: Gated Recurrent Unit Cell (Christopher, 2015) The update gate in a GRU unit serves a similar purpose as the forget and input gates of an LSTM, i.e. it controls the amount of past information that needs to be passed to the next step, as well as, what new information to add. The reset gate on the other hand is used to determine the amount of past information to forget. Due to the fact that GRU unit consists of only two gates, it is faster to train as compared to LSTM.
34 3. RELATED WORK 3.1. POSSIBLE TIME SERIES APPLICATIONS The analysis of experimental data recorded at different points in time requires a special approach as it leads to new and unique problems in the field of statistical modelling and inference. This is mainly due to the nature of time series breaks the assumption of many conventional statistical methods, which rely on the fact that the observations are independent and identically distributed. The below-described list of fields where time series problems may arise is a proof of the impact that time series analysis may have on diverse scientific applications. One of the most common time series applications can be found in the field of economics, where daily stock market quotations or monthly employment rates need to be analyzed and predicted. Other examples of time series analyses’ applications include sociodemographic series, such as school enrollments, birth rates, gender or fertility tendencies. In medicine, on the other hand, analysis of blood pressure measurements over time might be useful for evaluating drugs used in treating hypertension. Time series in combination with computer vision in the form of a series of magnetic resonance imaging can be effective for analysis of the brain’s reaction to certain stimuli under various experimental conditions. Finally, a number of sophisticated applications of time series methodologies have been practiced in the environmental and physical sciences. This being said, the monthly sunspot numbers are one of the earliest recorded series studied by Schuster (1906). Environmental sciences rely on time series also in more modern investigations, such as global temperature measurements and analysis of global warming evolution. Speech series modelling is another important area where time series analysis is used and it makes the transmission of voice recordings efficient. Rainfall and air temperature may also be predicted based on geophysical time series. Finally, seismic recordings over time can be useful to differentiate the earthquakes from nuclear explosions. Above listed examples of time series analysis applications are just a few of all that are being used nowadays. 3.2. TIME SERIES COMPARATIVE STUDIES There is a number of studies focusing on comparison of traditional time series analysis methodology with the methods from the family of Artificial Neural Networks. With the use of a dataset from the famous “M-3 competition” Foster, et.al. (1991) proved that deep neural networks are inferior to the least squares statistical models for a yearly tie series data. The results of studies conducted by Sharda and Patil (1992) and Tang, et.al. (1991) argued that for
35 a large number of observations, ANN models and Box-Jenkins models deliver similarly good results. Kang (1991) observed in his study comparing 18 different neural network architectures that forecast errors tend to be smaller for the series which contain the trend and seasonal component. Additionally, according to Kang the neural networks often outperform the simple statistical time series forecasting models in the long horizon forecast periods. Another study comparing neural networks to the traditional forecasting methods have been performed by Hill, et.al. (1996) who compared his forecasts to those obtained by Makridakis, et.al. (1982) and concluded that ANNs do better for monthly and quarterly series. Another conclusion driven by their study is that fewer network parameters to be estimated is crucial to successful neural network modelling. Kohzadi, et.al. (1996) is the owner of a very controversial statement, that he has made based on his empirical investigation aiming at comparing the forecasting performance of ANNs to ARIMA model: “The neural network with only one hidden layer can precisely and satifactorily approximate any continuous function” (Kohzadi, et.al., 1996, p.179). Kohzadi, et.al. (1996) has also concluded that ANNs are more efficient at catching the turning points of the series when compared to ARIMA model. However, some of the studies conducted by Adya and Collopy (1998) based on 48 articles published between 1988 and 1994 resulted in contradicting to Kohzadi’s statements, indicating that real-world data may not always be consistent with theoretical inferences. Even though a big part of the time series literature is focused on modelling time series data and comparing the performance of various competing models, Gorr, et.al. (1994) used cross section data to predict the values of student grade point averages and compared the predictive power of a linear regression and a stepwise polynomial regression versus the ANN. Based on these studies, they have concluded that the mean errors of forecasts generated by different models were not comparable as none of the models was significantly superior compared to the others. This result has been justified by the selection ANN structure. However, it can be also argued that another reason for the unsatisfactory results delivered by the neural network is the fact that qualitative binary variables have been used in 6 of the models. In such cases, ANN learning algorithm may not work well due to the large numerical distinction in the observations between the binary and continuous variables. The effect of a time series stationarity on the forecasting performance of the statistical and deep learning models has been tested by Lachtermacher and Fuller (1995) in their study of a series of annual river flows. Lachtermacher and Fuller followed Box-Jenkins methodology to produce an ARIMA model, as well as, the ANN model. They have concluded that the ANN
36 delivered better prediction results as compared to the ARIMA model. Additionally, the forecast improvement was much higher for the models trained on non-stationary data, meaning that stationary data is essential for good quality traditional forecasting models. This is consistent with the study of of Tang, et.al. (1991). Nelson, et.al. (1999) focused on emphasizing the effect of seasonal component on the time series forecasting accuracy. Comparison of ANN with Box- Jenkins methodology forecasts made in this study indicated that in case of a seasonal time series, ANN forecasts can deliver better quality forecasts when trained on de-seasonalized data as compared to the model trained on the raw, non de-seasonalized data. A number of studies on time series predictions of macroeconomic phenomena have proved to be problematic to capture by linear models, which is caused by the non-linear nature of macroeconomic relations. Maasoumi, et.al. (1994) constructed a Neural Network to predict US macroeconomic series, such as GDP, wages, Price Index or unemployment rate. The downside of this study is lack of comparison between different models and as a result it has been only interpreted that the sample results fails to show the prediction power in the underlying study. Swanson and White (1997) delivered comparably more clear conclusions in their study where they have applied an ANN model to forecast 9 macroeconomic series, comparing its predictive power to traditional forecasting methods. The results of this study are not clear cut, however, Swanson and White do conclude that ANN models have a good forecast performance as compared to the traditional approaches even if there is no clear evidence of nonlinearity in the data. Moshiri and Cameron (2000) on the other hand proved in their comparative studies of linear and non-linear inflation rate forecasting approaches that artificial neural networks perform equally well as econometric models but they tend to outperform the latter ones in some cases.
37 4. EXPERIMENTS AND DISCUSSION This section of the report is dedicated to present the empirical work, which goal is to develop time series forecasting models and compare their performance to find the most optimal modelling approach. To start with statistical modelling, Box Jenkins methodology was used to identify an optimal ARIMA model. This approach leads to a linear prediction on a univariate time series. Secondly, the ARIMA model has been extended to capture the seasonality component leading to a development of a SARIMA model. Finally, another attempt to increase the model accuracy has been made by adding a set of exogenous variables which could boost the predictions’ accuracy. This way, SARIMAX model has been produced, which is the first multivariate modelling case studied in below dissertation. After statistical modelling, deep learning methods from the family of recurrent neural networks have been explored, such as Gated Recurrent Unit and Long-Short Term Memory models. In these methods, only multivariate modelling approach has been tested due to the fact that neural networks are able to perform an automatic feature selection by setting the appropriate weights to the connections between the neurons. Finally, different architectures of neural networks have been tested and their impact on the predictive power was presented. According to the No Free Lunch Theorem any forecasting model might work the best for our particular problem, thus all of above forecasting methods have been compared and one model with the best predictive power has been selected as the final result. 4.1. DATASET EXPLANATION After the research of possible opportunities for modelling within the company and ideas prioritization alongside the business analysts, prediction of call center arrivals in response to the press-published advertisements has been selected as the goal of this project. The first fundamental step was concerning the access of the data. The call center data is of incidencebased structure, i.e. each time a customer was contacting the call center, a new data point was recorded in a database stored in a SQL server (event-driven data). The data concerning the inbound phone calls is distributed across multiple tables, thus the first goal is to consolidate and export all needed information into one dataset, which would be easily fed onto forecasting models afterwards. Additionally, the data regarding the strategy details of press advertisements, including newspaper titles, where ads would be published, ad formats, the costs associated with ad placement, etc. was stored in a comma-separated values file (.csv), thus it also needed to be
38 aggregated with the data about incoming phone calls to limit the various database connections needed to fetch the data onto the models. For the first, incidence-based dataset regarding phone call arrivals a set of data cleaning actions were necessary. First of all, the data has been filtered to include only the phone calls incoming as dialed to press-published phone numbers, indicating that they were related to press marketing campaigns. Each such successfully collected by an agent phone call was treated as one lead attracted by the ad. Then, the records marked as fraud phone calls, as well as phone calls with erroneous call start and end timestamps (call picked up later than ended) have been filtered out not to introduce noise onto the model. Finally, phone calls which were outbound (call-backs made by call center agents), never picked up by a call center agent or interrupted for some reason were also filtered out as a result of business decision and company’s definition of a lead, which is internally considered as a unique inbound phone call, collected by an agent and correctly recorded by the system. After the data cleaning process, in order to keep the uniformity of a time index across the dataset, a stored procedure in SQL server was used to import the time series data aggregated to a daily incidence dataset on a uniform time index. This exported from SQL server data constituted the first dataset used for modelling, which was univariate and only contained the timestamp along with the number of phone call arrivals on that day which were related to press-published advertisements. The other dataset prepared for forecasting included incidence-based data related to exogenous variables used for multivariate forecasting. More specifically, this dataset contained information about marketing strategic plans for press-published advertisements, such as the timestamp of when the ad is planned to be published, the ad format, the cost associated with the ad publishing, the name of the publisher, as well as, the newspaper name. Firstly, a business decision has been made to select the relevant features which can affect the press-published ads’ efficiency, which in turn translate into a bigger number of phone calls received by a call center. Secondly, since time series forecasting can be framed as a supervised learning problem in a way that whichever series of training data is provided to the algorithm for training, it also requires to be provided with the future values of these training features for the model to predict on further time steps. This being said, in case of a monthly univariate model prediction, we only need to pass it a set of following thirty time stamps so the model knows what to predict on. In case of multivariate forecasting, however, we need to be able to provide the algorithm with a series of future values of all exogenous variables used in the model training phase. That is why, some features included in the press marketing plans .csv file needed to be excluded from a final dataset used for modelling, as they are not planned as early as 40 days in advance, which is a
39 prerequisite for that model taking into account the business requirement to deliver inbound press-related phone calls forecasts for the next 40 days. Finally, after taking into consideration above feature exclusions, which were mostly the results of business decisions, the multivariate dataset has been aggregated to the daily timestamp level (it was possible for more than one ad to be published on one day). Each time step is assigned with the following set of values: an average number of ads published, average cost spent on ad publishing, average ad format, the number of ads published by specific publisher and the number of ads published in a specific newspaper. To conclude, the data extraction process led to a creation of two daily-aggregated datasets, the univariate one about call center inbound press-published ads related phone calls, and a multivariate one, with information about published ads on specific days. Both datasets are based on uniform time series indexes and cover the time period between September 2017 and October 2019, making up 810 data points in total. 4.2. DATA EXPLORATION The first step taken in the data exploration phase is to visualize the target variable in its original form, as received from the company and try to understand the hidden insights or patterns in it. The below figure presents the time plot of collected call center arrivals regarding the presspublished ads (internally considered as Press Leads). Figure 13: Univariate Dataset Distribution. Above visualization of call center press leads across the years 2017-2019 suggests that the data is not evenly distributed along the timeline and some clear trends are visible, as well as, seasonal patterns. Due to these clear fluctuations, we can state that the underlying data is not a white noise process, as its mean and variance are not constant over time. This being said, we assume
40 that the time series is not stationary in its raw form and will most likely require a set of data transformations to become stationary and comply with the necessary prerequisites required by ARIMA models. Further testing and transforming of the data into its stationary form is described in the sections below. 4.2.1. Time series stationarity Stationarity of a time series have been tested in three steps, starting with seasonal decomposition of a time series to visualize trend, seasonality and the residual components existing in the underlying process. Further, a set of data transformations were applied as an attempt to make the residuals more stationary. After that, rolling statistics of the time series were plotted to verify whether the mean and standard deviation of the series is constant over time. Finally, statistical tests were used to verify the hypothesis whether the time series satisfies the stationarity conditions. 4.2.1.1. Time series decomposition To start with, for a more thorough picture of existing tendencies in the data, a seasonal decomposition of the time series has been plotted and presented below: Figure 14: Time Series Component Decomposition. Above visualization of a univariate time series data presents raw series, as well as, 3 of its components individually: trend component, seasonal component, random error component. This way, it gives a clearer view on each of them, often providing valuable insights which impact the underlying process. Looking at above-presented seasonal decomposition of call
41 center’s press leads, we can deduct that there is a nonlinear trend component, which has an upward direction until July 2018 and then it goes downward until January 2019, staying approximately constant or slightly upward all the way until October 2019. Another insight provided by the above plot is a strong seasonal component of order 7 present in the data. Finally, the residual component should be centered around zero and have a constant variance for it to be independent of time and stochastic in nature. As long as the former condition is met, as we can see that mean of the residuals is centered at zero, ensuring unbiased forecasts, we cannot be so confident about meeting the latter condition due to the less stable variance in the period between April and September of 2018. As an attempt to reduce observed residuals’ heteroscedasticity, following data transformation methods have been tried out with resulting residuals across time plots presented below: - Residuals of original time series (Benchmark) Figure 15: Residuals of original time series. - Residuals of time series after Log Transformation log(x+1) Figure 16: Residuals of log-transformed time series. - Residuals of time series after Square Root Transformation Figure 17: Residuals of Square Root-transformed time series. - Residuals of time series after Box Cox Transformation (lambda = 0.416259)
48 Figure 23: Manually defined model summary. Above summary indicates that association between the target variable and both, seasonal and non-seasonal moving average terms is significant due to the p-values associated with respective terms, which are lower than the threshold of 5 %. The Akaike Information Criterion (AIC) score is a measure of how well the model fits the data avoiding overfitting by penalizing overly complex models. Even though the value of AIC does not say much, it is widely used to compare competing models and selecting the one with the lowest AIC score. In above-tested model, the AIC is equal to 9835.940. Next, we will check if auto.arima function from pmdarima Python package which performs an automatic search for the best possible model is able to find a better model with lower value of AIC. Figure 24: Automatically defined model summary.
49 The auto.arima function returned a SARIMA(1,1,2)(1,0,1)_7 as an optimal model. However, since the yielded AIC score is higher than of the manually defined model, meaning it has a worse balance between its ability to fit the data set and avoid overfitting, we are going to stick to the simpler and better performing model, i.e. SARIMA(0,1,1)(0,1,1)_7. 4.3.3. Model diagnostics The last part of the Box-Jenkins approach involves diagnostics of the model’s residual errors. Residuals generated by an ideal model should resemble a white noise process, i.e. Gaussian distribution with a mean zero and a symmetrical variance. Additionally, residuals should be independent of time. Below figure represents a set of generated by residuals’ visualizations which should help to diagnose the forecasting errors. Figure 25: Model diagnostics plots. The first plot of standardized residuals informs about the mean of residuals being independent of time and centered at 0, meaning that there is no need to correct for a bias in the forecasts provided by the model. Histogram and the density plot of residuals prove that the error distribution is similar to normal apart from the fact that the distribution is slightly skewed to the left. Moving onto a Normal QQ-plot, great majority of points lays on the red line, which is desired to conclude that the data follows a normal distribution. Finally, the last chart plotted in the bottom right part of above figure represents a correlogram with no significant
50 autocorrelation at successive lags. As a result, it can be concluded that residuals are independent of time. 4.4. SARIMAX MULTIVARIATE MODELLING The other statistical model studied in this report is known as Autoregressive Integrated Moving Average with Exogenous Inputs (ARIMAX). ARIMAX works similarly to the traditional ARIMA model but it additionally takes the impact of covariates on the forecasting into account, which often leads to better accuracy of the predictions. Given that we were provided with selected media planning data regarding the advertisements published in press, we will take advantage of them and incorporate these as new set of time-dependent vector hoping for better prediction accuracy as compared to the traditional ARIMA model developed in the previous section. 4.4.1. Multivariate dataset The dataset provided by the Media Planning Team includes information about ads being published in the press across time. This data has been transformed, aggregated and enriched with feature engineering methods to extract more information about the data. Categorical variables have been transformed into dummy variables and only the dummy variables with at least 5% of positive values were kept in order to limit the number of variables in the dataset. This was necessary for instance in the case of Press string variable which described the name of the newspaper where ads are published, as we had over 100 unique newspaper names, a lot of these were sparse and had very few publications. Another data preprocessing step involved imputation of null values, which was done by means of mean imputation and mode imputation for numerical and categorical variables, respectively. The dataset did not contain any erroneous values, thus no outlier imputation was needed. Finally, the pre-processed dataset used for multivariate modelling consists of following series of variables: - Unique_reflinkno – Number of unique ads published in press - Avg_cost – The average budget spent on ads publishing in press - Avg_format – The average ad format of ads published in press - Pub-1 – The number of ads published at Publisher Pub-1 - Pub-2 - The number of ads published at Publisher Pub-2 - Pub-3 - The number of ads published at Publisher Pub-3 - Press-1 – The number of ads published in the newspaper of Press-1
51 - Press-2 – The number of ads published in the newspaper of Press-2 - Press-3 - The number of ads published in the newspaper of Press-3 - Press-4 – The number of ads published in the newspaper of Press-4 - Press-5 – The number of ads published in the newspaper of Press-5 - Press-6 - The number of ads published in the newspaper of Press-6 - Press-7 – The number of ads published in the newspaper of Press-7 - Press-8 – The number of ads published in the newspaper of Press-8 - Press-9 – The number of ads published in the newspaper of Press-9 - Dayofweek-1 – Dummy variable indicating whether the day is Sunday - Dayofweek-2 – Dummy variable indicating whether the day is Monday - Dayofweek-3 – Dummy variable indicating whether the day is Tuesday - Dayofweek-4 – Dummy variable indicating whether the day is Wednesday - Dayofweek-5 – Dummy variable indicating whether the day is Thursday - Dayofweek-6 – Dummy variable indicating whether the day is Friday - Is-holiday – Dummy variable indicating whether the day is holiday - Next_is_holiday – Dummy variable indicating whether the following day is holiday - Count – The number of call center collected inbound phone calls related to presspublished ads 4.4.2. Feature selection The goal of the feature selection process is to identify the variables that can best describe the target variable. Efficient feature selection can improve the predictive power of the model thanks to the elimination of irrelevant, noisy variables from the model. Additionally, feature selection is advised in order to reduce the dataset dimensionality and avoid producing computationally complex models. Some algorithms, such as Artificial Neural Networks are able to perform the feature selection work by themselves, however, this is not the case for statistical time series models. The basic type of feature selection has already been applied in the preprocessing step, where after one-hot encoding categorical variables, one of the generated dummy features has been dropped in order to avoid the phenomena known as the Curse of Dimensionality, which takes place when the dataset contains too many sparse features. For media planning dataset, backward elimination method for feature selection was used. Gini feature importance index serves as a criterion to select the most relevant features for our multivariate modelling problem. Gini Importance is one of the impurity measures used in the Decision Tree machine learning models. It is in fact a criterion to minimize the probability
52 of misclassification, meaning that smaller values of Gini index mean that a given variable is a better regressor or classifier of the target variable. Gini feature importance has been widely used as a feature selection method in various machine learning applications and so has been applied in our modelling problem. Below figure illustrates features sorted according to their importance. Figure 26: Gini feature importance bar plot. Above figure indicates that the variables with the highest feature importance include the average cost spent on press advertising on a particular day (avg_cost), the number of ads published on that day (unique_reflinkno), the number of ads published by a publisher Pub-1 (Pub-1) and the average ad format (avg_format). These results make an intuitive sense, as the number of collected press-published ads phone calls incoming to the call center is usually the highest on the first day when the ad was published, as customers usually buy them right on the release day. Also, more money spent on ads publishing is also contributing to the higher number of press leads. Regarding the least relevant variables, these include the dummy variable indicating that it is Thursday (dayofweek-5) and some other dummy variables indicating particular newspaper names (e.g. Press-4, Press-6). 4.4.3. SARIMAX results In this section the cross-validated results of SARIMAX modelling will be presented and compared to the model which is currently used by the company (Company Model). The goal is to take advantage of conducted feature importance analysis by using backward elimination
53 methodology, i.e. we will start with fitting a SARIMAX model including all exogenous variables. After that, we will be gradually excluding the least relevant variables from the model until we finally get to the univariate model, which uses solely lagged values and weighted prediction errors to predict future values. The seasonal and non-seasonal parameters will be defined with the use of auto.arima function which performs an automatic search of the most optimal model. Finally, the prediction accuracies achieved by each of the models will be compared to the currently used by the company model and the most accurate setup will be selected. N most relevant exogenous variables Optimal model AIC Cross – validated error measures MAE RMSE 23 SARIMAX(1, 1, 2)x(1, 0, 1)_7 9845.121 75.494785 96.286265 22 SARIMAX(4, 1, 2)x(2, 0, 2)_7 9832.958 80.704501 103.979423 21 SARIMAX(4, 1, 2)x(1, 0, 2)_7 9824.091 82.584269 107.880913 20 SARIMAX(1, 1, 2)x(1, 0, 1)_7 9888.515 80.007072 103.860881 19 SARIMAX(1, 1, 2)x(1, 0, 1)_7 9882.835 82.507558 106.638797 18 SARIMAX(2, 1, 3)x(2, 0, 1)_7 9885.122 81.209798 107.252855 17 SARIMAX(4, 1, 2)x(2, 0, 2)_7 9840.809 75.026542 94.816101 16 SARIMAX(1, 1, 2)x(2, 0, 2)_7 9901.299 82.707534 101.035266 15 SARIMAX(4, 1, 2)x(2, 0, 2)_7 9834.998 83.052508 101.217615 14 SARIMAX(4, 1, 2)x(2, 0, 2)_7 9828.445 84.081256 102.038029 13 SARIMAX(1, 1, 2)x(1, 0, 1)_7 9911.960 79.931227 98.958813 12 SARIMAX(1, 1, 2)x(1, 0, 1)_7 9888.145 84.262227 102.190261 11 SARIMAX(4, 1, 2)x(1, 0, 1)_7 9932.508 90.461700 108.738352 10 SARIMAX(4, 1, 2)x(1, 0, 1)_7 9910.672 86.130049 103.662428 9 SARIMAX(1, 1, 2)x(1, 0, 1)_7 9905.604 83.638324 99.998627 8 SARIMAX(1, 1, 2)x(1, 0, 1)_7 9943.249 83.916326 101.801737 7 SARIMAX(1, 1, 2)x(1, 0, 1)_7 10065.717 90.927261 109.477274 6 SARIMAX(0, 1, 2)x(1, 0, 1)_7 9998.221 91.297980 110.687680 5 SARIMAX(4, 1, 2)x(2, 0, 2)_7 9943.999 91.909677 111.396810 4 SARIMAX(1, 1, 2)x(2, 0, 2)_7 10065.666 96.898702 116.399103 3 SARIMAX(3, 1, 3)x(1, 0, 1)_7 10036.464 95.735298 115.717307 2 SARIMAX(2, 1, 5)x(1, 0, 1)_7 10024.631 95.786078 114.633758 1 SARIMAX(2, 1, 5)x(1, 0, 1)_7 10104.690 95.276864 114.155127 0 SARIMAX(0, 1, 1)x(0, 1, 1)_7 9835.940 82.208944 99.940257 Company Model Average of 40 proceeding values - 150.033760 169.917893 Table 3: Backward elimination results for SARIMAX vs Base Model. Above table shows values of Mean Absolute Error (MAE) and Root Mean Squared Error (RMSE) for models with top 23, 22, 21… 0 most relevant according to the gini index exogenous values. The values of error metrics were obtained by walk-forward cross-validation method, as such each of the models was trained and tested on a 40-day prediction interval 4 times. After that, the final values of MAE and RMSE were calculated as an average of the 4 rounds of
54 testing, which was further recorded into the above table. Looking at above results, we can conclude that all of above tested SARIMA models outperform the currently used by the company model, which simply estimates the following 40 daily inbound phone call volume to be equal to the average calculated over 40 previous time steps. Above results suggest that it is best to use all available exogenous features, as such model generates predictions with a MAE of 75 Press Leads, resulting in a significant improvement of predictions accuracy, decreasing the prediction error by 50% as compared to the Company Model. Regarding the feature selection aspect, the conclusion possible to be drawn from above table is that not using exogenous features as model indicators at all decreases the prediction accuracy by only 7 units as compared to the multivariate model. To visualize the ability to capture seasonal patterns by univariate vs multivariate model, true values and predictions generated by the former and the latter method have been illustrated in the figure below (Figure 27). Figure 27: Predictive accuracy of univariate and multivariate SARIMA(X) models. Above figure shows real values in orange and predictions in blue generated by univariate SARIMA (left panel) and multivariate SARIMAX (right panel). Comparing both visualizations from the left to the right panel, we can clearly see that the latter, i.e. multivariate model does a better job at capturing the turning points of the series, as the blue line corresponding to predictions is more sensitive to abrupt changes in the direction of the series. This is achieved
55 thanks to the advantage of information hidden in the exogenous variables used at training the exogenous model. Univariate model, on the other hand, depicted in the left panel visualizations, generates predictions of very regular patterns, being less sensitive to abrupt peaks or falls in the series. The relatively small improvement of 7 in the error metric between these models’ accuracies is probably caused by the non-linear relationships between the exogenous variables and the target variable, which cannot be captured by a linear model. Additionally, it is likely that other factors, which are not included in the set of exogenous variables, affect the number of inbound press-related phone calls in the call center, which cannot be captured by the model due to missing information. In the next section the so-far best found linear model will be attempted to be improved by means of applying models from a family of Recurrent Neural Networks, which is capable of capturing the non-linear relationships between the features. 4.5. GATED RECURRENT UNIT EXPERIMENT Since the previous research on time series prediction strongly supports the No Free Lunch Theorem concluding that depending on a variety of factors statistical modelling can overcome the predictive power of Recurrent Neural Networks and vice versa, we decided to experiment with two deep learning approaches commonly used for time series prediction: GRU and LSTM. The first part of this section focuses on the former method which is proved to be faster at training the model. Time efficiency is especially important for our use-case taking into account the fact that the input fed onto a network is 24-dimensional including volume history of inbound phone calls, as well as, 23 exogenous variables extracted from Media Planning. The multidimensionality of the input data has a significant impact on the training time. No feature selection has been made for the RNN taking into account the nature of neural networks, which are able to perform automatic feature selection by setting particular weights connecting irrelevant features to close to 0 values. The initial training setup of the Gated Recurrent Unit model along with testing for different architectures has been described in the section below. 4.5.1. GRU Base Model Setup We started off with a default GRU model that was further attempted to be improved by means of parameter tuning experiments. The training set-up of the initial model is covered below. - The model has been developed in Python with use of Keras machine learning library on top of the open-source machine learning framework called TensorFlow.
56 - Custom Mean Squared Error (MSE) was selected as a loss function to penalize large errors more heavily. The time-shift between the input and output signals is fixed at 40 days, thus the MSE metric has been customized not to include the early time-steps in its loss calculation, to avoid the distortion in the later output of the model. Thus, a “warmup-period” of 30 time-steps has been given to the model, which is not taken into account in the loss calculation. - Optimizer - The RMSprop optimizer has been used with the initial learning rate of 1e-3. - Callbacks - ReduceLROnPlateau keras callback was used to decrease the value of a learning rate by a factor of 0.1 when the validation loss has not improved since the last epoch (patience=0). EarlyStopping callback was applied to stop the model training process unless the validation loss went down in the since 5 epochs (patience=5). - Data preparation - Artificial Neural Networks, such as GRU differ from statistical forecasting methods by the fact that they are one of the supervised learning methods, meaning that we need to transform the series of data in a way to feed onto the network the series of inputs along with a sequence of target outputs. Neural networks can be fed with one or more attributes, as well as, they are able to output vectors of values. Since the goal of the model is to predict the number of inbound phone calls for the following 40 days, the initial model was designed to intake batches of 40-day long sequences of historical data as an input and it outputs a sequence of following 40 target values in a series. Since we also need to include the exogenous variables in the training process, the input data consists of not only the historical records of inbound phone calls but also it includes a series of 23 exogenous variables extracted from Media Planning. As a result, the training input data is of shape (64, 40, 24), where 64 constitutes the batch size, 40 is the sequence length and 24 is the number of features. The output, on the other hand, is of (64, 40, 1) shape, meaning it outputs a series of expected phone calls in the next 40 days. - Batch size - batch size determines the number of training samples based on which the loss function is computed. In the initial model the batch size is set to 64. - Maximum epoch – Maximum epoch in the initial model is set to 30, however, the training may finish earlier due to the EarlyStopping callback in use. - Train and test sets – the data has been partitioned by 80:20 splitting rule, i.e. the earliest 80% of time series constitutes for the training set, while the remaining 20% is used to validate the generalization ability of the model.
57 - Data transformation – The data has been scaled to the interval of (0,1), which is known to help the neural network learn underlying patterns both, more accurately and more efficiently. The visual presentation of the initial model setup is presented in the illustration below. Figure 28: GRU Base model architecture visualization. Taking into account the stochastic nature of the neural networks caused by random weights initialization, the model performance will be tested as an average error over calculated over 3 seeds. This way, the base model yields cross-validated predictions with Mean Absolute Error of 137.609351207. Meaning that the initial model is wrong on average by nearly 138 phone calls. The predictions versus the true values have been plotted in the graphs below for both, train and test sets. Figure 29: GRU Base Model predictions over real data for train and test sets. It is important to highlight that above plot shows the output-signals of the model, which are 40 days into the future. The time-shift between the input and output signals is fixed at 40 days and since the model always predicts a sequence of 40 outputs, the x axis merely shows how many time-steps of the input-signals has been seen by the predictive model so far. This being said, the first 30 values presented in the above plots are very bad predictions caused by the fact that the model, generating a single time-step prediction for each time-step of the input data, it knows
64 the GRU model, as an average value obtained from tests run on 3 seeds, as well as, crossvalidated with use of a walk forward cross-validation method of step 1. 4.6.1. LSTM Base Model Setup The parameter values of the base model are taken after the most optimal GRU model. As such, the base Long-Short Term Memory model consists of 1 layer of 128 hidden neurons, starting learning rate of 0.005, batch size of 64 and a sequence length of 40. Model set up this way provides predictions that are on average wrong by 94.9113853228 phone calls. This constitutes for an improvement in the model’s accuracy of 6 phone calls as compared to the GRU model run with the same parameter values. Predictions versus true values of the initial LSTM model are plotted for both, train and test sets in the graphs below. Figure 31: LSTM Base and Final Model predictions over real data for train and test sets. Above plots prove that base LSTM model is able to capture the weekly seasonality with a slightly lower bias as compared to the GRU model. This result is already giving the LSTM an advantage over GRU model and we hope to achieve a yet better accuracy of the LSTM by fine tuning its parameters based on a set of experiments, which was described in the next sections of the report. 4.6.2. LSTM nodes The first parameter search includes the number of LSTM nodes in the layer. The cross-validated results obtained with different parameter values of the model are presented in the table below.
65 LSTM nodes Validation Loss MSE (over 3 seeds) Cross-validated MAE (over 3 seeds) 64 0.00230794112 99.8904650703 128 (Base model) 0.00217102367 94.9113853228 256 0.00792687487 175.858612652 512 0.00772189038 171.640870962 Table 9: LSTM parameter tuning: LSTM nodes. Looking at above table of the results, we can conclude that the number of LSTM nodes which gives the most accurate predictions is the same as in case of the most optimal GRU model and it equals 64. Therefore, the value of this parameter will be set to 64 in the next rounds of parameter tuning for the LSTM model. 4.6.3. Batch size Similarly, as in the parameter search for GRU, the next examined parameter is the batch size. The cross-validated prediction accuracy of models with different values of this parameter are presented in the table below. Batch size Validation Loss MSE (over 3 seeds) Cross-validated MAE (over 3 seeds) 16 0.00343510865 114.65276475 32 0.00252165156 101.772592588 64 (Base model) 0.00217102367 94.9113853228 128 0.00267651902 104.272608753 Table 10: LSTM parameter tuning: Batch Size. Above table indicates that the optimal batch size yielding best LSTM predictions is the same as in case of GRU and it equals to 64. This being said, the batch size will be set to 64 in the following sections in the search of optimal values for remaining LSTM parameters. 4.6.4. Sequence length In this section we are checking the impact of different sequence lengths in the training set on the LSTM model’s predictive power. The results of these experiments have been shown in the table below.
66 Sequence length Validation Loss MSE (over 3 seeds) Cross-validated MAE (over 3 seeds) 40 (Base model) 0.00217102367 94.9113853228 60 0.00962270346 146.899543609 80 0.00619360439 118.163417619 100 0.00275136615 103.85033778 Table 11: LSTM parameter tuning: Sequence Length. The cross-validated Mean Absolute Error proves to be the lowest for the base model, thus the most optimal sequence length for that case is the same as in the optimal version of GRU model, equal to 40. 4.6.5. Learning rate The following part of parameter tuning involves searching for an optimal initial learning rate. This parameter has been tested across 3 seeds and its impact of LSTM model’s performance is presented in the table below. Initial learning rate Validation Loss MSE (over 3 seeds) Cross-validated MAE (over 3 seeds) 0.001 0.0055219874 155.264774973 0.003 0.00268421089 108.612304687 0.005 (Base model) 0.00217102367 94.9113853228 0.007 0.00252816546 98.7090978146 0.01 0.00250119001 98.1544482541 Table 12: LSTM parameter tuning: Learning Rate. Above table indicates that the most optimal initial learning rate turns out to be the same as in the case of GRU optimal model, i.e. it equals 0.005. 4.6.6. Layer setup The last part of parameter tuning involves checking for the most optimal layer setup of a deep LSTM network. The results of different configurations and its prediction accuracies are presented in the table below.
67 Layer setup Validation Loss MSE (over 3 seeds) Cross-validated MAE (over 3 seeds) Layer_1(LSTM=128) (Base model) 0.00217102367 94.9113853228 Layer_1(LSTM =128); Layer_2(LSTM =64) 0.00457890657 129.247157256 Layer_1(LSTM =128); Layer_2(LSTM =128) 0.00710014572 154.427538832 Layer_1(LSTM =64); Layer_2(LSTM =64) 0.00578577397 148.10400959 Layer_1(LSTM =256); Layer_2(LSTM =128) 0.00762837209 163.478928806 Layer_1(LSTM =32); Layer_2(LSTM =32) 0.00386882231 118.216303277 Layer_1(LSTM =32); Layer_2(LSTM =16) 0.00346415823 112.144094827 Table 13: LSTM parameter tuning: Layer Setup. The final parameter search suggests that again, the same layer configuration is optimal for both GRU and LSTM models, which is one layer consisting of 128 neurons. 4.6.7. Final LSTM Model The final LSTM model provides predictions that are more accurate from both: the final GRU model and the currently used by the company model by 6 and 56 units, respectively. After the above-reported parameter search which was performed to find the most optimal values for the LSTM model’s parameters, we can conclude that the same neural network setup works best for both tried types of recurrent neural networks, however, the predictions made with LSTM model are off by on average 94.9113853228, while GRU model’s predictions Mean Absolute Error equals 100.225130295. As long as the parameter search was helpful in case of the GRU model as it increased its predictive power significantly, the same sequence of parameter search experiments applied on the LSTM network did not provide such improvement in its accuracy.
68 5. CONCLUSION The main goal of this project was to deliver time series predictions of the number of inbound phone calls related to press-published ads expected to arrive in a call center in the consecutive 40 days. The first steps of analysis include data extraction, aggregation and preprocessing. After that, data visualization methods have been used in order to identify general tendencies and seasonal patterns hidden in the data. Finally, following the No Free Lunch Theorem, a number of univariate and multivariate predictive models have been conducted and compared. The result of comparative study performed on a variety of tested predictive models leads to a number of conclusions. The first surprising insight is that statistical models, yet mathematically simpler, outperformed the tested recurrent neural networks (GRU and LSTM). One possible reason for this phenomena is the fact that statistical models require much less data as compared to the neural networks to be able to learn the underlying patterns. This reasoning is additionally supported by the multidimensionality of the data inputs, in result increasing the size of data required for training. Another interesting insight can be derived from the parameter tuning process of the recurrent neural networks, as the most optimal architecture setup turned out to be the same for both: GRU and LSTM models. Finally, it is interesting to note that increasing a number of layers for both networks didn’t result in a higher model accuracy. This conclusion may be supported by 2 hypotheses. First, the underlying pattern is simple enough to be captured by a 1-layer network. Second, a deeper neural network is more complex and thus it requires larger amount of training data before it can learn the underlying patterns. The final conclusion drawn from the comparative study of the neural networks states that LSTM exhibited advantage over the GRU model providing significantly more accurate predictions. However, its performance was yet worse than the one of the statistical models. Finally, the performance analysis of various types of predictive models proved that multivariate SARIMA(X) outperformed each of the other tested approaches and thus is recommended to be used as a final model by the company. The obtained prediction accuracy of the final model is also significantly higher as compared to the model used by the company. This being said, the objective of the internship was fulfilled and the internship was evaluated as successful.
69 5.1. LIMITATIONS AND FUTURE WORK The limitations of the conducted research include the limited amount of historical data which merely covers 810 consecutive days and may not be sufficient for an effective training of recurrent neural networks. Another important limitation is the non-exhaustive set of exogenous features provided for analysis. As discussed with the specialists in the relevant business area, there is a number of factors affecting the number of press leads within the company which is not recorded and currently cannot be known beforehand by the company – such features include the competitive company advertising in the press at the same time. Another limitation of the research is the cross-validation methodology for the recurrent neural networks. In case of the statistical model the regular walk-forward cross-validation methodology was possible to be applied as the model does not require large amounts of data for the training to capture the underlying patterns effectively. In case of the neural networks, however, we only performed the walk-forward cross-validation method on the 20% of the most recent data for two reasons: first, applying regular cross-validation technique on entire dataset would mean training the neural network multiple times which is impossible for the sake of given time limitation, secondly, training the neural network on the even smaller amount of data would not be sufficient for the model to learn underlying patterns. Last but not least, given more time, more detailed parameter search could be performed and a larger number of epochs set up to give the model more time for learning. Finally, in the future work, some other time series modelling approaches, such as a novel CNN for time series prediction can be tested as an attempt to increase the predictions’ accuracy. 5.2. FINAL THOUGHTS Regarding my overall experience during the internship, I have to admit that this was an outstanding opportunity to be immersed into the professional working environment right after the first year of theoretical classes. I am very grateful for having this opportunity to work with both, business and technical professionals, who were always there sharing their expertise and advice on the development of my work. This working experience has enriched both, my technical and organizational skills, and I am now feeling much more confident moving onto another job as a more experienced data scientist. I also have to admit that the internship was not a bed of roses and I learnt how to deal with work under pressure and how make complex things understood easily by the business audience. Another set of skills that have been developed during my time spent at the Company X was adaptation and presentational skills, as I was to regularly update the decisive persons in the company about the development of my work and
70 adjust further actions according to the priorities, as aligned. Finally, it is important to highlight that NOVA IMS master program in Data Science and Advanced Analytics provided me with necessary fundamentals which were of a huge help during my internship. The skills obtained at the NOVA IMS and used during this project development include coding in Python, querying the SQL database, developing and assessing predictive models and many more. To conclude, this internship would not have been completed successfully if it wasn’t for the valuable knowledge gained at NOVA IMS master program and the always supportive colleagues.
71 6. BIBLIOGRAPHY Abraham, B. & Ledolter, J. (1986). Forecast functions implied by autoregressive integrated moving average models and other related forecast procedures. International Statistical Review 54(1), 51-66. Bottcher, M., Hoppner, F., & Spiliopoulou, M. (2008). On exploiting the power of time in data mining. Box, G. & Jenkins, G. (1970). Time Series Analysis: Forecasting and Control, Holden-Day. Chatfield C. (2000). Time-series forecasting. Chapman & Hall/CRC. Chen, Z., Yang, Y. (2004). Assessing Forecast Accuracy Measures. Iowa State University. Gerbing D. (2016). Time series components. Goodwin, P., & Lawton, R. (1999). On the asymmetry of the symmetric MAPE. International journal of forecasting, 15(4), 405-408. Gooijer, J. G. D. & Hyndman, R. J. (2006), 25 years of time series forecasting. International Journal of Forecasting 22(3), 443-473. Hippert, H., Pedreira, C. & Souza, R. (2001), Neural networks for short-term load forecasting: a review and evaluation, IEEE Transactions on Power Systems 16(1), 44-55. Hyndman, R. J. (2001), It's time to move from what to why. International Journal of Forecasting 17, 567- 570. Hyndman, R. J., & Koehler, A. B. (2006). Another look at measures of forecast accuracy. International Journal of Forecasting, 22, 679–688. Hyndman, R.J., & Athanasopoulos, G. (2018). Forecasting: principles and practice (2nd edition). OTexts: Melbourne, Australia. OTexts.com/fpp2. Kourentzes N. (2014). Additive and Multiplicative Seasonality – can you identify them correctly? Forecasting research. https://kourentzes.com/forecasting/ Makridakis, S. & Hibon, M. (2000). The M3-competition: Results, conclusions and implications. International Journal of Forecasting 16(4), 451-476.
72 Mittelman R. (2015). Time-series modeling with undecimated fully convolutional neural networks. ArXiv preprint arXiv:1508.00317. Nau, R. (2019). Statistical forecasting: notes on regression and time series analysis. [Fuqua School of Business, Duke University] Olah, C. (27, 08, 2015). Understanding LSTM Networks. Olah’s Blog. http://colah.github.io/posts/2015- 08-Understanding-LSTMs Ostashchuk, O. (2017). Time Series Data Prediction and Analysis. Pascanu, R., Mikolov, T., Bengio, Y. (2013). On the difficulty of training Recurrent Neural Networks. Schmidhuber, J. (2014). Deep Learning in Neural Networks: An Overview. Staudemeyer, R., C. (2012). The importance of time: Modelling network intrusions with long short-term memory recurrent neural networs. [Doctoral dissertation, University of Applied Sciences Schmalkalden] Zaremba, W., Sutskever, I., & Vinyals, O. (2014). Recurrent Neural Network Regularization. Zhang, G., Patuwo, B. & Hu, M. (1998). Forecasting with artificial neural networks: The state of the art. International Journal of Forecasting 14(1), 35-62.
Page | i