<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/importance-sampling-adds-an-interesting-twist-to-monte-carlo-simulation/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.rdatagen.net/post/importance-sampling-adds-a-little-excitement-to-monte-carlo-simulation/"> ouR data generation</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>I’m contemplating the idea of teaching a course on simulation next fall, so I have been exploring various topics that I might include. (If anyone has great ideas either because you have taught such a course or taken one, definitely drop me a note.) Monte Carlo (MC) simulation is an obvious one. I like the idea of talking about <em>importance sampling</em>, because it sheds light on the idea that not all MC simulations are created equally. I thought I’d do a brief blog to share some code I put together that demonstrates MC simulation generally, and shows how importance sampling can be an improvement.</p>
<p>Like many of the topics I’ve written about, this is a vast one that certainly warrants much, much more than a blog entry. MC simulation in particular, since it is so fundamental to the practice of statistics. MC methods are an essential tool to understand the behavior of statistical models. In fact, I’ve probably used MC simulations in just about all of my posts – to generate repeated samples from a model to explore bias, variance, and other distributional characteristics of a particular method.</p>
<p>For example, if we want to assess the variability of a regression parameter estimate, we can repeatedly generate data from a particular “hidden” model, and for each data set fit a regression model to estimate the parameter in question. For each iteration, we will arrive at a different estimate; the variation of all those estimates might be of great interest. In particular, the standard deviation of those estimates is the standard error of the estimate. (Of course, with certain problems, there are ways to analytically derive the standard errors. In these cases, MC simulation can be used to verify an analysis was correct. That’s the beauty of statistics – you can actually show yourself you’ve gotten the right answer.)</p>
<div>
<h3>A simple problem</h3>
<p>In this post, I am considering a simple problem. We are interested in estimating the probability of drawing a value between 2 and 2.5 from a standard normal distribution. That is, we want to use MC simulation to estimate</p>
<p><span>\[p =P(2.0 &lt;=X &lt;=2.5), \ \ \ X\sim N(0,1)\]</span></p>
<p>Of course, we can use <code>R</code> to get us the true <span>\(p\)</span> directly without any simulation at all, but that is no fun:</p>
<pre><code>pnorm(2.5, 0, 1) - pnorm(2, 0, 1)</code></pre>
<pre><code>## [1] 0.01654047</code></pre>
<p>To do this using simulation, I wrote a simple function that checks to see if a value falls between two numbers.</p>
<pre><code>inSet &lt;- function(x, minx, maxx) {
  result &lt;- (x >= minx &amp; x &lt;= maxx) 
  return(as.integer(result))
}</code></pre>
<p>To estimate the desired probability, we just repeatedly draw from the standard normal distribution. After each draw, we check to see if the value falls between 2.0 and 2.5, and store that information in a vector. The vector will have a value of 1 each time a value falls into the range, and 0 otherwise. The proportion of 1’s is the desired probability. Or in other words, <span>\(\hat{p} = \bar{z}\)</span>, where <span>\(\bar{z} = \frac{1}{1000} \sum{z}\)</span>.</p>
<pre><code>set.seed(1234)
z &lt;- vector(&quot;numeric&quot;, 1000)

for (i in 1:1000) {
    
  y &lt;- rnorm(1, 0, 1)
  z[i] &lt;- inSet(y, 2, 2.5)
    
}

mean(z)</code></pre>
<pre><code>## [1] 0.018</code></pre>
<p>The estimate is close to the true value, but there is no reason it would be exact. In fact, I would be suspicious if it were. Now, we can also use the variance of <span>\(z\)</span> to estimate the standard error of <span>\(\hat{p}\)</span>:</p>
<pre><code>sd(z)/sqrt(1000)</code></pre>
<pre><code>## [1] 0.004206387</code></pre>
</div>
<div>
<h3>Faster code?</h3>
<p>If you’ve read any of my other posts, you know I am often interested in trying to make <code>R</code> run a little faster. This can be particularly important if we need to repeat tasks over and over, as we will be doing here. The <code>for</code> loop I used here is not ideal. Maybe <code>simstudy</code> (and you could do this without simstudy) can do better. Let’s first see if it provides the same estimates:</p>
<pre><code>library(data.table)
library(simstudy)

# define the data

defMC &lt;- defData(varname = &quot;y&quot;, formula = 0, 
                 variance = 1, dist = &quot;normal&quot;)
defMC &lt;- defData(defMC, varname = &quot;z&quot;, formula = &quot;inSet(y, 2, 2.5)&quot;, 
                 dist = &quot;nonrandom&quot;)

# generate the data - the MC simulation without a loop

set.seed(1234)  
dMC &lt;- genData(1000, defMC)

# evaluate mean and standard error

dMC[ , .(mean(z), sd(z)/sqrt(1000))]</code></pre>
<pre><code>##       V1          V2
## 1: 0.018 0.004206387</code></pre>
<p>So, the results are identical – no surprise there. But which approach used fewer computing resources. To find this out, we turn to the <code>microbenchmark</code> package. (I created a function out of the loop above that returns a vector of 1’s and 0’s.)</p>
<pre><code>library(microbenchmark)
mb &lt;- microbenchmark(tradMCsim(1000), genData(1000, defMC))
summary(mb)[, c(&quot;expr&quot;, &quot;lq&quot;, &quot;mean&quot;, &quot;uq&quot;, &quot;neval&quot;)]</code></pre>
<pre><code>##                   expr       lq     mean       uq neval
## 1      tradMCsim(1000) 1.428656 2.186979 2.573003   100
## 2 genData(1000, defMC) 1.376450 1.668248 1.674146   100</code></pre>
<p>With 1000 draws, there is actually very little difference between the two approaches. But if we start to increase the number of simulations, the differences become apparent. With 10000 draws, the simstudy approach is more than 7 times faster. The relative improvement continues to increase as the number of draws increases.</p>
<pre><code>mb &lt;- microbenchmark(tradMCsim(10000), genData(10000, defMC))
summary(mb)[, c(&quot;expr&quot;, &quot;lq&quot;, &quot;mean&quot;, &quot;uq&quot;, &quot;neval&quot;)]</code></pre>
<pre><code>##                    expr        lq      mean        uq neval
## 1      tradMCsim(10000) 18.453128 21.619022 22.226165   100
## 2 genData(10000, defMC)  2.006622  2.432078  2.508662   100</code></pre>
</div>
<div>
<h3>Estimating variation of <span>\(\hat{p}\)</span></h3>
<p>Now, we can stop using the loop, at least to generate a single set of draws. But, in order to use MC simulation to estimate the variance of <span>\(\hat{p}\)</span>, we still need to use a loop. In this case, we will generate 1500 data sets of 1000 draws each, so we will have 1500 estimates of <span>\(\hat{p}\)</span>. (It would probably be best to do all of this using Rcpp, where we can loop with impunity.)</p>
<pre><code>iter &lt;- 1500
estMC &lt;- vector(&quot;numeric&quot;, iter)

for (i in 1:iter) {
  
  dtMC &lt;- genData(1000, defMC)
  estMC[i] &lt;- dtMC[, mean(z)]
  
}

head(estMC)</code></pre>
<pre><code>## [1] 0.020 0.013 0.023 0.017 0.016 0.019</code></pre>
<p>We can estimate the average of the <span>\(\hat{p}\)</span>’s, which should be close to the true value of <span>\(p \approx 0.0165\)</span>. And we can check to see if the standard error of <span>\(\hat{p}\)</span> is close to our earlier estimate of 0.004.</p>
<pre><code>c(mean(estMC), sd(estMC))</code></pre>
<pre><code>## [1] 0.016820000 0.004113094</code></pre>
</div>
<div>
<h3>Importance sampling</h3>
<p>As we were trying to find an estimate for <span>\(p\)</span> using the simulations above, we spent a lot of time drawing values far outside the range of 2 to 2.5. In fact, almost all of the draws were outside that range. You could almost so that most of those draws were providing little if any information. What if we could focus our attention on the area we are interested in – in this case the 2 to 2.5, without sacrificing our ability to make an unbiased estimate? That would be great, wouldn’t it? That is the idea behind importance sampling.</p>
<p>The idea is to draw from a distribution that is (a) easy to draw from and (b) is close to the region of interest. Obviously, if 100% of our draws is from the set/range in question, then we’ve way over-estimated the proportion. So, we need to reweight the draws in such a way that we get an unbiased estimate.</p>
</div>
<div>
<h3>A very small amount of theory</h3>
<p>A teeny bit of stats theory here (hope you don’t jump ship). The expected value of a draw falling between 2 and 2.5 is</p>
<p><span>\[E_x(I_R) = \int_{-\infty}^{\infty}{I_{R}(x)f(x)dx} \ ,\]</span></p>
<p>where <span>\(I_R(x)=1\)</span> when <span>\(2.0 \le x \le 2.5\)</span>, and is 0 otherwise, and <span>\(f(x)\)</span> is the standard normal density. This is the quantity that we were estimating above. Now, let’s say we want to draw closer to the range in question – say using <span>\(Y\sim N(2.25, 1)\)</span>. We will certainly get more values around 2 and 2.5. If <span>\(g(y)\)</span> represents this new density, we can write <span>\(E(I_R)\)</span> another way:</p>
<p><span>\[E_y(I_R) = \int_{-\infty}^{\infty}{I_{R}(y)\frac{f(y)}{g(y)}g(y)dy} \ .\]</span> Notice that the <span>\(g(y)\)</span>’s cancel out and we end up with the same expectation as above, except it is with respect to <span>\(y\)</span>. Also, notice that the second equation is also a representation of <span>\(E_y \left( I_{R}(y)\frac{f(y)}{g(y)} \right)\)</span>.</p>
<p>I know I am doing a lot of hand waving here, but the point is that</p>
<p><span>\[E_x(I_R) = E_y \left( I_{R}\frac{f}{g} \right)\]</span></p>
<p>Again, <span>\(f\)</span> and <span>\(g\)</span> are just the original density of interest – <span>\(N(0,1)\)</span> – and the “important” density – <span>\(N(2.25, 1)\)</span> – respectively. In our modified MC simulation, we draw a <span>\(y_i\)</span> from the <span>\(N(2.25, 1)\)</span>, and then we calculate <span>\(f(y_i)\)</span>, <span>\(g(y_i)\)</span>, and <span>\(I_R(y_i)\)</span>, or more precisely, <span>\(z_i = I_{R}(y_i)\frac{f(y_i)}{g(y_i)}\)</span>. To get <span>\(\hat{p}\)</span>, we average the <span>\(z_i\)</span>’s, as we did before.</p>
</div>
<div>
<h3>Beyond theory</h3>
<p>Why go to all of this trouble? Well, it turns out that the <span>\(z_i\)</span>’s will be much less variable if we use importance sampling. And, as a result, the standard error of our estimate can be reduced. This is always a good thing, because it means a reduction in uncertainty.</p>
<p>Maybe a pretty plot will provide a little intuition? Our goal is to estimate the area under the black curve between 2 and 2.5. An importance sample from a <span>\(N(2.25, 1)\)</span> distribution is represented by the green curve. I think, however, it might be easiest to understand the adjustment mechanism by looking at the orange curve, which represents the uniform distribution between 2 and 2.5. The density is <span>\(g(y) = 2\)</span> for all values within the range, and <span>\(g(y) = 0\)</span> outside the range. Each time we generate a <span>\(y_i\)</span> from the <span>\(U(2,2.5)\)</span>, the value is guaranteed to be in the target range. As calculated, the average of all the <span>\(z_i\)</span>’s is the ratio of the area below the black line relative to the area below the orange line, but only in the range between 2 and 2.5. (This may not be obvious, but perhaps staring at the plot for a couple of minutes will help.)</p>
<p><img src="https://i2.wp.com/www.rdatagen.net/post/2018-01-18-importance-sampling-adds-a-little-excitement-to-monte-carlo-simulation_files/figure-html/unnamed-chunk-11-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
</div>
<div>
<h3>Reducing standard errors by improving focus</h3>
<p>Now we can generate data and estimate <span>\(\hat{p}\)</span> and <span>\(se(\hat{p})\)</span>. First, here is a simple function to calculate <span>\(z\)</span>.</p>
<pre><code>h &lt;- function(I, f, g) {
  
  dx &lt;- data.table(I, f, g)
  
  dx[I != 0, result := I * f / g]
  dx[I == 0, result := 0]
  
  return(dx$result)
}</code></pre>
<p>We can define the three Monte Carlo simulations based on the three different distributions using <code>simstudy</code>. The elements that differ across the three MC simulations are the distribution we are drawing from and the density <span>\(g\)</span> of that function.</p>
<pre><code># Normal(2.5, 1)
def1 &lt;- defData(varname = &quot;y&quot;, formula = 2.25, 
                variance = 1, dist = &quot;normal&quot;)
def1 &lt;- defData(def1, varname = &quot;f&quot;, formula = &quot;dnorm(y, 0, 1)&quot;,
                dist = &quot;nonrandom&quot;)
def1 &lt;- defData(def1, varname = &quot;g&quot;, formula = &quot;dnorm(y, 2.25, 1)&quot;, 
                dist = &quot;nonrandom&quot;)
def1 &lt;- defData(def1, varname = &quot;I&quot;, formula = &quot;inSet(y, 2, 2.5)&quot;, 
                dist = &quot;nonrandom&quot;)
def1 &lt;- defData(def1, varname = &quot;z&quot;, formula = &quot;h(I, f, g)&quot;, 
                dist = &quot;nonrandom&quot;)

# Normal(2.5, .16)
def2 &lt;- updateDef(def1, &quot;y&quot;, newvariance = 0.4^2)
def2 &lt;- updateDef(def2, &quot;g&quot;, newformula = &quot;dnorm(y, 2.25, 0.4)&quot;)

# Uniform(2, 3)
def3 &lt;- updateDef(def1, &quot;y&quot;, newformula = &quot;2;2.5&quot;, 
                  newvariance = 0, newdist = &quot;uniform&quot;)
def3 &lt;- updateDef(def3, &quot;g&quot;, newformula = &quot;dunif(y, 2, 2.5)&quot;)</code></pre>
<p>Here is a peek at one data set using the uniform sampling approach:</p>
<pre><code>genData(1000, def3)</code></pre>
<pre><code>##         id        y          f g I           z
##    1:    1 2.181324 0.03695603 2 1 0.018478013
##    2:    2 2.381306 0.02341805 2 1 0.011709023
##    3:    3 2.338066 0.02593364 2 1 0.012966819
##    4:    4 2.200399 0.03544350 2 1 0.017721749
##    5:    5 2.461919 0.01926509 2 1 0.009632543
##   ---                                         
##  996:  996 2.118506 0.04229983 2 1 0.021149914
##  997:  997 2.433722 0.02064175 2 1 0.010320876
##  998:  998 2.265325 0.03066025 2 1 0.015330127
##  999:  999 2.107219 0.04332075 2 1 0.021660374
## 1000: 1000 2.444599 0.02010130 2 1 0.010050651</code></pre>
<p>And here are the estimates based on the three different importance samples. Again each iteration is 1000 draws from the distribution – and we use 1500 iterations:</p>
<pre><code>iter &lt;- 1500
N &lt;- 1000

est1 &lt;- vector(&quot;numeric&quot;, iter)
est2 &lt;- vector(&quot;numeric&quot;, iter)
est3 &lt;- vector(&quot;numeric&quot;, iter)

for (i in 1:iter) {
  
  dt1 &lt;- genData(N, def1)
  est1[i] &lt;- dt1[, mean(z)]
  
  dt2 &lt;-  genData(N, def2)
  est2[i] &lt;- dt2[, mean(z)]

  dt3 &lt;- genData(N, def3)
  est3[i] &lt;- dt3[, mean(z)]
  
}

# N(2.25, 1)
c(mean(est1), sd(est1))</code></pre>
<pre><code>## [1] 0.016525503 0.001128918</code></pre>
<pre><code># N(2.25, .16)
c(mean(est2), sd(est2))</code></pre>
<pre><code>## [1] 0.0165230677 0.0005924007</code></pre>
<pre><code># Uniform(2, 2.5)
c(mean(est3), sd(est3))</code></pre>
<pre><code>## [1] 0.0165394920 0.0001643243</code></pre>
<p>In each case, the average <span>\(\hat{p}\)</span> is 0.0165, and the standard errors are all below the standard MC standard error of 0.0040. The estimates based on draws from the uniform distribution are the most efficient, with a standard error below 0.0002.</p>
</div>
	<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://www.rdatagen.net/post/importance-sampling-adds-a-little-excitement-to-monte-carlo-simulation/"> ouR data generation</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/JZL74-46iTQ" height="1"></a></div>