# HTW Berlin - Angewandte Informatik - Advanced Topics - Exercise - Monte Carlo Estimator

## Table of Contents

## Introduction

In this notebook you will first see why it is important to draw samples according to the probability distribution and not just using a grid (`np.linspace(...)`

) or a uniform distribution. Afterwards, you will implement inverse transform sampling and use it to estimate a function with respect to a probability density function. Finally, you will make use of control variates to reduce the variance of the estimator and to improve the estimation.

In order to detect errors in your own code, execute the notebook cells containing `assert`

or `assert_almost_equal`

. These statements raise exceptions, as long as the calculated result is not yet correct.

## Requirements

### Knowledge

To complete this exercise notebook, you should possess knowledge about the following topics.

- Probability density function
- Probability mass function
- Expected value (
**Exercise - Expected Value**) - Monte Carlo estimator
- Inverse transform sampling
- Variance reduction

The following material can help you to acquire this knowledge:

- Read Chapter 3 "Probability and Information Theory" of the Deep Learning Book
- https://www.youtube.com/watch?v=irheiVXJRm8 (Smirnov Transform)
- https://www.math.nyu.edu/faculty/goodman/teaching/MonteCarlo2005/notes/VarianceReduction.pdf (Variance reduction)

### Python Modules

```
# External Modules
import matplotlib.pyplot as plt
import numpy as np
from numpy.testing import assert_almost_equal
%matplotlib inline
```

```
def plot_p_f_and_samples(x, p, f, samples_x1=[], samples_x2=[]):
"""
Plots two functions p(x) and f(x) for given x values
and f(samples_x) as single points
:param x: x-values for the functions p and f
:type x: 1D ndarray
:param p: pdf
:type p: lambda function
:param f: function evaluated with x and samples_x
:type f: lambda function
:param samples x: x-values for the function f drawn as single points
"""
plt.plot(x, p(x), label='p(x)')
plt.plot(x, f(x),label='f(x)')
if len(samples_x1) > 0:
plt.plot([samples_x1[:-1]], [f(samples_x1)[:-1]], marker='x', color='g')
plt.plot([samples_x1[-1]], [f(samples_x1)[-1]], marker='x', color='g', label='f(samples_x1)')
if len(samples_x2) > 0:
plt.plot([samples_x2[:-1]], [f(samples_x2)[:-1]], marker='x', color='r')
plt.plot([samples_x2[-1]], [f(samples_x2)[-1]], marker='x', color='r', label='f(samples_x2)')
plt.xlabel('x')
plt.legend(loc='upper left')
```

### Crude Monte Carlo Estimator (CMC)

We have a function, which estimates$ \mathbb E_{x \sim p} [f(x)] $ with the use of$ n $ drawn samples, with the given functions:

$ f(x)=\sin(x) $

and $ p(x) = \text{uniform}(0, \pi/2) $

### Exercise - Variance Reduction by Control Variates

**Task:**

Determine the empirical variance (also sample variance) of the CMC-estimator for n = 10 by computing the expected value 10,000 times.

```
# Complete this cell
#(...)
#(...)
e_variance = None
```

```
# Executing this cell must not throw an Exception
# The solution is obfuscated so you can solve the exercise without unintendedly spoiling yourself
#obfuscated_solution = 2366.531932907348 * 626 / 72727
#assert_almost_equal(e_variance, obfuscated_solution, decimal=2)
```

The following plot visualizes how the estimation converges towards the true expected value as n increases.

```
# PLOT
n=500
x_, fs_mean, fs = estimate_f_CMC(n=n)
x = np.arange(n-1)
e = np.ndarray(n-1)
for i in range(1,n):
e[i-1] = fs[:i].mean()
print(fs.mean())
plt.figure(figsize=(20,4))
plt.plot(x,e)
#plt.axhline(y=2., c='g')
plt.xlabel("num of samples")
plt.ylabel("estimate")
```

### Exercise - Variance Reduction by Control Variates

**Task:**

- Reduce the empirical variance and improve the estimator with the use of control variates.
- What's the error (empirical standard deviation) of the estimation?

**Hint:**

We have -$ \hat F $ is CMC the estimator of$ \mathbb E_p [f(x)] $: $ \hat F = \frac{1}{n}\sum_i^n f(x^{(i)}) $

Search for a variable$ g(x) $, which fulfills the following:

*$ g(x) $ is correlated with$ f(x) $

- its expected value$ \mathbb E[g(X)] $ is known

**Reminder:**
$ \bar F $ is the improved estimated value

$ \bar F = \hat F - \beta \cdot ( G - \mathbb E[g(X)] ) $

with $ G = \frac{1}{n}\sum_i^n g(x^{(i)}) $ with optimum$ \beta $:

$ \beta = \frac{cov(\hat F,\bar F)}{var(\bar F)} $

```
# Complete this cell
# get some values for V and W
x_, fs_mean, fs = estimate_f_CMC(n=10)
# (...)
b = None# calculate beta first
```

```
# Executing this cell must not throw an Exception
# The solution is obfuscated, so you can solve the exercise without unintendedly spoiling yourself
#obfuscated_solution = TODO
#assert_almost_equal(b,obfuscated_solution)
```

```
# Now calculate the improved estimation of f
# (...)
Z = None
```

```
# Executing this cell must not throw an Exception
solution = .636
assert_almost_equal(cmc_estimates.mean(), solution, decimal=3)
```

## Literature

## Licenses

### Notebook License (CC-BY-SA 4.0)

*The following license applies to the complete notebook, including code cells. It does however not apply to any referenced external media (e.g., images).*

HTW Berlin - Angewandte Informatik - Advanced Topics - Exercise - Monte Carlo Estimator

by Christian Herta, Klaus Strohmenger

is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

Based on a work at https://gitlab.com/deep.TEACHING.

### Code License (MIT)

*The following license only applies to code cells of the notebook.*

Copyright 2018 Christian Herta, Klaus Strohmenger

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.