<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="http://www.r-bloggers.com/bootstrap-and-cross-validation-for-evaluating-modelling-strategies/"></div></div><div><a data-url="http://www.r-bloggers.com/bootstrap-and-cross-validation-for-evaluating-modelling-strategies/" data-counturl="http://www.r-bloggers.com/bootstrap-and-cross-validation-for-evaluating-modelling-strategies/" data-count="horizontal" data-text="Bootstrap and cross-validation for evaluating modelling strategies" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://ellisp.github.io/blog/2016/06/05/bootstrap-cv-strategies"> Peter's stats stuff - R</a></strong>, and kindly contributed to <a rel="nofollow" href="http://www.r-bloggers.com/">R-bloggers)</a> </div>
<h2>Modelling strategies</h2>
<p>I’ve been re-reading Frank Harrell’s <a target="_blank" href="http://www.springer.com/us/book/9781441929181">Regression Modelling Strategies</a>, a must read for anyone who ever fits a regression model, although be prepared – depending on your background, you might get 30 pages in and suddenly become convinced you’ve been doing nearly everything wrong before, which can be disturbing.</p>
<p>I wanted to evaluate three simple modelling strategies in dealing with data with many variables. Using data with 54 variables on 1,785 area units from New Zealand’s 2013 census, I’m looking to predict median income on the basis of the other 53 variables. The features are all continuous and are variables like “mean number of bedrooms”, “proportion of individuals with no religion” and “proportion of individuals who are smokers”. Restricting myself to traditional linear regression with a normally distributed response, my three alternative strategies were:</p>
<ul>
<li>use all 53 variables;</li>
<li>eliminate the variables that can be predicted easily from the other variables (defined by having a <a target="_blank" href="https://en.wikipedia.org/wiki/Variance_inflation_factor">variance inflation factor</a> greater than ten), one by one until the main collinearity problems are gone; or</li>
<li>eliminate variables one at a time from the full model on the basis of comparing <a target="_blank" href="https://en.wikipedia.org/wiki/Akaike_information_criterion">Akaike’s Information Criterion</a> of models with and without each variable.</li>
</ul>
<p>None of these is exactly what I would use for real, but they serve the purpose of setting up a competition of strategies that I can test with a variety of model validation techniques.</p>
<h2>Validating models</h2>
<p>The main purpose of the exercise was actually to ensure I had my head around different ways of estimating the validity of a model, loosely definable as how well it would perform at predicting new data. As there is no possibility of new areas in New Zealand from 2013 that need to have their income predicted, the “prediction” is a thought-exercise which we need to find a plausible way of simulating. Confidence in hypothetical predictions gives us confidence in the insights the model gives into relationships between variables.</p>
<p>There are many methods of validating models, although I think k-fold cross-validation has market dominance (not with Harrell though, who prefers varieties of the bootstrap). The three validation methods I’ve used for this post are:</p>
<ol>
<li>‘simple’ bootstrap. This involves creating resamples with replacement from the original data, of the same size; applying the modelling strategy to the resample; using the model to predict the values of the full set of original data and calculating a goodness of fit statistic (eg either R-squared or root mean squared error) comparing the predicted value to the actual value. <em>Note – Following Efron, Harrell calls this the “simple bootstrap”, but other authors and the useful <code>caret</code> package use “simple bootstrap” to mean the resample model is used to predict the out-of-bag values at each resample point, rather than the full original sample.</em></li>
<li>‘enhanced’ bootstrap. This is a little more involved and is basically a method of estimating the ‘optimism’ of the goodness of fit statistic. There’s a nice step by step explanation by <a target="_blank" href="http://thestatsgeek.com/2014/10/04/adjusting-for-optimismoverfitting-in-measures-of-predictive-ability-using-bootstrapping/">thestatsgeek</a> which I won’t try to improve on.</li>
<li>repeated 10-fold cross-validation. 10-fold cross-validation involves dividing your data into ten parts, then taking turns to fit the model on 90% of the data and using that model to predict the remaining 10%. The average of the 10 goodness of fit statistics becomes your estimate of the actual goodness of fit. One of the problems with k-fold cross-validation is that it has a high variance ie doing it different times you get different results based on the luck of you k-way split; so repeated k-fold cross-validation addresses this by performing the whole process a number of times and taking the average.</li>
</ol>
<p>As the sample sizes get bigger relative to the number of variables in the model the methods should converge. The bootstrap methods can give over-optimistic estimates of model validity compared to cross-validation; there are various other methods available to address this issue although none seem to me to provide all-purpose solution.</p>
<p>It’s critical that the re-sampling in the process envelopes the entire model-building strategy, not just the final fit. In particular, if the strategy involves variable selection (as two of my candidate strategies do), you have to automate that selection process and run it on each different resample. That’s because one of the highest risk parts of the modelling process is that variable selection. Running cross-validation or the bootstrap on a final model after you’ve eliminated a bunch of variables is missing the point, and will give materially misleading statistics (biased towards things being more “significant” than there really is evidence for). Of course, that doesn’t stop this being common misguided practice.</p>
<h2>Results</h2>
<p>One nice feature of statistics since the revolution of the 1980s is that the bootstrap helps you conceptualise what might have happened but didn’t. Here’s the root mean squared error from the 100 different bootstrap resamples when the three different modelling strategies (including variable selection) were applied:</p>
<p><img alt="boot-results" src="http://ellisp.github.io/img/0043-boot-results.svg"></p>
<p>Notice anything? Not only does it seem to be generally a bad idea to drop variables just because they are collinear with others, but occasionally it turns out to be a <em>really</em> bad idea – like in resamples #4, #6 and around thirty others. Those thirty or so spikes are in resamples where random chance led to one of the more important variables being dumped before it had a chance to contribute to the model.</p>
<p>The thing that surprised me here was that the generally maligned step-wise selection strategy performed nearly as well as the full model, judged by the simple bootstrap. That result comes through for the other two validation methods as well:</p>
<p><img alt="boot-v-cv" src="http://ellisp.github.io/img/0043-boot-v-cv.svg"></p>
<p>In all three validation methods there’s really nothing substantive to choose between the “full model” and “stepwise” strategies, based purely on results.</p>
<h2>Reflections</h2>
<p>The full model is much easier to fit, interpret, estimate confidence intervals and perform tests on than stepwise. All the standard statistics for a final model chosen by stepwise methods are misleading and careful recalculations are needed based on elaborate bootstrapping. So the full model wins hands-down as a general strategy in this case.</p>
<p>With this data, we have a bit of freedom from the generous sample size. If approaching this for real I wouldn’t eliminate any variables unless there were theoretical / subject matter reasons to do so. I have made the mistake of eliminating the co-linear variables before from this dataset but will try not to do it again. The rule of thumb is to have 20 observations for each parameter (this is one of the most asked and most dodged questions in statistics education; see Table 4.1 of <em>Regression Modelling Strategies</em> for this particular answer), which suggests we can have up to 80 parameters with a bit to spare. This gives us 30 parameters to use for non-linear relationships and/or interactions, which is the direction I might go in a subsequent post. Bearing that in mind, I’m not bothering to report here the actual substantive results (eg which factors are related to income and how); that can wait for a better model down the track.</p>
<h2>Data and computing</h2>
<p>The census data are ultimately from Statistics New Zealand of course, but are tidied up and available in my <a target="_blank" href="https://github.com/ellisp/nzelect"><code>nzelect</code></a> R package, which is still very much under development and may change without notice. It’s only available from GitHub at the moment (installation code below).</p>
<p>I do the bootstrapping with the aid of the <code>boot</code> package, which is generally the recommended approach in R. For repeated cross-validation of the two straightforward strategies (full model and stepwise variable selection) I use the <code>caret</code> package, in combination with <code>stepAIC</code> which is in the Venables and Ripley <code>MASS</code> package. For the more complex strategy that involved dropping variables with high variance inflation factors I found it easiest to do the repeated cross-validation old-school with my own <code>for</code> loops.</p>
<p>This exercise was a bit complex and I won’t be astonished if someone points out an error. If you see a problem, or have any suggestions or questions, please leave a comment.</p>
<p>Here’s the code:</p>
<div>
<pre><code data-lang="r"><a name="True-1"></a><span>#===================setup=======================</span>
<a name="True-2"></a><span>library</span><span>(</span>ggplot2<span>)</span>
<a name="True-3"></a><span>library</span><span>(</span>scales<span>)</span>
<a name="True-4"></a><span>library</span><span>(</span>MASS<span>)</span>
<a name="True-5"></a><span>library</span><span>(</span>boot<span>)</span>
<a name="True-6"></a><span>library</span><span>(</span>caret<span>)</span>
<a name="True-7"></a><span>library</span><span>(</span>dplyr<span>)</span>
<a name="True-8"></a><span>library</span><span>(</span>tidyr<span>)</span>
<a name="True-9"></a><span>library</span><span>(</span>directlabels<span>)</span>
<a name="True-10"></a>
<a name="True-11"></a><span>set.seed</span><span>(</span><span>123</span><span>)</span>
<a name="True-12"></a>
<a name="True-13"></a><span># install nzelect package that has census data</span>
<a name="True-14"></a>devtools<span>::</span>install_github<span>(</span><span>&quot;ellisp/nzelect/pkg&quot;</span><span>)</span>
<a name="True-15"></a><span>library</span><span>(</span>nzelect<span>)</span>
<a name="True-16"></a>
<a name="True-17"></a><span># drop the columns with areas' code and name</span>
<a name="True-18"></a>au <span>&lt;-</span> AreaUnits2013 <span>%>%</span>
<a name="True-19"></a>   select<span>(</span><span>-</span>AU2014<span>,</span> <span>-</span>Area_Code_and_Description<span>)</span>
<a name="True-20"></a>
<a name="True-21"></a><span># give meaningful rownames, helpful for some diagnostic plots later</span>
<a name="True-22"></a><span>row.names</span><span>(</span>au<span>)</span> <span>&lt;-</span> AreaUnits2013<span>$</span>Area_Code_and_Description
<a name="True-23"></a>
<a name="True-24"></a><span># remove some repetition from the variable names</span>
<a name="True-25"></a><span>names</span><span>(</span>au<span>)</span> <span>&lt;-</span> <span>gsub</span><span>(</span><span>&quot;2013&quot;</span><span>,</span> <span>&quot;&quot;</span><span>,</span> <span>names</span><span>(</span>au<span>))</span>
<a name="True-26"></a>
<a name="True-27"></a><span># restrict to areas with no missing data. If this was any more complicated (eg</span>
<a name="True-28"></a><span># imputation),it would need to be part of the validation resampling too; but</span>
<a name="True-29"></a><span># just dropping them all at the beginning doesn't need to be resampled; the only</span>
<a name="True-30"></a><span># implication would be sample size which would be small impact and complicating.</span>
<a name="True-31"></a>au <span>&lt;-</span> au<span>[</span>complete.cases<span>(</span>au<span>),</span> <span>]</span>
<a name="True-32"></a>
<a name="True-33"></a><span>#==================functions for two of the modelling strategies=====================</span>
<a name="True-34"></a><span># The stepwise variable selection:</span>
<a name="True-35"></a>model_process_step <span>&lt;-</span> <span>function</span><span>(</span>the_data<span>){</span>
<a name="True-36"></a>   model_full <span>&lt;-</span> lm<span>(</span>MedianIncome <span>~</span> <span>.</span><span>,</span> data <span>=</span> the_data<span>)</span>
<a name="True-37"></a>   model_final <span>&lt;-</span> stepAIC<span>(</span>model_full<span>,</span> direction <span>=</span> <span>&quot;both&quot;</span><span>,</span> trace <span>=</span> <span>0</span><span>)</span>
<a name="True-38"></a>   <span>return</span><span>(</span>model_final<span>)</span>
<a name="True-39"></a><span>}</span>
<a name="True-40"></a>
<a name="True-41"></a><span># The dropping of highly collinear variables, based on Variance Inflation Factor:</span>
<a name="True-42"></a>model_process_vif <span>&lt;-</span> <span>function</span><span>(</span>the_data<span>){</span>
<a name="True-43"></a>   <span># remove the collinear variables based on vif</span>
<a name="True-44"></a>   x <span>&lt;-</span> <span>20</span>
<a name="True-45"></a>   
<a name="True-46"></a>   <span>while</span><span>(</span><span>max</span><span>(</span>x<span>)</span> <span>></span> <span>10</span><span>){</span>
<a name="True-47"></a>      mod1 <span>&lt;-</span> lm<span>(</span>MedianIncome <span>~</span> <span>.</span> <span>,</span> data <span>=</span> the_data<span>)</span>
<a name="True-48"></a>      x <span>&lt;-</span> <span>sort</span><span>(</span>car<span>::</span>vif<span>(</span>mod1<span>)</span> <span>,</span> decreasing <span>=</span> <span>TRUE</span><span>)</span>
<a name="True-49"></a>      the_data <span>&lt;-</span> the_data<span>[</span> <span>,</span> <span>names</span><span>(</span>the_data<span>)</span> <span>!=</span> <span>names</span><span>(</span>x<span>)[</span><span>1</span><span>]]</span>
<a name="True-50"></a>      <span># message(paste(&quot;dropping&quot;, names(x)[1]))</span>
<a name="True-51"></a>   <span>}</span>
<a name="True-52"></a>   
<a name="True-53"></a>   model_vif <span>&lt;-</span> lm<span>(</span>MedianIncome <span>~</span> <span>.</span><span>,</span> data <span>=</span> the_data<span>)</span>
<a name="True-54"></a>   <span>return</span><span>(</span>model_vif<span>)</span>
<a name="True-55"></a><span>}</span>
<a name="True-56"></a>
<a name="True-57"></a><span># The third strategy, full model, is only a one-liner with standard functions</span>
<a name="True-58"></a><span># so I don't need to define a function separately for it.</span>
<a name="True-59"></a>
<a name="True-60"></a><span>#==================Different validation methods=================</span>
<a name="True-61"></a>
<a name="True-62"></a><span>#------------------simple bootstrap comparison-------------------------</span>
<a name="True-63"></a><span># create a function suitable for boot that will return the goodness of fit</span>
<a name="True-64"></a><span># statistics testing models against the full original sample.</span>
<a name="True-65"></a>compare <span>&lt;-</span> <span>function</span><span>(</span>orig_data<span>,</span> i<span>){</span>
<a name="True-66"></a>   <span># create the resampled data</span>
<a name="True-67"></a>   train_data <span>&lt;-</span> orig_data<span>[</span>i<span>,</span> <span>]</span>
<a name="True-68"></a>   test_data <span>&lt;-</span> orig_data <span># ie the full original sample</span>
<a name="True-69"></a>   
<a name="True-70"></a>   <span># fit the three modelling processes</span>
<a name="True-71"></a>   model_step <span>&lt;-</span> model_process_step<span>(</span>train_data<span>)</span>
<a name="True-72"></a>   model_vif  <span>&lt;-</span> model_process_vif<span>(</span>train_data<span>)</span>
<a name="True-73"></a>   model_full <span>&lt;-</span> lm<span>(</span>MedianIncome <span>~</span> <span>.</span><span>,</span> data <span>=</span> train_data<span>)</span>
<a name="True-74"></a>   
<a name="True-75"></a>   <span># predict the values on the original, unresampled data</span>
<a name="True-76"></a>   predict_step <span>&lt;-</span> predict<span>(</span>model_step<span>,</span> newdata <span>=</span> test_data<span>)</span>
<a name="True-77"></a>   predict_vif  <span>&lt;-</span> predict<span>(</span>model_vif<span>,</span> newdata <span>=</span> test_data<span>)</span>
<a name="True-78"></a>   predict_full  <span>&lt;-</span> predict<span>(</span>model_full<span>,</span> newdata <span>=</span> test_data<span>)</span>
<a name="True-79"></a>   
<a name="True-80"></a>   <span># return a vector of 6 summary results</span>
<a name="True-81"></a>   results <span>&lt;-</span> <span>c</span><span>(</span>
<a name="True-82"></a>      step_R2 <span>=</span> R2<span>(</span>predict_step<span>,</span> test_data<span>$</span>MedianIncome<span>),</span>
<a name="True-83"></a>      vif_R2  <span>=</span> R2<span>(</span>predict_vif<span>,</span> test_data<span>$</span>MedianIncome<span>),</span>
<a name="True-84"></a>      full_R2  <span>=</span> R2<span>(</span>predict_full<span>,</span> test_data<span>$</span>MedianIncome<span>),</span>
<a name="True-85"></a>      step_RMSE <span>=</span> RMSE<span>(</span>predict_step<span>,</span> test_data<span>$</span>MedianIncome<span>),</span>
<a name="True-86"></a>      vif_RMSE  <span>=</span> RMSE<span>(</span>predict_vif<span>,</span> test_data<span>$</span>MedianIncome<span>),</span>
<a name="True-87"></a>      full_RMSE  <span>=</span> RMSE<span>(</span>predict_full<span>,</span> test_data<span>$</span>MedianIncome<span>)</span>
<a name="True-88"></a>   <span>)</span>
<a name="True-89"></a>   <span>return</span><span>(</span>results<span>)</span>
<a name="True-90"></a><span>}</span>
<a name="True-91"></a>
<a name="True-92"></a><span># perform bootstrap</span>
<a name="True-93"></a>Repeats <span>&lt;-</span> <span>100</span>
<a name="True-94"></a>res <span>&lt;-</span> boot<span>(</span>au<span>,</span> statistic <span>=</span> compare<span>,</span> R <span>=</span> Repeats<span>)</span>
<a name="True-95"></a>
<a name="True-96"></a><span># restructure results for a graphic showing root mean square error, and for</span>
<a name="True-97"></a><span># later combination with the other results. I chose just to focus on RMSE;</span>
<a name="True-98"></a><span># the messages are similar if R squared is used.</span>
<a name="True-99"></a>RMSE_res <span>&lt;-</span> <span>as.data.frame</span><span>(</span>res<span>$</span><span>t</span><span>[</span> <span>,</span> <span>4</span><span>:</span><span>6</span><span>])</span>
<a name="True-100"></a><span>names</span><span>(</span>RMSE_res<span>)</span> <span>&lt;-</span> <span>c</span><span>(</span><span>&quot;AIC stepwise selection&quot;</span><span>,</span> <span>&quot;Remove collinear variables&quot;</span><span>,</span> <span>&quot;Use all variables&quot;</span><span>)</span>
<a name="True-101"></a>
<a name="True-102"></a>RMSE_res <span>%>%</span>
<a name="True-103"></a>   mutate<span>(</span>trial <span>=</span> <span>1</span><span>:</span>Repeats<span>)</span> <span>%>%</span>
<a name="True-104"></a>   gather<span>(</span>variable<span>,</span> value<span>,</span> <span>-</span>trial<span>)</span> <span>%>%</span> 
<a name="True-105"></a>   <span># re-order levels:</span>
<a name="True-106"></a>   mutate<span>(</span>variable <span>=</span> <span>factor</span><span>(</span>variable<span>,</span> levels <span>=</span> <span>c</span><span>(</span>
<a name="True-107"></a>      <span>&quot;Remove collinear variables&quot;</span><span>,</span> <span>&quot;AIC stepwise selection&quot;</span><span>,</span> <span>&quot;Use all variables&quot;</span>
<a name="True-108"></a>   <span>)))</span> <span>%>%</span>
<a name="True-109"></a>   ggplot<span>(</span>aes<span>(</span>x <span>=</span> trial<span>,</span> y <span>=</span> value<span>,</span> colour <span>=</span> variable<span>))</span> <span>+</span>
<a name="True-110"></a>   geom_line<span>()</span> <span>+</span>
<a name="True-111"></a>   geom_point<span>()</span> <span>+</span>
<a name="True-112"></a>   ggtitle<span>(</span><span>&quot;'Simple' bootstrap of model fit of three different regression strategies&quot;</span><span>,</span>
<a name="True-113"></a>           subtitle <span>=</span> <span>&quot;Predicting areas' median income based on census variables&quot;</span><span>)</span> <span>+</span>
<a name="True-114"></a>   labs<span>(</span>x <span>=</span> <span>&quot;Resample id (there no meaning in the order of resamples)n&quot;</span><span>,</span>
<a name="True-115"></a>        y <span>=</span> <span>&quot;Root Mean Square Error (higher is worse)n&quot;</span><span>,</span>
<a name="True-116"></a>        colour <span>=</span> <span>&quot;Strategy&quot;</span><span>,</span>
<a name="True-117"></a>        caption <span>=</span> <span>&quot;Data from New Zealand Census 2013&quot;</span><span>)</span>
<a name="True-118"></a>
<a name="True-119"></a><span># store the three &quot;simple bootstrap&quot; RMSE results for later</span>
<a name="True-120"></a>simple <span>&lt;-</span> <span>apply</span><span>(</span>RMSE_res<span>,</span> <span>2</span><span>,</span> <span>mean</span><span>)</span>
<a name="True-121"></a>
<a name="True-122"></a><span>#-----------------------enhanced (optimism) bootstrap comparison-------------------</span>
<a name="True-123"></a><span># for convenience, estimate the models on the original sample of data</span>
<a name="True-124"></a>orig_step <span>&lt;-</span> model_process_step<span>(</span>au<span>)</span>
<a name="True-125"></a>orig_vif <span>&lt;-</span> model_process_vif<span>(</span>au<span>)</span>
<a name="True-126"></a>orig_full <span>&lt;-</span> lm<span>(</span>MedianIncome <span>~</span> <span>.</span><span>,</span> data <span>=</span> au<span>)</span>
<a name="True-127"></a>
<a name="True-128"></a><span># create a function suitable for boot that will return the optimism estimates for</span>
<a name="True-129"></a><span># statistics testing models against the full original sample.</span>
<a name="True-130"></a>compare_opt <span>&lt;-</span> <span>function</span><span>(</span>orig_data<span>,</span> i<span>){</span>
<a name="True-131"></a>   <span># create the resampled data</span>
<a name="True-132"></a>   train_data <span>&lt;-</span> orig_data<span>[</span>i<span>,</span> <span>]</span>
<a name="True-133"></a>
<a name="True-134"></a>   <span># fit the three modelling processes</span>
<a name="True-135"></a>   model_step <span>&lt;-</span> model_process_step<span>(</span>train_data<span>)</span>
<a name="True-136"></a>   model_vif  <span>&lt;-</span> model_process_vif<span>(</span>train_data<span>)</span>
<a name="True-137"></a>   model_full <span>&lt;-</span> lm<span>(</span>MedianIncome <span>~</span> <span>.</span><span>,</span> data <span>=</span> train_data<span>)</span>
<a name="True-138"></a>   
<a name="True-139"></a>   <span># predict the values on the original, unresampled data</span>
<a name="True-140"></a>   predict_step <span>&lt;-</span> predict<span>(</span>model_step<span>,</span> newdata <span>=</span> orig_data<span>)</span>
<a name="True-141"></a>   predict_vif  <span>&lt;-</span> predict<span>(</span>model_vif<span>,</span> newdata <span>=</span> orig_data<span>)</span>
<a name="True-142"></a>   predict_full  <span>&lt;-</span> predict<span>(</span>model_full<span>,</span> newdata <span>=</span> orig_data<span>)</span>
<a name="True-143"></a>   
<a name="True-144"></a>   <span># return a vector of 6 summary optimism results</span>
<a name="True-145"></a>   results <span>&lt;-</span> <span>c</span><span>(</span>
<a name="True-146"></a>      step_R2 <span>=</span> R2<span>(</span>fitted<span>(</span>model_step<span>),</span> train_data<span>$</span>MedianIncome<span>)</span> <span>-</span> R2<span>(</span>predict_step<span>,</span> orig_data<span>$</span>MedianIncome<span>),</span>
<a name="True-147"></a>      vif_R2  <span>=</span> R2<span>(</span>fitted<span>(</span>model_vif<span>),</span> train_data<span>$</span>MedianIncome<span>)</span> <span>-</span> R2<span>(</span>predict_vif<span>,</span> orig_data<span>$</span>MedianIncome<span>),</span>
<a name="True-148"></a>      full_R2  <span>=</span> R2<span>(</span>fitted<span>(</span>model_full<span>),</span> train_data<span>$</span>MedianIncome<span>)</span> <span>-</span> R2<span>(</span>predict_full<span>,</span> orig_data<span>$</span>MedianIncome<span>),</span>
<a name="True-149"></a>      step_RMSE <span>=</span> RMSE<span>(</span>fitted<span>(</span>model_step<span>),</span> train_data<span>$</span>MedianIncome<span>)</span> <span>-</span> RMSE<span>(</span>predict_step<span>,</span> orig_data<span>$</span>MedianIncome<span>),</span>
<a name="True-150"></a>      vif_RMSE  <span>=</span> RMSE<span>(</span>fitted<span>(</span>model_vif<span>),</span> train_data<span>$</span>MedianIncome<span>)</span> <span>-</span> RMSE<span>(</span>predict_vif<span>,</span> orig_data<span>$</span>MedianIncome<span>),</span>
<a name="True-151"></a>      full_RMSE  <span>=</span> RMSE<span>(</span>fitted<span>(</span>model_full<span>),</span> train_data<span>$</span>MedianIncome<span>)</span> <span>-</span> RMSE<span>(</span>predict_full<span>,</span> orig_data<span>$</span>MedianIncome<span>)</span>
<a name="True-152"></a>   <span>)</span>
<a name="True-153"></a>   <span>return</span><span>(</span>results<span>)</span>
<a name="True-154"></a><span>}</span>
<a name="True-155"></a>
<a name="True-156"></a><span># perform bootstrap</span>
<a name="True-157"></a>res_opt <span>&lt;-</span> boot<span>(</span>au<span>,</span> statistic <span>=</span> compare_opt<span>,</span> R <span>=</span> Repeats<span>)</span>
<a name="True-158"></a>
<a name="True-159"></a><span># calculate and store the results for later</span>
<a name="True-160"></a>original <span>&lt;-</span> <span>c</span><span>(</span>
<a name="True-161"></a>   RMSE<span>(</span>fitted<span>(</span>orig_step<span>),</span> au<span>$</span>MedianIncome<span>),</span> 
<a name="True-162"></a>   RMSE<span>(</span>fitted<span>(</span>orig_vif<span>),</span> au<span>$</span>MedianIncome<span>),</span>
<a name="True-163"></a>   RMSE<span>(</span>fitted<span>(</span>orig_full<span>),</span> au<span>$</span>MedianIncome<span>)</span>
<a name="True-164"></a><span>)</span>
<a name="True-165"></a>
<a name="True-166"></a>optimism <span>&lt;-</span> <span>apply</span><span>(</span>res_opt<span>$</span><span>t</span><span>[</span> <span>,</span> <span>4</span><span>:</span><span>6</span><span>],</span> <span>2</span><span>,</span> <span>mean</span><span>)</span>
<a name="True-167"></a>enhanced <span>&lt;-</span> original <span>-</span> optimism
<a name="True-168"></a>
<a name="True-169"></a>
<a name="True-170"></a><span>#------------------repeated cross-validation------------------</span>
<a name="True-171"></a><span># The number of cross validation repeats is the number of bootstrap repeats / 10:</span>
<a name="True-172"></a>cv_repeat_num <span>&lt;-</span> Repeats <span>/</span> <span>10</span>
<a name="True-173"></a>
<a name="True-174"></a><span># use caret::train for the two standard models:</span>
<a name="True-175"></a>the_control <span>&lt;-</span> trainControl<span>(</span>method <span>=</span> <span>&quot;repeatedcv&quot;</span><span>,</span> number <span>=</span> <span>10</span><span>,</span> repeats <span>=</span> cv_repeat_num<span>)</span>
<a name="True-176"></a>cv_full <span>&lt;-</span> train<span>(</span>MedianIncome <span>~</span> <span>.</span><span>,</span> data <span>=</span> au<span>,</span> method <span>=</span> <span>&quot;lm&quot;</span><span>,</span> trControl <span>=</span> the_control<span>)</span>
<a name="True-177"></a>cv_step <span>&lt;-</span> train<span>(</span>MedianIncome <span>~</span> <span>.</span><span>,</span> data <span>=</span> au<span>,</span> method <span>=</span> <span>&quot;lmStepAIC&quot;</span><span>,</span> trControl <span>=</span> the_control<span>,</span> trace <span>=</span> <span>0</span><span>)</span>
<a name="True-178"></a>
<a name="True-179"></a><span># do it by hand for the VIF model:</span>
<a name="True-180"></a>results <span>&lt;-</span> <span>numeric</span><span>(</span><span>10</span> <span>*</span> cv_repeat_num<span>)</span>
<a name="True-181"></a><span>for</span><span>(</span>j <span>in</span> <span>0</span><span>:</span><span>(</span>cv_repeat_num <span>-</span> <span>1</span><span>)){</span>
<a name="True-182"></a>   cv_group <span>&lt;-</span> <span>sample</span><span>(</span><span>1</span><span>:</span><span>10</span><span>,</span> <span>nrow</span><span>(</span>au<span>),</span> replace <span>=</span> <span>TRUE</span><span>)</span>
<a name="True-183"></a>   <span>for</span><span>(</span>i <span>in</span> <span>1</span><span>:</span><span>10</span><span>){</span>
<a name="True-184"></a>      train_data <span>&lt;-</span> au<span>[</span>cv_group <span>!=</span> i<span>,</span> <span>]</span>
<a name="True-185"></a>      test_data <span>&lt;-</span> au<span>[</span>cv_group <span>==</span> i<span>,</span> <span>]</span>
<a name="True-186"></a>      results<span>[</span>j <span>*</span> <span>10</span> <span>+</span> i<span>]</span> <span>&lt;-</span> RMSE<span>(</span>
<a name="True-187"></a>         predict<span>(</span>model_process_vif<span>(</span>train_data<span>),</span> newdata <span>=</span> test_data<span>),</span>
<a name="True-188"></a>         test_data<span>$</span>MedianIncome<span>)</span>
<a name="True-189"></a>   <span>}</span>
<a name="True-190"></a><span>}</span>
<a name="True-191"></a>cv_vif <span>&lt;-</span> <span>mean</span><span>(</span>results<span>)</span>
<a name="True-192"></a>
<a name="True-193"></a>cv_vif_results <span>&lt;-</span> <span>data.frame</span><span>(</span>
<a name="True-194"></a>   results <span>=</span> results<span>,</span>
<a name="True-195"></a>   trial <span>=</span> <span>rep</span><span>(</span><span>1</span><span>:</span><span>10</span><span>,</span> cv_repeat_num<span>),</span>
<a name="True-196"></a>   cv_repeat <span>=</span> <span>rep</span><span>(</span><span>1</span><span>:</span>cv_repeat_num<span>,</span> each <span>=</span> <span>10</span><span>)</span>
<a name="True-197"></a><span>)</span>
<a name="True-198"></a>
<a name="True-199"></a>
<a name="True-200"></a><span>#===============reporting results===============</span>
<a name="True-201"></a><span># combine the three cross-validation results together and combined with</span>
<a name="True-202"></a><span># the bootstrap results from earlier</span>
<a name="True-203"></a>summary_results <span>&lt;-</span> <span>data.frame</span><span>(</span><span>rbind</span><span>(</span>
<a name="True-204"></a>   simple<span>,</span> 
<a name="True-205"></a>   enhanced<span>,</span>
<a name="True-206"></a>   <span>c</span><span>(</span><span>mean</span><span>(</span>cv_step<span>$</span>resample<span>$</span>RMSE<span>),</span> 
<a name="True-207"></a>     cv_vif<span>,</span>
<a name="True-208"></a>     <span>mean</span><span>(</span>cv_full<span>$</span>resample<span>$</span>RMSE<span>)</span>
<a name="True-209"></a>     <span>)</span>
<a name="True-210"></a>   <span>),</span> check.names <span>=</span> <span>FALSE</span><span>)</span> <span>%>%</span>
<a name="True-211"></a>   mutate<span>(</span>method <span>=</span> <span>c</span><span>(</span><span>&quot;Simple bootstrap&quot;</span><span>,</span> <span>&quot;Enhanced bootstrap&quot;</span><span>,</span> 
<a name="True-212"></a>                     <span>paste</span><span>(</span>cv_repeat_num<span>,</span> <span>&quot;repeats 10-foldncross-validation&quot;</span><span>)))</span> <span>%>%</span>
<a name="True-213"></a>   gather<span>(</span>variable<span>,</span> value<span>,</span> <span>-</span>method<span>)</span>
<a name="True-214"></a>
<a name="True-215"></a><span># Draw a plot summarising the results</span>
<a name="True-216"></a>direct.label<span>(</span>
<a name="True-217"></a>summary_results <span>%>%</span>
<a name="True-218"></a>   mutate<span>(</span>variable <span>=</span> <span>factor</span><span>(</span>variable<span>,</span> levels <span>=</span> <span>c</span><span>(</span>
<a name="True-219"></a>      <span>&quot;Use all variables&quot;</span><span>,</span> <span>&quot;AIC stepwise selection&quot;</span><span>,</span> <span>&quot;Remove collinear variables&quot;</span>
<a name="True-220"></a>   <span>)))</span> <span>%>%</span>
<a name="True-221"></a>   ggplot<span>(</span>aes<span>(</span>y <span>=</span> method<span>,</span> x <span>=</span> value<span>,</span> colour <span>=</span> variable<span>))</span> <span>+</span>
<a name="True-222"></a>   geom_point<span>(</span>size <span>=</span> <span>3</span><span>)</span> <span>+</span>
<a name="True-223"></a>   labs<span>(</span>x <span>=</span> <span>&quot;Estimated Root Mean Square Error (higher is worse)n&quot;</span><span>,</span>
<a name="True-224"></a>        colour <span>=</span> <span>&quot;Modellingnstrategy&quot;</span><span>,</span>
<a name="True-225"></a>        y <span>=</span> <span>&quot;Method of estimating model fitn&quot;</span><span>,</span>
<a name="True-226"></a>        caption <span>=</span> <span>&quot;Data from New Zealand Census 2013&quot;</span><span>)</span> <span>+</span>
<a name="True-227"></a>   ggtitle<span>(</span><span>&quot;Three different validation methods of three different regression strategies&quot;</span><span>,</span>
<a name="True-228"></a>           subtitle <span>=</span> <span>&quot;Predicting areas' median income based on census variables&quot;</span><span>)</span>
<a name="True-229"></a>   
<a name="True-230"></a><span>)</span></code></pre>
</div>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="http://www.r-bloggers.com/bootstrap-and-cross-validation-for-evaluating-modelling-strategies/"></div></div><div><a data-url="http://www.r-bloggers.com/bootstrap-and-cross-validation-for-evaluating-modelling-strategies/" data-counturl="http://www.r-bloggers.com/bootstrap-and-cross-validation-for-evaluating-modelling-strategies/" data-count="vertical" data-text="Bootstrap and cross-validation for evaluating modelling strategies" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://ellisp.github.io/blog/2016/06/05/bootstrap-cv-strategies"> Peter's stats stuff - R</a></strong>.</div>
<hr>
<a rel="nofollow" href="http://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="http://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="http://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="http://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="http://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="http://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="http://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="http://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="http://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="http://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="http://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="http://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="http://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="http://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="http://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="http://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="http://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="http://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="http://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/24RV41yUfpY"></a></div>