<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/understanding-overfitting-an-inaccurate-meme-in-supervised-learning/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://memosisland.blogspot.com/2017/08/understanding-overfitting-inaccurate.html"> Memo's Island</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div></div>
<p>
<div><b>Preamble </b><span>There is a lot of confusion among practitioners regarding the concept of </span><a rel="nofollow" href="https://en.wikipedia.org/wiki/Overfitting" target="_blank">overfitting</a><span>. It seems like, a kind of </span><i>an</i><span> </span><i>urban legend</i><span> or a </span><span><i>meme, a folklore </i>is circulating</span><span> in data science or allied fields with the following statement:</span><br>
<blockquote><i>Applying <a rel="nofollow" href="https://en.wikipedia.org/wiki/Cross-validation_(statistics)" target="_blank">cross-validation</a> prevents overfitting and a good out-of-sample performance, low generalisation error in unseen data, indicates not an overfit.</i></blockquote>
</div>
<p>
<div>
<div>This statement is of course not true: cross-validation does not prevent your model to overfit and good out-of-sample performance does not guarantee not-overfitted model. What actually people refer to in one aspect of this statement is called <i>overtraining.</i><i> </i>Unfortunately, this meme is not only propagated in industry but in some academic papers as well. This might be at best a confusion on <i>jargon</i>. But, it will be a good practice if we set the <i>jargon</i> right and clear on what do we refer to when we say <i>overfitting,</i> in communicating our results.
<p><b>Aim</b> In this post, we will give an intuition on why <a rel="nofollow" href="https://en.wikipedia.org/wiki/Regression_validation" target="_blank">model validation</a> as approximating generalization error of a <a rel="nofollow" href="https://en.wikipedia.org/wiki/Goodness_of_fit" target="_blank">model fit</a> and detection of overfitting can not be resolved simultaneously on a single model. We will work on  a concrete example workflow in understanding <i>overfitting</i>, <i>overtraining</i> and a typical final model building stage  after some conceptual introduction. We will avoid giving a reference to the Bayesian interpretations and regularisation and restrict the post to regression and cross-validation. While regularisation has different ramification due to its mathematical properties and prior distributions have different implications in Bayesian statistics. We assume an introductory background in machine learning, so this is not a beginners tutorial.</p>
<p>A recent question from <a rel="nofollow" href="https://en.wikipedia.org/wiki/Andrew_Gelman" target="_blank">Andrew Gelman</a>, a Bayesian guru, regarding <i>What is overfitting?</i> was one of the reasons why this post is developed along with my frustration to see practitioners being muddy on the meaning of <i>overfitting</i> and continuing recently published data science related technical articles circulating around and even in some academic papers claiming the above statement.<br><b><br></b> <b>What do we need to satisfy in supervised learning? </b><span><span>One of the most basic tasks in mathematics is to find a solution to a function: If we restrict ourselves to real numbers in $n$-dimensions and our domain of interest would be $\mathbb{R}^{n}$. Now imagine set of $p$ points living in this domain</span></span><span>  $x_{i}$ </span><span>form a dataset, this is actually <i>a partial</i> solution to a function. The main purpose of modelling is to find an explanation of the </span>dataset, meaning that we need to determine <span>$m$-parameters, $a \in \mathbb{R}^{m}$ which are </span><i>unknown</i><span>. (Note that a non-parametric model does not mean no parameters.) Mathematically speaking this manifests as a function as we said before,  $f(x, a)$. This modelling is usually called <i>regression</i>, <i>interpolation</i> or <i>supervised learning </i>depending on the literature you are reading. This is a form of </span><a rel="nofollow" href="https://en.wikipedia.org/wiki/Inverse_problem" target="_blank">an inverse problem</a><span>, while we don’t know the parameters but we have a partial information regarding variables. The main issue here is ill-posedness, meaning that solutions are not </span><a rel="nofollow" href="https://en.wikipedia.org/wiki/Well-posed_problem" target="_blank">well-posed</a><span>. Omitting axiomatic technical details, practical problem is that we can find many functions </span> $f(x, a)$<span> </span><span> or models, explaining the </span>dataset<span>. So, we seek the following two concepts to be satisfied by our model solution, </span> $f(x, a)=0$.</div>
</div>
<div></div>
<div><span>1. Generalized: A model should not depend on the dataset. This step is called </span><i>model validation.</i></div>
<div><span>2. Minimally complex: A model should obey </span><a rel="nofollow" href="https://en.wikipedia.org/wiki/Occam%27s_razor" target="_blank">Occam’s razor or principle of parsimony</a><span>. This step is called </span><i>model selection</i><span>.</span><br><span><br></span></div>
<div>
<div>
<table cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td><a rel="nofollow" href="https://i2.wp.com/3.bp.blogspot.com/-K5kN3pyTxs4/WZH578AyEjI/AAAAAAAAFSs/6sYVE2WO7KYBwbI8xQr8NOL7_pqSykpYgCLcBGAs/s1600/understand_overfitting.png?ssl=1" target="_blank"><img border="0" data-original-height="562" src="https://i2.wp.com/3.bp.blogspot.com/-K5kN3pyTxs4/WZH578AyEjI/AAAAAAAAFSs/6sYVE2WO7KYBwbI8xQr8NOL7_pqSykpYgCLcBGAs/s320/understand_overfitting.png?resize=450%2C562&ssl=1" data-recalc-dims="1" data-original-width="450"></a></td>
</tr>
<tr>
<td>Figure 1: A workflow for model validation and<br> selection in supervised learning.</td>
</tr>
</tbody>
</table>
<p>Generalization of a model can be measured by <a rel="nofollow" href="https://en.wikipedia.org/wiki/Goodness_of_fit" target="_blank">goodness-of-fit</a>. It essentially tells us how good our model (chosen function) explains the dataset. To find a minimally complex model<b> </b>requires comparison against another model. </div>
</div>
<div>
<div>Up to now, we have not named a technique how to check if a model is generalized and selected as the best model. Unfortunately, there is no unique way of doing both and that’s the task of data scientist or quantitative practitioner that requires human judgement.
</div>
</div>
<div><b>Model validation: An example </b>One way to check if a model is generalized enough is to come up with a metric on how good it explains the dataset. Our task in model validation is to estimate the model error. For example, <a rel="nofollow" href="https://en.wikipedia.org/wiki/Root-mean-square_deviation" target="_blank">root mean square deviation</a> (RMDS) is one metric we can use.  If  RMSD is low, we could say that our model fit is good, ideally it should be close to zero.  But it is not generalized enough if we use the same dataset to measure the goodness-of-fit.  We could use different dataset, specially out-of-sample dataset, to validate this as much as we can, i.e. so called hold out method.  Out-of-sample is just a fancy way of saying we did not use the same dataset to find the value of parameters $a$. An improved way of doing this is cross-validation. We split our dataset into $k$ partitions, and we obtain $k$ RMDS values to averaged over. This is summarised in Figure 1.  <span>Note that, different parameterisation of the same model does not </span>constitute<span> a different model.</span><br><span><br></span></div>
<div><b>Model Selection: Detection of overfitting </b><span>Overfitting comes into play when we try to satisfy ‘minimally complex model’. This is a comparison problem and we need more than one model to judge if a given model is an overfit. </span><span>Douglas Hawkins in his classic paper </span><span><i><a rel="nofollow" href="http://pubs.acs.org/doi/abs/10.1021/ci0342472" target="_blank">The Problem of Overfitting</a></i>, states that </span></div>
<blockquote><p><span><i><span>Overfitting of models is widely recognized as a concern. </span></i></span><span><i><span>It is less recognized however that overfitting is not an </span></i></span><span><i><span>absolute but involves a comparison.</span><span> A model overfits if it is </span></i><span><i>more complex than another model that fits equally well.</i></span></span></p></blockquote>
<p>The important point here what do we mean by complex model, or how can we quantify model complexity? Unfortunately, again there is no unique way of doing this. One of the most used approaches is that a model having more parameters is getting more complex. But this is again a bit of a <i>meme</i> and not generally true. One could actually resort to different measures of complexity. For example, by this definition $f_{1}(a,x)=ax$ and $f_{2}(a,x)=ax^2$ have the same complexity by having the same number of free parameters, but intuitively $f_{2}$ is more complex, while it is nonlinear. There are a lot of information theory based measures of complexity but discussion of those are beyond the scope of our post. For demonstration purposes, we will consider more parameters and degree of <span>nonlinearity as more complex a model.</span><span><br></span> <div></div>
<div></div>
<table cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td><a rel="nofollow" href="https://i0.wp.com/1.bp.blogspot.com/-n1vo-YEeJcw/WZQ8_piIRnI/AAAAAAAAFTs/pqo_UVVHbCczDw8djTEdjUeZaKSfdJBkgCEwYBhgL/s1600/simdata.png?ssl=1" target="_blank"><img border="0" data-original-height="480" src="https://i0.wp.com/1.bp.blogspot.com/-n1vo-YEeJcw/WZQ8_piIRnI/AAAAAAAAFTs/pqo_UVVHbCczDw8djTEdjUeZaKSfdJBkgCEwYBhgL/s320/simdata.png?resize=450%2C480&ssl=1" data-recalc-dims="1" data-original-width="450"></a></td>
</tr>
<tr>
<td>Figure 2: Simulated data and the non-stochastic<br>part of the data.</td>
</tr>
</tbody>
</table>
<p><b>Hand on example </b><span>We have intuitively covered the reasons behind how we can’t resolve model validation and judge overfitting simultaneously. Now try to demonstrate this with a simple dataset and models, yet essentially capturing the above premise.</span><br><span>A usual procedure is to generate a synthetic dataset, or simulated dataset, from a model, as a gold standard and use this dataset to build other models. Let’s use the following functional form, from <a rel="nofollow" href="http://www.springer.com/de/book/9780387310732?referer=www.springer.de" target="_blank">classic text of Bishop</a>, but with an added Gaussian noise </span><span>$$ f(x) = sin(2\pi x) + \mathcal{N}(0,0.1).$$ </span><span>We generate large enough set, 100 points to avoid sample size issue discussed in Bishop’s book, see Figure 2. Let’s decide on two models we would like to apply to this dataset in supervised learning task. Note that, we won’t be discussing Bayesian interpretation here, so equivalency of these model under a strong prior assumption is not an issue as we are using this example for ease of demonstrating the concept. A polynomial model of degree $3$ and degree $5$, we call them $g(x)$ and $h(x)$ respectively are used to learn from the simulated data. $$g(x) = a_{0} + a_{1} x + a_{2} x^{2} + a_{3} x^{3}$$ and </span><span>$$h(x) = b_{0} + b_{1} x + b_{2} x^{2} + b_{3} x^{3} + b_{4} x^{4} + b_{5} x^{5} + b_{6} x^{6}.$$ </span><br>
<table cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td><a rel="nofollow" href="https://i2.wp.com/4.bp.blogspot.com/-PIzITKxyGZI/WZQ9DZ9OWlI/AAAAAAAAFT0/pTiSEZqa_dUL13qIjb7GZ1QfO2sYFQZ2wCEwYBhgL/s1600/over_training_g.png?ssl=1" target="_blank"><img border="0" data-original-height="480" src="https://i2.wp.com/4.bp.blogspot.com/-PIzITKxyGZI/WZQ9DZ9OWlI/AAAAAAAAFT0/pTiSEZqa_dUL13qIjb7GZ1QfO2sYFQZ2wCEwYBhgL/s320/over_training_g.png?resize=450%2C480&ssl=1" data-recalc-dims="1" data-original-width="450"></a></td>
</tr>
<tr>
<td>Figure 3: Overtraining occurs at around after 40<br>percent of the data usage for g(x).</td>
</tr>
</tbody>
</table>
<p><span></span><b>Overtraining is not overfitting </b><span><i>Overtraining</i> means a model performance degrades in learning model parameters against an objective variable that effects how model is build, for example, an objective variable can be a training data size or iteration cycle in neural network. This is more prevalent in neural networks (see <a rel="nofollow" href="http://onlinelibrary.wiley.com/doi/10.1002/1097-0142(20010415)91:8%2B%3C1615::AID-CNCR1175%3E3.0.CO;2-L/full" target="_blank">Dayhoff 2011</a>). In our practical example, this will manifest in hold out method to measure RMSD in modelling with g(x). In other words finding an optimal number of data points to use to train the model to give a better performance on unseen data, See Figure 3 and 4.</span>
<div><span></span></div>
<p><b><b>Overfitting with low validation error </b></b><span>We can also estimate 10-fold cross-validation error, CV-RMSD. For this sampling, g and h have 0.13 and 0.12 CV-RMSD respectively. So as we can see, we have a situation that more complex model reaches similar predictive power with cross validation and we can not distinguish this overfitting by just looking at CV-RMSD value or detecting ‘overtraining’ curve from Figures 4. We need two models to compare, hence both Figure 3 and 4, with both CV-RMSD values. We might argue that in small data sets we might be able tell the difference by looking at test and training error differences, this is exactly how Bishop explains <i>overfitting;</i> where he points out <i>overtraining</i> in small datasets. </span><br><span><b>Which trained model to deploy?</b></span><span> Now the question is, we found out best performing model with minimal complexity empirically. All well, but which trained model should we use in production?</span><br><span>Actualy we have already build the model in model selection. In above case, since we got similar</span><br><span>predictive power from g and h, we obviously will use g, trained on the splitting sweet spot from Figure 3.</span><br><b></b><br><b></b> <br>
<table cellspacing="0" align="center" cellpadding="0">
<tbody>
<tr>
<td><a rel="nofollow" href="https://i0.wp.com/3.bp.blogspot.com/-cFamsyVpPCo/WZQ9DJMwmiI/AAAAAAAAFT8/BsAa1JPl2a0VPlQSnQkm_GxomFcgXz0CgCEwYBhgL/s1600/over_training_h.png?ssl=1" target="_blank"><img border="0" data-original-height="480" src="https://i1.wp.com/3.bp.blogspot.com/-cFamsyVpPCo/WZQ9DJMwmiI/AAAAAAAAFT8/BsAa1JPl2a0VPlQSnQkm_GxomFcgXz0CgCEwYBhgL/s320/over_training_h.png?resize=450%2C480&ssl=1" data-recalc-dims="1" data-original-width="450"></a></td>
</tr>
<tr>
<td>Figure 4: Overtraining occurs at around after 30<br>percent of the data usage for h(x)</td>
</tr>
</tbody>
</table>
<p><span><b>Conclusion </b></span><span>The essential message here is poor validation performance would not guarantee the detection of an <i>overfitted</i> model. As we have seen from examples using synthetic data in one dimension. </span><i>Overtraining</i><span> is actually what most practitioners mean when they use the term </span><i>overfitting</i><span>. </span></p>
<p><span><b>Outlook </b><span>As more and more people are using techniques from machine learning or inverse problems, both in academia and industry, some key technical concepts are deviated a bit and take different definitions and meaning for different people, due to the fact that people learn some concepts not from reading the literature carefully but from their line managers or senior colleagues verbally. This creates <i>memes</i> which are actually wrong or at least creating lots of confusion in jargon. It is very important for all of us as practitioners that we must </span><i>question</i><span> all technical concepts and try to seek origins from the published scientific literature and not rely entirely on verbal explanations from our experienced colleagues. Also, we should strongly avoid ridiculing question from colleagues even they sound too simple, at the end of the day we don’t stop learning and naive looking questions might have very important consequences in fundamentals of the field.</span><b></b></span></p>
<table cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td><a rel="nofollow" href="https://i1.wp.com/4.bp.blogspot.com/-smLEhaDDhew/WZQ9DAS5E0I/AAAAAAAAFT8/7yFry4unV_kpgJdiWkzymsIhsQA24-rEQCEwYBhgL/s1600/test_set_predictions.png?ssl=1" target="_blank"><img border="0" data-original-height="480" src="https://i2.wp.com/4.bp.blogspot.com/-smLEhaDDhew/WZQ9DAS5E0I/AAAAAAAAFT8/7yFry4unV_kpgJdiWkzymsIhsQA24-rEQCEwYBhgL/s320/test_set_predictions.png?resize=450%2C480&ssl=1" data-recalc-dims="1" data-original-width="450"></a></td>
</tr>
<tr>
<td>Figure 5: A deployed models h and g  on the testing set with<br>the original data. </td>
</tr>
</tbody>
</table>
<p><span><b>Appendix: Reproducing the example using R </b></span></p>
<p><span>The code used in producing the synthetic data, modelling step and visualising the results can be found in github [<a rel="nofollow" href="https://github.com/msuzen/memosisland/tree/master/understandingOverfitting" target="_blank">repo</a>]. In this appendix, we present this R code with detailed comments, but visualisation codes are omitted, they are available in the github repository. </span><br><span><br></span> <span><a rel="nofollow" href="https://www.r-project.org/" target="_blank">R (GNU S)</a> provides very powerful formula interface. It is probably the most advanced and expressive <a rel="nofollow" href="https://stat.ethz.ch/R-manual/R-devel/library/stats/html/formula.html" target="_blank">formula interface</a> in statistical computing, of course along with S. </span><br><span><br></span> <span><br></span> <span><br></span> <span><br></span> <span><br></span> <span><br></span> <span><br></span> <span>Above two polynomials can be expressed as formula and as well as a function where we can evaluate. </span><br><span><br></span> 
<div>
<table>
<tbody>
<tr>
<td>
<pre>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9</pre>
</td>
<td>
<pre><span>#'</span><br><span>#' Two polynomial models: g and h, 3rd and 5th degree respectively.</span><br><span>#' </span><br>g_fun <span>&lt;-</span> function(x,params) <span>as</span><span>.</span>numeric(params[<span>1</span>]<span>+</span>x<span>*</span>params[<span>2</span>]<span>+</span>x<span>^</span><span>2</span><span>*</span>params[<span>3</span>]<span>+</span>x<span>^</span><span>3</span><span>*</span>params[<span>4</span>])<br>h_fun <span>&lt;-</span> function(x,params) <span>as</span><span>.</span>numeric(params[<span>1</span>]<span>+</span>x<span>*</span>params[<span>2</span>]<span>+</span>x<span>^</span><span>2</span><span>*</span>params[<span>3</span>]<span>+</span>params[<span>4</span>]<span>*</span>x<span>^</span><span>3</span><span>+</span><br>                                                   params[<span>5</span>]<span>*</span>x<span>^</span><span>4</span><span>+</span>params[<span>6</span>]<span>*</span>x<span>^</span>{<span>5</span>}<span>+</span><br>                                                   params[<span>7</span>]<span>*</span>x<span>^</span>{<span>6</span>})<br>g_formula <span>&lt;-</span> ysim <span>~</span> I(x) <span>+</span> I(x<span>^</span><span>2</span>) <span>+</span> I(x<span>^</span><span>3</span>) <br>h_formula <span>&lt;-</span> ysim <span>~</span> I(x) <span>+</span> I(x<span>^</span><span>2</span>) <span>+</span> I(x<span>^</span><span>3</span>) <span>+</span> I(x<span>^</span><span>4</span>) <span>+</span> I(x<span>^</span><span>5</span>) <span>+</span> I(x<span>^</span><span>6</span>)  <br></pre>
</td>
</tr>
</tbody>
</table>
</div>
<p><span><br></span> <span>A learning from data will be achieved with <a rel="nofollow" href="https://stat.ethz.ch/R-manual/R-devel/library/stats/html/lm.html" target="_blank">lm</a> function from R, </span><br>
<div>
<table>
<tbody>
<tr>
<td>
<pre>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8</pre>
</td>
<td>
<pre><span>#'</span><br><span>#' Given data.frame with x and ysim, and an R formula with ysim=f(x), </span><br><span>#' fit a linear model </span><br><span>#'</span><br>get_coefficients <span>&lt;-</span> function(data_portion, model_formula) {<br> model <span>&lt;-</span> lm(model_formula, data<span>=</span>data_portion)<br> <span>return</span>(model<span>$</span>coefficients)<br>}<br></pre>
</td>
</tr>
</tbody>
</table>
</div>
<p><span>and the resulting approximated function can be applied to new data set with the following helper functions with measuring RMSD as a performance metric.</span><br>
<div>
<table>
<tbody>
<tr>
<td>
<pre>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9</pre>
</td>
<td>
<pre><span>#'</span><br><span>#' Find the prediction error for a given model_function and model_formula</span><br><span>#'</span><br>lm_rmsd <span>&lt;-</span> function(x_train, y_train, x_test, y_test, model_function, model_formula) {<br>   params <span>&lt;-</span> get_coefficients(data<span>.</span>frame(x<span>=</span>x_train,ysim<span>=</span>y_train), model_formula)<br>   params[<span>as</span><span>.</span>numeric(which(<span>is</span><span>.</span>na(params)))] <span>&lt;-</span> <span>0</span> <span># if there is any co-linearity</span><br>   f_hat  <span>&lt;-</span> sapply(x_test, model_function, params<span>=</span>params)<br>   <span>return</span>(sqrt(<span>sum</span>((f_hat<span>-</span>y_test)<span>^</span><span>2</span>)<span>/</span>length(f_hat)))<br>}<br></pre>
</td>
</tr>
</tbody>
</table>
</div>
<p><span><br></span> <span>We can generate a simulated data as we discussed above by using runif. </span><br><span><br></span> 
<div>
<table>
<tbody>
<tr>
<td>
<pre> 1<br> 2<br> 3<br> 4<br> 5<br> 6<br> 7<br> 8<br> 9<br>10<br>11<br>12<br>13</pre>
</td>
<td>
<pre><span>#' </span><br><span>#' Generate a synthetic dataset</span><br><span>#' A similar model from Bishop : </span><br><span>#' </span><br><span>#' f(x) = sin(2pi*x) + N(0, 0.1)</span><br><span>#' </span><br><span>set</span><span>.</span>seed(<span>424242</span>)<br>f       <span>&lt;-</span> function(x) <span>return</span>(sin(<span>2</span><span>*</span>pi<span>*</span>x))<br>fsim    <span>&lt;-</span> function(x) <span>return</span>(sin(<span>2</span><span>*</span>pi<span>*</span>x)<span>+</span>rnorm(<span>1</span>,<span>0</span>,<span>0.1</span>))<br>x       <span>&lt;-</span> seq(<span>0</span>,<span>1</span>,<span>1e-2</span>)<br>y       <span>&lt;-</span> sapply(x,f)<br>ysim    <span>&lt;-</span> sapply(x,fsim)<br>simdata <span>&lt;-</span> data<span>.</span>frame(x<span>=</span>x, y<span>=</span>y, ysim<span>=</span>ysim)<br></pre>
</td>
</tr>
</tbody>
</table>
</div>
<p><span>To detect <i>overtraining</i> we can split the data in different places in increasing training size, and measure the the performance on the training data itself and unseen test data.</span><br><span><br></span> 
<div>
<table>
<tbody>
<tr>
<td>
<pre> 1<br> 2<br> 3<br> 4<br> 5<br> 6<br> 7<br> 8<br> 9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>19<br>20<br>21<br>22<br>23<br>24<br>25<br>26<br>27<br>28<br>29<br>30<br>31<br>32<br>33<br>34</pre>
</td>
<td>
<pre><span>#'</span><br><span>#' Demonstration of overtraining with g</span><br><span>#' </span><br><span>#'</span><br><span>set</span><span>.</span>seed(<span>424242</span>)<br>model_function <span>&lt;-</span> g_fun<br>model_formula  <span>&lt;-</span> g_formula<br>split_percent  <span>&lt;-</span> seq(<span>0.05</span>,<span>0.95</span>,<span>0.03</span>)<br>split_len      <span>&lt;-</span> length(split_percent)<br>data_len       <span>&lt;-</span> length(simdata<span>$</span>ysim) <br>splits         <span>&lt;-</span> <span>as</span><span>.</span>integer(data_len<span>*</span>split_percent)<br>test_rmsd      <span>&lt;-</span> vector(<span>&quot;integer&quot;</span>, split_len<span>-</span><span>1</span>)<br>train_rmsd     <span>&lt;-</span> vector(<span>&quot;integer&quot;</span>, split_len<span>-</span><span>1</span>)<br><span>for</span>(i <span>in</span> <span>2</span>:split_len) {<br> train_ix <span>&lt;-</span> sample(<span>1</span>:data_len,splits[i<span>-</span><span>1</span>]) <br> test_ix  <span>&lt;-</span> (<span>1</span>:data_len)[<span>-</span>train_ix]<br> train_rmsd[i<span>-</span><span>1</span>] <span>&lt;-</span>  lm_rmsd(simdata<span>$</span>x[train_ix], <br>                            simdata<span>$</span>ysim[train_ix], <br>                            simdata<span>$</span>x[train_ix], <br>                            simdata<span>$</span>ysim[train_ix],<br>                            model_function, <br>                            model_formula)<br> test_rmsd[i<span>-</span><span>1</span>] <span>&lt;-</span>  lm_rmsd(simdata<span>$</span>x[train_ix], <br>                             simdata<span>$</span>ysim[train_ix], <br>                             simdata<span>$</span>x[test_ix], <br>                             simdata<span>$</span>ysim[test_ix],<br>                             model_function, <br>                             model_formula)<br>}<br><br>rmsd_df            <span>&lt;-</span> data<span>.</span>frame(test_rmsd<span>=</span>test_rmsd, train_rmsd<span>=</span>train_rmsd, percent<span>=</span>split_percent[<span>-</span><span>1</span>]) <br>rmsd_df2           <span>&lt;-</span> melt(rmsd_df, <span>id</span><span>=</span>c(<span>&quot;percent&quot;</span>))<br>colnames(rmsd_df2) <span>&lt;-</span> c(<span>&quot;percent&quot;</span>, <span>&quot;Error_on&quot;</span>, <span>&quot;rmsd&quot;</span>)<br>rmsd_df2<span>$</span>test_train <span>&lt;-</span> <span>as</span><span>.</span>factor(rmsd_df2<span>$</span>Error_on)<br></pre>
</td>
</tr>
</tbody>
</table>
</div>
<p><span>And the last portion of the code does 10-fold cross-validation.</span><br><span><br></span> 
<div>
<table>
<tbody>
<tr>
<td>
<pre> 1<br> 2<br> 3<br> 4<br> 5<br> 6<br> 7<br> 8<br> 9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>19<br>20<br>21<br>22<br>23<br>24<br>25<br>26<br>27<br>28<br>29<br>30</pre>
</td>
<td>
<pre><span>#' CV for g(x) and h(x)</span><br>split_percent  <span>&lt;-</span> seq(<span>0</span>,<span>1</span>,<span>0.1</span>)<br>split_len      <span>&lt;-</span> length(split_percent)<br>data_len       <span>&lt;-</span> length(simdata<span>$</span>ysim) <br>splits         <span>&lt;-</span> <span>as</span><span>.</span>integer(data_len<span>*</span>split_percent)<br>cv_rmsd_g      <span>&lt;-</span> <span>0</span><br>cv_rmsd_h      <span>&lt;-</span> <span>0</span><br><span>for</span>(i <span>in</span> <span>2</span>:split_len) { <span># 10-fold cross validation</span><br>  test_ix  <span>&lt;-</span> (splits[i<span>-</span><span>1</span>]<span>+</span><span>1</span>):splits[i]<br>  train_ix   <span>&lt;-</span> (<span>1</span>:data_len)[<span>-</span>test_ix]<br>  x_train   <span>&lt;-</span> simdata<span>$</span>x[train_ix]<br>  y_train   <span>&lt;-</span> simdata<span>$</span>ysim[train_ix]<br>  x_test    <span>&lt;-</span> simdata<span>$</span>x[test_ix]<br>  y_test    <span>&lt;-</span> simdata<span>$</span>ysim[test_ix]<br>  cv_rmsd_g <span>&lt;-</span>  lm_rmsd(x_train,<br>                        y_train,<br>                        x_test,<br>                        y_test,<br>                        g_fun, <br>                        g_formula)<span>+</span>cv_rmsd_g<br>  cv_rmsd_h <span>&lt;-</span>   lm_rmsd(x_train,<br>                         y_train,<br>                         x_test,<br>                         y_test,<br>                         h_fun, <br>                         h_formula)<span>+</span>cv_rmsd_h<br>}<br><br>cat(<span>&quot;10-fold CV error G = &quot;</span>, cv_rmsd_g<span>/</span>split_len,<span>&quot;</span><span>\n</span><span>&quot;</span>) <span># 0.1304164</span><br>cat(<span>&quot;10-fold CV error H = &quot;</span>, cv_rmsd_h<span>/</span>split_len,<span>&quot;</span><span>\n</span><span>&quot;</span>) <span># 0.1206458</span><br></pre>
</td>
</tr>
</tbody>
</table>
</div>
<p><span><br></span> <span><br></span> <span><br></span> <span><br></span></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="http://memosisland.blogspot.com/2017/08/understanding-overfitting-inaccurate.html"> Memo's Island</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/2Wz9cbfUBTc" height="1"></a></div>