# Difference between revisions of "stat341 / CM 361"

Computational Statistics and Data Analysis is a course offered at the University of Waterloo
Spring 2009
Instructor: Ali Ghodsi

## Sampling (Generating random numbers)

### Generating Random Numbers - May 12, 2009

Generating random numbers in a computational setting presents challenges. A good way to generate random numbers in computational statistics involves analyzing various distributions using computational methods. As a result, the probability distribution of each possible number appears to be uniform (pseudo-random). Outside a computational setting, presenting a uniform distribution is fairly easy (for example, rolling a fair die repetitively to produce a series of random numbers from 1 to 6).

We begin by considering the simplest case: the uniform distribution.

#### Multiplicative Congruential Method

One way to generate pseudo random numbers from the uniform distribution is using the Multiplicative Congruential Method. This involves three integer parameters a, b, and m, and a seed variable x0. This method deterministically generates a sequence of numbers (based on the seed) with a seemingly random distribution (with some caveats). It proceeds as follows:

$x_{i+1} = (ax_{i} + b) \mod{m}$

For example, with a = 13, b = 0, m = 31, x0 = 1, we have:

$x_{i+1} = 13x_{i} \mod{31}$

So,

\begin{align} x_{0} &{}= 1 \end{align}
\begin{align} x_{1} &{}= 13 \times 1 + 0 \mod{31} = 13 \\ \end{align}
\begin{align} x_{2} &{}= 13 \times 13 + 0 \mod{31} = 14 \\ \end{align}
\begin{align} x_{3} &{}= 13 \times 14 + 0 \mod{31} =27 \\ \end{align}

etc.

The above generator of pseudorandom numbers is called a Mixed Congruential Generator or Linear Congruential Generator, as they involve both an additive and a muliplicative term. For correctly chosen values of a, b, and m, this method will generate a sequence of integers including all integers between 0 and m - 1. Scaling the output by dividing the terms of the resulting sequence by m - 1, we create a sequence of numbers between 0 and 1, which is similar to sampling from a uniform distribution.

Of course, not all values of a, b, and m will behave in this way, and will not be suitable for use in generating pseudo random numbers.

For example, with a = 3, b = 2, m = 4, x0 = 1, we have:

$x_{i+1} = (3x_{i} + 2) \mod{4}$

So,

\begin{align} x_{0} &{}= 1 \end{align}
\begin{align} x_{1} &{}= 3 \times 1 + 2 \mod{4} = 1 \\ \end{align}
\begin{align} x_{2} &{}= 3 \times 1 + 2 \mod{4} = 1 \\ \end{align}

etc.

For an ideal situation, we want m to be a very large prime number, $x_{n}\not= 0$ for any n, and the period is equal to m-1. In practice, it has been found by a paper published in 1988 by Park and Miller, that a = 75, b = 0, and m = 231 - 1 = 2147483647 (the maximum size of a signed integer in a 32-bit system) are good values for the Multiplicative Congruential Method.

Java's Random class is based on a generator with a = 25214903917, b = 11, and m = 248<ref>http://java.sun.com/javase/6/docs/api/java/util/Random.html#next(int)</ref>. The class returns at most 32 leading bits from each xi, so it is possible to get the same value twice in a row, (when x0 = 18698324575379, for instance) without repeating it forever.

#### General Methods

Since the Multiplicative Congruential Method can only be used for the uniform distribution, other methods must be developed in order to generate pseudo random numbers from other distributions.

##### Inverse Transform Method

This method uses the fact that when a random sample from the uniform distribution is applied to the inverse of a cumulative density function (cdf) of some distribution, the result is a random sample of that distribution. This is shown by this theorem:

Theorem:

If $U \sim~ \mathrm{Unif}[0, 1]$ is a random variable and $X = F^{-1}(U)$, where F is continuous, monotonic, and is the cumulative density function (cdf) for some distribution, then the distribution of the random variable X is given by F(X).

Proof:

Recall that, if f is the pdf corresponding to F, then,

$F(x) = P(X \leq x) = \int_{-\infty}^x f(x)$
$\int_1^{\infty} \frac{x^k}{x^2} dx$

So F is monotonically increasing, since the probability that X is less than a greater number must be greater than the probability that X is less than a lesser number.

Note also that in the uniform distribution on [0, 1], we have for all a within [0, 1], $P(U \leq a) = a$.

So,

\begin{align} P(F^{-1}(U) \leq x) &{}= P(F(F^{-1}(U)) \leq F(x)) \\ &{}= P(U \leq F(x)) \\ &{}= F(x) \end{align}

Completing the proof.

Procedure (Continuous Case)

This method then gives us the following procedure for finding pseudo random numbers from a continuous distribution:

• Step 1: Draw $U \sim~ Unif [0, 1]$.
• Step 2: Compute $X = F^{-1}(U)$.

Example:

Suppose we want to draw a sample from $f(x) = \lambda e^{-\lambda x}$ where $x \gt 0$ (the exponential distribution).

We need to first find $F(x)$ and then its inverse, $F^{-1}$.

$F(x) = \int^x_0 \theta e^{-\theta u} du = 1 - e^{-\theta x}$
$F^{-1}(x) = \frac{-\log(1-y)}{\theta} = \frac{-\log(u)}{\theta}$

Now we can generate our random sample $i=1\dots n$ from $f(x)$ by:

$1)\ u_i \sim Unif[0, 1]$
$2)\ x_i = \frac{-\log(u_i)}{\theta}$

The $x_i$ are now a random sample from $f(x)$.

This example can be illustrated in Matlab using the code below. Generate $u_i$, calculate $x_i$ using the above formula and letting $\theta=1$, plot the histogram of $x_i$'s for $i=1,...,100,000$.

u=rand(1,100000);
x=-log(1-u)/1;
hist(x)


The histogram shows exponential pattern as expected.

The major problem with this approach is that we have to find $F^{-1}$ and for many distributions it is too difficult (or impossible) to find the inverse of $F(x)$. Further, for some distributions it is not even possible to find $F(x)$ (i.e. a closed form expression for the distribution function, or otherwise; even if the closed form expression exists, it's usually difficult to find $F^{-1}$).

Procedure (Discrete Case)

The above method can be easily adapted to work on discrete distributions as well.

In general in the discrete case, we have $x_0, \dots , x_n$ where:

\begin{align}P(X = x_i) &{}= p_i \end{align}
$x_0 \leq x_1 \leq x_2 \dots \leq x_n$
$\sum p_i = 1$

Thus we can define the following method to find pseudo random numbers in the discrete case (note that the less-than signs from class have been changed to less-than-or-equal-to signs by me, since otherwise the case of $U = 1$ is missed):

• Step 1: Draw $U~ \sim~ Unif [0,1]$.
• Step 2:
• If $U \lt p_0$, return $X = x_0$
• If $p_0 \leq U \lt p_0 + p_1$, return $X = x_1$
• ...
• In general, if $p_0+ p_1 + \dots + p_{k-1} \leq U \lt p_0 + \dots + p_k$, return $X = x_k$

Example (from class):

Suppose we have the following discrete distribution:

\begin{align} P(X = 0) &{}= 0.3 \\ P(X = 1) &{}= 0.2 \\ P(X = 2) &{}= 0.5 \end{align}

The cumulative density function (cdf) for this distribution is then:

$F(x) = \begin{cases} 0, & \text{if } x \lt 0 \\ 0.3, & \text{if } 0 \leq x \lt 1 \\ 0.5, & \text{if } 1 \leq x \lt 2 \\ 1, & \text{if } 2 \leq x \end{cases}$

Then we can generate numbers from this distribution like this, given $u_0, \dots, u_n$ from $U \sim~ Unif[0, 1]$:

$x_i = \begin{cases} 0, & \text{if } u_i \leq 0.3 \\ 1, & \text{if } 0.3 \lt u_i \leq 0.5 \\ 2, & \text{if } 0.5 \lt u_i \leq 1 \end{cases}$

This example can be illustrated in Matlab using the code below:

p=[0.3,0.2,0.5];
for i=1:1000;
u=rand;
if u <= p(1)
x(i)=0;
elseif u < sum(p(1,2))
x(i)=1;
else
x(i)=2;
end
end


### Acceptance-Rejection Sampling - May 14, 2009

Today, we continue the discussion on sampling (generating random numbers) from general distributions with the Acceptance/Rejection Method.

#### Acceptance/Rejection Method

Suppose we wish to sample from a target distribution $f(x)$ that is difficult or impossible to sample from directly. Suppose also that we have a proposal distribution $g(x)$ from which we have a reasonable method of sampling (e.g. the uniform distribution). Then, if there is a constant $c \ |\ c \cdot g(x) \geq f(x)\ \forall x$, accepting samples drawn in successions from $c \cdot g(x)$ with ratio $\frac {f(x)}{c \cdot g(x)}$ close to 1 will yield a sample that follows the target distribution $f(x)$; on the other hand we would reject the samples if the ratio is not close to 1.

The following graph shows the pdf of $f(x)$ (target distribution) and $c \cdot g(x)$ (proposal distribution)

At x=7; sampling from $c \cdot g(x)$ will yield a sample that follows the target distribution $f(x)$

At x=9; we will reject samples according to the ratio $\frac {f(x)}{c \cdot g(x)}$ after sampling from $c \cdot g(x)$

Proof

Note the following:

• $Pr(X|accept) = \frac{Pr(accept|X) \times Pr(X)}{Pr(accept)}$ (Bayes' theorem)
• $Pr(accept|X) = \frac{f(x)}{c \cdot g(x)}$
• $Pr(X) = g(x)\frac{}{}$

So, $Pr(accept) = \int^{}_x Pr(accept|X) \times Pr(X) dx$ $= \int^{}_x \frac{f(x)}{c \cdot g(x)} g(x) dx$ $= \frac{1}{c} \int^{}_x f(x) dx$ $= \frac{1}{c}$

Therefore, $Pr(X|accept) = \frac{\frac{f(x)}{c\ \cdot g(x)} \times g(x)}{\frac{1}{c}} = f(x)$ as required.

Procedure (Continuous Case)

• Choose $g(x)$ (a density function that is simple to sample from)
• Find a constant c such that :$c \cdot g(x) \geq f(x)$
1. Let $Y \sim~ g(y)$
2. Let $U \sim~ Unif [0,1]$
3. If $U \leq \frac{f(x)}{c \cdot g(x)}$ then X=Y; else reject and go to step 1

Example:

Suppose we want to sample from Beta(2,1), for $0 \leq x \leq 1$. Recall:

$Beta(2,1) = \frac{\Gamma (2+1)}{\Gamma (2) \Gamma(1)} \times x^1(1-x)^0 = \frac{2!}{1!0!} \times x = 2x$
• Choose $g(x) \sim~ Unif [0,1]$
• Find c: c = 2 (see notes below)
1. Let $Y \sim~ Unif [0,1]$
2. Let $U \sim~ Unif [0,1]$
3. If $U \leq \frac{2Y}{2} = Y$, then X=Y; else go to step 1

$c$ was chosen to be 2 in this example since $\max \left(\frac{f(x)}{g(x)}\right)$ in this example is 2. This condition is important since it helps us in finding a suitable $c$ to apply the Acceptance/Rejection Method.

In MATLAB, the code that demonstrates the result of this example is:

   j = 1;
while i < 1000
y = rand;
u = rand;
if u <= y
x(j) = y;
j = j + 1;
i = i + 1;
end
end
hist(x);



The histogram produced here should follow the target distribution, $f(x) = 2x$, for the interval $0 \leq x \leq 1$.

The histogram shows the PDF of a Beta(2,1) distribution as expected.

The Discrete Case

The Acceptance/Rejection Method can be extended for discrete target distributions. The difference compared to the continuous case is that the proposal distribution $g(x)$ must also be discrete distribution. For our purposes, we can consider g(x) to be a discrete uniform distribution on the set of values that X may take on in the target distribution.

Example

Suppose we want to sample from a distribution with the following probability mass function (pmf):

P(X=1) = 0.15
P(X=2) = 0.55
P(X=3) = 0.20
P(X=4) = 0.10

• Choose $g(x)$ to be the discrete uniform distribution on the set $\{1,2,3,4\}$
• Find c: $c = \max \left(\frac{f(x)}{g(x)} \right)= 0.55/0.25 = 2.2$
1. Generate $Y \sim~ Unif \{1,2,3,4\}$
2. Let $U \sim~ Unif [0,1]$
3. If $U \leq \frac{f(x)}{2.2 \times 0.25}$, then X=Y; else go to step 1

Limitations

If the proposed distribution is very different from the target distribution, we may have to reject a large number of points before a good sample size of the target distribution can be established. It may also be difficult to find such $g(x)$ that satisfies all the conditions of the procedure.

We will now begin to discuss sampling from specific distributions.

#### Special Technique for sampling from Gamma Distribution

Recall that the cdf of the Gamma distribution is:

$F(x) = \int_0^{\lambda x} \frac{e^{-y}y^{t-1}}{(t-1)!} dy$

If we wish to sample from this distribution, it will be difficult for both the Inverse Method (difficulty in computing the inverse function) and the Acceptance/Rejection Method.

Recall that if $X_1, \dots, X_t$ are independent exponential distributions with mean $\lambda$ (in other words, $X_i\sim~ Exp (\lambda)$), then $\Sigma_{i=1}^t X_i \sim~ Gamma (t, \lambda)$

It appears that if we want to sample from the Gamma distribution, we can consider sampling from t independent exponential distributions with mean $\lambda$ (using the Inverse Method) and add them up. Details will be discussed in the next lecture.

### Techniques for Normal and Gamma Sampling - May 19, 2009

We have examined two general techniques for sampling from distributions. However, for certain distributions more practical methods exist. We will now look at two cases,
Gamma distributions and Normal distributions, where such practical methods exist.

#### Gamma Distribution

Given the additive property of the gamma distribution,

If $X_1, \dots, X_t$ are independent random variables with $X_i\sim~ Exp (\lambda)$ then,

$\Sigma_{i=1}^t X_i \sim~ Gamma (t, \lambda)$

We can use the Inverse Transform Method and sample from independent uniform distributions seen before to generate a sample following a Gamma distribution.

Procedure
1. Sample independently from a uniform distribution $t$ times, giving $u_1,\dots,u_t$
2. Sample independently from an exponential distribution $t$ times, giving $x_1,\dots,x_t$ such that,
\begin{align} x_1 \sim~ Exp(\lambda)\\ \vdots \\ x_t \sim~ Exp(\lambda) \end{align}

Using the Inverse Transform Method,
\begin{align} x_i = -\frac {1}{\lambda}\log(u_i) \end{align}
\begin{align} X &{}= x_1 + x_2 + \dots + x_t \\ X &{}= -\frac {1}{\lambda}\log(u_1) - \frac {1}{\lambda}\log(u_2) \dots - \frac {1}{\lambda}\log(u_t) \\ X &{}= -\frac {1}{\lambda}\log(\prod_{i=1}^{t}u_i) \sim~ Gamma (t, \lambda) \end{align}

This procedure can be illustrated in Matlab using the code below with $t = 5, \lambda = 1$ :

U = rand(10000,5);
X = sum( -log(U), 2);
hist(X)


#### Normal Distribution

"Diagram of the Box Muller transform, which transforms uniformly distributed value pairs to normally distributed value pairs." [Box-Muller Transform, Wikipedia]

The cdf for the Standard Normal distribution is:

$F(Z) = \int_{-\infty}^{Z}\frac{1}{\sqrt{2\pi}}e^{-x^2/2}dx$

We can see that the normal distribution is difficult to sample from using the general methods seen so far, eg. the inverse is not easy to obtain from F(Z); we may be able to use the Acceptance-Rejection method, but there are still better ways to sample from a Standard Normal Distribution.

##### Box-Muller Method

[Add a picture WikiSysop 19:25, 1 June 2009 (UTC)]

The Box-Muller or Polar method uses an approach where we have one space that is easy to sample in, and another with the desired distribution under a transformation. If we know such a transformation for the Standard Normal, then all we have to do is transform our easy sample and obtain a sample from the Standard Normal distribution.

Properties of Polar and Cartesian Coordinates
If x and y are points on the Cartesian plane, r is the length of the radius from a point in the polar plane to the pole, and θ is the angle formed with the polar axis then,
• \begin{align} r^2 = x^2 + y^2 \end{align}
• $\tan(\theta) = \frac{y}{x}$

• \begin{align} x = r \cos(\theta) \end{align}
• \begin{align} y = r \sin(\theta) \end{align}

Let X and Y be independent random variables with a standard normal distribution,

$X \sim~ N(0,1)$
$Y \sim~ N(0,1)$

also, let $r$ and $\theta$ be the polar coordinates of (x,y). Then the joint distribution of independent x and y is given by,

\begin{align} f(x,y) = f(x)f(y) &{}= \frac{1}{\sqrt{2\pi}}e^{-\frac{x^2}{2}}\frac{1}{\sqrt{2\pi}}e^{-\frac{y^2}{2}} \\ &{}=\frac{1}{2\pi}e^{-\frac{x^2+y^2}{2}} \end{align}

It can also be shown that the joint distribution of r and θ is given by,

$\begin{matrix} f(r,\theta) = \frac{1}{2}e^{-\frac{d}{2}}*\frac{1}{2\pi},\quad d = r^2 \end{matrix}$

Note that $\begin{matrix}f(r,\theta)\end{matrix}$ consists of two density functions, Exponential and Uniform, so assuming that r and $\theta$ are independent $\begin{matrix} \Rightarrow d \sim~ Exp(1/2), \theta \sim~ Unif[0,2\pi] \end{matrix}$

Procedure for using Box-Muller Method
1. Sample independently from a uniform distribution twice, giving \begin{align} u_1,u_2 \sim~ \mathrm{Unif}(0, 1) \end{align}
2. Generate polar coordinates using the exponential distribution of d and uniform distribution of θ,
\begin{align} d = -2\log(u_1),& \quad r = \sqrt{d} \\ & \quad \theta = 2\pi u_2 \end{align}
3. Transform r and θ back to x and y,
\begin{align} x = r\cos(\theta) \\ y = r\sin(\theta) \end{align}

Notice that the Box-Muller Method generates a pair of independent Standard Normal distributions, x and y.

This procedure can be illustrated in Matlab using the code below:

u1 = rand(5000,1);
u2 = rand(5000,1);

d = -2*log(u1);
theta = 2*pi*u2;

x = d.^(1/2).*cos(theta);
y = d.^(1/2).*sin(theta);

figure(1);

subplot(2,1,1);
hist(x);
title('X');
subplot(2,1,2);
hist(y);
title('Y');


Also, we can confirm that d and theta are indeed exponential and uniform random variables, respectively, in Matlab by:

subplot(2,1,1);
hist(d);
title('d follows an exponential distribution');
subplot(2,1,2);
hist(theta);
title('theta follows a uniform distribution over [0, 2*pi]');


##### Useful Properties (Single and Multivariate)

Box-Muller can be used to sample a standard normal distribution. However, there are many properties of Normal distributions that allow us to use the samples from Box-Muller method to sample any Normal distribution in general.

Properties of Normal distributions
• \begin{align} \text{If } & X = \mu + \sigma Z, & Z \sim~ N(0,1) \\ &\text{then } X \sim~ N(\mu,\sigma ^2) \end{align}
• \begin{align} \text{If } & \vec{Z} = (Z_1,\dots,Z_d)^T, & Z_1,\dots,Z_d \sim~ N(0,1) \\ &\text{then } \vec{Z} \sim~ N(\vec{0},I) \end{align}
• \begin{align} \text{If } & \vec{X} = \vec{\mu} + \Sigma^{1/2} \vec{Z}, & \vec{Z} \sim~ N(\vec{0},I) \\ &\text{then } \vec{X} \sim~ N(\vec{\mu},\Sigma) \end{align}

These properties can be illustrated through the following example in Matlab using the code below:

Example: For a Multivariate Normal distribution $u=\begin{bmatrix} -2 \\ 3 \end{bmatrix}$ and $\Sigma=\begin{bmatrix} 1&0.5\\ 0.5&1\end{bmatrix}$

u = [-2; 3];
sigma = [ 1 1/2; 1/2 1];

r = randn(15000,2);
ss = chol(sigma);

X = ones(15000,1)*u' + r*ss;
plot(X(:,1),X(:,2), '.');


Note: In the example above, we had to generate the square root of $\Sigma$ using the Cholesky decomposition,

ss = chol(sigma);


which gives $ss=\begin{bmatrix} 1&0.5\\ 0&0.8660\end{bmatrix}$. Matlab also has the sqrtm function:

ss = sqrtm(sigma);


which gives a different matrix, $ss=\begin{bmatrix} 0.9659&0.2588\\ 0.2588&0.9659\end{bmatrix}$, but the plot looks about the same (X has the same distribution).

## Monte Carlo Integration - May 26, 2009

Today's lecture completes the discussion on the Frequentists and Bayesian schools of thought and introduces Basic Monte Carlo Integration.

#### Frequentist vs Bayesian Example - Estimating Parameters

Estimating parameters of a univariate Gaussian:

Frequentist: $f(x|\theta)=\frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{1}{2}*(\frac{x-\mu}{\sigma})^2}$
Bayesian: $f(\theta|x)=\frac{f(x|\theta)f(\theta)}{f(x)}$

##### Frequentist Approach

Let $X^N$ denote $(x_1, x_2, ..., x_n)$. Using the Maximum Likelihood Estimation approach for estimating parameters we get:

$L(X^N; \theta) = \prod_{i=1}^N \frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{1}{2}(\frac{x_i- \mu} {\sigma})^2}$
$l(X^N; \theta) = \sum_{i=1}^N -\frac{1}{2}log (2\pi) - log(\sigma) - \frac{1}{2} \left(\frac{x_i- \mu}{\sigma}\right)^2$
$\frac{dl}{d\mu} = \displaystyle\sum_{i=1}^N(x_i-\mu)$

Setting $\frac{dl}{d\mu} = 0$ we get

$\displaystyle\sum_{i=1}^Nx_i = \displaystyle\sum_{i=1}^N\mu$
$\displaystyle\sum_{i=1}^Nx_i = N\mu \rightarrow \mu = \frac{1}{N}\displaystyle\sum_{i=1}^Nx_i$
##### Bayesian Approach

Assuming the prior is Gaussian:

$P(\theta) = \frac{1}{\sqrt{2\pi}\tau}e^{-\frac{1}{2}(\frac{x-\mu_0}{\tau})^2}$
$f(\theta|x) \propto \frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{1}{2}(\frac{x_i-\mu}{\sigma})^2} * \frac{1}{\sqrt{2\pi}\tau}e^{-\frac{1}{2}(\frac{x-\mu_0}{\tau})^2}$

By completing the square we conclude that the posterior is Gaussian as well:

$f(\theta|x)=\frac{1}{\sqrt{2\pi}\tilde{\sigma}}e^{-\frac{1}{2}(\frac{x-\tilde{\mu}}{\tilde{\sigma}})^2}$

Where

$\tilde{\mu} = \frac{\frac{N}{\sigma^2}}{{\frac{N}{\sigma^2}}+\frac{1}{\tau^2}}\bar{x} + \frac{\frac{1}{\tau^2}}{{\frac{N}{\sigma^2}}+\frac{1}{\tau^2}}\mu_0$

The expectation from the posterior is different from the MLE method. Note that $\displaystyle\lim_{N\to\infty}\tilde{\mu} = \bar{x}$. Also note that when $N = 0$ we get $\tilde{\mu} = \mu_0$.

#### Basic Monte Carlo Integration

Although it is almost impossible to find a precise definition of "Monte Carlo Method", the method is widely used and has numerous descriptions in articles and monographs. As an interesting fact, the term Monte Carlo is claimed to have been first used by Ulam and von Neumann as a Los Alamos code word for the stochastic simulations they applied to building better atomic bombs. Stochastic simulation refers to a random process in which its future evolution is described by probability distributions (counterpart to a deterministic process), and these simulation methods are known as Monte Carlo methods. [Stochastic process, Wikipedia]. The following example (external link) illustrates a Monte Carlo Calculation of Pi: [1]

$I = \displaystyle\int_a^b h(x)\,dx$
$= \displaystyle\int_a^b w(x)f(x)\,dx$

where

$\displaystyle w(x) = h(x)(b-a)$
$f(x) = \frac{1}{b-a} \rightarrow$ the p.d.f. is Unif$(a,b)$
$\hat{I} = E_f[w(x)] = \frac{1}{N}\displaystyle\sum_{i=1}^Nw(x_i)$

If $x_i \sim~ Unif(a,b)$ then by the Law of Large Numbers $\frac{1}{N}\displaystyle\sum_{i=1}^Nw(x_i) \rightarrow \displaystyle\int w(x)f(x)\,dx = E_f[w(x)]$

##### Process

Given $I = \displaystyle\int^b_ah(x)\,dx$

1. $\begin{matrix} w(x) = h(x)(b-a)\end{matrix}$
2. $\begin{matrix} x_1, x_2, ..., x_n \sim UNIF(a,b)\end{matrix}$
3. $\hat{I} = \frac{1}{N}\displaystyle\sum_{i=1}^Nw(x_i)$

From this we can compute other statistics, such as

1. $SE=\frac{s}{\sqrt{N}}$ where $s^2=\frac{\sum_{i=1}^{N}(Y_i-\hat{I})^2 }{N-1}$ with $\begin{matrix}Y_i=w(x_i)\end{matrix}$
2. $\begin{matrix} 1-\alpha \end{matrix}$ CI's can be estimated as $\hat{I}\pm Z_\frac{\alpha}{2}*SE$

Example 1

Find $E[\sqrt{x}]$ for $\begin{matrix} f(x) = e^{-x}\end{matrix}$

1. We need to draw from $\begin{matrix} f(x) = e^{-x}\end{matrix}$
2. $\hat{I} = \frac{1}{N}\displaystyle\sum_{i=1}^Nw(x_i)$

This example can be illustrated in Matlab using the code below:

u=rand(100,1)
x=-log(u)
h= x.* .5
mean(h)
%The value obtained using the Monte Carlo method
F = @ (x) sqrt (x). * exp(-x)
%The value of the real function using Matlab


Example 2 Find $I = \displaystyle\int^1_0h(x)\,dx, h(x) = x^3$

1. $\displaystyle I = x^4/4 = 1/4$
2. $\displaystyle W(x) = x^3*(1-0)$
3. $Xi \sim~Unif(0,1)$
4. $\hat{I} = \frac{1}{N}\displaystyle\sum_{i=1}^N(x_i^3)$

This example can be illustrated in Matlab using the code below:

x = rand (1000)
mean(x^3)


Example 3 To estimate an infinite integral such as $I = \displaystyle\int^\infty_5 h(x)\,dx, h(x) = 3e^{-x}$

1. Substitute in $y=\frac{1}{x-5+1} =\gt dy=-\frac{1}{(x-4)^2}dx =\gt dy=-y^2dx$
2. $I = \displaystyle\int^1_0 \frac{3e^{-(\frac{1}{y}+4)}}{-y^2}\,dy$
3. $w(y) = \frac{3e^{-(\frac{1}{y}+4)}}{-y^2}(1-0)$
4. $Y_i \sim~Unif(0,1)$
5. $\hat{I} = \frac{1}{N}\displaystyle\sum_{i=1}^N(\frac{3e^{-(\frac{1}{y_i}+4)}}{-y_i^2})$

## Importance Sampling and Monte Carlo Simulation - May 28, 2009

During this lecture we covered two more examples of Monte Carlo simulation, finishing that topic, and begun talking about Importance Sampling.

#### Binomial Probability Monte Carlo Simulations

##### Example 1:

You are given two independent Binomial distributions with probabilities $\displaystyle p_1\text{, }p_2$. Using a Monte Carlo simulation, approximate the value of $\displaystyle \delta$, where $\displaystyle \delta = p_1 - p_2$.

$\displaystyle X \sim BIN(n, p_1)$; $\displaystyle Y \sim BIN(n, p_2)$; $\displaystyle \delta = p_1 - p_2$

So $\displaystyle f(p_1, p_2 | x,y) = \frac{f(x, y|p_1, p_2)*f(p_1,p_2)}{f(x,y)}$ where $\displaystyle f(x,y)$ is a flat distribution and the expected value of $\displaystyle \delta$ is as follows:

$\displaystyle \hat{\delta} = \int\int\delta f(p_1,p_2|X,Y)\,dp_1dp_2$

Since X, Y are independent, we can split the conditional probability distribution:

$\displaystyle f(p_1,p_2|X,Y) \propto f(p_1|X)f(p_2|Y)$

We need to find conditional distribution functions for $\displaystyle p_1, p_2$ to draw samples from. In order to get a distribution for the probability 'p' of a Binomial, we have to divide the Binomial distribution by n. This new distribution has the same shape as the original, but is scaled. A Beta distribution is a suitable approximation. Let

$\displaystyle f(p_1 | X) \sim \text{Beta}(x+1, n-x+1)$ and $\displaystyle f(p_2 | Y) \sim \text{Beta}(y+1, n-y+1)$, where
$\displaystyle \text{Beta}(\alpha,\beta) = \frac{\Gamma(\alpha+\beta)}{\Gamma(\alpha)\Gamma(\beta)}p^{\alpha-1}(1-p)^{\beta-1}$

Process:

1. Draw samples for $\displaystyle p_1$ and $\displaystyle p_2$: $\displaystyle (p_1,p_2)^{(1)}$, $\displaystyle (p_1,p_2)^{(2)}$, ..., $\displaystyle (p_1,p_2)^{(n)}$;
2. Compute $\displaystyle \delta = p_1 - p_2$ in order to get n values for $\displaystyle \delta$;
3. $\displaystyle \hat{\delta}=\frac{\displaystyle\sum_{\forall i}\delta^{(i)}}{N}$.

Matlab Code:

The Matlab code for recreating the above example is as follows:
n=100; %number of trials for X
m=100; %number of trials for Y
x=80; %number of successes for X trials
y=60; %number of successes for y trials
p1=betarnd(x+1, n-x+1, 1, 1000);
p2=betarnd(y+1, m-y+1, 1, 1000);
delta=p1-p2;
mean(delta);


The mean in this example is given by 0.1938.

A 95% confidence interval for $\delta$ is represented by the interval between the 2.5% and 97.5% quantiles which covers 95% of the probability distribution. In Matlab, this can be calculated as follows:

q1=quantile(delta,0.025);
q2=quantile(delta,0.975);


The interval is approximately $95% CI \approx (0.06606, 0.32204)$

The histogram of delta is:

Note: In this case, we can also find $E(\delta)$ analytically since $E(\delta) = E(p_1 - p_2) = E(p_1) - E(p_2) = \frac{x+1}{n+2} - \frac{y+1}{m+2} \approx 0.1961$. Compare this with the maximum likelihood estimate for $\delta$: $\frac{x}{n} - \frac{y}{m} = 0.2$.

##### Example 2:

Bayesian Inference for Dose Response

We conduct an experiment by giving rats one of ten possible doses of a drug, where each subsequent dose is more lethal than the previous one:

$\displaystyle x_1\lt x_2\lt ...\lt x_{10}$

For each dose $\displaystyle x_i$ we test n rats and observe $\displaystyle Y_i$, the number of rats that survive. Therefore,

$\displaystyle Y_i \sim~ BIN(n, p_i)$
.

We can assume that the probability of death grows with the concentration of drug given, i.e. $\displaystyle p_1\lt p_2\lt ...\lt p_{10}$. Estimate the dose at which the animals have at least 50% chance of dying.

Let $\displaystyle \delta=x_j$ where $\displaystyle j=min\{i|p_i\geq0.5\}$
We are interested in $\displaystyle \delta$ since any higher concentrations are known to have a higher death rate.

Solving this analytically is difficult:

$\displaystyle \delta = g(p_1, p_2, ..., p_{10})$ where g is an unknown function
$\displaystyle \hat{\delta} = \int \int..\int_A \delta f(p_1,p_2,...,p_{10}|Y_1,Y_2,...,Y_{10})\,dp_1dp_2...dp_{10}$
where $\displaystyle A=\{(p_1,p_2,...,p_{10})|p_1\leq p_2\leq ...\leq p_{10} \}$

Process: Monte Carlo
We assume that

1. Draw $\displaystyle p_i \sim~ BETA(y_i+1, n-y_i+1)$
2. Keep sample only if it satisfies $\displaystyle p_1\leq p_2\leq ...\leq p_{10}$, otherwise discard and try again.
3. Compute $\displaystyle \delta$ by finding the first $\displaystyle p_i$ sample with over 50% deaths.
4. Repeat process n times to get n estimates for $\displaystyle \delta_1, \delta_2, ..., \delta_N$.
5. $\displaystyle \bar{\delta} = \frac{\displaystyle\sum_{\forall i} \delta_i}{N}$.

For instance, for each dose level $X_i$, for $1\lt =i\lt =10$, 10 rats are used and it is observed that the numbers that are dying is $Y_i$, where $Y_1 = 4, Y_2 = 3,$etc.

#### Importance Sampling

In statistics, Importance Sampling helps estimating the properties of a particular distribution. As in the case with the Acceptance/Rejection method, we choose a good distribution from which to simulate the given random variables. The main difference in importance sampling however, is that certain values of the input random variables in a simulation have more impact on the parameter being estimated than others. [Importance Sampling, Wikipedia] The following diagram illustrates a Monte Carlo approximation for g(x):

As the figure above shows, the uniform distribution $U\sim~Unif[0,1]$ is a proposal distribution to sample from and g(x) is the target distribution. Here we cast the integral $\int_{0}^1 g(x)dx$, as the expectation with respect to U such that $\int_{0}^1 g(x)= E(g(U))$. Hence we can approximate by $\frac{1}{n}\displaystyle\sum_{i=1}^{n} g(u_i)$.
[Source: Monte Carlo Methods and Importance Sampling, Eric C. Anderson (1999). Retrieved June 9th from URL: http://ib.berkeley.edu/labs/slatkin/eriq/classes/guest_lect/mc_lecture_notes.pdf]

In $I = \displaystyle\int h(x)f(x)\,dx$, Monte Carlo simulation can be used only if it easy to sample from f(x). Otherwise, another method must be applied. If sampling from f(x) is difficult but there exists a probability distribution function g(x) which is easy to sample from, then $I$ can be written as

$I = \displaystyle\int h(x)f(x)\,dx$
$= \displaystyle\int \frac{h(x)f(x)}{g(x)}g(x)\,dx$
$= \displaystyle E_g(w(x)) \rightarrow$the expectation of w(x) with respect to g(x) and therefore $\displaystyle x_1,x_2,...,x_N \sim~ g$
$= \frac{\displaystyle\sum_{i=1}^{N} w(x_i)}{N}$ where $\displaystyle w(x) = \frac{h(x)f(x)}{g(x)}$

Process

1. Choose $\displaystyle g(x)$ such that it's easy to sample from.
2. Compute $\displaystyle w(x)=\frac{h(x)f(x)}{g(x)}$
3. $\displaystyle \hat{I} = \frac{\displaystyle\sum_{i=1}^{N} w(x_i)}{N}$

Note: By the law of large number, we can say that $\hat{I}$ converges in probability to $I$.

"Weighted" average

The term "importance sampling" is used to describe this method because a higher 'importance' or 'weighting' is given to the values sampled from $\displaystyle g(x)$ that are closer to the original distribution $\displaystyle f(x)$, which we would ideally like to sample from (but cannot because it is too difficult).
$\displaystyle I = \int\frac{h(x)f(x)}{g(x)}g(x)\,dx$
$=\displaystyle \int \frac{f(x)}{g(x)}h(x)g(x)\,dx$
$=\displaystyle \int \frac{f(x)}{g(x)}E_g(h(x))\,dx$ which is the same thing as saying that we are applying a regular Monte Carlo Simulation method to $\displaystyle\int h(x)g(x)\,dx$, taking each result from this process and weighting the more accurate ones (i.e. the ones for which $\displaystyle \frac{f(x)}{g(x)}$ is high) higher.

One can view $\frac{f(x)}{g(x)}\ = B(x)$ as a weight.

Then $\displaystyle \hat{I} = \frac{\displaystyle\sum_{i=1}^{N} w(x_i)}{N} = \frac{\displaystyle\sum_{i=1}^{N} B(x_i)*h(x_i)}{N}$

i.e. we are computing a weighted sum of $h(x_i)$ instead of a sum

### A Deeper Look into Importance Sampling - June 2, 2009

From last class, we have determined that an integral can be written in the form $I = \displaystyle\int h(x)f(x)\,dx$ $= \displaystyle\int \frac{h(x)f(x)}{g(x)}g(x)\,dx$ We continue our discussion of Importance Sampling here.

#### Importance Sampling

We can see that the integral $\displaystyle\int \frac{h(x)f(x)}{g(x)}g(x)\,dx = \int \frac{f(x)}{g(x)}h(x) g(x)\,dx$ is just $\displaystyle E_g(h(x)) \rightarrow$the expectation of h(x) with respect to g(x), where $\displaystyle \frac{f(x)}{g(x)}$ is a weight $\displaystyle\beta(x)$. In the case where $\displaystyle f \gt g$, a greater weight for $\displaystyle\beta(x)$ will be assigned. Thus, the points with more weight are deemed more important, hence "importance sampling". This can be seen as a variance reduction technique.

##### Problem

The method of Importance Sampling is simple but can lead to some problems. The $\displaystyle \hat I$ estimated by Importance Sampling could have infinite standard error.

Given $\displaystyle I= \int w(x) g(x) dx$ $= \displaystyle E_g(w(x))$ $= \displaystyle \frac{1}{N}\sum_{i=1}^{N} w(x_i)$ where $\displaystyle w(x)=\frac{f(x)h(x)}{g(x)}$.

Obtaining the second moment,

$\displaystyle E[(w(x))^2]$
$\displaystyle = \int (\frac{h(x)f(x)}{g(x)})^2 g(x) dx$
$\displaystyle = \int \frac{h^2(x) f^2(x)}{g^2(x)} g(x) dx$
$\displaystyle = \int \frac{h^2(x)f^2(x)}{g(x)} dx$

We can see that if $\displaystyle g(x) \rightarrow 0$, then $\displaystyle E[(w(x))^2] \rightarrow \infty$. This occurs if $\displaystyle g$ has a thinner tail than $\displaystyle f$ then $\frac{h^2(x)f^2(x)}{g(x)}$ could be infinitely large. The general idea here is that $\frac{f(x)}{g(x)}$ should not be large.

##### Remark 1

It is evident that $\displaystyle g(x)$ should be chosen such that it has a thicker tail than $\displaystyle f(x)$. If $\displaystyle f$ is large over set $\displaystyle A$ but $\displaystyle g$ is small, then $\displaystyle \frac{f}{g}$ would be large and it would result in a large variance.

##### Remark 2

It is useful if we can choose $\displaystyle g$ to be similar to $\displaystyle f$ in terms of shape. Ideally, the optimal $\displaystyle g$ should be similar to $\displaystyle \left| h(x) \right|f(x)$, and have a thicker tail. It's important to take the absolute value of $\displaystyle h(x)$, since a variance can't be negative. Analytically, we can show that the best $\displaystyle g$ is the one that would result in a variance that is minimized.

##### Remark 3

Choose $\displaystyle g$ such that it is similar to $\displaystyle \left| h(x) \right| f(x)$ in terms of shape. That is, we want $\displaystyle g \propto \displaystyle \left| h(x) \right| f(x)$

#### Theorem (Minimum Variance Choice of $\displaystyle g$)

The choice of $\displaystyle g$ that minimizes variance of $\hat I$ is $\displaystyle g^*(x)=\frac{\left| h(x) \right| f(x)}{\int \left| h(s) \right| f(s) ds}$.

##### Proof:

We know that $\displaystyle w(x)=\frac{f(x)h(x)}{g(x)}$

The variance of $\displaystyle w(x)$ is

$\displaystyle Var[w(x)]$
$\displaystyle = E[(w(x)^2)] - [E[w(x)]]^2$
$\displaystyle = \int \left(\frac{f(x)h(x)}{g(x)} \right)^2 g(x) dx - \left[\int \frac{f(x)h(x)}{g(x)}g(x)dx \right]^2$
$\displaystyle = \int \left(\frac{f(x)h(x)}{g(x)} \right)^2 g(x) dx - \left[\int f(x)h(x) \right]^2$

As we can see, the second term does not depend on $\displaystyle g(x)$. Therefore to minimize $\displaystyle Var[w(x)]$ we only need to minimize the first term. In doing so we will use Jensen's Inequality.

$\displaystyle ======Aside: Jensen's Inequality======$

If $\displaystyle g$ is a convex function ( twice differentiable and $\displaystyle g''(x) \geq 0$ ) then $\displaystyle g(\alpha x_1 + (1-\alpha)x_2) \leq \alpha g(x_1) + (1-\alpha) g(x_2)$
Essentially the definition of convexity implies that the line segment between two points on a curve lies above the curve, which can then be generalized to higher dimensions:

$\displaystyle g(\alpha_1 x_1 + \alpha_2 x_2 + ... + \alpha_n x_n) \leq \alpha_1 g(x_1) + \alpha_2 g(x_2) + ... + \alpha_n g(x_n)$ where $\displaystyle \alpha_1 + \alpha_2 + ... + \alpha_n = 1$
=======================================================
##### Proof (cont)

Using Jensen's Inequality,

$\displaystyle g(E[x]) \leq E[g(x)]$ as $\displaystyle g(E[x]) = g(p_1 x_1 + ... p_n x_n) \leq p_1 g(x_1) + ... + p_n g(x_n) = E[g(x)]$

Therefore

$\displaystyle E[(w(x))^2] \geq (E[\left| w(x) \right|])^2$
$\displaystyle E[(w(x))^2] \geq \left(\int \left| \frac{f(x)h(x)}{g(x)} \right| g(x) dx \right)^2$

and

$\displaystyle \left(\int \left| \frac{f(x)h(x)}{g(x)} \right| g(x) dx \right)^2$
$\displaystyle = \left(\int \frac{f(x)\left| h(x) \right|}{g(x)} g(x) dx \right)^2$
$\displaystyle = \left(\int \left| h(x) \right| f(x) dx \right)^2$ since $\displaystyle f$ and $\displaystyle g$ are density functions, $\displaystyle f, g$ cannot be negative.

Thus, this is a lower bound on $\displaystyle E[(w(x))^2]$. If we replace $\displaystyle g^*(x)$ into $\displaystyle E[g^*(x)]$, we can see that the result is as we require. Details omitted.

However, this is mostly of theoritical interest. In practice, it is impossible or very difficult to compute $\displaystyle g^*$.

Note: Jensen's inequality is actually unnecessary here. We just use it to get $E[(w(x))^2] \geq (E[|w(x)|])^2$, which could be derived using variance properties: $0 \leq Var[|w(x)|] = E[|w(x)|^2] - (E[|w(x)|])^2 = E[(w(x))^2] - (E[|w(x)|])^2$.

### Importance Sampling and Markov Chain Monte Carlo (MCMC) - June 4, 2009

Remark 4: $I = \displaystyle\int^\ h(x)f(x)\,dx$

$= \displaystyle\int \ h(x)\frac{f(x)}{g(x)}g(x)\,dx$
$= \displaystyle\sum_{i=1}^{N} h(x_i)b(x_i)$ where $\displaystyle b(x_i) = \frac{f(x_i)}{g(x_i)}$
$=\displaystyle \frac{\int\ h(x)f(x)\,dx}{\int f(x) dx}$

Apply the idea of importance sampling to both the numerator and denominator:

$=\displaystyle \frac{\int\ h(x)\frac{f(x)}{g(x)}g(x)\,dx}{\int\frac{f(x)}{g(x)}g(x) dx}$
$= \displaystyle\frac{\sum_{i=1}^{N} h(x_i)b(x_i)}{\sum_{1=1}^{N} b(x_i)}$
$= \displaystyle\sum_{i=1}^{N} h(x_i)b'(x_i)$ where $\displaystyle b'(x_i) = \frac{b(x_i)}{\sum_{i=1}^{N} b(x_i)}$

The above results in the following form of Importance Sampling:

$\hat{I} = \displaystyle\sum_{i=1}^{N} b'(x_i)h(x_i)$ where $\displaystyle b'(x_i) = \frac{b(x_i)}{\sum_{i=1}^{N} b(x_i)}$

This is very important and useful especially when f is known only up to a proportionality constant. Often, this is the case in the Bayesian approach when f is a posterior density function.

#### Example of Importance Sampling

Estimate $I = \displaystyle\ Pr (Z\gt 3)$ when $Z \sim~ N(0,1)$

$I = \displaystyle\int^\infty_3 f(x)\,dx \approx 0.0013$
$= \displaystyle\int^\infty_3 h(x)f(x)\,dx$
Define $h(x) = \begin{cases} 0, & \text{if } x \lt 3 \\ 1, & \text{if } 3 \leq x \end{cases}$

Approach I: Monte Carlo

$\hat{I} = \frac{1}{N}\displaystyle\sum_{i=1}^Nh(x_i)$ where $X \sim~ N(0,1)$

The idea here is to sample from normal distribution and to count number of observations that is greater than 3.

The variability will be high in this case if using Monte Carlo since this is considered a low probability event (a tail event), and different runs may give significantly different values. For example: the first run may give only 3 occurences (i.e if we generate 1000 samples, thus the probability will be .003), the second run may give 5 occurences (probability .005), etc.

This example can be illustrated in Matlab using the code below (we will be generating 100 samples in this case):

format long
for i = 1:100
a(i) = sum(randn(100,1)>=3)/100;
end
meanMC  = mean(a)
varMC   = var(a)


On running this, we get $meanMC = 0.0005$ and $varMC \approx 1.31313 * 10^{-5}$

Approach II: Importance Sampling

$\hat{I} = \frac{1}{N}\displaystyle\sum_{i=1}^Nh(x_i)\frac{f(x_i)}{g(x_i)}$ where $f(x)$ is standard normal and $g(x)$ needs to be chosen wisely so that it is similar to the target distribution.
Let $g(x) \sim~ N(4,1)$
$b(x) = \frac{f(x)}{g(x)} = e^{(8-4x)}$
$\hat{I} = \frac{1}{N}\displaystyle\sum_{i=1}^Nb(x_i)h(x_i)$

This example can be illustrated in Matlab using the code below:

for j = 1:100
N = 100;
x = randn (N,1) + 4;
for ii = 1:N
h = x(ii)>=3;
b = exp(8-4*x(ii));
w(ii) = h*b;
end
I(j) = sum(w)/N;
end
MEAN = mean(I)
VAR = var(I)


Running the above code gave us $MEAN \approx 0.001353$ and $VAR \approx 9.666 * 10^{-8}$ which is very close to 0, and is much less than the variability observed when using Monte Carlo

#### Markov Chain Monte Carlo (MCMC)

Before we tackle Markov chain Monte Carlo methods, which essentially are a 'class of algorithms for sampling from probability distributions based on constructing a Markov chain' [MCMC, Wikipedia], we will first give a formal definition of Markov Chain.

Consider the same integral: $I = \displaystyle\int^\ h(x)f(x)\,dx$

Idea: If $\displaystyle X_1, X_2,...X_N$ is a Markov Chain with stationary distribution f(x), then under some conditions

$\hat{I} = \frac{1}{N}\displaystyle\sum_{i=1}^Nh(x_i)\xrightarrow{P}\int^\ h(x)f(x)\,dx = I$

Stochastic Process:
A Stochastic Process is a collection of random variables $\displaystyle \{ X_t : t \in T \}$

• State Space Set:$\displaystyle X$is the set that random variables $\displaystyle X_t$ takes values from.
• Indexed Set:$\displaystyle T$is the set that t takes values from, which could be discrete or continuous in general, but we are only interested in discrete case in this course.

Example 1
i.i.d random variables

$\{ X_t : t \in T \}, X_t \in X$
$X = \{0, 1, 2, 3, 4, 5, 6, 7, 8\} \rightarrow$State Space
$T = \{1, 2, 3, 4, 5\} \rightarrow$Indexed Set

Example 2

$\displaystyle X_t$: price of a stock
$\displaystyle t$: opening date of the market

Basic Fact: In general, if we have random variables $\displaystyle X_1,...X_n$

$\displaystyle f(X_1,...X_n)= f(X_1)f(X_2|X_1)f(X_3|X_2,X_1)...f(X_n|X_n-1,...,X_1)$
$\displaystyle f(X_1,...X_n)= \prod_{i = 1}^n f(X_i|Past_i)$ where $\displaystyle Past_i = (X_{i-1}, X_{i-2},...,X_1)$

Markov Chain:
A Markov Chain is a special form of stochastic process in which $\displaystyle X_t$ depends only on $X_t-1$.

For example,

$\displaystyle f(X_1,...X_n)= f(X_1)f(X_2|X_1)f(X_3|X_2)...f(X_n|X_n-1)$

Transition Probability:
The probability of going from one state to another state.

$p_{ij} = \Pr(X=X_j\mid X= X_i). \,$

Transition Matrix:
For n states, transition matrix P is an $N \times N$ matrix with entries $\displaystyle P_{ij}$ as below:

$P=\left(\begin{matrix}p_{1,1}&p_{1,2}&\dots&p_{1,j}&\dots\\ p_{2,1}&p_{2,2}&\dots&p_{2,j}&\dots\\ \vdots&\vdots&\ddots&\vdots&\ddots\\ p_{i,1}&p_{i,2}&\dots&p_{i,j}&\dots\\ \vdots&\vdots&\ddots&\vdots&\ddots \end{matrix}\right)$

Example:
A "Random Walk" is an example of a Markov Chain. Let's suppose that the direction of our next step is decided in a probabilistic way. The probability of moving to the right is $\displaystyle Pr(heads) = p$. And the probability of moving to the left is $\displaystyle Pr(tails) = q = 1-p$. Once the first or the last state is reached, then we stop. The transition matrix that express this process is shown as below:

$P=\left(\begin{matrix}1&0&\dots&0&\dots\\ p&0&q&0&\dots\\ 0&p&0&q&0\dots\\ \vdots&\vdots&\ddots&\vdots&\ddots\\ p_{i,1}&p_{i,2}&\dots&p_{i,j}&\dots\\ \vdots&\vdots&\ddots&\vdots&\ddots\\ 0&0&\dots&0&1 \end{matrix}\right)$

### Markov Chain Definitions - June 9, 2009

Practical application for estimation: The general concept for the application of this lies within having a set of generated $x_i$ which approach a distribution $f(x)$ so that a variation of importance estimation can be used to estimate an integral in the form
$I = \displaystyle\int^\ h(x)f(x)\,dx$ by $\hat{I} = \frac{1}{N}\displaystyle\sum_{i=1}^Nh(x_i)$
All that is required is a Markov chain which eventually converges to $f(x)$.

In the previous example, the entries $p_{ij}$ in the transition matrix $P$ represent the probability of reaching state $j$ from state $i$ after one step. For this reason, the sum over all entries j in a particular column sum to 1, as this itself must be a pmf if a transition from $i$ is to lead to a state still within the state set for $X_t$.

Homogeneous Markov Chain
The probability matrix $P$ is the same for all indicies $n\in T$. $\displaystyle Pr(X_n=j|X_{n-1}=i)= Pr(X_1=j|X_0=i)$

If we denote the pmf of $X_n$ by a probability vector $\frac{}{}\mu_n = [P(X_n=x_1),P(X_n=x_2),..,P(X_n=x_i)]$
where $i$ denotes an ordered index of all possible states of $X$.
Then we have a definition for the
marginal probabilty $\frac{}{}\mu_n(i) = P(X_n=i)$
where we simplify $X_n$ to represent the ordered index of a state rather than the state itself.

From this definition it can be shown that, $\frac{}{}\mu_{n-1}P=\mu_0P^n$

Proof:

$\mu_{n-1}P=[\sum_{\forall i}(\mu_{n-1}(i))P_{i1},\sum_{\forall i}(\mu_{n-1}(i))P_{i2},..,\sum_{\forall i}(\mu_{n-1}(i))P_{ij}]$ and since

$\sum_{\forall i}(\mu_{n-1}(i))P_{ij}=\sum_{\forall i}P(X_n=x_i)Pr(X_n=j|X_{n-1}=i)=\sum_{\forall i}P(X_n=x_i)\frac{Pr(X_n=j,X_{n-1}=i)}{P(X_n=x_i)}$ $=\sum_{\forall i}Pr(X_n=j,X_{n-1}=i)=Pr(X_n=j)=\mu_{n}(j)$

Therefore,
$\frac{}{}\mu_{n-1}P=[\mu_{n}(1),\mu_{n}(2),...,\mu_{n}(i)]=\mu_{n}$

With this, it is possible to define $P(n)$ as an n-step transition matrix where $\frac{}{}P_{ij}(n) = Pr(X_n=j|X_0=i)$

Theorem: $\frac{}{}\mu_n=\mu_0P^n$
Proof: $\frac{}{}\mu_n=\mu_{n-1}P$ From the previous conclusion
$\frac{}{}=\mu_{n-2}PP=...=\mu_0\prod_{i = 1}^nP$ And since this is a homogeneous Markov chain, $P$ does not depend on $i$ so
$\frac{}{}=\mu_0P^n$

From this it becomes easy to define the n-step transition matrix as $\frac{}{}P(n)=P^n$

#### Summary of definitions

• transition matrix is an NxN when $N=|X|$ matrix with $P_{ij}=Pr(X_1=j|X_0=i)$ where $i,j \in X$
• n-step transition matrix also NxN with $P_{ij}(n)=Pr(X_n=j|X_0=i)$
• marginal (probability of X)$\mu_n(i) = Pr(X_n=i)$
• Theorem: $P_n=P^n$
• Theorem: $\mu_n=\mu_0P^n$

---

#### Definitions of different types of state sets

Define $i,j \in$ State Space
If $P_{ij}(n) \gt 0$ for some $n$ , then we say $i$ reaches $j$ denoted by $i\longrightarrow j$
This also mean j is accessible by i: $j\longleftarrow i$
If $i\longrightarrow j$ and $j\longrightarrow i$ then we say $i$ and $j$ communicate, denoted by $i\longleftrightarrow j$

Theorems
1) $i\longleftrightarrow i$
2) $i\longleftrightarrow j \Rightarrow j\longleftrightarrow i$
3) If $i\longleftrightarrow j,j\longleftrightarrow k\Rightarrow i\longleftrightarrow k$
4) The set of states of $X$ can be written as a unique disjoint union of subsets (equivalence classes) $X=X_1\bigcup X_2\bigcup ...\bigcup X_k,k\gt 0$ where two states $i$ and $j$ communicate $IFF$ they belong to the same subset

More Definitions
A set is Irreducible if all states communicate with each other (has only one equivalence class).
A subset of states is Closed if once you enter it, you can never leave.
A subset of states is Open if once you leave it, you can never return.
An Absorbing Set is a closed set with only 1 element (i.e. consists of a single state).

Note

• We cannot have $\displaystyle i\longleftrightarrow j$ with i recurrent and j transient since $\displaystyle i\longleftrightarrow j \Rightarrow j\longleftrightarrow i$.
• All states in an open class are transient.
• A Markov Chain with a finite number of states must have at least 1 recurrent state.
• A closed class with an infinite number of states has all transient or all recurrent states.

### Again on Markov Chain - June 11, 2009

#### Decomposition of Markov chain

In the previous lecture it was shown that a Markov Chain can be written as the disjoint union of its classes. This decomposition is always possible and it is reduced to one class only in the case of an irreducible chain.

Example:
Let $\displaystyle X = \{1, 2, 3, 4\}$ and the transition matrix be:

$P=\left(\begin{matrix}1/3&2/3&0&0\\ 2/3&1/3&0&0\\ 1/4&1/4&1/4&1/4\\ 0&0&0&1 \end{matrix}\right)$

The decomposition in classes is:

class 1: $\displaystyle \{1, 2\} \rightarrow$ From the matrix we see that the states 1 and 2 have only $\displaystyle P_{12}$ and $\displaystyle P_{21}$ as nonzero transition probability
class 2: $\displaystyle \{3\} \rightarrow$ The state 3 can go to every other state but none of the others can go to it
class 3: $\displaystyle \{4\} \rightarrow$ This is an absorbing state since it is a close class and there is only one element

#### Recurrent and Transient states

A state i is called $\emph{recurrent}$ or $\emph{persistent}$ if

$\displaystyle Pr(x_{n}=i$ for some $\displaystyle n\geq 1 | x_{0}=i)=1$

That means that the probability to come back to the state i, starting from the state i, is 1.

If it is not the case (ie. probability less than 1), then state i is $\emph{transient}$.

It is straight forward to prove that a finite irreducible chain is recurrent.

Theorem
Given a Markov chain,
A state $\displaystyle i$ is $\emph{recurrent}$ if and only if $\displaystyle \sum_{\forall n}P_{ii}(n)=\infty$
A state $\displaystyle i$ is $\emph{transient}$ if and only if $\displaystyle \sum_{\forall n}P_{ii}(n)\lt \infty$

Properties

• If $\displaystyle i$ is $\emph{recurrent}$ and $i\longleftrightarrow j$ then $\displaystyle j$ is $\emph{recurrent}$
• If $\displaystyle i$ is $\emph{transient}$ and $i\longleftrightarrow j$ then $\displaystyle j$ is $\emph{transient}$
• In an equivalence class, either all states are recurrent or all states are transient
• A finite Markov chain should have at least one recurrent state
• The states of a finite, irreducible Markov chain are all recurrent (proved using the previous preposition and the fact that there is only one class in this kind of chain)

In the example above, state one and two are a closed set, so they are both recurrent states. State four is an absorbing state, so it is also recurrent. State three is transient.

Example
Let $\displaystyle X=\{\cdots,-2,-1,0,1,2,\cdots\}$ and suppose that $\displaystyle P_{i,i+1}=p$, $\displaystyle P_{i,i-1}=q=1-p$ and $\displaystyle P_{i,j}=0$ otherwise. This is the Random Walk that we have already seen in a previous lecture, except it extends infinitely in both directions.

We now see other properties of this particular Markov chain:

• Since all states communicate if one of them is recurrent, then all states will be recurrent. On the other hand, if one of them is transient, then all the other will be transient too.
• Consider now the case in which we are in state $\displaystyle 0$. If we move of n steps to the right or to the left, the only way to go back to $\displaystyle 0$ is to have n steps on the opposite direction.

$\displaystyle Pr(x_{2n}=0/X_{0}=0)=P_{00}(2n)=[ {2n \choose n} ]p^{n}q^{n}$ We now want to know if this event is transient or recurrent or, equivalently, whether $\displaystyle \sum_{\forall i}P_{ii}(n)\geq\infty$ or not.

To proceed with the analysis, we use the $\emph{Stirling }$ $\displaystyle\emph{formula}$:

$\displaystyle n!\sim~n^{n}\sqrt(n)e^{-n}\sqrt(2\pi)$

The probability could therefore be approximated by:

$\displaystyle P_{00}(n)=\sim~\frac{(4pq)^{n}}{\sqrt(n\pi)}$

And the formula becomes:

$\displaystyle \sum_{\forall n}P_{00}(n)=\sum_{\forall n}\frac{(4pq)^{n}}{\sqrt(n\pi)}$

We can conclude that if $\displaystyle 4pq \lt 1$ then the state is transient, otherwise is recurrent.

$\displaystyle \sum_{\forall n}P_{00}(n)=\sum_{\forall n}\frac{(4pq)^{n}}{\sqrt(n\pi)} = \begin{cases} \infty, & \text{if } p = \frac{1}{2} \\ \lt \infty, & \text{if } p\neq \frac{1}{2} \end{cases}$

An alternative to Stirling's approximation is to use the generalized binomial theorem to get the following formula:

$\frac{1}{\sqrt{1 - 4x}} = \sum_{n=0}^{\infty} \binom{2n}{n} x^n$

Then substitute in $x = pq$.

$\frac{1}{\sqrt{1 - 4pq}} = \sum_{n=0}^{\infty} \binom{2n}{n} p^n q^n = \sum_{n=0}^{\infty} P_{00}(2n)$

So we reach the same conclusion: all states are recurrent iff $p = q = \frac{1}{2}$.

#### Convergence of Markov chain

We define the $\displaystyle \emph{Recurrence}$ $\emph{time}$$\displaystyle T_{i,j}$ as the minimum time to go from the state i to the state j. It is also possible that the state j is not reachable from the state i.

$\displaystyle T_{ij}=\begin{cases} min\{n: x_{n}=i\}, & \text{if }\exists n \\ \infty, & \text{otherwise } \end{cases}$

The mean of the recurrent time $\displaystyle m_{i}$is defined as:

$m_{i}=\displaystyle E(T_{ij})=\sum nf_{ii}$

where $\displaystyle f_{ij}=Pr(x_{1}\neq j,x_{2}\neq j,\cdots,x_{n-1}\neq j,x_{n}=j/x_{0}=i)$

Using the objects we just introduced, we say that:

$\displaystyle \text{state } i=\begin{cases} \text{null}, & \text{if } m_{i}=\infty \\ \text{non-null or positive} , & \text{otherwise } \end{cases}$

Lemma
In a finite state Markov Chain, all the recurrent state are positive

#### Periodic and aperiodic Markov chain

A Markov chain is called $\emph{periodic}$ of period $\displaystyle n$ if, starting from a state, we will return to it every $\displaystyle n$ steps with probability $\displaystyle 1$.

Example
Considerate the three-state chain:

$P=\left(\begin{matrix} 0&1&0\\ 0&0&1\\ 1&0&0 \end{matrix}\right)$

It's evident that, starting from the state 1, we will return to it on every $3^{rd}$ step and so it works for the other two states. The chain is therefore periodic with perdiod $d=3$

An irreducible Markov chain is called $\emph{aperiodic}$ if:

$\displaystyle Pr(x_{n}=j | x_{0}=i) \gt 0 \text{ and } Pr(x_{n+1}=j | x_{0}=i) \gt 0 \text{ for some } n\ge 0$

Another Example
Consider the chain $P=\left(\begin{matrix} 0&0.5&0&0.5\\ 0.5&0&0.5&0\\ 0&0.5&0&0.5\\ 0.5&0&0.5&0\\ \end{matrix}\right)$

This chain is periodic by definition. You can only get back to state 1 after at least 2 steps $\Rightarrow$ period $d=2$

## Markov Chains and their Stationary Distributions - June 16, 2009

#### New Definition:Ergodic

A state is Ergodic if it is non-null, recurrent, and aperiodic. A Markov Chain is ergodic if all its states are ergodic.

Define a vector $\pi$ where $\pi_i \gt 0 \forall i$ and $\sum_i \pi_i = 1$(ie. $\pi$ is a pmf)

$\pi$ is a stationary distribution if $\pi=\pi P$ where P is a transition matrix.

#### Limiting Distribution

If as $n \longrightarrow \infty , P^n \longrightarrow \left[ \begin{matrix} \pi\\ \pi\\ \vdots\\ \pi\\ \end{matrix}\right]$ then $\pi$ is the limiting distribution of the Markov Chain represented by P.
Theorem: An irreducible, ergodic Markov Chain has a unique stationary distribution $\pi$ and there exists a limiting distribution which is also $\pi$.

#### Detailed Balance

The condition for detailed balanced is $\displaystyle \pi_i p_{ij} = p_{ji} \pi_j$

##### Theorem

If $\pi$ satisfies detailed balance then it is a stationary distribution.

Proof.
We need to show $\pi = \pi P$ $\displaystyle [\pi p]_j = \sum_{i} \pi_i p_{ij} = \sum_{i} p_{ji} \pi_j = \pi_j \sum_{i} p_{ji}= \pi_j$ as required

Warning! A chain that has a stationary distribution does not necessarily converge.

For example, $P=\left(\begin{matrix} 0&1&0\\ 0&0&1\\ 1&0&0 \end{matrix}\right)$ has a stationary distribution $\left(\begin{matrix} 1/3&1/3&1/3 \end{matrix}\right)$ but it will not converge.

#### Stationary Distribution

$\pi$ is stationary (or invariant) distribution if $\pi$ = $\pi * p$ [0.5 0 0.5] Half of time their chain will spend half time in 1st state and half time in 3rd state.

#### Theorem

An irreducible ergodic Markov Chain has a unique stationary distribution $\pi$. The limiting distribution exists and is equal to $\pi$.

If g is any bounded function, then with probability 1: $lim \frac{1}{N}\displaystyle\sum_{i=1}^Ng(x_n)\longrightarrow E_n(g)=\displaystyle\sum_{j}g(j)\pi_j$

#### Example

Find the limiting distribution of $P=\left(\begin{matrix} 1/2&1/2&0\\ 1/2&1/4&1/4\\ 0&1/3&2/3 \end{matrix}\right)$

Solve $\pi=\pi P$

$\displaystyle \pi_0 = 1/2\pi_0 + 1/2\pi_1$
$\displaystyle \pi_1 = 1/2\pi_0 + 1/4\pi_1 + 1/3\pi_2$
$\displaystyle \pi_2 = 1/4\pi_1 + 2/3\pi_2$

Also $\displaystyle \sum_i \pi_i = 1 \longrightarrow \pi_0 + \pi_1 + \pi_2 = 1$

We can solve the above system of equations and obtain
$\displaystyle \pi_2 = 3/4\pi_1$
$\displaystyle \pi_0 = \pi_1$

Thus, $\displaystyle \pi_0 + \pi_1 + 3/4\pi_1 = 1$ and we get $\displaystyle \pi_1 = 4/11$

Subbing $\displaystyle \pi_1 = 4/11$ back into the system of equations we obtain
$\displaystyle \pi_0 = 4/11$ and $\displaystyle \pi_2 = 3/11$

Therefore the limiting distribution is $\displaystyle \pi = (4/11, 4/11, 3/11)$

## Monte Carlo using Markov Chain - June 18, 2009

Consider the problem of computing $I = \displaystyle\int^\ h(x)f(x)\,dx$

$\bullet$ Generate $\displaystyle X_1$, $\displaystyle X_2$,... from a Markov Chain with stationary distribution $\displaystyle f(x)$

$\bullet$ $\hat{I} = \frac{1}{N}\displaystyle\sum_{i=1}^Nh(x_i)\longrightarrow E_f(h(x))=\hat{I}$

#### Metropolis Hastings Algorithm

The Metropolis Hastings Algorithm first originated in the physics community in 1953 and was adopted later on by statisticians. It was originally used for the computation of a Boltzmann distribution, which describes the distribution of energy for particles in a system. In 1970, Hastings extended the algorithm to the general procedure described below.

Suppose we wish to sample from the distribution $\displaystyle f(x)$. Let $q(y\mid{x})$ be a distribution that is easy to sample from, we call it the "Proposal Distribution".

$\emph{Procedure:}$
<br\>1. Initialize $\displaystyle X_0$, this is the starting point of the chain, choose it randomly and set index $\displaystyle i=0$
<br\>2. $Y~ \sim~ q(y\mid{x})$
<br\>3. Compute $\displaystyle r(X_i,Y)$, where $r(x,y)=min{\{\frac{f(y)}{f(x)}*\frac{q(x\mid{y})}{q(y\mid{x})},1}\}$
<br\>4. $U~ \sim~ Unif [0,1]$
<br\>5. If $\displaystyle U\lt r$
then $\displaystyle X_{i+1}=Y$
else $\displaystyle X_{i+1}=X_i$
<br\>6. Update index $\displaystyle i=i+1$, and go to step 2

A couple of remarks about the algorithm

Remark 1: A good choice for $q(y\mid{x})$ is $\displaystyle N(x,b^2)$ where $\displaystyle b\gt 0$ is a constant. The starting point of the algorithm $X_0=x$, i.e. the proposal distibution is a normal centered at the current, randomly chosen, state.

Remark 2: If the proposal distribution is symmetric, $q(y\mid{x})=q(x\mid{y})$, then $r(x,y)=min{\{\frac{f(y)}{f(x)},1}\}$. This is called the Metropolis Algorithm, which is a special case of the original algorithm of Metropolis (1953).

Remark 3: $\displaystyle N(x,b^2)$ is symmetric. Probability of setting mean to x and sampling y is equal to the probability of setting mean to y and samplig x.

Example: The Cauchy distribution has density $f(x)=\frac{1}{\pi}*\frac{1}{1+x^2}$

Let the proposal distribution be $q(y\mid{x})=N(x,b^2)$

$r(x,y)=min{\{\frac{f(y)}{f(x)}*\frac{q(x\mid{y})}{q(y\mid{x})},1}\}$

$=min{\{\frac{f(y)}{f(x)},1}\}$ since $q(y\mid{x})$ is symmetric $\Rightarrow$ $\frac{q(x\mid{y})}{q(y\mid{x})}=1$
$=min{\{\frac{ \frac{1}{\pi}\frac{1}{1+y^2} }{ \frac{1}{\pi} \frac{1}{1+x^2} },1}\}$
$=min{\{\frac{1+x^2 }{1+y^2},1}\}$

Now, having calculated $\displaystyle r(x,y)$, we complete the problem in Matlab using the following code:

b=2; % let b=2 for now, we will see what happens when b is smaller or larger
X(1)=randn;
for i=2:10000
Y=b*randn+X(i-1); % we want to decide whether we accept this Y
r=min( (1+X(i-1)^2)/(1+Y^2),1);
u=rand;
if u<r
X(i)=Y; % accept Y
else
X(i)=X(i-1); % reject Y remaining in the current state
end;
end;


We need to be careful about choosing b!

If b is too large
Then the fraction $\frac{f(y)}{f(x)}$ would be very small $\Rightarrow$ $r=min{\{\frac{f(y)}{f(x)},1}\}$ is very small aswell.
It is highly unlikely that $\displaystyle u\lt r$, the probability of rejecting $\displaystyle Y$ is high so the chain is likely to get stuck in the same state for a long time $\rightarrow$ chain may not coverge to the right distribution.
It is easy to observe by looking at the histogram of $\displaystyle X$, the shape will not resemble the shape of the target $\displaystyle f(x)$
Most likely we reject y and the chain will get stuck.
For the above example, the following output occurs when choosing B too large (B=1000)

If b is too small
Then we are setting up our proposal distribution $q(y\mid{x})$ to be much narrower then than the target $\displaystyle f(x)$ so the chain will not have a chance to explore the sample state space and visit majority of the states of the target $\displaystyle f(x)$.
For the above example, the following output occurs when choosing B too small (B=0.001)

If b is just right
Well chosen b will help avoid the issues mentioned above and we can say that the chain is "mixing well".
For the above example, the following output occurs when choosing a good value for B (B=2)

Mathematical explanation for why this algorithm works:

We talked about $\emph{discrete}$ MC so far.

<br\> We have seen that: <br\>- $\displaystyle \pi$ satisfies detailed balance if $\displaystyle \pi_iP_{ij}=P_{ji}\pi_j$ and <br\>- if $\displaystyle\pi$ satisfies $\emph{detailed}$ $\emph{balance}$then it is a stationary distribution $\displaystyle \pi=\pi P$

In $\emph{continuous}$case we write the Detailed Balance as $\displaystyle f(x)P(x,y)=P(y,x)f(y)$ and say that <br\>$\displaystyle f(x)$ is $\emph{stationary}$ $\emph{distribution}$ if $f(x)=\int f(y)P(y,x)dy$.

We want to show that if Detailed Balance holds (i.e. assume $\displaystyle f(x)P(x,y)=P(y,x)f(y)$) then $\displaystyle f(x)$ is stationary distribution.

That is to show: $\displaystyle f(x)P(x,y)=P(y,x)f(y)\Rightarrow$ $\displaystyle f(x)$ is stationary distribution.

$f(x)=\int f(y)P(y,x)dy$
$=\int f(x)P(x,y)dy$
$=f(x)\int P(x,y)dy$ and since $\int P(x,y)dy=1$
$=\displaystyle f(x)$

Now, we need to show that detailed balance holds in the Metropolis-Hastings...

Consider 2 points $\displaystyle x$ and $\displaystyle y$:

Either $\frac{f(y)}{f(x)}*\frac{q(x\mid{y})}{q(y\mid{x})}\gt 1$ OR $\frac{f(y)}{f(x)}*\frac{q(x\mid{y})}{q(y\mid{x})}\lt 1$ (ignoring that it might equal to 1)

Without loss of generality. suppose that the product is $\displaystyle\lt 1$.

In this case $r(x,y)=\frac{f(y)}{f(x)}*\frac{q(x\mid{y})}{q(y\mid{x})}$ and $\displaystyle r(y,x)=1$

Some intuitive meanings before we continue:
$\displaystyle P(x,y)$ is jumping from $\displaystyle x$ to $\displaystyle y$ if proposal distribution generates $\displaystyle y$ and $\displaystyle y$ is accepted
$\displaystyle P(y,x)$ is jumping from $\displaystyle y$ to $\displaystyle x$ if proposal distribution generates $\displaystyle x$ and $\displaystyle x$ is accepted
$q(y\mid{x})$ is the probability of generating $\displaystyle y$
$q(x\mid{y})$ is the probability of generating $\displaystyle x$
$\displaystyle r(x,y)$ probability of accepting $\displaystyle y$
$\displaystyle r(y,x)$ probability of accepting $\displaystyle x$.

With that in mind we can show that $\displaystyle f(x)P(x,y)=P(y,x)f(y)$ as follows:

$P(x,y)=q(y\mid{x})*(r(x,y))=q(y\mid{x})\frac{f(y)}{f(x)}\frac{q(x\mid{y})}{q(y\mid{x})}$ Cancelling out $\displaystyle q(y\mid{x})$ and bringing $\displaystyle f(x)$ to the other side we get <br\>$f(x)P(x,y)=f(y)q(y\mid{x})$ $\Leftarrow$ equation $\clubsuit$

$P(y,x)=q(x\mid{y})*(r(y,x))=q(x\mid{y})*1$ Multiplying both sides by $\displaystyle f(y)$ we get <br\>$f(y)P(y,x)=f(y)q(x\mid{y})$ $\Leftarrow$ equation $\clubsuit\clubsuit$

Noticing that the right hand sides of the equation $\clubsuit$ and equation $\clubsuit\clubsuit$ are equal we conclude that:

<br\>$\displaystyle f(x)P(x,y)=P(y,x)f(y)$ as desired and thus showing that Metropolis-Hastings satisfies detailed balance.

Next lecture we will see that Metropolis-Hastings is also irreducible and ergodic thus showing that it converges.

## Metropolis Hastings Algorithm Continued - June 25

Metropolis–Hastings algorithm is a Markov chain Monte Carlo method. It is used to help sample from probability distributions that are difficult to sample from. The algorithm was named after Nicholas Metropolis (1915-1999), also co-author of the Simulated Anealing method (that is introduced in this lecture as well). The Gibbs sampling algorithm, that will be introduced next lecture, is a special case of the Metropolis–Hastings algorithm. This is a more efficient method, although less applicable at times.

In the last class, we showed that Metropolis Hastings satisfied the the detail-balance equations. i.e.

<br\>$\displaystyle f(x)P(x,y)=P(y,x)f(y)$, which means $\displaystyle f(x)$ is the stationary distribution of the chain.

But this is not enough, we want the chain to converge to the stationary distribution as well.

Thus, we also need it to be:

Irreducible: There is a positive probability to reach any non-empty set of states from any starting point. This is trivial for many choice of $\emph{q}$ including the one that we used in the example in the previous lecture (which was normally distributed)

Aperiodic: The chain will not oscillate between different set of states. In the previous example, $q(y\mid{x})$ is $\displaystyle N(x,b^2)$, which will clearly not oscillate.

Next we discuss a couple of variations of Metropolis Hastings

#### Random Walk Metropolis Hastings

$\emph{Procedure:}$
<br\>1. Draw $\displaystyle Y = X_i + \epsilon$, where $\displaystyle \epsilon$ has distribution $\displaystyle g$; $\epsilon = Y-X_i \sim~ g$; $\displaystyle X_i$ is current state & $\displaystyle Y$ is going to be close to $\displaystyle X_i$
<br\>2. It means $q(y\mid{x}) = g(y-x)$. (Note that $\displaystyle g$ is a function of distance between the current state and the state the chain is going to travel to, i.e. it's of the form $\displaystyle g(|y-x|)$. Hence we know in this version that $\displaystyle q$ is symmetric $\Rightarrow q(y\mid{x}) = g(|y-x|) = g(|x-y|) = q(x\mid{y})$)
<br\>3. $Y=min{\{\frac{f(y)}{f(x)},1}\}$

Recall in our previous example we wanted to sample from the Cauchy distribution and our proposal distribution was $q(y\mid{x})$ $\sim~ N(x,b^2)$

In matlab, we defined this as

$\displaystyle Y = b* randn + x$ (i.e $\displaystyle Y = X_i + randn*b)$

In this case, we need $\displaystyle \epsilon \sim~ N(0,b^2)$

The hard problem is to choose b so that the chain will mix well.

Rule of thumb: choose b such that the rejection probability is 0.5 (i.e. half the time accept, half the time reject)

Example

If we draw $\displaystyle y_1$ then ${\frac{f(y_1)}{f(x)}} \gt 1 \Rightarrow min{\{\frac{f(y_1)}{f(x)},1}\} = 1$, accept $\displaystyle y_1$ with probability 1

If we draw $\displaystyle y_2$ then ${\frac{f(y_2)}{f(x)}} \lt 1 \Rightarrow min{\{\frac{f(y_2)}{f(x)},1}\} = \frac{f(y_2)}{f(x)}$, accept $\displaystyle y_2$ with probability $\frac{f(y_2)}{f(x)}$

Hence, each point drawn from the proposal that belongs to a region with higher density will be accepted for sure (with probability 1), and if a point belongs to a region with less density, then the chance that it will be accepted will be less than 1.

#### Independence Metropolis Hastings

In this case, the proposal distribution is independent of the current state, i.e. $\displaystyle q(y\mid{x}) = q(y)$

We draw from a fixed distribution

And define $r = min{\{\frac{f(y)}{f(x)} \cdot \frac{q(x)}{q(y)},1}\}$

And, this does not work unless $\displaystyle q$ is very similar to the target distribution $\displaystyle f$ (i.e. usually used when $\displaystyle f$ is known up to a proportionality constant - the form of the distibution is known, but the distribution is not exactly known)

Now, we pose the question: if $\displaystyle q(y\mid{x})$ does not depend on $\displaystyle X$, does it mean that the sequence generated from this chain is really independent?

Answer: Even though $Y \sim~ g(y)$ does not depend on $\displaystyle X$, but $\displaystyle r$ depends on $\displaystyle X$. So it's not really an independent sequence!

$x_{i+1} = \begin{cases} x_i \\ y \\ \end{cases}$

Thus, the sequence is not really independent because acceptance probability $\displaystyle r$ depends on the state $\displaystyle X_i$

#### Simulated Annealing

This is essentially a method for optimization and an application of Metropolis Hastings.

Consider the problem of $\displaystyle \min_{x}(h(x))$, i.e. we need to find x that minimizes $\displaystyle h(x)$. But, this is the same problem as $\displaystyle \max(e^{\frac{-h(x)}{T}})$ for some constant T (since the exponential function is a monotone function)

We then consider some distribution function $\displaystyle f$ such that $\displaystyle f \propto e^{\frac{-h(x)}{T}}$, where T is called the temperature, and define the following procedure:

$\emph{Procedure:}$
1. Set T to be a large number
2. Start with some random $\displaystyle X_0,$ $\displaystyle i = 0$
3. $Y \sim~ q(y\mid{x})$ (note that $\displaystyle q$ is usually chosen to be symmetric)
4. $U \sim~ Unif[0,1]$
5. Define $r = min{\{\frac{f(y)}{f(x)},1}\}$ (when $\displaystyle q$ is symmetric)
6. $X_{i+1} = \begin{cases} Y, & \text{with probability r} \\ X_i & \text{with probability 1-r}\\ \end{cases}$
7. Decrease T and go to Step 2

Now, we know that $r = min{\{\frac{f(y)}{f(x)},1}\}$

Consider $\frac{f(y)}{f(x)} = \frac{e^{\frac{-h(y)}{T}}}{e^{\frac{-h(x)}{T}}} = e^{\frac{h(x)-h(y)}{T}}$

Now, suppose T is large,

$\rightarrow$ if $h(y)\lt h(x) \Rightarrow r = 1$ and we therefore accept $\displaystyle y$ with probability 1

$\rightarrow$ if $h(y)\gt h(x) \Rightarrow r = e^{\frac{h(x)-h(y)}{T}} \lt 1$ and we therefore accept $\displaystyle y$ with probability $\displaystyle \lt 1$

On the other hand, suppose T is small ($T \rightarrow 0$),

$\rightarrow$ if $h(y)\lt h(x) \Rightarrow r = 1$ and we therefore accept $\displaystyle y$ with probability 1

$\rightarrow$ if $h(y)\gt h(x) \Rightarrow r = 0$ and we therefore reject $\displaystyle y$

Example 1

Consider the problem of minimizing the function $\displaystyle f(x) = -2x^3 - x^2 + 40x + 3$

We can plot this function and observe that it makes a local minimum near $\displaystyle x = -3$

We then plot the graphs of $\displaystyle \frac{f(x)}{T}$ for $\displaystyle T = 100, 0.1$ and observe that the distribution expands for a large T, and contracts for T small - i.e. T plays the role of variance - making the distribution expand and contract accordingly.

At the end, we get T to be pretty small, our distribution that we're sampling from becomes sharper, and the points that we sample are close to the local max of the exponential function (which is the mode of the distribution), thereby corresponding to the local min of our original function (as can be seen above).

#### Example 2 (from June 30th lecture)

Suppose we want to minimize the function $\displaystyle f(x) = (x - 2)^2$

Intuitively, we know that the answer is 2. To apply the Simulated Annealing procedure however, we require a proposal distribution. Suppose we use $\displaystyle Y \sim~ N(x, b^2)$ and we begin with $\displaystyle T = 10$

Then the problem may be solved in MATLAB using the following:

function v = obj(x)
v = (x - 2).^2;

T = 10; %this is the initial value of T, which we must gradually decrease
b = 2;
X(1) = 0;
for i = 2:100 %as we change T, we will change i (e.g. i=101:200)
Y = b*randn + X(i-1);
r = min(1 , exp(-obj(Y)/T)/exp(-obj(X(i-1))/T) );
U = rand;
if U < r
X(i) = Y; %accept Y
else
X(i) = X(i-1); %reject Y
end;
end;


The first run (with $\displaystyle T = 10$) gives us $\displaystyle X = 1.2792$

Next, if we let $\displaystyle T = {9, 5, 2, 0.9, 0.1, 0.01, 0.005, 0.001}$ in the order displayed, then we get the following graph when we plot X:

i.e. it converges to the minimum of the function

Travelling Salesman Problem

This problem consists of finding the shortest path connecting a group of cities. The salesman must visit each city once and come back to the start in the shortest possible circuit. This problem is essentially one of optimization because the goal is to minimize the salesman's cost function (this function consists of the costs associated with travelling between two cities on a given path).

The travelling salesman problem is one of the most intensely investigated problems in computational mathematics and has been researched by many from diverse academic backgrounds including mathematics, CS, chemistry, physics, psychology, etc... Consequently, the travelling salesman problem now has applications in manufacturing, telecommunications, and neuroscience to name a few.<ref> Applegate, D.L., Bixby, R.E., Chvátal, V., Cook, W.J., The Travelling Salesman Problem: A Computational Study Copyright 2007 Princeton University Press </ref>

For a good introduction to the travelling salesman problem, along with a description of the theory involved in the problem and examples of its application, refer to a paper by Michael Hahsler and Kurt Hornik entitled Introduction to TSP - Infrastructure for the Travelling Salesman Problem. [2] The examples are particularly useful because they are implemented using R (a statistical computing software environment).

## Gibbs Sampling - June 30, 2009

This algorithm is a specific form of Metropolis-Hastings and is the most widely used version of the algorith. It is used to generate a sequence of samples from the joint distribution of multiple random variables. It was first introduced by Geman and Geman (1984) and then further developed by Gelfand and Smith (1990).<ref> Gentle, James E. Elements of Computational Statistics Copyright 2002 Springer Science +Business Media, LLC </ref> In order to use Gibbs Sampling, we must know how to sample from the conditional distributions. The point of Gibbs sampling is that given a multivariate distribution it is simpler to sample from a conditional distribution than to integrate over a joint distribution. Gibbs Sampling also satisfies detailed balance equation, similar to Metropolis-Hastings

$f(x) p_{xy} = f(y) p_{yx}$

This implies that the chain is irreversible. The procedure of proving this balance equation is similar to what was done with Metropolis-Hasting proof.

• The algorithm has an acceptance rate of 1. Thus it is efficient because we keep all the points we sample.
• It is useful for high-dimensional distributions.

• We rarely know how to sample from the conditional distributions.
• The algorithm can be extremely slow to converge.
• It is often difficult to know when convergence has occurred.
• The method is not practical when there are relatively small correlations between the random variables.

Example: Gibbs sampling is used if we want to sample from a multidimensional distribution - i.e. $\displaystyle f(x_1, x_2, ... , x_n)$

We can use Gibbs sampling (assuming we know how to draw from the conditional distributions) by drawing

$\displaystyle x_1 \sim~ f(x_1|x_2, x_3, ... , x_n)$

$x_2 \sim~ f(x_2|x_1, x_3, ... , x_n)$

$\vdots$

$x_n \sim~ f(x_n|x_1, x_2, ... , x_{n-1})$

and the resulting set of points drawn $\displaystyle (x_1, x_2, \ldots, x_n)$ follows the required multivariate distribution.

Suppose we want to sample from a bivariate distribution $\displaystyle f(x,y)$ with initial point $\displaystyle(x_i, y_i) = (0,0)$, i = 0
Furthermore, suppose that we know how to sample from the conditional distributions $\displaystyle f_{X|Y}(x|y)$ and $\displaystyle f_{Y|X}(y|x)$

$\emph{Procedure:}$

1. $\displaystyle Y_{i+1} \sim~ f_{Y_i|X_i}(y|x)$ (i.e. given the previous point, sample a new point)
2. $\displaystyle X_{i+1} \sim~ f_{X_{i}|Y_{i+1}}(x|y)$
3. Repeat Steps 1 and 2

Example Suppose we want to generate samples from a bivariate normal distribution where $\displaystyle \mu = \left[\begin{matrix} 1 \\ 2 \end{matrix}\right]$ and $\sigma = \left[\begin{matrix} 1 & \rho \\ \rho & 1 \end{matrix}\right]$

Note that for a bivariate distribution it may be shown that the conditional distributions are normal. So, $\displaystyle f(x_2|x_1) \sim~ N(\mu_2 + \rho(x_1 - \mu_1), 1 - \rho^2)$ and $\displaystyle f(x_1|x_2) \sim~ N(\mu_1 + \rho(x_2 - \mu_2), 1 - \rho^2)$

The problem (for a specified value rho) may be solved in MATLAB using the following:

Y = [1 ; 2];
rho = 0.01;
sigma = sqrt(1 - rho^2);
X(1,:) = [0 0];

for i = 2:5000
mu = Y(1) + rho*(X(i-1,2) - Y(2));
X(i,1) = mu + sigma*randn;
mu = Y(2) + rho*(X(i-1,1) - Y(1));
X(i,2) = mu + sigma*randn;
end;
%plot(X(:,1),X(:,2),'.') plots all of the points
%plot(X(1000:end,1),X(1000:end,2),'.') plots the last 4000 points ->
this demonstrates that convergence occurs after a while
(this is called the burning time)


The output of plotting all points is:

## Metropolis-Hastings within Gibbs Sampling - July 2

Thus far when discussing Gibbs Sampling, it has been assumed that we know how to sample from the conditional distributions. Even if this is not known, it is still possible to use Gibbs using the Metropolis-Hastings algorithm.

• Choose $\displaystyle q$ as a proposal distribution for X (assuming Y fixed)
• Choose $\displaystyle \tilde{q}$ as a proposal distribution for Y (assuming X fixed)
• Do a Metropolis-Hastings step for X, treating Y as fixed
• Do a Metropolis-Hastings step for Y, treating X as fixed.
$\emph{Procedure:}$
1. Start with some random $\displaystyle X_0, Y_0, n = 0$
2. Draw $Z~ \sim~ q(Z\mid{X_n})$
3. Set $r = \min \{ 1, \frac{f(Z,Y_n)}{f(X_n,Y_n)} \frac{q(X_n\mid{Z})}{q(Z\mid{X_n})} \}$
4. $X_{n+1} = \begin{cases} Z, & \text{with probability r}\\ X_n & \text{with probability 1-r}\\ \end{cases}$
5. Draw $Z~ \sim~ \tilde{q}(Z\mid{Y_n})$
6. Set $r = \min \{ 1, \frac{f(X_{n+1},Z)}{f(X_{n+1},Y_n)} \frac{\tilde{q}(Y_n\mid{Z})}{\tilde{q}(Z\mid{Y_n})} \}$
7. $Y_{n+1} = \begin{cases} Z, & \text{with probability r} \\ Y_n & \text{with probability 1-r}\\ \end{cases}$
8. Set $\displaystyle n = n + 1$ and return to step 2