Lab 3: Sampling and Monte Carlo Integration#

This lab is adapted from AM207 (Harvard). Data files are in the book’s data/ folder. Worked solutions are collapsed: try each exercise before expanding them.

In this lab

  1. Monte Carlo Estimation of a General Integral

  2. Practice: Implementing Monte Carlo Integration

Hide code cell content

### Import basic libraries
from functools import partial
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

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).

Exercise: Monte Carlo Integration#

Use Monte Carlo methods to estimate the following integral:

\[ \int_{0}^{1} \frac{3x^2}{x^3 - x^2 - 11x - 4} dx \]

Hint: write the integrand \(f\) as \(f(x) = g(x)h(x)\) where \(h(x)\) defines a pdf over \([0, 1]\) and is easy to sample from.