# stat341f11

Please contribute to the discussion of splitting up this page into multiple pages on the talk page.

## Contents

- 1 Editor Sign Up
- 2 Notation
- 3 Sampling - September 20, 2011
- 4 Bayesian Inference and Frequentist Inference - October 4, 2011
- 5
**Basic Monte Carlo Integration - October 6th, 2011** - 6
**Importance Sampling and Basic Monte Carlo Integration - October 11th, 2011** - 7
**Importance Sampling with Normalized Weight and Markov Chain Monte Carlo - October 13th, 2011** - 8
**Markov Chain Properties and Page Rank - October 18th, 2011** - 9
**Markov Chain Monte Carlo - Metropolis-Hastings - October 25th, 2011** - 10
**Theory and Applications of Metropolis-Hastings - October 27th, 2011** - 11
**References** - 12
**Simulated Annealing and Gibbs Sampling - November 1, 2011** - 13
**Principal Component Analysis (PCA) - November 8, 2011** - 14
**References** - 15
**PCA and Introduction to Kernel Function - November 10, 2011** - 16
**Kernel PCA - November 15, 2011** - 17 PCA
- 18 Dual PCA
- 19
**Multidimensional Scaling (MDS)** - 20
**Continued with MDS, Isomap and Classification - November 22, 2011** - 21
**Classification - November 24, 2011** - 22
**LDA, QDA and FDA - November 29, 2011**

## Editor Sign Up

## Notation

The following guidelines on notation were posted on the Wiki Course Note page for STAT 946. Add to them as necessary for consistent notation on this page.

Capital letters will be used to denote random variables and lower case letters denote observations for those random variables:

- random variables
- observations of the random variables

The joint *probability mass function* can be written as:

or as shorthand, we can write this as . In these notes both types of notation will be used. We can also define a set of random variables where represents a set of subscripts.

## Sampling - September 20, 2011

The meaning of sampling is to generate data points or numbers such that these data follow a certain distribution.

i.e. From sample

In practice, it maybe difficult to find the joint distribution of random variables. We will explore different methods for simulating random variables, and how to draw conclusions using the simulated data.

### Sampling from Uniform Distribution

Computers cannot generate random numbers as they are deterministic; however they can produce pseudo random numbers using algorithms. Generated numbers mimic the properties of random numbers but they are never truly random. One famous algorithm that is considered highly reliable is the Mersenne twister[1], which generates random numbers in an almost uniform distribution.

#### Multiplicative Congruential

- involves four parameters: integers , and an initial value which we call the seed
- a sequence of integers is defined as

**Example:** creates a uniform histogram.

MATLAB code for generating 1000 random numbers using the multiplicative congruential method:

a = 13; b = 0; m = 31; x(1) = 1; for ii = 2:1000 x(ii) = mod(a*x(ii-1)+b, m); end

MATLAB code for displaying the values of x generated:

x

MATLAB code for plotting the histogram of x:

hist(x)

Histogram Output:

Facts about this algorithm:

- In this example, the first 30 terms in the sequence are a permutation of integers from 1 to 30 and then the sequence repeats itself. In the general case, this algorithm has a period of m-1.
- Values are between
**0**and**m-1**, inclusive. - Dividing the numbers by
**m-1**yields numbers in the interval**[0,1]**. - MATLAB's
`rand`

function once used this algorithm with**a= 7**,^{5}**b= 0**,**m= 2**,for reasons described in Park and Miller's 1988 paper "Random Number Generators: Good Ones are Hard to Find" (available online).^{31}-1 - Visual Basic's
`RND`

function also used this algorithm with**a= 1140671485**,**b= 12820163**,**m= 2**. (Reference)^{24}

### Inverse Transform Method

This is a basic method for sampling. Theoretically using this method we can generate sample numbers at random from any probability distribution once we know its cumulative distribution function (cdf). This method is very efficient computationally if the cdf of can be analytically inverted.

#### Theorem

Take and let . Then has a cumulative distribution function of , ie. , where is the inverse of .

**Proof**

Recall that

Note that if , we have

Completing the proof.

#### Continuous Case

Generally it takes two steps to get random numbers using this method.

- Step 1. Draw
- Step 2.
*X=F*^{−1}(U)

**Example**

Take the exponential distribution for example

Let:

Therefore, to get a exponential distribution from a uniform distribution takes 2 steps.

- Step 1. Draw
- Step 2.

Note: If U~Unif[0, 1], then (1 - U) and U have the same distribution. This allows us to slightly simplify step 2 into an alternate form:

- Alternate Step 2.

**MATLAB code**

for exponential distribution case,assuming

for ii = 1:1000 u = rand; x(ii) = -log(1-u)/0.5; end hist(x)

**MATLAB result**

#### Discrete Case - September 22, 2011

This same technique can be applied to the discrete case. Generate a discrete random variable that has probability mass function where and

- Step 1. Draw
- Step 2. if

**Example**

Let x be a discrete random variable with the following probability mass function:

Given the pmf, we now need to find the cdf.

We have:

We can apply the inverse transform method to obtain our random numbers from this distribution.

**Pseudo Code for generating the random numbers:**

Draw U ~ Unif[0,1] if U <= 0.3 return 0 else if 0.3 < U <= 0.5 return 1 else if 0.5 < U <= 1 return 2

**MATLAB code for generating 1000 random numbers in the discrete case:**

for ii = 1:1000 u = rand; if u <= 0.3 x(ii) = 0; else if u <= 0.5 x(ii) = 1; else x(ii) = 2; end end

Matlab Output:

**Pseudo code for the Discrete Case:**

1. Draw U ~ Unif [0,1]

2. If , deliver *X= x _{0}*

3. Else if , deliver *X= x _{1}*

4. Else If , deliver *X= x _{k}*

#### Limitations

This method is useful, but it's not practical in many cases because we can't always obtain or (some functions are not integrable or invertible), and sometimes cannot be obtained in closed form. Let's look at some examples:

- Continuous case

If we want to use this method to draw the *pdf* of **normal distribution**, we may find ourselves geting stuck when trying to find its *cdf*.
The simplest case of **normal distribution** is ,
whose *cdf* is . This integral cannot be expressed in terms of elementary functions. So evaluating it and then finding the inverse is a very difficult task.

- Discrete case

It is easy for us to simulate when there are only a few values taken by the particular random variable, like the case above.
And it is easy to simulate the **binomial distribution** when the parameter n is not too large.
But when n takes on values that are very large, say 50, it is hard to do so.

### Acceptance/Rejection Method

The aforementioned difficulties of the inverse transform method motivates a sampling method that does not require analytically calculating cdf's and their inverses, which is the acceptance/rejection sampling method. Here, is approximated by another function, say , with the idea being that is a "nicer" function to work with than .

Suppose we assume the following:

1. There exists another distribution that is easier to work with and that you know how to sample from, and

2. There exists a constant c such that for all x

Under these assumptions, we can sample from by sampling from

#### General Idea

Looking at the image below we have graphed and .

Using the acceptance/rejection method we will accept some of the points from and reject some of the points from . The points that will be accepted from will have a distribution similar to . We can see from the image that the values around will be sampled more often under than under , so we will have to reject more samples taken at x_{1}. Around the number of samples that are drawn and the number of samples we need are much closer, so we accept more samples that we get at . We should remember to take these considerations into account when evaluating the efficiency of a given acceptance-rejection method. Rejecting a high proportion of samples ultimately leaves us with a longer time until we retrieve our desired distribution. We should question whether a better function can be chosen in our situation.

#### Procedure

1. Draw y ~ g

2. Draw U ~ Unif [0,1]

3. If then x=y; else return to 1

Note that the choice of plays an important role in the efficiency of the algorithm. We want to be "tightly fit" over to increase the probability of accepting points, and therefore reducing the number of sampling attempts. Mathematically, we want to minimize such that . We do this by setting

, solving for a maximum point and setting

#### Proof

Mathematically, we need to show that the sample points given that they are accepted have a distribution of f(x).

(Bayes' Rule)

,where u ~ Unif [0,1]

So,

#### Continuous Case

**Example**

Sample from Beta(2,1)

In general:

,

Note: if n is a positive integer

We want to choose that is easy to sample from. So we choose to be uniform distribution on since that is the domain for the Beta function.

We now want a constant c such that for all x from Unif(0,1)

So,

, for all x from (0,1)

Now that we have c =2,

1. Draw y ~ g(x) => Draw y ~ Unif [0,1]

2. Draw u ~ Unif [0,1]

3. if then x=y; else return to 1

**MATLAB code for generating 1000 samples following Beta(2,1):**

close all clear all ii=1; while ii < 1000 y = rand; u = rand; if u <= y x(ii)=y; ii=ii+1; end end hist(x)

**MATLAB result**

#### Discrete Example

Generate random variables according to the p.m.f:

find a g(y) discrete uniform distribution from 1 to 5

Since P(Y=3) is the max of P(Y) and g(y) = 0.2 for all y.

1. Generate Y according to the discrete uniform between 1 - 5

2. U ~ unif[0,1]

3. If , then x = y; else return to 1.

In MATLAB, the code would be:

py = [0.15 0.22 0.33 0.1 0.2]; ii =1; while ii <= 1000 y = unidrnd(5); u = rand; if u <= py(y)/0.33 x(ii) = y; ii = ii+1; end end hist(x);

MATLAB result

#### Limitations

Most of the time we have to sample many more points from g(x) before we can obtain an acceptable amount of samples from f(x), hence this method may not be computationally efficient. It depends on our choice of g(x). For example, in the example above to sample from Beta(2,1), we need roughly 2000 samples from g(X) to get 1000 acceptable samples of f(x).

In addition, in situations where a g(x) function is chosen and used, there can be a discrepancy between the functional behaviors of f(x) and g(x) that render this method unreliable. For example, given the normal distribution function as g(x) and a function of f(x) with a "fat" mid-section and "thin tails", this method becomes useless as more points near the two ends of f(x) will be rejected, resulting in a tedious and overwhelming number of sampling points having to be sampled due to the high rejection rate of such a method.

### Sampling From Gamma and Normal Distribution - September 27, 2011

#### Sampling From Gamma

**Gamma Distribution**

The Gamma function is written as

If you have t samples of the exponential distribution,

The sum of these t samples has a gamma distribution,

- where

**Method**

Suppose we want to sample points from .

We can sample the exponential distribution using the inverse transform method from the previous class,

(1 - u) is the same as x since

**MATLAB code** for a Gamma(3,1) is

x = sum(-log(rand(1000,3)),2); hist(x)

And the Histogram of X follows a Gamma distribution with long tail:

We can improve the quality of histogram by adjusting the Matlab code to include the number of bins we want: hist(x, number_of_bins)

x = sum(-log(rand(20000,3)),2); hist(x,40)

** R code** for a Gamma(3,1) is

a<-apply(-log(matrix(runif(3000),nrow=1000)),1,sum); hist(a);

Histogram:

Here is another histogram of Gamma coding with R

a<-apply(-log(matrix(runif(3000),nrow=1000)),1,sum); hist(a,freq=F); lines(density(a),col="blue"); rug(jitter(a));

#### Sampling from Normal Distribution using Box-Muller Transform - September 29, 2011

##### Procedure

- Generate and , two values sampled from a uniform distribution between 0 and 1.
- Set so that is exponential with mean 2

Set so that ~ - Set

Set

##### Justification

Suppose we have X ~ N(0, 1) and Y ~ N(0, 1) where X and Y are independent normal random variables. The relative probability density function of these two random variables using Cartesian coordinates is:

In polar coordinates , so the relative probability density function of these two random variables using polar coordinates is:

If we have and we get an equivalent relative probability density function. Notice that when doing a two by two linear transformation, the determinant of the Jacobian needs to be included in the change of variable formula where:

where

Therefore we can generate a point in polar coordinates using the uniform and exponential distributions, then convert the point to Cartesian coordinates and the resulting X and Y values will be equivalent to samples generated from N(0, 1).

**MATLAB code**

In MatLab this algorithm can be implemented with the following code, which generates 20,000 samples from N(0, 1):

x = zeros(10000, 1); y = zeros(10000, 1); for ii = 1:10000 u1 = rand; u2 = rand; R2 = -2 * log(u1); theta = 2 * pi * u2; x(ii) = sqrt(R2) * cos(theta); y(ii) = sqrt(R2) * sin(theta); end hist(x)

In one execution of this script, the following histogram for x was generated:

##### Non-Standard Normal Distributions

**Example 1: Single-variate Normal**

If X ~ Norm(0, 1) then (a + bX) has a normal distribution with a mean of and a standard deviation of (which is equivalent to a variance of ). Using this information with the Box-Muller transform, we can generate values sampled from some random variable for arbitrary values of .

- Generate a sample u from Norm(0, 1) using the Box-Muller transform.
- Set v = a + bu.

The values for v generated in this way will be equivalent to sample from a distribution. We can modify the MatLab code used in the last section to demonstrate this. We just need to add one line before we generate the histogram:

v = a + b * x;

For instance, this is the histogram generated when b = 15, a = 125:

**Example 2: Multi-variate Normal**

The Box-Muller method can be extended to higher dimensions to generate multivariate normals. The objects generated will be nx1 vectors, and their variance will be described by nxn covariance matrices.

defines the n by 1 vector such that:

- is the average of
- is the variance of
- is the co-variance of and

If are normal variables with mean 0 and variance 1, then the vector has mean 0 and variance , where 0 is the zero vector and is the identity matrix. This fact suggests that the method for generating a multivariate normal is to generate each component individually as single normal variables.

The mean and the covariance matrix of a multivariate normal distribution can be adjusted in ways analogous to the single variable case. If , then . Note here that the covariance matrix is symmetric and nonnegative, so its square root should always exist.

We can compute in the following way:

- Generate an n by 1 vector where ~ Norm(0, 1) using the Box-Muller transform.
- Calculate using singular value decomposition.
- Set .

The following MatLab code provides an example, where a scatter plot of 10000 random points is generated. In this case x and y have a co-variance of 0.9 - a very strong positive correlation.

x = zeros(10000, 1); y = zeros(10000, 1); for ii = 1:10000 u1 = rand; u2 = rand; R2 = -2 * log(u1); theta = 2 * pi * u2; x(ii) = sqrt(R2) * cos(theta); y(ii) = sqrt(R2) * sin(theta); end E = [1, 0.9; 0.9, 1]; [u s v] = svd(E); root_E = u * (s ^ (1 / 2)); z = (root_E * [x y]'); z(1,:) = z(1,:) + 0; z(2,:) = z(2,:) + -3; scatter(z(1,:), z(2,:))

This code generated the following scatter plot:

In Matlab, we can also use the function "sqrtm()" or "chol()" (Cholesky Decomposition) to calculate square root of a matrix directly. Note that the resulting root matrices may be different but this does materially affect the simulation. Here is an example:

E = [1, 0.9; 0.9, 1]; r1 = sqrtm(E); r2 = chol(E);

R code for a multivariate normal distribution:

n=10000; r2<--2*log(runif(n)); theta<-2*pi*(runif(n)); x<-sqrt(r2)*cos(theta); y<-sqrt(r2)*sin(theta); a<-matrix(c(x,y),nrow=n,byrow=F); e<-matrix(c(1,.9,09,1),nrow=2,byrow=T); svde<-svd(e); root_e<-svde$u %*% diag(svde$d)^1/2; z<-t(root_e %*%t(a)); z[,1]=z[,1]+5; z[,2]=z[,2]+ -8; par(pch=19); plot(z,col=rgb(1,0,0,alpha=0.06))

##### Remarks

MATLAB's randn function uses the ziggurat method to generate normal distributed samples. It is an efficient rejection method based on covering the probability density function with a set of horizontal rectangles so as to obtain points within each rectangle. It is reported that a 800 MHz Pentium III laptop can generate over 10 million random numbers from normal distribution in less than one second. (Reference)

### Sampling From Binomial Distributions

In order to generate a sample x from , we can follow the following procedure:

1. Generate n uniform random numbers sampled from : .

2. Set x to be the total number of cases where for all .

In MatLab this can be coded with a single line. The following generates a sample from

sum(rand(n, 1) <= p, 1)

## Bayesian Inference and Frequentist Inference - October 4, 2011

### Bayesian inference vs Frequentist inference

The Bayesian method has become popular in the last few decades as simulation and computer technology makes it more applicable. For more information about its history and application, please refer to http://en.wikipedia.org/wiki/Bayesian_inference. As for frequentist inference, please refer to http://en.wikipedia.org/wiki/Frequentist_inference.

#### Example

Consider the 'probability' that a person drinks a cup of coffee on a specific day. The interpretations of this for a frequentist and a bayesian are as follows:

Frequentist: There is no explanation to this expression. It is essentially meaningless since it has only occurred once. Therefore, it is not a probability.

Bayesian: Probability captures not only the frequency of occurrences but also one's degree of belief about the random component of a proposition. Therefore it is a valid probability.

#### Example of face identification

Consider a picture of a face that is associated with an identity (person). Take the face as input x and the person as output y. The person can be either Ali or Tom. We have y=1 if it is Ali and y=0 if it is Tom. We can divide the picture into 100*100 pixels and insert them into a 10,000*1 column vector, which captures x.

If you are a frequentist, you would compare with and see which one is higher.

If you are Bayesian, you would compare with .

#### Summary of differences between two schools

- Frequentist: Probability refers to limiting relative frequency. (objective)
- Bayesian: Probability describes degree of belief not frequency. (subjective)

e.g. The probability that you drank a cup of tea on May 20, 2001 is 0.62 does not refer to any frequency.

- Frequentist: Parameters are fixed, unknown constants.
- Bayesian: Parameters are random variables and we can make probabilistic statement about them.

- Frequentist: Statistical procedures should be designed to have long run frequency properties.

e.g. a 95% confidence interval should trap true value of the parameter with limiting frequency at least 95%.

- Bayesian: It makes inferences about by producing a probability distribution for . Inference (e.g. point estimates and interval estimates) will be extracted from this distribution :

#### Bayesian inference

Bayesian inference is usually carried out in the following way:

1. Choose a prior probability density function of which is . This is our belief about before we see any data.

2. Choose a statistical model that reflects our beliefs about X.

3. After observing data , we update our beliefs and calculate the posterior probability.

, where is the posterior probability, is the prior probability, is the likelihood of observing X=x given and f(x) is the marginal probability of X=x.

If we have i.i.d. observations , we can replace with because of independency.

We denote as which is called likelihood. And we use to denote .

, where is a constant which does not depend on . So . The posterior probability is proportional to the likelihood times prior probability. Note that it does not matter if we throw away ,we can always recover it.

What do we do about the posterier distribution?

- Point estimate

- Baysian Interval estimate

Let C=(a,b); Then . C is a posterior interval.

Let , then and

#### Example 1: Estimating parameters of a univariate Gaussian distribution

Suppose X follows a univariate Gaussian distribution (i.e. a Normal distribution) with parameters and .

(a) For Frequentists:

To get the maximum likelihood estimator of (mle), we find the which maximizes :

(b) For Bayesians:

We assume that the mean of the above normal distribution is itself distributed normally with mean and variance .

Suppose ),

so

, where is the estimator of .

- If prior belief about is strong, then is small and is large. is close to and the observations will not affect too much. On the contrary, if prior belief about is weak, is large and is small. depends more on observations. (This is intuitive, when our original belief is reliable, then the sample is not important in improving the result; when the belief is not reliable, then we depend a lot on the sample.)

- When the sample is large (i.e. n ), and the impact of prior belief about is weakened.

**Basic Monte Carlo Integration - October 6th, 2011**

Three integration methods would be taught in this course:

- Basic Monte Carlo Integration
- Importance Sampling
- Markov Chain Monte Carlo (MCMC)

The first, and most basic, method of numerical integration we will see is Monte Carlo Integration. We use this to solve an integral of the form:

Note the following derivation:

~

Where w(x) = h(x)(b-a) and f(x) is the probability density function of a uniform random variable on the interval [a,b]. The expectation, with respect to the distribution of f, of w is taken from n samples of x.

**General Procedure**

i) Draw n samples

ii) Compute for every sample

iii) Obtain an estimate of the integral, , as follows:

. Clearly, this is just the average of the simulation results.

By the strong law of large numbers converges to as . Because of this, we can compute all sorts of useful information, such as variance, standard error, and confidence intervals.

Standard Error:

Variance:

Confidence Interval:

**Example: Uniform Distribution**

Consider the integral, , which is easily solved through standard analytical integration methods, and is equal to .25. Now, let us check this answer with a numerical approximation using Monte Carlo Integration.

We generate a 1 by 10000 vector of uniform (on the interval [0,1]) random variables and call that vector 'u'. We see that our 'w' in this case is , so we set . Our is equal to the mean of w.

In Matlab, we can solve this integration problem with the following code:

u = rand(1,10000); w = u.^3; mean(w) ans = 0.2475

Note the '.' after 'u' in the second line of code, indicating that each entry in the matrix is cubed. Also, our approximation is close to the actual value of .25. Now let's try to get an even better approximation by generating more sample points.

u= rand(1,100000); w= u.^3; mean(w) ans = .2503

We see that when the number of sample points is increased, our approximation improves, as one would expect.

**Generalization**

Up to this point we have seen how to numerically approximate an integral when the distribution of f is uniform. Now we will see how to generalize this to other distributions.

If f is a distribution function (pdf), then can be estimated as E_{f}[h(x)]. This means taking the expectation of h with respect to the distribution of f. Our previous example is the case where f is the uniform distribution between [a,b].

**Procedure for the General Case**

i) Draw n samples from f

ii) Compute h(x_{i})

iii) _{i}

**Example: Exponential Distribution**

Find for , which is the exponential distribution with mean 1.

We can see that we must draw samples from f, the exponential distribution.

To find a numerical solution using Monte Carlo Integration we see that:

u= rand(1,10000)

X= -log(u)

h=

I= mean(h)

To implement this procedure in Matlab, use the following code:

u = rand(1,10000); X = -log(u); h = x.^.5; mean(h) ans = .8841

An easy way to check whether your approximation is correct is to use the built in Matlab function 'quadl' which takes a function and bounds for the integral and returns a solution for the definite integral of that function. For this specific example, we can enter:

f = @(x) sqrt(x).*exp(-x); % quadl runs into computational problems when the upper bound is "inf" or an extremely large number, % so choose just a moderately large number. quadl(f,0,100) ans = 0.8862

From the above result, we see that our approximation was quite close.

**Example: Normal Distribution**

Let . Compute the cumulative distribution function at some point x.

. The (1) is inserted to illustrate that our h(x) will be the constant function 1, and our f(x) is the normal distribution. To take into account the upper bound of integration, x, any values sampled that are greater than x will be set to zero.

This is the Matlab code for solving F(2):

u = randn(1,10000) h = u < 2; mean(h) ans = .9756

We generate a 1 by 10000 vector of standard normal random variables and we return a value of 1 if u is less than 2, and 0 otherwise.

We can also build the function F(x) in matlab in the following way:

function F(x) u=rand(1,1000000); h=u<x; mean(h)

**Example: Binomial Distribution**

In this example we will see the Bayesian Inference for 2 Binomial Distributions.

Let and , and let .

Therefore, which is the frequentist approach.

Bayesian wants , where is a constant.

Thus, . Now we assume that and f(p) and f(q) are uniform.

Therefore, .

.

As you can see this is much tougher than the frequentist approach.

**Importance Sampling and Basic Monte Carlo Integration - October 11th, 2011**

**Example: Binomial Distribution (Continued)**

Suppose we are given two independent Binomial Distributions , . We would like to give an Monte Carlo estimate of

Frequentist approach:

;

Bayesian approach to compute the expected value of :

Assume that and the sample size is 1000.

MATLAB code of the above example:

n = 100; m = 100; p_1 = 0.5; p_2 = 0.8; p1 = mean(rand(n,1000)<p_1,1); p2 = mean(rand(m,1000)<p_2,1); delta = p2 - p1; hist(delta) mean(delta)

In one execution of the code, the mean of delta was 0.3017. The histogram of delta generated was:

Through Monte Carlo simulation, we can obtain an empirical distribution of delta and carry out inference on the data obtained, such as computing the mean, maximum, variance, standard deviation and the standard error of delta.

**Importance Sampling**

#### Motivation

Consider the integral

According to basic Monte Carlo Integration, if we can sample from the probability density function and feed the samples of back to , can be estimated as an average of ( i.e. )

However, the Monte Carlo method works when we know how to sample from . In the case where it is difficult to sample from , importance sampling is a technique that we can apply. Importance Sampling relies on another function which we know how to sample from.

The above integral can be rewritten as follow:

The integral can thus be simulated as

#### Procedure

Suppose we know how to sample from

- Choose a suitable and draw n samples
- Set
- Compute

By the Law of large numbers, provided that the sample size n is large enough.

**Remarks:** One can think of as a weight to in the computation of

Therefore, is a weighted average of

#### Problem

If is not chosen appropriately, then the variance of the estimate may be very large. The problem here is actually similar to what we encounter with the Rejection-Acceptance method. Consider the second moment of :

When is very small, then the above integral could be very large, hence the variance can be very large when g is not chosen appropriately. This occurs when has a thinner tail than such that the quantity is large.

**Remarks:**

1. We can actually compute the form of to have optimal variance.

Mathematically, it is to find subject to

It can be shown that the optimal is . Using the optimal will minimize the variance of estimation in Importance Sampling. This is of theoretical interest but not useful in practice. As we can see, if we can actually show the expression of g(x), we must first have the value of the integration---which is what we want in the first place.

2. In practice, we shall choose which has similar shape as but with a thicker tail than in order to avoid the problem mentioned above.

#### Example

Estimate

**Method 1: Basic Monte Carlo**

MATLAB code to compute from 100 samples of standard normal distribution:

h = randn(100,1) > 3; I = mean(h)

In one execution of the code, it returns a value of 0 for , which differs significantly from the true value of . The problem of using Basic Monte Carlo in this example is that has a small value, and hence many points sampled from the standard normal distribution will be wasted. Therefore, although Basic Monte Carlo is a feasible method to compute , it gives a poor estimation.

**Method 2: Importance Sampling**

To apply importance sampling, we have to choose a which we will sample from. In this example, we can choose to be the probability density function of exponential distribution, normal distribution with mean 0 and variance greater than 1 or normal distribution with mean greater than 0 and variance 1 etc. The goal is to minimize the number of rejected samples in order to produce a more accurate result! For the following, we take to be the pdf of .

Procedure:

- Draw n samples
- Calculate
- Set
- Compute

The above procedure from 100 samples of can be implemented in MATLAB as follow:

for ii = 1:100 x = randn + 4 ; h = x > 3 ; y(ii) = h * exp(8-4*x) ; end mean(y)

In one execution of the code, it returns a value of 0.001271 for , which is much closer to the true value of . From many executions of the code, the variance of basic monte carlo is approximately 150 times that of importance sampling. This demonstrates that this method can provide a better estimate than the Basic Monte Carlo method.

** Importance Sampling with Normalized Weight and Markov Chain Monte Carlo - October 13th, 2011**

**Importance Sampling with Normalized Weight**

Recall that we can think of as a weight applied to the samples . If the form of is known only up to a constant, we can use an alternate, normalized form of the weight, . (This situation arises in Bayesian inference.) Importance sampling with normalized or standard weight is also called indirect importance sampling.

We derive the normalized weight as follows:

Then, the normalized weight is

Note that

We can also determine the associated Monte Carlo variance of this estimate by

**Markov Chain Monte Carlo**

We still want to solve

#### Stochastic Process

A stochastic process is a collection of random variables. Variables take values in some set called the **state space.** The set is called the **index set.**

**Markov Chain**

A Markov Chain is a stochastic process for which the distribution of depends only on . It is a random process characterized as being memoryless, meaning that the next occurrence of a defined event is only dependent on the current event;not on the preceding sequence of events.

Formal Definition: The process is a Markov Chain if for all and for all

For a Markov Chain,
**Real Life Example:**

When going for an interview, the employer only looks at your highest education achieved. The employer would not look at the past educations received (elementary school, high school etc.) because the employer believes that the highest education achieved summarizes your previous educations. Therefore, anything before your most recent previous education is irrelevant. In other word, we can say that is regarded as the summary of , so when we need to determine , we only need to pay attention in .

#### Transition Probabilities

The **transition probability** is the probability of jumping from one state to another state in a Markov Chain.

Formally, let us define to be the transition probability.

That is, is the probability of transitioning from state i to state j in a single step. Then the matrix whose (i,j) element is is called the **transition matrix**.

Properties of P:

- 1) (The probability of going to another state cannot be negative)
- 2) (The probability of transitioning to some state from state i (including remaining in state i) is one)

#### Random Walk

Example: Start at one point and flip a coin where and . Take one step right if heads and one step left if tails. If at an endpoint, stay there. The transition matrix is

Let be the matrix such that its (i,j) element is . This is called n-step probability.

** Markov Chain Properties and Page Rank - October 18th, 2011**

### Summary of Terminology

#### Transition Matrix

A matrix that defines a Markov Chain has the form:

where is the probability of transitioning from state i to state j in the Markov Chain in a single step. Note that this implies that all rows add up to one.

#### n-step Transition matrix

A matrix whose (i,j)^{th} entry is the probability of moving from state i to state j after n transitions:

This probability is called the n-step transition probability. A nice property of this matrix is that

For all n >= 0, where P is the transition matrix. Note that the rows of should still add up to one.

#### Marginal distribution of a Markov Chain

We represent the state at time t as a vector.

Consider this Markov Chain:

, where A is the probability of being in state a at time t, and B is the probability of being in state b at time t.

For example if , we have a 10% chance of being in state a at time t, and a 90% chance of being in state b at time t.

Suppose we run this Markov chain many times, and record the state at each step.

In this example, we run 4 trials, up until t=5.

t | Trial 1 | Trial 2 | Trial 3 | Trial 4 | Observed |
---|---|---|---|---|---|

1 | a | b | b | a | (0.5, 0.5) |

2 | b | a | a | a | (0.75, 0.25) |

3 | a | a | b | a | (0.75, 0.25) |

4 | b | b | a | b | (0.25, 0.75) |

5 | b | b | b | a | (0.25, 0.75) |

Imagine simulating the chain many times. If we collect all the outcomes at time t from all the chains, the histogram of this data would look like .

We can find the marginal probabilities as

#### Stationary Distribution

Let be a vector of non-negative numbers that sum to 1. (i.e. is a pmf)

If , then is a stationary distribution, also known as an invariant distribution.

#### Limiting Distribution

A Markov chain has limiting distribution if

That is, exists and is independent of i.

Here is an example:

Suppose we want to find the stationary distribution of

We want to solve and we want

Solving the system of equations, we get

So using our condition above, we have and by solving we get

Using this in our system of equations, we obtain:

Thus, the stationary distribution is

#### Detailed Balance

has the detailed balance property if

**Theorem**

If satisfies detailed balance, then is a stationary distribution.

In other words, if , then

**Proof:**

Observe that the j^{th} element of is

- , by the definition of detailed balance.

- , as the sum of the entries in a row of P must sum to 1.

So .

**Example**

Find the marginal distribution of

Start by generating the matrix P.

We must assume some starting value for

For t = 1, the marginal distribution is

Notice that this converges.

If you repeatedly run:

It converges to

This can be seen by running the following Matlab code:

P = [0.2 0.8; 0.6 0.4]; mu = [0.1 0.9]; while 1 mu_old = mu; mu = mu * P; if mu_old == mu disp(mu); break; end end

Another way of looking at this simple question is that we can see whether the ultimate pmf converges:

Let denote the estimator of the stationary probability of state 1, denote the estimator of the stationary probability of state 2, where and are indicator variables which equal 1 if (or for the latter one).

Matlab codes for this explanation is

n=1; if rand<0.1 x(1)=1; else x(1)=0; end p1(1)=sum(x)/n; p2(1)=1-p1(1); for i=2:10000 n=n+1; if (x(i-1)==1&rand<0.2)|(x(i-1)==0&rand<0.6) x(i)=1; else x(i)=0; end p1(i)=sum(x)/n; p2(i)=1-p1(i); end plot(p1,'red'); hold on; plot(p2)

The results can be easily seen from the graph below:

Additionally, we can plot the marginal distribution as it converges without estimating it. The following Matlab code shows this:

%transition matrix P=[0.2 0.8; 0.6 0.4]; %mu at time 0 mu=[0.1 0.9]; %number of points for simulation n=20; for i=1:n mu_a(i)=mu(1); mu_b(i)=mu(2); mu=mu*P; end t=[1:n]; plot(t, mu_a, t, mu_b); hleg1=legend('state a', 'state b');

Note that there are chains with stationary distributions that don't converge (the chain might not naturally reach the stationary distribution, and isn't limiting). An example of this is:

is a stationary distribution, so is the same for all iterations.

But,

So is not a limiting distribution. Also, if

Then .

This can be observed through the following Matlab code.

P = [0 0 1; 1 0 0; 0 1 0]; mu = [0.2 0.1 0.7]; for i= 1:4 mu = mu * P; disp(mu); end

Output:

0.1000 0.7000 0.2000 0.7000 0.2000 0.1000 0.2000 0.1000 0.7000 0.1000 0.7000 0.2000

Note that , which indicates that will cycle forever.

This means that this chain has a stationary distribution, but is not limiting. A chain has a limiting distribution iff it is ergodic, that is, aperiodic and positive recurrent. While cycling breaks detailed balance and limiting distribution on the whole state space does not exist, the cycling behavior itself is the "limiting distribution". Also, for each cycles (closed class), we will have a mini-limiting distribution which is useful in analyzing small scale long-term behavior.

### Page Rank

Page Rank was the original ranking algorithm used by Google's search engine to rank web pages.<ref> http://ilpubs.stanford.edu:8090/422/ </ref> The algorithm was created by the founders of Google, Larry Page and Sergey Brin as part of Page's PhD thesis. When a query is entered in a search engine, there are a set of web pages which are matched by this query, but this set of pages must be ordered by their "importance" in order to identify the most meaningful results first. Page Rank is an algorithm which assigns importance to every web page based on the links in each page.

#### Intuition

We can represent web pages by a set of nodes, where web links are represented as edges connecting these nodes. Based on our intuition, there are three main factors in deciding whether a web page is important or not.

- A web page is important if many other pages point to it.
- The more important a webpage is, the more weight is placed on its links.
- The more links a webpage has, the less weight is placed on its links.

#### Modelling

We can model the set of links as a N-by-N matrix L, where N is the number of web pages we are interested in:

The number of outgoing links from page j is

For example, consider the following set of links between web pages:

According to the factors relating to importance of links, we can consider two possible rankings :

or

if we consider that the high importance of the link from 3 to 1 is more influent than the fact that there are two outgoing links from page 1 and only one from page 2.

We have , and

We can represent the ranks of web pages as the vector P, where the i^{th} element is the rank of page i:

Here we take the sum of the weights of the incoming links, where links are reduced in weight if the linking page has a lot of outgoing links, and links are increased in weight if the linking page has a lot of incoming links.

We don't want to completely ignore pages with no incoming links, which is why we add the constant (1 - d).

If

Then

where is the vector with all 1's

To simplify the problem, we let . This means that the average importance of all pages on the internet is 1.

Then

- , where is an NxN matrix filled with ones.

Let

Then .

Note that P is a stationary distribution and, more importantly, P is an eigenvector of A with eigenvalue 1. Therefore, we can find the ranks of all web pages by solving this equation for P.

We can find the vector P for the example above, using the following Matlab code:

L = [0 0 1 0; 1 0 0 0; 1 1 0 1; 0 0 0 0]; D = [2 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1]; d = 0.8 ;% pages with no links get a weight of 0.2 N = 4 ;

A = ((1-d)/N) * ones(N) + d * L * inv(D); [EigenVectors, EigenValues] = eigs(A) s=sum(EigenVectors(:,1));% we should note that the average entry of P should be 1 according to our assumption P=(EigenVectors(:,1))/s*N

This outputs:

EigenVectors = -0.6363 0.7071 0.7071 -0.0000 -0.3421 -0.3536 + 0.3536i -0.3536 - 0.3536i -0.7071 -0.6859 -0.3536 - 0.3536i -0.3536 + 0.3536i 0.0000 -0.0876 0.0000 + 0.0000i 0.0000 - 0.0000i 0.7071

EigenValues = 1.0000 0 0 0 0 -0.4000 - 0.4000i 0 0 0 0 -0.4000 + 0.4000i 0 0 0 0 0.0000

P =

1.4528 0.7811 1.5660 0.2000

Note that there is an eigenvector with eigenvalue 1. The reason why there always exist a 1-eigenvector is that A is a stochastic matrix.

Thus our vector P is

However, this method is not practical, because there are simply too many web pages on the internet. So instead Google uses a method to approximate an eigenvector with eigenvalue 1.

Note that page three has the rank with highest magnitude and page four has the rank with lowest magnitude, as expected.

** Markov Chain Monte Carlo - Metropolis-Hastings - October 25th, 2011**

We want to find , but we don't know how to sample from .

We have seen simple techniques earlier in the course; here is an example of a real life application. It consists of the search for a Markov Chain such that its stationary distribution is .

#### Main procedure

Let us suppose that is a friendly distribution: we can sample from this function.

1. Initialize the chain with and set .

2. Draw a point from i.e. .

3. Evaluate

4. Draw a point .

5. .

6. . Go back to 2.

#### Remark 1

A very common choice for is , a normal distribution centered at the current point.

Note : In this case is symmetric i.e. .

(Because and ).

Thus we have , which implies :

.

In general, if is symmetric then the algorithm is called Metropolis in reference to the original algorithm (made in 1953)<ref>http://en.wikipedia.org/wiki/Equations_of_State_Calculations_by_Fast_Computing_Machines</ref>.

#### Remark 2

The value y is accepted if so it is accepted with the probability .

Thus, if , then is always accepted.

The higher that value of the pdf is in the vicinity of a point , the more likely it is that a random variable will take on values around . As a result it makes sense that we would want a high probability of acceptance for points generated near .

#### Remark 3

One strength of the Metropolis-Hastings algorithm is that normalizing constants, which are often quite difficult to determine, can be cancelled out in the ratio . For example, consider the case where we want to sample from the beta distribution, which has the pdf:

The beta function, *B*, appears as a normalizing constant but it can be simplified by construction of the method.

#### Example

Then, we have .

And let us take .

Then is symmetric.

Therefore Y can be simplified.

We get :

.

The Matlab code of the algorithm is the following :

clear all close all clc b=2; x(1)=randn; for i=2:10000 y=b*randn+x(i-1); r=min((1+x(i-1)^2)/(1+y^2),1); u=rand; if u<r x(i)=y; else x(i)=x(i-1); end end hist(x(5000:end)); %The Markov Chain usually takes some time to converge and this is known as the "burning time". %Therefore, we don't display the first 5000 points because they don't show the limiting behaviour of the Markov Chain.

As we can see, the choice of the value of b is made by us.

Changing this value has a significant impact on the results we obtain. There is a pitfall when b is too big or too small.

Example with (Also with graph after we run j=5000:10000; plot(j,x(5000:10000)):

With , the chain takes small steps so the chain doesn't explore enough of the sample space. It doesn't give an accurate report of the function we want to sample.

Example with :

With , jumps are very unlikely to be accepted as they deviate far from the mean (i.e. is rejected as and most of the time, hence most sample points stay fairly close to the origin. The third graph that resembles white noise (as in the case of ) indicates better sampling as more points are covered and accepted. For , we have lots of jumps but most values are not repeated, hence the stationary distribution is less obvious; whereas in the case, many points remains around 0. Approximately 73% were selected as x(i-1).

Example with :

With , we get a more accurate result as we avoid these extremes. Approximately 37% were selected as x(i-1).

If the sample from the Markov Chain starts to look like the target distribution quickly, we say the chain is mixing well.

** Theory and Applications of Metropolis-Hastings - October 27th, 2011**

As mentioned in the previous section, the idea of the Metropolis-Hastings (MH) algorithm is to produce a Markov chain that converges to a stationary distribution which we are interested in sampling from.

#### Convergence

One important fact to check is that is indeed a stationary distribution in the MH scheme. For this, we can appeal to the implications of the detailed balance property:

Given a probability vector and a transition matrix , has the detailed balance property if

If satisfies detailed balance, then it is a stationary distribution.

The above definition applies to the case where the states are discrete. In the continuous case, satisfies detailed balance if . Where and are the probabilities of transitioning from x to y and y to x respectively. If we can show that has the detailed balance property, we can conclude that it is a stationary distribution. Because .

In the MH algorithm, we use a proposal distribution to generate ~, and accept y with probability

Suppose, without loss of generality, that . This implies that

Let be the chance of accepting point y given that we are at point x.

So

Let be the chance of accepting point x given that we are at point y.

So

is the probability of generating and accepting y, while at point x.

So

is the probability of generating and accepting x, while at point y.

So

Thus, detailed balance holds.

- i.e. is stationary distribution

It can be shown (although not here) that is a limiting distribution as well. Therefore, the MH algorithm generates a sequence whose distribution converges to , the target.

#### Implementation

In the implementation of MH, the proposal distribution is commonly chosen to be symmetric, which simplifies the calculations and makes the algorithm more intuitively understandable. The MH algorithm can usually be regarded as a random walk along the distribution we want to sample from. Suppose we have a distribution :

Suppose we start the walk at point . The point is in a denser region than , therefore, the walk will always progress from to . On the other hand, is in a less dense region, so it is not certain that the walk will progress from to . In terms of the MH algorithm:

since . Thus, any generated value with a higher density will be accepted.

. The lower the density of is, the less chance it will have of being accepted.

A certain class of proposal distributions can be written in the form:

where

The density depends only on the distance between the current point and the next one (which can be seen as the "step" being taken). These proposal distributions give the Markov chain the random walk nature. The normal distribution that we frequently use in our examples satisfies the above definition.

In actual implementations of the MH algorithm, the proposal distribution needs to be chosen judiciously, because not all proposals will work well with all target distributions we want to sample from. Take a trimodal distribution for example:

If we choose the proposal distribution to be a standard normal as we have done before, problems will arise. The low densities between the peaks means that the MH algorithm will almost never walk to any points generated in these regions and get stuck at one peak. One way to address this issue is to increase the variance, so that the steps will be large enough to cross the gaps. Of course, in this case, it would probably be beneficial to come up with a different proposal function. As a rule of thumb, such functions should result in an approximately 50% acceptance rate for generated points.

#### Simulated Annealing

Metropolis-Hastings is very useful in simulation methods for solving optimization problems. One such application is simulated annealing, which addresses the problems of minimizing a function . This method will not always produce the global solution, but it is intuitively simple and easy to implement.

Consider , maximizing this expression is equivalent to minimizing . Suppose is the maximizing value and , then the maximization function is a gaussian distribution . When many samples are taken from this distribution, the mean will converge to the desired maximizing value. The annealing comes into play by lowering *T* (the temperature) as the sampling progresses, making the distribution narrower. The steps of simulated annealing are outlined below:

1. start with a random and set *T* to a large number

2. generate from a proposal distribution , which should be symmetric

3. accept with probability . (Note: )

4. decrease *T*, and then go to step 2

To decrease *T* in Step 4, a variety of functions can be used. For example, a common temperature function used is with geometric decline, given by an initial temperature , final temperature , the number of steps n, and the temperature function

The following plot and Matlab code illustrates the simulated annealing procedure as temperature *T*, the variance, decreases for a Gaussian distribution with zero mean. Starting off with a large value for the temperature *T* allows the Metropolis-Hastings component of the procedure to capture the mean, before gradually decreasing the temperature *T* in order to converge to the mean.

x=-10:0.1:10; mu=0; T=5; colour = ['b', 'g', 'm', 'r', 'k']; for i=1:5 pdfNormal=normpdf(x, mu, T); plot(x, pdfNormal, colour(i)); T=T-1; hold on end hleg1=legend('T=5', 'T=4', 'T=3', 'T=2', 'T=1'); title('Simulated Annealing Illustration');

**References**

<references/>

**Simulated Annealing and Gibbs Sampling - November 1, 2011**

continued from previous lecture...

Recall where where represents the probability of accepting .

We will now look at a couple cases where or , and explore whether to accept or reject .

#### Cases

Case a) Suppose . Since we want to find the minimum value for , and the point creates a lower value than our previous point, we accept the new point. Mathematically, implies that:

. Therefore, . So, we will always accept .

Case b) Suppose . This is bad, since our goal is to minimize . However, we may still accept with some chance:

. Therefore, . So, we may accept with probability .

Next, we will look at these cases as .

As and case a) happens, , so we will always accept .

As and case b) happens, , so the probability that will be accepted gets extremely small.

It is worth noting that if we simply start with a small value of T, we may end up rejecting all the generated points, and hence we will get stuck somewhere in the function (due to case b)), which might be a maximum value in some intervals (local maxima), but not in the whole domain (global maxima). It is therefore necessary to start with a large value of T in order to explore the whole function. At the same time, a good estimation of < is needed (at least cannot differ from the maximum point too much).

##### Example

Let . The graph of it is:

Then, . Take an initial value of T = 20. A graph of this is:

In comparison, we look a graph of T = 0.2:

One can see that with a low T value, the graph has a lot of r = 0, and r >1, while having a bigger T value gives smoother transitions in the graph.

The MATLAB code for the above graphs are:

ezplot('(x-2)^2',[-6,10]) ezplot('exp((-(x-2)^2)/20)',[-6,10]) ezplot('exp((-(x-2)^2)/0.2)',[-6,10])

##### Travelling Salesman Problem

The simulated annealing method can be applied to compute the solution to the travelling salesman problem. Suppose there are N cities and the salesman only have to visit each city once. The objective is to find out the shortest path (i.e. shortest total length of journey) connecting the cities. An algorithm using simulated annealing on the problem can be found here (Reference).

### Gibbs Sampling

Gibbs sampling is another Markov chain Monte Carlo method, similar to Metropolis-Hastings. There are two main differences between Metropolis-Hastings and Gibbs sampling. First, the candidate state is always accepted as the next state in Gibbs sampling. Second, it is assumed that the full conditional distributions are known, i.e. for all . The idea is that it is easier to sample from conditional distributions which are sets of one dimensional distributions than to sample from a joint distribution which is a higher dimensional distribution. Gibbs is a way to turn the joint distribution into multiple conditional distributions.

**Advantages:**

- Sampling from conditional distributions may be easier than sampling from joint distributions

**Disadvantages:**

- We do not necessarily know the conditional distributions

For example, if we want to sample from , we need to know how to sample from and . Suppose the chain starts with and have been sampled. Then,

Gibbs sampling turns a multi-dimensional distribution into a set of one-dimensional distributions. If we want to sample from

and the full conditionals are known, then:

With Gibbs sampling, we can simulate random variables sequentially from univariate conditionals rather than generating one -dimensional vector using the full joint distribution, which could be a lot more complicated.

Computational inference deals with probabilistic graphical models. Gibbs sampling is useful here: graphical models show the dependence relations among random variables. For instance, Bayesian networks are graphical models represented using directed acyclic graphs. Looking at such a graphical model tells us on which random variable the distribution of a certain random variable depends (i.e. its parent). The model can be used to "factor" a joint distribution into conditional distributions.

For example, consider the five random variables A, B, C, D, and E. Without making any assumptions about dependence relations among them, all we know is

However, if we know the relation between the random variables, e.g. given the graphical model on the left, we can simplify this expression:

Although the joint distribution may be very complicated, the conditional distributions may not be.

Check out the following notes on Gibbs sampling:

- MCMC and Gibbs Sampling, MIT Lecture Notes
- chapter 7.4 in Notes on Computational Methods in Statistics
- chapter 4.9 in Introduction to Probability Models by Sheldon Ross

#### Example of Gibbs sampling: Multi-variate normal

We'd like to generate samples from a bivariate normal with parameters

and

The conditional distributions of multi-variate normal random variables are also normal:

In general, if the joint distribution has parameters

and

then the conditional distribution has mean and variance .

Thus, the algorithm for Gibbs sampling is:

- 1) Set i = 1
- 2) Draw ~
- 3) Draw ~
- 4) Set
- 5) Increment i, return to step 2.

The Matlab code implementation of this algorithm is as follows:

mu = [1; 2]; sigma = [1 0.9; 0.9 1]; X(:,1) = [1; 2]; r = 1 - 0.9^2; for i = 2:2000 X(1,i) = 1 + 0.9*(X(2,i-1) - mu(2)) + r*randn; X(2,i) = 2 + 0.9*(X(1,i) - mu(1)) + r*randn; end plot(X(1,:),X(2,:),'.')

Which gives the following plot:

**Principal Component Analysis (PCA) - November 8, 2011**

Principal Component Analysis is a 100 year old algorithm used for reducing the dimensionality of data. As the number of dimensions increase, the number of data points needed to sample accurately increase by an exponential factor.

We want to transform to such that we reduce the dimensionality yet lose little information. Generally, variation in the data provides information. Thus we would like to reduce the dimensionality but keep as much variation, or information, as the original set of data. Also, covariance amongst the data reduces the amount of information we can infer from the data. Therefore, we would like to also reduce covariance when we reduce dimensionality.

For example, consider dots in a three dimensional space. By unrolling the 2D manifold that they are on, we can reduce the data to 2D while losing little information. **Note:** This is not an application of PCA, but it simply illustrates one way we can reduce dimensionality.

Principle Component Analysis allows us to reduce data to a linear subspace of its original space. It works best when data is in a lower dimensional subspace of its original space.

#### Probabilistic View

We can see a data set as a high dimensional random variable governed by a low dimensional random variable . Given , we are trying to estimate .

We can see this in 2D linear regression, as the locations of data points in a scatter plot are governed by its approximate linear regression. The subspace that we have reduced the data to here is in the direction of variation in the data.

#### Principal Component Analysis

Principal component analysis is an orthogonal linear transformation on a data set. It associates the data coordinates with a new set of orthogonal vectors, each representing the direction of the maximum variance of the data. That is, the first principal component is the direction of the maximum variance, the second principal component is the direction of the maximum variance orthogonal to the first principal component, the third principal component is the direction of the maximum variance orthogonal to the first and second principal component and so on, until we have D principal components, where D is the dimension of the original data.

Suppose we have data represented by

Note that we are assuming that the data is mean centered. In other words, the average of every row is zero. If it isn't, we shift the data to have a mean of zero by subtracting the mean of every row from each value in that row. This pre-processing step essentially alters the data such that each row in includes only how the data differs from the mean of the sample, hence ensuring that the first PC describes the direction of maximum variance.

To find the first principal component, we want to find a unit vector that maximizes the variance of . We restrict to unit vectors since we are only looking for the direction of the vector of maximum variation: the actual scale of it is unnecessary. So .

The variance of is where is the covariance matrix of X.

, since is just the zero vector after we center the data around the mean.

So we have to solve the problem

Using the method of Lagrange multipliers, we have

We set

Note that is a quadratic form. So we have

Since S is a matrix and lambda is a scaler, W is an eigenvector of S and lambda is its corresponding eigenvalue.

Suppose that

are eigenvalues of S and are their corresponding eigenvectors.

We want to choose some

So to maximize , choose the eigenvector corresponding to the max eiegenvalue, e.g. .

So we let be the first principal component.

The principal components decompose the total variance in the data.

### Singular Value Decomposition

Singular value decomposition is a "generalization" of eigenvalue decomposition "to rectangular matrices of size *mxn*."<ref name="Abdel_SVD">Abdel-Rahman, E. (2011). Singular Value Decomposition [Lecture notes]. Retrieved from http://uwace.uwaterloo.ca</ref> Singular value decomposition solves:

"for the right singular vector *v*, the singular value *s*, and the left singular vector *u*. There are *n* singular values *s*_{i} and *n* right and left singular vectors that must satisfy the following conditions"<ref name="Abdel_SVD"/>:

- "All singular values are non-negative"<ref name="Abdel_SVD"/>,

- All "right singular vectors are pairwise orthonormal"<ref name="Abdel_SVD"/>,

- All "left singular vectors are pairwise orthonormal"<ref name="Abdel_SVD"/>,

where

**Procedure to find the singular values and vectors**

Observe the following about the eigenvalue decomposition of a real square matrix *A* where *v* is the unit eigenvector:

As a result:

- "The matrices
*A*and*A*^{T}*A*have the same eigenvectors."<ref name="Abdel_SVD"/> - "The eigenvalues of matrix
*A*^{T}*A*are the square of the eigenvalues of matrix*A*."<ref name="Abdel_SVD"/> - Since matrix
*A*^{T}*A*is symmetric for any matrix A,- "all the eigenvalues of matrix
*A*^{T}*A*are real and distinct."<ref name="Abdel_SVD"/> - "the eigenvectors of matrix
*A*^{T}*A*are orthogonal and can be chosen to be orthonormal."<ref name="Abdel_SVD"/>

- "all the eigenvalues of matrix
- "The eigenvalues of matrix
*A*^{T}*A*are non-negative"<ref name="Abdel_SVD"/> since

Conclusions 3 and 4 are "true even for a rectangular matrix *A* since *A*^{T}*A* is still a square symmetric matrix"<ref name="Abdel_SVD"/> and its eigenvalues and eigenvectors can be found.

Therefore, for a rectangular matrix *A*, assuming *m>n*, the singular values and vectors can be found by:

- "Form the
*nxn*symmetric matrix*A*^{T}*A*."<ref name="Abdel_SVD"/> - Perform an eigenvalue decomposition to get
*n*eigenvalues and their "corresponding eigenvectors, ordered such that"<ref name="Abdel_SVD"/>

and - "The singular values are"<ref name="Abdel_SVD"/>:

"The non-zero singular values are distinct; the equal sign applies only to the singular values that are equal to zero."<ref name="Abdel_SVD"/> - "The
*n*-dimensional right singular vectors are"<ref name="Abdel_SVD"/> - "For the first singular values such that
*s*_{i}*> 0*, the left singular vectors are obtained as unit vectors"<ref name="Abdel_SVD"/> by - Select "the left singular vectors corresponding to the zero singular values such that they are unit vectors orthogonal to each other and to the first
*r*left singular vectors"<ref name="Abdel_SVD"/>

**Finding the Singular Value Decomposition Using MATLAB Code**

Please refer to the following link: http://www.mathworks.com/help/techdoc/ref/svd-singular-value-decomposition.html

**Formal definition**

"We can now decompose the rectangular matrix *A* in terms of singular values and vectors as follows"<ref name="Abdel_SVD"/>:

Where

Since "the matrices *V* and *U* are orthogonal"<ref name="Abdel_SVD"/>, *V *^{-1}=*V*^{T} and *U *^{-1}=*U*^{T}:

"which is the formal definition of the singular value decomposition."<ref name="Abdel_SVD"/>

**Relevance to PCA**

In order to perform PCA, one needs to do eigenvalue decomposition on the covariance matrix. By transforming the mean for all attributes to zero, the covariance matrix can be simplified to:

Since the eigenvalue decomposition of *A*^{T}*A* gives the same eigenvectors as the singular value decomposition of *A*, an additional and more consistent method (if a matrix has eigenvectors that are not invertible, its eigenvalue decomposition does not exist) for performing PCA is through the singular value decomposition of *X*.

The following MATLAB code uses singular value decomposition for performing PCA; 20 principal components, and thus the top 20 maximum variation directions, are selected for reconstructing facial images that have had noise applied to them:

load noisy.mat %first noisy image; each image has a resolution of 20x28 imagesc(reshape(X(:,1),20,28)') %to grayscale colormap gray %singular value decomposition [u s v]=svd(X); %reduced feature space: 20 principal components Xh=u(:,1:20)*s(1:20,1:20)*v(:,1:20)'; figure imagesc(reshape(Xh(:,1),20,28)') colormap gray

Since the reduced feature space image is noiseless, the added noise feature has less variation than the 20 principal components.

**References**

<references/>

** PCA and Introduction to Kernel Function - November 10, 2011**

(Continue from the last lecture)

Some notations:

Let be a d by n matrix.

Let be the j th column of .

Let be the covariance matrix of . So , where . Strictly speaking, is only the observed covariance matrix from the data collected as the real covariance matrix is unknown.

But we are assuming that we have already centered the data, which means that .

So .

Now the principal components of are the eigenvectors of . If we do the singular value decomposition, setting , then the columns of are eigenvectors of .

Let be a matrix, where , that is composed of the eigenvectors of corresponding to the largest eigenvalues.

To map the data in a lower dimensional space we project onto the dimensional subspace defined by the columns of , which are the first principal components of .

Let . So is a lower dimensional approximation of our original data

We can also approximately reconstruct the original data using the dimension-reduced data. However, we will lose some information because when we map those points into lower dimension, we throw away the last eigenvectors which contain some of the original information.

, where is an approximate reconstruction of .

### Example Using Handwritten 2s and 3s

The data X is a 64 by 400 matrix. Every column represents an 8 by 8 image of either a handwritten "2" or "3". The first 200 columns are 2s and the last 200 columns are 3s. First we center the data, and then we find the first 2 eigenvectors of using singular value decomposition. Finally we calculate and plot the 200 data points in

**MATLAB CODE:**

MU = repmat(mean(X,2),1,400); % mean(X,2) is the average of all the rows stored in a column vector. % In order to center the data, we extend mean(X,2), which is a 64 by 1 matrix, into a 64 by 400 matrix. Xt = X-MU; % We have modified the data to zero mean data by subtracting the average of each row from every entry in that row. [u s v] = svd(Xt); % Note that size(u) == 64*64, and the columns of u are eigenvectors of VCM. Y = u(:,1:2)'*X; % We project X onto the subspace defined by the first two PCs to get Y. % This transforms the high dimensional points to lower 2 dimensional ones. plot(Y(1,1:200)',Y(2,1:200)','d') hold on plot(Y(1,201:400)',Y(2,201:400)','ro') % We now plot the lower dimensional projection of X. % Essentially we are plotting each point based on the magnitude of Principle Component #1 % and Principle Component #2 in that point. % Note that the first 200 columns represent 2s and are recorded by blue diamonds. % Note that the next 200 columns represent 3s and are recorded with red "o"s.

The result is as follows, we can see clearly there are two classes - the 2s and 3s are generally divided into two sections:

In order to analyze the projection in more detail we can plot the original images on the graph.

image = reshape(X,8,8,400); plotdigits(image,Y,.1,1);

The result can now be seen more clearly from the following picture:

By examining this plot we can infer the approximate "meaning" of the first two principal components in this data. For instance, the points at the top of the plot tend to be slanted to the right, while the ones at the bottom are slanted to the left. So the second principal component quantifies the amount of slant in the number.

### Introduction to Kernel Function

PCA is useful when those data points spread in or close to a plane. This means that PCA is powerful when dealing with linear problems. But when data points spread in a manifold space, PCA is hard to implement. But there is a solution to this problem - we can use a method to change the linear algorithm into a nonlinear one. This is called the "Kernel Trick".

**An intuitive example**

From the picture, we can see the red circles are in the middle of the blue Xs. However, it is hard to separate those two classes by using any linear function (lines in the two dimensional space). But we can use a Kernal function to project the points onto a three dimensional space. Once the blue Xs and red circles have been mapped to a three dimensional space in this way it is easy to separate them using a linear function.

For more details about this trick, please see http://omega.albany.edu:8008/machine-learning-dir/notes-dir/ker1/ker1.pdf

The significance of a Kernel Function, , is that we can implicitly change the data into a high dimension. Let's look at how this is possible:

The inner product of and , which is denoted as , is equal to:

.

**The most common Kernel functions are as follows:**

- Linear:
- Polynomial:
- Gaussian:
- Exponential:

Note: denotes the distance between and .

### Disadvantages of the Kernel Trick

Since the kernel trick brings a lower dimensional problem to a higher dimensional space, it is affected by the curse of dimensionality. The curse of dimensionality states that it takes exponentially more points to estimate a solution in higher dimensions. ex) if needs 10 points, then needs 100, needs 1000 etc.

** Kernel PCA - November 15, 2011**

PCA doesn't work well when the directions of variation in our data are nonlinear. Especially in the case where the dataset has very high dimensions, the dataset lies near or on a nonlinear manifold which prevents PCA from determining principal components correctly. To deal with this problem, we apply kernels to PCA. By transforming the original data with a nonlinear mapping, we can obtain much better principal components.

First we look at the algorithm for PCA and see how we can kernelize PCA:

## PCA

Find eigenvectors of , call it

to map data points to a lower dimensional space:

to reconstruct points:

to map a new point:

to reconstruct point:

## Dual PCA

Consider the singular value decomposition of n-by-m matrix X:

Where:

- The columns of U are the eigenvectors of corresponding to the eigenvalues in decreasing order.
- The columns of V are the eigenvectors of .
- The diagonal matrix contains the square roots of the eigenvalues of in decreasing order.

Now we want to kernelize this classical version of PCA. We would like to express everything based on V which can be kernelized. The reason why we want to do this is because if n >> m (i.e. the feature space is much larger than the number of sample points) then the original PCA algorithm would be impractical. We want an algorithm that depends less on n. This is called Dual PCA.

U in terms of V:

Y in terms of V:

Reconstructed points in terms of V:

The value of y, a single point in the sample reduced to low-dimensional space, in terms of V:

A single reconstructed point from the sample in terms of V:

### Kernel PCA

The nonlinear mapping allows for very high dimensional spaces and is never calculated explicitly.

, , and could have many different kernels.

Generally, we want to replace with a kernel. The idea in Kernel PCA is that instead of finding the eigenvectors of , we can find the eigenvectors of a kernel.

Example.

Find the eigenvectors of the matrix

However, since the is never calculated explicitly, kernel PCA cannot reconstruct points using the equation where .

In kernel PCA, we replace for . This is correct if has a mean of zero.

We need to find a way to centralize .

### Centralizing Kernel PCA

Recall in regular PCA, our variance-covariance matrix was defined as .

With kernel PCA, we will never explicitly define so we need a method to calculate its mean without calculating the actual transformation of itself.

We define:

And thus, our kernel function becomes:

In practice, we would do the following:

1. Start with our matrix of data:

2. Choose a kernel function

3. Compute , an nxn matrix:

4. Find

**Note:** On the right hand side, the second item is the average of the columns of , the third item is the average of the rows of , and the last item is the average of all the entries of .
As a result, they are vectors of dimension , , and (a scalar) respectively. To do the actual arithmetic, all matrix dimensions must match. In MATLAB, this is accomplished through the repmat() function.

5. Find the eigenvectors of . Take the first few and combine them in a matrix , and use that as the in the dual PCA mapping and reconstruction steps shown above.

**Multidimensional Scaling (MDS)**

Most of the common linear and polynomial kernels do not give very good results in practice. For real data, there is an alternate approach that can yield much better results but, as we will see later, is equivalent to a kernel PCA process.

Multidimensional Scaling (MDS) is an algorithm, much like PCA, that maps the original high dimensional space to a lower dimensional space.

### Introduction to MDS

The main purpose of MDS is to try to map high dimensional data to a lower dimensional space while preserving the pairwise distances between points. ie: MDS addresses the problem of constructing a configuration of points in Euclidean space by using information about the distance between the patterns.

It may not be possible to preserve the exact distances between points, so in this case we need to find a representation that is as close as possible.

**Definition**: A matrix is called the **distance matrix** if:

is symmetric and its entries have the properties:

and

Given a distance matrix , MDS attempts to find data points in dimensions, such that if denotes the Euclidean distance between then is similar to .

### Metric MDS

One of the possible methods to preserve the pairwise distance is to use Metric MDS, which attempts to minimize:

where and

** Continued with MDS, Isomap and Classification - November 22, 2011**

The distance matrix can be converted to a kernel matrix of inner products by ,

where and is a column vector of all 1.

Now can be reduced to .

So far we have rewritten the objective function, but we must remember that our definition of introduces constraints on its components. We must ensure that these constraints are respected in the way we have expressed the minimization problem with traces. Luckily, we can capture these constraints with a single requirement thanks to the following theorem:

** Theorem**: Let be a distance matrix and . Then is Euclidean if and only if is a positive semi-definite matrix.

Therefore, to complete the rewriting of our original minimization problem from norms to traces, it suffices to impose that be , as this guarantees that is a distance matrix and the components of and satisfy the original constraints.

Proceeding with singular value decomposition, and can be decomposed as:

Since is , has no negative value and therefore: .

The above definitions help rewrite the cost function as:

Multiply on the left and on the right, we will get

Then let

We can rewrite the target function as:

For a fixed we can minimize for G. The result is that . Then we can simplify the target function:

Obviously, .

If is matrix, , the rank of is no greater than . Then the rank of is no greater than since . The dimension of is smaller than , so therefore the rank of is smaller than .

Since we want to do dimensionality reduction and make and as similar as possible, we can let be the top diagonal elements of .

We also have , obviously since .

The solution is:

where is the eigenvector of corresponding to the top
eigenvalues, and is the top eigenvalues of .

Compare this with dual PCA.

In dual PCA, the result is

.

Clearly, the result of dual PCA is the same with MDS. Actually, one property of PCA is to preserve the pairwise distances between data points in both high dimensional and low dimensional space.

Now as an appendix, we provide a short proof to the first equation .

Let be a vector where .

First notice as data are centered.

,

as all other terms contains or .

Hence, .

### Isomap (As per Handout - Section 1.6)

The Isomap algorithm is a nonlinear generalization of classical MDS with the main idea being that MDS is perfomed on the geodesic space of the non-linear data manifold as opposed to being performed on the input space. Isomap applies geodesic distances in the distance matrix for MDS rather than the straight line distances between the 2 points in order to find the low-dimensional mapping that preserves the pairwise distances. This geodesic distance is approximated by building a k-neighbourhood graph of all the points on the manifold and finding the shortest path to a given point. This gives a much better distance measurement in a manifold such as the 'Swiss Roll' manifold than using Euclidean distances.

**Note**: Geodesic distance is the shortest path along the curved surface of the manifold measured as if the surface was flat

Similarly to LLE, the Isomap algorithm proceeds in three steps:

1. Finding the neighbours of each data points in high-dimensional data space

2. Compute the geodesic pairwise distance between all points

3. Integrate the data via MDS in order to preserve the distances

**Process:**

1. Identify the k nearest neighbours or choose points from a fixed radius

2. Neighbour relations are represented by a graph G conneted with edges of weights

3. The geodesic distances, between all pair points on the manifold, M, are then estimated

**Note**: Isomap approximates as the shortest path distance in Graph G. The k in the algorithm must be chosen carefully, too small a k and the graph will not be connected, but to large a k, and the algorithm will be closer to the euclidean distance instead.

4. Isomap applies classical MDS to to generate an embedding of the data in d-dimensional Euclidean space Y

### Classification

Classification is a technique in pattern recognition. It can yield very complex decision boundaries as they are very suitable for ordered data, categorical data or a mixture of the two types. A decision or classification represents a multi-stage decision process where a binary decision is made at each stage.

**E.g**: A hand-written object can be scanned and recognized by the **classification** technique. The model realized the class it belongs to and pairs it with the corresponding object in its library.

Mathematically, each object have a set of features and a corresponding label which is the class it belongs to:

Since the training set is labelled with the correct answers, classification is called a "**supervised learning**" method.

In contrast, the **Clustering** technique is used to explore a data set whereby the main objective is to separate the sample into groups or to provide an understanding about the underlying structure or nature of the data. Clustering is an "**unsupervised classification**" method, because we do not know the groups that are in the data or any group characteristics of any unit observation. There are no labels to classify the data points, all we have is the feature set :

** Classification - November 24, 2011**

### Classification

Classification is predicting a discrete random variable Y (the label) from another random variable X. It is analogous to regression, but the difference between them is that regression uses continuous values, while classification uses discrete values (labels).

Consider iid data where

, representing an object,

is the label of the i-th object, and is some finite set.

We wish to determine a function that can predict the value of given the value . When we observe a new , predict to be .(We use h(x)) for the following discussion).

The difference between classification and clustering is that clustering do not have and it only puts into different classes.

#### Examples

**Object:** An image of a pepper'

The features are defined to be colour, length, diameter, and weight.

200px
**Features(X):** (Red,6,2,3.5)

**Labels(Y):** Red Pepper

The objective of classification is to use the classification function for unseen data - data for which we do not know the classification. Given the features, we want to classify the object, or in other words find the label. This is the typical classification problem.

**Real Life Examples**: Face Recognition - Pictures are just a points in high dimensional space; we can represent them in vectors. Sound waves can also be classified in a similar manner using Fourier Transforms. Classification is also used to find drugs which cure disease. Molecules are classified as either a good fit into the cavity of a protein, or not.

In machine learning, classification is also known as supervised learning. Often we separate the data set into two parts. One is called a training set and the other, a testing set. We use the training set to establish a classifier rule and use the testing set to test its effectiveness.

** Error Rate **

**Definition**: The true error rate of a classifier h is and the empirical error rate or training error rate is:

Where is the indicator function. That is, if the statement inside the bracket is true, and otherwise.

The empirical error rate is the the proportion of points that have not been classified correctly. It can be shown that this estimation always underestimates the true error rate, although we do not cover it in this course.
A way to get a better estimate of the error is to construct the classifier with half of the given data and use the other half to calculate the error rate.

** Bayesians vs Frequentists**

Bayesians view probability as the measure of confidence that a person holds in a proposition given certain information. They state a "prior probability" exist, which represents the possibility of a event's occurrence given no information. As we add new information regarding this event, our belief adjusts according to the new information, which gives us a posterior probability. Frequentists interpret probability as a "propensity" of some event.

** Bayes Classifier **

Consider the special case where , then

**Definition**: The Bayes classification rule h* is:

The set is called the decision boundary.

**Theorem:** The Bayes rule is optimal, that is, if is any other classification rule, then

So if Bayes rule is optimal, why do we need any other method? Well, we don't always know the distributions of the data. The Bayes rule depends on unknown quantities, so we need to use the data to find some approximation to the Bayes rule.

** Three Main Approaches **

1. Empirical Risk Minimization: Choose a set of classifiers H and find a that minimizes the expected value of some loss function . The distribution of (X,Y) is not known, therefore must be estimated using empirical data. For more conceptual knowledge on how this approach works, please refer to http://en.wikipedia.org/wiki/Empirical_risk_minimization

2. Regression: Find an estimate of the function and define:

3. Density Estimation: Estimate from the for which , and estimate from the for which and let:

Define

and define

So we have

where

** Multi-class Classification **

We want to generalize to the case that Y takes on more than two values

**Theorem:** Suppose that , the optimal rule is

where

with

A direct interpretation of this method called "naive Bayes classifier", is that the classifier chooses an y value which maximizes the probability of getting the current x value. In other words, the value y here can be viewed as a parameter as in maximum likelihood estimation, where the optimal value is .

** LDA, QDA and FDA - November 29, 2011**

** Linear Discriminant Analysis (LDA) and Quadratic Discriminant Analysis (QDA)**

The simplest approach to classification is to use the third approach listed above and assume a parametric model for densities.

Applying Bayes rule:

We notice that the denominator value is always the same independent of k; thus will be cancelled out. Hence we will only need to evaluate the numerator value.

Define class conditional distribution, prior distribution and posterior distribution as follows:

**LDA (Linear Discriminant Analysis)**

LDA is a classifier which makes the 2 assumptions:

- The class conditional distribution is Gaussian

where is the determinant of

- The two classes share the same covariance matrix

Thus the class conditional distribution for in LDA is as follows:

To demonstrate, suppose we have a two class scenario, i.e , and we want to compute the decision boundary for this LDA. Recall that the decision boundary is a set of points such that:

where the probability is given by:

Hence we want to find such that

Upon expanding , we get

Rearranging the equation and taking logarithm on both sides we get:

That is, after expanding the quadratic form of our vector values,

Cancelling out the terms and notice that is constant and a linear expression of , the final equation is simply linear system of equations:

**QDA (Quadratic Discriminant Analysis)**

If we relax the assumption in LDA that the covariances are identical between classes, the decision boundary becomes quadratic and we get QDA. Mathematically we mean that . In fact, we may also drop the assumption of a bi-class problem. QDA is therefore a more generalized version of LDA.

The general form of the boundary for a K-class problem is

and the classifier will be

In other words we would assign each to the label that produces the largest .

The reason for this becomes more obvious if we consider the components of .

Notice that the middle component (without the coefficient), , is expressing the squared Mahalanobis distance between and , the mean of class . Therefore, by requiring that is maximized, we are requiring this distance to be minimized. This makes sense from a classification perspective since it is intuitive to label with the class that it is closest to (on an average basis).

Also, to illustrate the role that plays, consider the case where each class is comprised of the same number of points so that . Then this term makes no difference in determining the appropriate label. But if a particular class is comprised of many more points than others, then is larger and increases the probability for this class (label) being assigned. This is intuitive as represents the probability of a class being . Therefore it must contribute to the probability that a point is in the class.

In practice when we estimate the parameters,

If we assume for all , then

which is the weighted average of all .

** Fischer Discriminant Analysis (optional) **

Recall that PCA finds the direction of maximum variance. Imagine PCA, MDS or Isomap as a pre-step to classification as they all reduce the dimension of the data. But if the classification is not based on the maximum variance, PCA will not work well in this case. Suppose we want to reduce a set of two-dimensional and two-class data to one dimension in order to classify them. One way to achieve this is to draw the data set in each class as close as possible (almost collapse into one point) and set these classes far apart to distinguish them. This is the intuitive interpretation of FDA. FDA does not carry the assumption of QDA and LDA, where the conditional probability distributions are a normally distributed, this allows a more flexible approach to classifying a data set.

We want to find vector to project every point to so that maximum variation occurs between classes. Say there are two classes 0 and 1. The points that label 0 has a mean of and the points that label 1 has a mean of . Then , and

To make the two classes as far away as possible, we want to

In other words,

We define , which is the between-class covariance.

On the other hand, we want the variance within the same class as small as possible, we want to

In other words,

We define , the within-class covariance.

Our question becomes,

Or equivalently, such that

Using the langrage multiplier, , we have

Therefore, is the eigenvector of (the eigenvector of the largest )

Generally, FDA is a better choice than PCA in classification.