<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/smooth-package-for-r-common-ground-part-iv-exogenous-variables-advanced-stuff/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://forecasting.svetunkov.ru/en/2018/02/10/smooth-package-for-r-common-ground-part-iv-exogenous-variables-advanced-stuff/"> R – Modern Forecasting</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Previously we’ve covered the basics of exogenous variables in smooth functions. Today we will go slightly crazy and discuss automatic variables selection. But before we do that, we need to look at a Santa’s little helper function implemented in </p>
<pre>smooth</pre>
<p>. It is called </p>
<pre>xregExpander()</pre>
<p>. It is useful in cases when you think that your exogenous variable may influence the variable of interest either via some lag or lead. Let’s say that we think that BJsales.lead discussed in the <a rel="nofollow" href="https://forecasting.svetunkov.ru/en/2018/01/15/smooth-package-for-r-common-ground-part-iii-exogenous-variables-basic-stuff/" target="_blank">previous post</a> influences sales in a non-standard way: for example, we believe that today’s value of sales is driven by the several values of that variable: the value today, five and 10 days ago. This means that we need to include </p>
<pre>BJsales.lead</pre>
<p> with lags. And </p>
<pre>xregExpander()</pre>
<p> allows automating this for us:</p>
<pre>newXreg &lt;- xregExpander(BJsales.lead, lags=c(-5,-10))</pre>

<p>The </p>
<pre>newXreg</pre>
<p> is a matrix, which contains the original data, the data with lag 5 and the data with lag 10. However, if we just move the original data several observations ahead or backwards, we will have missing values, so </p>
<pre>xregExpander()</pre>
<p> fills in those values with the forecasts using </p>
<pre>es()</pre>
<p> and </p>
<pre>iss()</pre>
<p> functions (depending on the type of variable we are dealing with). This also means that in cases of binary variables you may have weird averaged values as forecasts (e.g. 0.7812), so beware and look at the produced matrix. Maybe in your case it makes sense to just substitute these weird numbers with zeroes…</p>
<p>You may also need leads instead of lags. This is regulated with the same “lags” parameter but with positive values:</p>
<pre>newXreg &lt;- xregExpander(BJsales.lead, lags=c(7,-5,-10))</pre>
<p>Once again, the values are shifted, and now the first 7 values are backcasted.</p>
<p>After expanding the exogenous variables, we can use them in </p>
<pre>smooth</pre>
<p> functions for forecasting purposes. All the rules discussed in <a rel="nofollow" href="https://forecasting.svetunkov.ru/en/2018/01/15/smooth-package-for-r-common-ground-part-iii-exogenous-variables-basic-stuff/" target="_blank">the previous post</a> apply:</p>
<pre>es(BJsales, &quot;XXN&quot;, xreg=newXreg, h=10, holdout=TRUE)</pre>
<p>But what should we do if we have several variables and we are not sure what lags and leads to select? This may become a complicated task which can have several possible solutions. </p>
<pre>smooth</pre>
<p> functions provide one. I should warn you that this is not necessarily the best solution, but <strong>a</strong> solution. There is a function called </p>
<pre>stepwise()</pre>
<p> in </p>
<pre>smooth</pre>
<p> that does the selection based on an information criterion and partial correlations. In order to run this function the response variable needs to be in the first column. The idea of the function is simple, it works iteratively the following way:</p>
<ol>
<li>The basic model of the first variable and the constant is constructed (this corresponds to simple mean). An information criterion is calculated;</li>
<li>The correlations of the residuals of the model with all the original exogenous variables is calculated;</li>
<li>The regression model of the response variable and all the variables in the previous model plus the new most correlated variable from (2) is constructed using
<pre>lm()</pre>
<p> function;
<li>An information criterion is calculated and is compared with the one from the previous model. If it is greater or equal to the previous one, then we stop and use the previous model. Otherwise we go to step 2.</li>

<p>This way we do not do a blind search, but we follow some sort of “trace” of a good model: if some significant part that can be explained by one of the exogenous variables is left in the residuals, then that variable is included in the model. Following correlations makes sure that we include only meaningful (from technical point of view) things in the model. Using information criteria allows overcoming the problem with the uncertainty of statistical tests. In general the function guarantees that you will have the model with the lowest information criterion. However this does not guarantee that you will end up with a meaningful model or with a model that produces the most accurate forecasts. And this is why evolution has granted human beings the almighty brain – it helps in selecting the most appropriate model in those cases, when statistics fails.</p>
<p>Let’s see how the function works with the same example and 1 to 10 leads and 1 to 10 lags (so we have 21 variables now). First we expand the data and form the matrix with all the variables:</p>
<pre>newXreg &lt;- as.data.frame(xregExpander(BJsales.lead,lags=c(-10:10)))
newXreg &lt;- cbind(as.matrix(BJsales),newXreg)
colnames(newXreg)[1] &lt;- &quot;y&quot;</pre>
<p>This way we have a nice data frame with nice names, not something weird with strange long names. It is important to note that the response variable should be in the first column of the resulting matrix. After that we use our magical stepwise function:</p>
<pre>ourModel &lt;- stepwise(newXreg)</pre>
<p>And here’s what it returns (the object of class “lm”):</p>
<pre>Call:
lm(formula = y ~ xLag4 + xLag9 + xLag3 + xLag10 + xLag5 + xLag6 + 
    xLead9 + xLag7 + xLag8, data = newXreg)

Coefficients:
(Intercept)        xLag4        xLag9        xLag3       xLag10        xLag5        xLag6  
    17.6448       3.3712       1.3724       4.6781       1.5412       2.3213       1.7075  
     xLead9        xLag7        xLag8  
     0.3767       1.4025       1.3370</pre>
<p><p>The values in the function are listed in the order of most correlated with the response variable to the least correlated ones. The function works very fast because it does not need to go through all the variables and their combinations in the dataset.</p>
<p>Okay. So, that’s the second nice function in </p>
<pre>smooth</pre>
<p> that you can use for exogenous variables. But what does it have to do with the main forecasting functions?</p>
<p>The thing is </p>
<pre>es()</pre>
<p>, </p>
<pre>ssarima()</pre>
<p>, </p>
<pre>ces()</pre>
<p>, </p>
<pre>ges()</pre>
<p> – all the forecasting functions in </p>
<pre>smooth</pre>
<p> have a parameter </p>
<pre>xregDo</pre>
<p>, which defines what to do with the provided exogenous variables, and by default it is set to </p>
<pre>&quot;use&quot;</pre>
<p>. However, there is also an option of </p>
<pre>&quot;select&quot;</pre>
<p>, which uses the aforementioned </p>
<pre>stepwise()</pre>
<p> function. The function is applied to the residuals of the specified model, and when the appropriate exogenous variables are found, the model with these variables is re-estimated. This may cause some inaccuracies in the selection mechanisms (because, for example, the optimisation of ETS and X parts does not happen simultaneously), but at least it is done in the finite time frame.</p>
<p>Let’s see how this works. First we use all the expanded variables for up to 10 lags and leads without the variables selection mechanism (I will remove the response variable from the first row of the data we previously used):</p>
<pre>newXreg &lt;- newXreg[,-1]
ourModelUse &lt;- es(BJsales, &quot;XXN&quot;, xreg=newXreg, h=10, holdout=TRUE, silent=FALSE, xregDo=&quot;use&quot;, intervals=&quot;sp&quot;)</pre>
<pre>Time elapsed: 1.13 seconds
Model estimated: ETSX(ANN)
Persistence vector g:
alpha 
0.922 
Initial values were optimised.
24 parameters were estimated in the process
Residuals standard deviation: 0.287
Xreg coefficients were estimated in a normal style
Cost function type: MSE; Cost function value: 0.068

Information criteria:
      AIC      AICc       BIC 
 69.23731  79.67209 139.83673 
95% semiparametric prediction intervals were constructed
100% of values are in the prediction interval
Forecast errors:
MPE: 0%; Bias: 55.7%; MAPE: 0.1%; SMAPE: 0.1%
MASE: 0.166; sMAE: 0.1%; RelMAE: 0.055; sMSE: 0%</pre>
<div class="wp-caption"><a rel="nofollow" href="https://i0.wp.com/forecasting.svetunkov.ru/wp-content/uploads/2018/01/BJsalesETSXUse.png?ssl=1" target="_blank"><img sizes="(max-width: 300px) 100vw, 300px" src="https://i2.wp.com/forecasting.svetunkov.ru/wp-content/uploads/2018/01/BJsalesETSXUse-300x175.png?resize=300%2C175&ssl=1" alt="" width="300" class="wp-image-1621" data-recalc-dims="1" height="175"></a>
<p class="wp-caption-text">BJsales series and ETSX with all the variables</p>
</div>
<p>As we see, the forecast became more accurate in this case than <a rel="nofollow" href="https://forecasting.svetunkov.ru/en/2018/01/15/smooth-package-for-r-common-ground-part-iii-exogenous-variables-basic-stuff/" target="_blank">in the case of using pure BJsales.lead</a>, which may mean that there can be a lagged relationship between the sales and the indicator. However, we have included too many exogenous variable, which may lead to the overfitting. So there is a potential for the accuracy increase if we remove the redundant variables. And that’s where the selection procedure kicks in:</p>
<pre>ourModelSelect &lt;- es(BJsales, &quot;XXN&quot;, xreg=newXreg, h=10, holdout=TRUE, silent=FALSE, xregDo=&quot;select&quot;, intervals=&quot;sp&quot;)</pre>
<pre>Time elapsed: 0.98 seconds
Model estimated: ETSX(ANN)
Persistence vector g:
alpha 
    1 
Initial values were optimised.
11 parameters were estimated in the process
Residuals standard deviation: 0.283
Xreg coefficients were estimated in a normal style
Cost function type: MSE; Cost function value: 0.074

Information criteria:
     AIC     AICc      BIC 
54.55463 56.61713 86.91270 
95% semiparametric prediction intervals were constructed
100% of values are in the prediction interval
Forecast errors:
MPE: 0%; Bias: 61.4%; MAPE: 0.1%; SMAPE: 0.1%
MASE: 0.159; sMAE: 0.1%; RelMAE: 0.052; sMSE: 0%</pre>
<div class="wp-caption"><a rel="nofollow" href="https://i2.wp.com/forecasting.svetunkov.ru/wp-content/uploads/2018/01/BJsalesETSXSelect.png?ssl=1" target="_blank"><img sizes="(max-width: 300px) 100vw, 300px" src="https://i1.wp.com/forecasting.svetunkov.ru/wp-content/uploads/2018/01/BJsalesETSXSelect-300x175.png?resize=300%2C175&ssl=1" alt="" width="300" class="wp-image-1622" data-recalc-dims="1" height="175"></a>
<p class="wp-caption-text">BJsales series and ETSX with the selected variables</p>
</div>
<p>Although it is hard to see from graph, there is an increase in forecasting accuracy: MASE was reduced from 0.166 to 0.159. AICc has also reduced from 79.67209 to 56.61713. This is because only 8 exogenous variables are used in the second model (instead of 21):</p>
<pre>ncol(ourModelUse$xreg)
ncol(ourModelSelect$xreg)</pre>
<p><p>The xreg selection works even when you have combination of forecasts. The exogenous variables are selected for each model separately in this case, and then the forecasts are combined based on IC weights. For example, this way we can combine different non-seasonal additive ETS models:</p>
<pre>ourModelCombine &lt;- es(BJsales, c(&quot;ANN&quot;,&quot;AAN&quot;,&quot;AAdN&quot;,&quot;CCN&quot;), xreg=newXreg, h=10, holdout=TRUE, silent=FALSE, xregDo=&quot;s&quot;, intervals=&quot;sp&quot;)</pre>

<pre>Time elapsed: 1.46 seconds
Model estimated: ETSX(CCN)
Initial values were optimised.
Residuals standard deviation: 0.272
Xreg coefficients were estimated in a normal style
Cost function type: MSE

Information criteria:
(combined values)
     AIC     AICc      BIC 
54.55463 56.61713 86.91270 
95% semiparametric prediction intervals were constructed
100% of values are in the prediction interval
Forecast errors:
MPE: 0%; Bias: 61.4%; MAPE: 0.1%; SMAPE: 0.1%
MASE: 0.159; sMAE: 0.1%; RelMAE: 0.052; sMSE: 0%</pre>
<p><p>Taking that ETSX(A,N,N) is significantly better in terms of AICc than the other models, we end up with a maximum weight for that model and infinitesimal weights for the others. That’s why the forecasts of the ourModelSelect and ourModelCombine are roughly the same. Starting from v2.3.2, es() function returns the matrix of information criteria for different models estimated in the process, so we can see what was used and what were the values for the models. This information is available through the element ICs:</p>
<pre>ourModelCombine$ICs</pre>
<pre>AIC      AICc      BIC
ANN       54.55463  56.61713  86.9127
AAN      120.85273 122.91523 153.2108
AAdN     107.76905 110.22575 143.0688
Combined  54.55463  56.61713  86.9127</pre>
<p>So, as we see, ETS(A,N,N) had indeed the lowest information criterion of all the models in the combination (substantially lower than the others), which led to its domination in the combination.</p>
<p>Keep in mind that this combination of forecasts does not mean the combination of regression models with different exogenous variables – this functionality is currently unavailable, and I am not sure how to implement it (and whether it is needed at all). The combination of forecasts is done for the whole ETS models, not just for the X parts of it.</p>
<p>Finally, it is worth noting that the variables selection approach we use here puts more importance on the dynamic model (in our examples it is ETS) rather than on the exogenous variables. We use exogenous variables as an additional instrument which allows increasing the forecasting accuracy. The conventional econometrics approach would be the other way around: construct regression, then add dynamic components to that in case you cannot explain the response variable with the available data. This approach has different aims and leads to different results.</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://forecasting.svetunkov.ru/en/2018/02/10/smooth-package-for-r-common-ground-part-iv-exogenous-variables-advanced-stuff/"> R – Modern Forecasting</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/1I-yfIDlXwM" height="1"></a></div></ol>