7. Monte Carlo Integration#

This chapter is adapted from AM207 (Harvard, Fall 2021). Watch the recorded lecture.

In this chapter

  1. Basics of Monte Carlo Simulation

  2. Variance Reduction: Control Variates

  3. Variance Reduction: Stratified Sampling

  4. Variance Reduction: Importance Sampling

  5. Application: Monte Carlo Estimation of Arbitrary Integrals

Hide code cell content

### Import basic libraries
import numpy as np
import scipy as sp
import pandas as pd
import sklearn as sk
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
%matplotlib inline

7.1. Motivation#

Posterior samples allow us to approximately compute posterior point estimates, for example, we can approximate the posterior mean as

\[ \mathbb{E}_{\theta|Y}[\theta] = \int_\Theta \theta\, p(\theta | Y)\,d\theta \approx \frac{1}{S}\sum_{s=1}^S \theta_s,\, \theta_s \sim p(\theta | Y) \]

In fact, for any function \(f\) of \(\theta | Y\), we can estimate the expected value of \(f\) by first sampling \(S\) samples from the posterior \(p(\theta | Y)\) and then compute the average value of \(f\) on these samples:

\[ \mathbb{E}_{\theta|Y}[f(\theta)] = \int_\Theta f(\theta)\, p(\theta | Y)\,d\theta \approx \frac{1}{S}\sum_{s=1}^S f(\theta_s),\, \theta_s \sim p(\theta | Y) \]

Question: But is this estimate consistent? Unbiased? Of minimal variance?

7.2. Basics of Monte Carlo Integration#

Naive Monte Carlo Estimation of Integrals#

Let \(I\) denote the integral

\[\mathbb{E}_{\theta|Y}[f(\theta)] = \int_\Theta f(\theta)\, p(\theta | Y)\,d\theta\]

and let \(\widehat{I}\) denote the approximation

\[\frac{1}{S}\sum_{s=1}^S f(\theta_s),\, \theta_s \sim p(\theta | Y).\]

We call \(\widehat{I}\) the Monte Carlo estimate of \(I\).

In general, Monte Carlo integration is the process of estimating a deterministic quantity (an integral) using a procedure involving stochasticity (sampling).

The Consistency and Unbiasedness of Monte Carlo Estimators#

Recall that the Strong Law of Large Numbers says that the sampling mean of \(S\) iid random variables converges to the theoretical mean, with probability 1, as \(S\to \infty\). This means that

\[ \lim_{S\to\infty} \frac{1}{S}\sum_{s=1}^S f(\theta_s),\, \theta_s \sim p(\theta | Y) \;= \;\mathbb{E}_{\theta|Y}\left[f(\theta) \right] \]

with probability 1. Hence, the Monte Carlo Estimator \(\widehat{I}\) is consistent.

The expected value of \(\widehat{I}\) is

\[ \mathbb{E}_{\theta_S}[\widehat{I}]\, = \, \mathbb{E}_{\theta_S}\left[\frac{1}{S}\sum_{s=1}^S f(\theta_s)\right] = \, \frac{1}{S}\sum_{s=1}^S \mathbb{E}_{\theta_s}\left[f(\theta_s)\right] = \frac{1}{S} \sum_{s=1}^S I = I, \]

where \(\theta_s \sim p(\theta | Y)\). Hence, the Monte Carlo Estimator \(\widehat{I}\) is unbiased.

The Variance and Error of Monte Carlo Estimators#

The variance of \(\widehat{I}\) is given by

\[ \mathrm{Var}\left[\widehat{I} \right] = \mathrm{Var} \left[ \frac{1}{S} \sum_{s=1}^{S} f(\theta_S) \right] = \frac{1}{S^2} \sum_{s=1}^{S} \mathrm{Var}\left[ f(\theta_S)\right] = \frac{\mathrm{Var}\left[ f(\theta)\right]}{S}, \]

where \(\theta_S\), \(\theta \sim p(\theta|Y)\). Plainly put, the variance of the estimator is reduced when the number of samples \(S\) is large and the variance \(\sigma_f^2\) of \(f(\theta)\) is low.

The Central Limit Theorem says that the difference between sample mean and the theoretical mean of iid random variables will approach a normal distribution as \(N\to \infty\). For us, this means that the error of \(\widehat{I}\) has a roughly normal distribution:

\[ p\left( \widehat{I} - I\right) \to \mathcal{N}\left(0, \frac{\sigma_f^2}{S} \right), \; N \to \infty \]

Again, this says that, to reduce the error of \(\widehat{I}\) we can increase the number of samples \(S\) or decrease the variance \(\sigma_f^2\) of \(f(\theta)\).

7.3. Variance Reduction: Control Variates#

A Baseline for Variance of Monte Carlo Estimates#

The variance of the naive Monte Carlo estimate \(\widehat{I}\) is:

\[\begin{split}\begin{aligned} \mathrm{Var}\left[ \widehat{I}\right] &= \frac{1}{S}\mathrm{Var}\left[ f(\theta)\right]\\ &= \frac{1}{S}\mathbb{E}_{\theta|Y}\left[\left( f(\theta) - \mathbb{E}_{\theta|Y}\left[ f(\theta)\right]\right)^2\right]\\ &= \frac{1}{S}\mathbb{E}_{\theta|Y}\left[ f(\theta)^2 \right] - \mathbb{E}_{\theta|Y}\left[ f(\theta)\right]^2\\ &= \frac{1}{S}\left(\int_\Theta f(\theta)^2 p(\theta|Y)d\theta - I^2\right) \end{aligned}\end{split}\]

We’ll compare the variance of alternative estimator to the above when checking for variance reduction.

Note: The variance of \(f(\theta)\) depends on both the variance of \(\theta\) and the amount of variation in the function \(f\). Functions that change a great amount over the domain will have a high variance and functions that are flat will have a low variance.

The General Idea of Control Variates#

Based on our realization that “flat” functions have lower variance, we will try to engineer “flat” functions that allow use to compute the integral of \(f\).

Observation: For a given function \(f(X)\), if \(h\) is a function of \(X\) that correlates with \(f\), then \(f(X)-h(X)\) will have lower variance.

../_images/control.jpg

Variance of Control Variates#

Fix a function \(f(\theta)\), \(\theta\sim p(\theta|Y)\). Let \(h(\theta)\) be a function with known mean \(\mu_h = \mathbb{E}_{\theta|Y}[h(\theta)]\) and such that \(h(\theta)\) is correlated with \(f(\theta)\). We call \(h\) the control variate for \(f\).

We define the control variate Monte Carlo estimate of \(\mathbb{E}_{\theta|Y}[f(\theta)]\) to be

\[ \widehat{I}_{\text{control}} = \frac{1}{S}\sum^S_{s=1} f(\theta_s) - c(h(\theta_s) - \mu_h) \]

where \(\theta_s \sim p(\theta|Y)\), \(c\) is our choice of a constant.

The variance of this estimator is:

\[ \sigma_{\widehat{I}_{\text{control}}}^2 = \frac{1}{S} \left(\sigma^2_f + c^2 \sigma_h^2 - 2c * \mathbf{cov}[f(\theta), h(\theta)]\right) \]

Thus, we see that when \(\mathbf{cov}[f(\theta), h(\theta)] \neq 0\) there is hope for variance reduction, i.e. \(\sigma_{\widehat{I}_{\text{control}}}^2 <\sigma_{f}^2/S\)!

Exercise: check that \(\widehat{I}_{\text{control}}\) is consistent and unbiased! Derive \(\sigma_{\widehat{I}_{\text{control}}}^2\)!

The Nitty Gritty of Control Variates#

Using control variate Monte Carlo requires that we:

  1. choose a control variate \(h\) with known mean and who is correlated with \(f\).

  2. choose a constant \(c\).

Typically, we want to choose an \(h\) that follows to the trends of \(f\) that is easy to integrate.

The value of \(c\) that minimizes \(\sigma_{\widehat{I}_{\text{control}}}^2\) is

\[ c^* = \frac{\mathbf{cov}[f(\theta), h(\theta)]}{\sigma_h^2}. \]

In case \(\mathbf{cov}[f(\theta), h(\theta)]^2\) and \(\sigma_h^2\) are difficult to compute analytically, they can be empirically estimated from the samples.

When we choose the optimal \(c = c^*\), the variance of \(\widehat{I}_{\text{control}}\) is

\[ \sigma_{\widehat{I}_{\text{control}}}^2 = \frac{1}{S}\left(1 - \frac{\mathbf{cov}[f(\theta), h(\theta)]}{\sigma_h^2\sigma_f^2}\right)\sigma_f^2 \sigma^2_{\widehat{I}_{\text{control}}} = \frac{1}{S}(1 - \rho_{f, h})\sigma_f^2, \]

where \(\rho_{f, h}\) is the correlation between the outputs of \(f\) and \(h\). Hence, the more \(h\) is correlated with the output the greater the variance reduction.

Example: Control Variates#

Let \(f(\theta) = -0.2 \theta^3 + 100\sin(\theta)\) for \(\theta|Y \sim U(0, 20)\). Let the control variate be \(h(\theta) = -0.2 \theta^3\). We aim to estimate:

\[ \mathbb{E}_{\theta|Y}[f(\theta)] = \int_{\Theta} f(\theta) p(\theta|Y) d\theta = \frac{1}{20} \int_{\Theta} f(\theta) d\theta. \]

We compare the sample variance of \(\widehat{I} = \frac{1}{S} \sum_{s=1}^S f(\theta_s)\) with that of the Monte Carlo estimate with the control variate:

\[\widehat{I}_{\text{control}} = \frac{1}{S} \sum_{s=1}^S \left(f(\theta_s) - 1.5(h(\theta_s) - \mu_h)\right),\]

for \(S = 100\) and where

\[ \mu_h = \mathbb{E}_{\theta|Y}[h(\theta)] = \frac{1}{20}\int_{0}^{20} h(\theta) d\theta = -400. \]

Hide code cell content

#total number of trials to run (for computing variance of estimators)
total_trials = 500
#total number of samples
S = 100
#list of monte carlo estimates
monte_carlo = []
#list of control variate estimates
control_variate = []

#definition of the monte carlo integrand
f = lambda x: -0.2 * x**3 + 100 * np.sin(x)
#definition of the control variate
h = lambda x: -0.2 * x**3
#definition of the control variate mc integrand
control_mc = lambda x: f(x) - 1.0 * (h(x) + 400)

#estimate the integral 
for i in range(total_trials):
    #sample theta's
    theta = np.random.uniform(0, 20, 100)
    #compute the MC estimate
    monte_carlo.append(f(theta).mean())
    #compute the control variate MC estimate
    control_variate.append(control_mc(theta).mean())
    
mc_variance = np.std(monte_carlo)**2
control_mc_variance = np.std(control_variate)**2
x = np.linspace(0, 20, 100)
fig, ax = plt.subplots(1, 1, figsize=(10, 5))
ax.plot(x, f(x), color='black', label='f')
ax.plot(x, h(x),linestyle=':', color='red', label='control variate')
ax.plot(x, control_mc(x), linestyle='--', color='blue', label='control variate integrand')
ax.set_title('Visualization of f and control variate')
ax.set_xlabel('theta')
ax.legend(loc='best')
plt.show()
../_images/a449d72d2b5b60ff42c9cec2e396ddb5ac73408a32b91396a0f72a1109ff1c25.png
print('variance of monte carlo estimate:', mc_variance)
print('variance of control variate monte carlo estimate:', control_mc_variance)
variance of monte carlo estimate: 2177.441459671328
variance of control variate monte carlo estimate: 52.49658213225613

7.4. Variance Reduction: Stratified Sampling#

The General Idea of Stratified Sampling#

Again, based on our realization that “flat” functions have lower variance, we will try to partition the domain of \(f\) into regions where \(f\) is relatively “flat”. We estimate the integral on each piece of the partition then sum over the pieces.

../_images/strata.jpg

The Stratified Sampling Monte Carlo Estimator#

Fix a function \(f(\theta)\), where \(\theta\) is a random variable over the domain \(\Theta\) whose pdf is \(p(\theta|Y)\). Then the integral for \(\mathbb{E}_{\theta|Y}[f(\theta)]\) can be decomposed as

\[ \mathbb{E}_{\theta|Y}[f(\theta)] = \int f(x)p(x) dx = \sum_{m=1}^M \int_{\Theta_m} f(\theta) p(\theta) d\theta \]

where \(\bigcup_{m=1}^M\Theta_m = \Theta\) and \(\Theta_m \cap \Theta_{m'} = \emptyset\) if \(m\neq m'\).

To make \(p(\theta)\) a pdf over \(\Theta_{m'}\) we need to normalize it, i.e.

\[ \frac{p(\theta)}{w_m},\quad w_m = \int_{\Theta_m} p(\theta)d\theta. \]

We can then rewrite the integral for \(\mathbb{E}_{\theta|Y}[f(\theta)]\) again

\[ \mathbb{E}_{\theta|Y}[f(\theta)] = \sum_{m=1}^M \int_{\Theta_m} w_m f(\theta) \left(\frac{p(\theta)}{w_m}\right) d\theta = \sum_{m=1}^M w_m \mathbb{E}_{\theta \sim \frac{p(\theta)}{w_m}\mathbb{1}_{\Theta_m}}[f(\theta)], \]

where \(\mathbb{1}_{\Theta_m}\) is the indicator function for the set \(\Theta_m\).

Fix a total sample size \(S\). Let \(\widehat{I}_m\) be the Monte Carlo estimate of \(\mathbb{E}_{\theta \sim \frac{p(\theta)}{w_m}\mathbb{1}_{\Theta_m}}[f(\theta)]\) estimated with \(S_m = w_m * S\) samples, the stratified sampling Monte Carlo estimator is

\[ \widehat{I}_{\text{SS}} = \sum_{m=1}^M w_m \widehat{I}_m. \]

since \(\mathrm{Var}\left[\widehat{I}_m\right]\) is lower than \(\mathrm{Var}\left[\widehat{I}\right]\), we hope that \(\mathrm{Var}\left[\widehat{I}_{\text{SS}}\right]\) is also lower.

Example: Stratified Sampling#

Again, let \(f(\theta) = -0.2 \theta^3 + 100\sin(\theta)\) for \(\theta|Y \sim U(0, 20)\). We aim to estimate:

\[ \mathbb{E}_{\theta|Y}[f(\theta)] = \int_{\Theta} f(\theta) p(\theta|Y) d\theta = \frac{1}{20} \int_{\Theta} f(\theta) d\theta. \]

We compare the sample variance of \(\widehat{I} = \frac{1}{S} \sum_{s=1}^S f(\theta_s)\) with that of the Monte Carlo estimate with stratified sampling:

\[ \widehat{I}_{\text{SS}} = \sum_{m=1}^M \frac{1}{S_m} \sum_{s_m=1}^{S_m} w_m f(\theta_{s_m}),\; \theta_{s_m} \sim U(t_{m-1}, t_{m}), \]

for sample sizes

\[ [13, 20, 9, 10, 15, 32], \]

where the number \(M\) of strata is 10, \(w_m = \frac{t_m - t_{m-1}}{20}\), and where the end points of the strata is given by

\[ [0, 2.75, 6.8, 8.6, 10.6, 13.6, 20.]. \]
#define the end points of the strata
strata = [0, 2.75, 6.8, 8.6, 10.6, 13.6, 20.]
x = np.linspace(0, 20, 100)
fig, ax = plt.subplots(1, 1, figsize=(10, 5))
ax.plot(x, f(x), color='black', label='f')
for stratus in strata:
    ax.axvline(x=stratus, linestyle=':', color='red')
ax.set_title('Visualization of f and strata')
ax.set_xlabel('theta')
ax.legend(loc='best')
plt.show()
../_images/4e4ad09cc82d81572df04a512bb0d51320932d94f65af5e38646560f86c91d53.png

Hide code cell content

#total number of trials to run (for computing variance of estimators)
total_trials = 500
#weights
w = [(strata[m + 1] - strata[m]) / 20. for m in range(len(strata) - 1)]
#sample sizes
S = [int(weight * 100) for weight in w]

stratified_estimates = []
monte_carlo = []

#repeat the estimate for many trials:
for i in range(total_trials):
    #compute the monte carlo estimate
    theta = np.random.uniform(0, 20, size=np.sum(S))
    monte_carlo.append(f(theta).mean())
    
    #compute the stratified sampling monte carlo estimate
    sum_over_strata = 0
    for m in range(len(strata) - 1):
        theta = np.random.uniform(strata[m], strata[m + 1], size=S[m])
        #compute the mc estimator for the mth stratus
        stratus_estimate = (w[m] * f(theta)).mean()
        sum_over_strata += stratus_estimate
        
    stratified_estimates.append(np.sum(sum_over_strata))

mc_variance = np.std(monte_carlo)**2
stratified_mc_variance = np.std(stratified_estimates)**2
print('variance of monte carlo estimate:', mc_variance)
print('variance of stratified monte carlo estimate:', stratified_mc_variance)
variance of monte carlo estimate: 2131.79723836582
variance of stratified monte carlo estimate: 379.4187342386133

7.5. Variance Reduction: Importance Sampling#

The General Idea of Importance Sampling#

The idea behind importance sampling is very similar to that of rejection sampling: we tackle the problem where the posterior \(p(\theta|Y)\) is typically hard to sample from. Instead,

  1. we approximate \(p(\theta|Y)\) with an easy distribution \(q(\theta)\) and sample \(\theta_1, \ldots, \theta_S\) from \(q\).

  2. rather than rejecting some of the samples, we evaluate \(f\) on all the samples, and then weight \(f(\theta_s)\) based on how likely is \(\theta_s\) to be from \(p\) vs \(q\). That is, we estimate \(\mathbb{E}_{\theta|Y}[f(\theta)] \approx\frac{1}{S}\sum_{s=1}^S \frac{p(\theta_s|Y)}{q(\theta_s)}f(\theta_s)\), \(\theta_s \sim q(\theta)\). Why is this a good idea?

../_images/importance.jpg

Variance of Importance Sampling#

Fix a total sample size \(S\). The importance sampling Monte Carlo estimator is

\[ \widehat{I}_{\text{IS}} = \frac{1}{S}\sum_{s=1}^S \frac{p(\theta_s|Y)}{q(\theta_s)}f(\theta_s), \; \theta_s \sim q(\theta_s) \]

We call \(q\) is the importance distribution, \(p\) the nominal distribution and \(\frac{p(\theta_s|Y)}{q(\theta_s)}\) the importance weight.

We can show that \(\widehat{I}_{\text{IS}}\) is unbiased and consistent using the following fact (assuming \(q\) and \(p\) have the same support):

\[ I = \mathbb{E}_{\theta \sim p(\theta|Y)}\left[f(\theta)\right] = \int_\Theta \frac{p(\theta|Y)}{q(\theta)}f(\theta) q(\theta) d\theta= \mathbb{E}_{\theta \sim q(\theta)}\left[\frac{p(\theta|Y)}{q(\theta)}f(\theta)\right]. \]

We can directly calculate the variance of \(\widehat{I}_{\text{IS}}\) to be \(\mathrm{Var}\left[\widehat{I}_{\text{IS}}\right] = \frac{\sigma^2_q}{S}\), where \(\sigma^2_q\) is the variance of \(\frac{p(\theta_s|Y)}{q(\theta_s)}f(\theta_s)\):

\[ \sigma^2_q = \int_\Theta f^2(\theta)p(\theta|Y)\frac{p(\theta|Y)}{q(\theta)} d\theta - I^2 = \int_\Theta\frac{\left(f(\theta)p(\theta|Y) - I q(\theta)\right)^2}{q(\theta)} d\theta. \]

For comparison, \(\mathrm{Var}\left[\widehat{I}\right] = \frac{1}{S}\left(\int_\Theta f(\theta)^2 p(\theta|Y)d\theta - I^2\right)\). So, we hope to get a variance reduction if \(\frac{p(\theta|Y)}{q(\theta)} <1\) when \(f(\theta)^2 p(\theta|Y)\) is large.

The Nitty Gritty of Importance Sampling: the Design of \(q\)#

  1. (When \(q=0\)) if \(q(\theta_0)=0\) but \(p(\theta_0|Y) \neq 0\) for some \(\theta_0\) then \(\widehat{I}_{\text{IS}}\) will be biased, since sampling from \(q\) can never simulate sampling from \(p\) even after reweighting.

  2. (When \(q\approx 0\)) related, if \(q(\theta_0)\) is very small (esp. when \(q(\theta_0) < p(\theta_0|Y)\)) then it is unlikely that your samples will include \(\theta_0\). Hence, \(\widehat{I}_{\text{IS}}\) will be biased. If you’ve never see snow, you can’t prepare for it!

  3. (Again, when \(q\approx 0\)) recall that \(\sigma^2_q = \int_\Theta\frac{\left(f(\theta)p(\theta|Y) - I q(\theta)\right)^2}{q(\theta)}\). For smaller \(\sigma^2_q\), we want \(\left(f(\theta)p(\theta|Y) - I q(\theta)\right)^2\approx 0\), i.e. \(q\propto f(\theta)p(\theta|Y)\). But where \(q(\theta) \approx 0\), \(\sigma^2_q\) can be large even when \(\left(f(\theta)p(\theta|Y) - I q(\theta)\right)^2\) is small.

  4. (Heterogenous weights) when \(q\) and \(p\) are very dissimilar, the weights will either be near 0 or huge. Say we have one sample with weight 0 and one with weight 999, how many samples are we effectively simulating from \(p\)? A way to measure the “quality” of the samples from \(q\) in estimating \(I\), is through the effective sample size.

    When we have \(100\) samples from \(q\) but ESS is 10, then essentially your IS estimate of \(I\) is as good as as Monte Carlo estimate with 10 samples from \(p\).

Example: Importance Sampling#

Again, let \(f(\theta) = -0.2 \theta^3 + 100\sin(\theta)\) for \(\theta|Y \sim U(0, 20)\). We aim to estimate:

\[ \mathbb{E}_{\theta|Y}[f(\theta)] = \int_{\Theta} f(\theta) p(\theta|Y) d\theta = \frac{1}{20} \int_{\Theta} f(\theta) d\theta. \]

We compare the sample variance of \(\widehat{I} = \frac{1}{S} \sum_{s=1}^S f(\theta_s)\) with that of the Monte Carlo estimate with importance sampling, with the importance distribution being \(\mathcal{N}(12, 3)\):

\[ \widehat{I}_{\text{IS}} = \sum_{s=1}^S \frac{1/20 * \mathbb{1}_{[0, 20]}}{\mathcal{N}(\theta_s; 12, 3)}\, f(\theta_{s}),\; \theta_{s} \sim \mathcal{N}(12, 3), \]

for sample size \(S=100\).

#normal pdf
normal = sp.stats.norm(loc=12, scale=3**0.5).pdf
#visualize nominal and importance distributions
x = np.linspace(0, 20, 100)
fig, ax = plt.subplots(1, 2, figsize=(20, 5))
ax[0].plot(x, [1./20] * 100, color='black', label='nominal distribution')
ax[0].set_xlabel('theta')
ax[0].legend(loc='best')
ax[1].plot(x, normal(x), color='red', label='importance distribution')
ax[1].set_xlabel('theta')
ax[1].legend(loc='best')
plt.show()
../_images/041461f6d3a38daa3e03776af41e53b85c0eff0d614b2e7820f310306be84227.png

Hide code cell content

#total number of trials to run (for computing variance of estimators)
total_trials = 500
#sample sizes
S = 100

is_estimates = []
monte_carlo = []
importance_weights = []

#repeat the estimate for many trials:
for i in range(total_trials):
    #compute the monte carlo estimate
    #sample from p
    theta = np.random.uniform(0, 20, size=S)
    #evaluate f at samples of p
    monte_carlo.append(f(theta).mean())
    
    #compute the IS sampling monte carlo estimate
    #sample from importance distribution q
    theta = np.random.normal(12, 3, size=S)
    #compute importance weight of each sample
    weights = np.array([0 if (t < 0 or t > 20) else 1. / (20 * normal(t)) for t in theta])
    #count the number of weights that are zero (i.e. samples that are impossible under p)
    importance_weights.append(len(weights[weights==0]))
    #compute the IS estimate
    is_estimates.append((weights * f(theta)).mean())

mc_variance = np.std(monte_carlo)**2
is_mc_variance = np.std(is_estimates)**2
print('variance of monte carlo estimate:', mc_variance)
print('variance of IS monte carlo estimate:', is_mc_variance)
variance of monte carlo estimate: 2171.4928181500945
variance of IS monte carlo estimate: 815108574708675.2
print('average numnber of zero importance weight:', np.mean(importance_weights))
average numnber of zero importance weight: 0.394

7.6. Summary of Monte Carlo Integration#

Monte Carlo Integration#

In Chapter 6 we studied ways of sampling from an arbitrary distribution \(p(\theta)\):

  • Inverse CDF Sampling: when the inverse of the CDF of \(p\) can be computed

  • Rejection Sampling: when a good substitute distribution for \(p\) can be found

  • Gibbs Sampling: when the conditionals of a multivariate distribution are simple

Samples from \(p(\theta)\) can be used to estimate the expected value of any function of \(\theta\):

\[ \underbrace{\mathbb{E}_{\theta\sim p(\theta)}\left[ f(\theta)\right]}_{I} = \int_{\Theta} f(\theta) p(\theta) d\theta \approx \underbrace{\frac{1}{S} \sum_{s=1}^S f(\theta_s),\; \theta_s \sim p(\theta)}_{\widehat{I}} \]

We call \(\widehat{I}\) the Monte Carlo estimate of \(I\). We proved that:

  • \(\widehat{I}\) is consistent and unbiased

  • The variance of \(\widehat{I}\) is \(\frac{\sigma_f}{S}\), where \(\sigma_f = \mathrm{Var}\left[f(\theta) \right]\)

What do these two properties of \(\widehat{I}\) tell us to do if we want better estimates of \(I\)?

Variance Reduction for Monte Carlo Integration#

We can reduce the variance of \(\widehat{I}\) by increasing the sample size \(S\). But this is not always practical. Why?

We studied three ways of reducing the variance of \(\widehat{I}\) by reducing the variance of the function inside the expectation:

  1. Control Variates: find a function \(h\) that captures the trend of \(f\):

    \[ \widehat{I}_{\text{control}} = \frac{1}{S}\sum^S_{s=1} f(\theta_s) - c(h(\theta_s) - \mu_h), \; \theta_s \sim p(\theta) \]
  2. Stratified Sampling: Split the domain \(\Theta\) into \(m\) pieces (strata):

    \[ \widehat{I}_{\text{SS}} = \sum_{m=1}^M w_m \widehat{I}_m. \]

    where \(w_m = \int_{\Theta_m} p(\theta)d\theta\), and \(\widehat{I}_m\) is the MC estimate over the \(m\)-th strata

  3. Importance Sampling: choose a \(q\) that places more weight where \(f(\theta)\) has high variance and \(p\) is more likely to produce samples:

    \[ \widehat{I}_{\text{IS}} = \frac{1}{S}\sum_{s=1}^S \frac{p(\theta_s|Y)}{q(\theta_s)}f(\theta_s),\; \theta_s \sim q(\theta). \]

For each method: What are the design choices you need to make? Where is the variance reduction coming from? Why is it hard to achieve?

7.7. Application: Monte Carlo Estimation of Arbitrary Integrals#

Arbitrary Definite Integrals#

We formulated Monte Carlo estimation as a way to approximate the expected value of functions of random variables. However, given a function of deterministic variables, \(f(x)\), we can rewrite the integral

\[ \int_{\Omega} f(x) dx, \]

where \(x\in\mathbb{R}^D\) and \(\Omega \subseteq \mathbb{R}^D\), like an expectation

\[ \int_{\Omega} f(x) dx = \int_{\Omega} g(x)h(x) dx, \]

if we can factor \(f\) as \(f(x) = g(x)h(x)\).

The rewritten integral looks a lot like the expectation of \(g(X)\) where the pdf of \(X\) is \(h(X)\). The only problem is that \(h(x)\) is not necessarily a pdf!

Rewriting an Arbitrary Definite Integral as an Expectation#

We want to rewrite the following expression as an expectation:

\[ \int_{\Omega} f(x) dx = \int_{\Omega} g(x)h(x) dx. \]

Let \(V\) denote the integral of \(h\) over \(\Omega\):

\[ V = \int_{\Omega} h(x)dx. \]

Note that, then, \(\int_{\Omega} \frac{1}{V}h(x)dx = 1\). Hence, \(\frac{1}{V}h(x)\) is a valid pdf over \(\Omega\).

Then we can write:

\[ \int_{\Omega} f(x) dx = \int_{\Omega} \left(Vg(x)\right)\left(\frac{1}{V}h(x)\right)dx. \]

We recognize the above integral as an expectation, and hence can estimated using Monte Carlo methods:

\[ \mathbb{E}_{X\sim \frac{1}{V}h(X)}[Vg(X)] \approx V\sum_{s=1}^S g(X_s),\; X_s\sim \frac{1}{V}h(X). \]

How Do You Factor the Integrand \(f\)?#

Once we factor \(f(x)\) as \(f(x) = g(x)h(x)\), then we can rewrite the integral of \(f\) (over \(\Omega\)) as an expectation

\[ \int_{\Omega} f(x) dx = \int_{\Omega} \left(Vg(x)\right)\left(\frac{1}{V}h(x)\right)dx = \mathbb{E}_{X\sim \frac{1}{V}h(X)}[Vg(X)]. \]

But how does one choose \(g\) and \(h\)? Two simple things to keep in mind:

  1. since we need to sample from \(h\), we need to choose \(h\) such that it is easily approximated by distributions from which we know how to sample.

  2. since the variance of the Monte Carlo estimator depends on \(g\), we should choose \(g\) to be relatively flat (so that the output of \(g\) has low variance).

7.8. Summary#

  1. Why Are We Sampling Again? AKA Bayesian Model Evaluation

    • (Posterior Predictive Check: Obviously Needs Sampling) Use the models in the posterior to generate synthetic data, in order to compare with real data, i.e. sample from the posterior predictive.

    • (Marginal Data Log-Likelihood: Secretly Needs Sampling) Compute the marginal log-likelihood of the data (train or test) over the posterior:

      \[\begin{aligned} \sum_{m=1}^M \log \int_\Theta p(\mathbf{y}^*_m | \theta) p(\theta| \text{Data}) d\theta \end{aligned}\]



  2. Integration Requires Sampling! Monte Carlo Integration

    • Recognize your integral as an expectation:

      \[\int_\Theta \underbrace{p(\mathbf{y}^*_m | \theta)}_{\text{$f(\theta)$}}\underbrace{p(\theta| \text{Data})}_{\text{pdf of $\theta$}} d\theta = \mathbb{E}_{\theta\sim p(\theta|\text{Data})}\left[ p(\mathbf{y}^*_m | \theta)\right]\]
    • Approximate the expectation (theoretical mean) with sampling mean:

      \[\underbrace{\mathbb{E}_{\theta\sim p(\theta|\text{Data})}\left[ p(\mathbf{y}^*_m | \theta)\right]}_{I} \approx \underbrace{\frac{1}{S}\sum_{s=1}^S p(\mathbf{y}^*_m | \theta_s),\, \theta_s \sim p(\theta | Y)}_{\widehat{I}}\]

      Why is this valid again? That is, what are the desirable properties of the estimator \(\widehat{I}\)?

    • Reduce the variance of estimator \(\widehat{I}\): What are the two factors contributing to the variance of \(\widehat{I}\)?

      • Control Variates:

        • Need to choose \(h(\theta)\) such that …?

        • Need to choose constant \(c\)

        • Then \( \widehat{I}_{\text{control}} = \frac{1}{S}\sum^S_{s=1} f(\theta_s) - c(h(\theta_s) - \mu_h) \)

        • How do I get the greatest variance reduction? Why is it hard to achieve?

      • Stratified Sampling:

        • Need to choose the strata, e.g. a way to break up the domain of \(\theta\), such that …?

        • Need to renormalize \(p\) so it’s a pdf over each stratum

          \[ \frac{p(\theta)}{w_m},\quad w_m = \int_{\Theta_m} p(\theta)d\theta. \]
        • Estimate the integral \(\mathbb{E}_{\theta \sim \frac{p(\theta)}{w_m}\mathbb{1}_{\Theta_m}}[f(\theta)]\) on each stratum estimated with \(S_m = w_m * S\) samples

        • Piece together the integral over the entire domain of \(\theta\)

          \[ \widehat{I}_{\text{SS}} = \sum_{m=1}^M w_m \widehat{I}_m. \]
      • Importance Sampling:

        • Need to choose importance distribution \(q(\theta)\) such that …?

        • Sample from your importance distribution and then, instead of trashing samples unlikely under \(p\), we down-weight their importance in the Monte Carlo sum

          \[\widehat{I}_{\text{IS}} = \frac{1}{S}\sum_{s=1}^S \underbrace{\frac{p(\theta_s|Y)}{q(\theta_s)}}_{\text{Importance Weight}}f(\theta_s), \; \theta_s \sim q(\theta_s)\]
        • Why do we need importance sampling? Why is it hard to achieve variance reduction with importance sampling?

7.9. Exercises#

These problems were originally assigned as homework. Data files are in the book’s data/ folder. Worked solutions, where available, are collapsed beneath the questions they answer; try each problem before expanding them.

Problem Set: Sampling and Monte Carlo Integration#

Hide code cell content

### Import basic libraries
import numpy as np
import pandas as pd
import sklearn as sk
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
%matplotlib inline

Problem Description#

Let \(X\) be a random variable with distribution described by the following pdf:

\[\begin{split} f_X(x) = \begin{cases} \frac{1}{12}(x-1), &1\leq x\leq 3\\ -\frac{1}{12}(x-5), &3< x\leq 5\\ \frac{1}{6}(x-5), &5< x\leq 7\\ -\frac{1}{6}(x-9), &7< x\leq 9\\ 0, &otherwise \end{cases} \end{split}\]

Let \(h\) be the following function of the random variable \(X\):

\[ h(x) = 7 * \mathrm{exp}\left\{\frac{(x-4)^2}{-2}\right\} + 3 * \mathrm{exp}\left\{\frac{(x-8)^2}{-2 * 0.7^2}\right\} \]

Our goal is to compute the expected value of \(h(X)\):

\[ I = \mathbb{E}_{X\sim f_X}\left[h(X)\right] = \int_{\Omega} h(x) f_X(x)dx, \]

where \(\Omega\) is the domain of \(f_X\).

Exercise: Part I. Implement Some Monte Carlo Estimates

Approximate \(\mathbb{E}_{X\sim f_X}[h(X)]\) using the Monte Carlo integration methods and your choice of a reasonable fixed \(S\) (for rejection sampling, this means run the algorithm \(S\) times):

  1. Inverse CDF Sampling and naive Monte Carlo estimation.

  2. Rejection Sampling and naive Monte Carlo estimation, using each of the following

    • a uniform proposal distribution

    • a normal proposal distribution

    and your choice of reasonable parameters for the proposal distributions.

  3. Importance Sampling using each of the following

    • a uniform importance distribution

    • a normal importance distribution

    and your choice of reasonable parameters for the importance distributions.

  4. Stratified Sampling using 4 strata, whose end points are given by

    \[ [1, 3, 5, 7, 9]. \]

    Use inverse cdf sampling on each stratum.

Exercise: Part II. Debug Your Samplers

  1. Visualize the pdf \(f_X\) as well as samples obtained from Inverse CDF Sampling and Rejection Sampling (for both proposal distributions). It’s probably better to make separate plots for each set of samples.

    What does the comparison say about the quality of your samples? In particular, which sampler (and which proposal distribution) produces “better” samples? Is this surprising – i.e. use some properties of these samplers discussed in Chapter 6 and this chapter to explain the patterns you’re observing?

    Hint: you might find it helpful to visualize the proposal distributions along with \(f_X\) in your analysis of rejection sampling.

  2. Visualize the distribution of the importance weights (one for each importance distribution).

    Is the weight distribution surprising – i.e. use some properties of these samplers discussed in Chapter 6 and this chapter to explain the patterns you’re observing?

    What do these importance weights tell you about the quality of your importance sampling estimate?

    Hint: you might find it helpful to visualize the importance distributions along with \(f_X\) and \(h\) in your analysis of importance sampling.

  3. Visualize the distribution of all the samples across strata. Is the distribution what you expect – i.e. use some properties of these samplers discussed in Chapter 6 and this chapter to explain the patterns you’re observing?

Exercise: Part III: Variance Reduction

  1. Compute the sample variance of the four Monte Carlo estimates in Part I. Based on the discussion in this chapter, which sampling methods (and proposal/importance distributions) is expected, in principle, to resulted in lower variances? How well do your results align with these expectations?

  2. Based on your experiments, would you feel comfortable concluding which type of Monte Carlo estimate will generally have the lowest variance? Why or why not?

7.10. Further Reading#

Monte Carlo Integration