## Motivation

Many real world applications involve observations and hidden (latent) variables . And often time we are interested in two problems.

- Given the current model, what are the probability of getting some hidden variable given the current observations? That is, what is ?
- Does our model match well with the data? That is, is reasonably high?

The first problem is an inference problem while the second problem is a model training problem. Typically, our model may be parametrized by some parameter, say . And in the second problem, more precisely we try to train the model by solving

Of course, if both conditional probability distributions are Gaussian, we probably can find the integral with a close form solution. However, for most distributions, such a solution does not exist. One may resort to numerical integrations. But Monte Carlo methods will often be simpler and more elegant.

Before discussing further on Monte Carlo methods, let’s also elaborate the first inference problem. Often time, we do not have a particular in mind that we want to compute . But instead we may want to find the most probable given , i.e., Maximum A Posteriori (MAP). That is

For low dimensional or scalar , we may be able to find the optimum with brute force. For high dimensional , the inference problem above easily become intractable as well.

## Basic Idea of Monte Carlo Methods

Ultimately, almost all Monte Carlo Methods are doing nothing but estimating the expectation of some function with by

,

where the above is guaranteed by the law of large number for sufficiently large .

For example, let’s consider the model training problem, we can approximate

,

where are sampled observation as we draw from and is an indicator function that is 1 when argument is satisfied and 0 otherwise.

For the inference problem, while we are not going to compute the maximum a posteriori directly as an expectation, we can draw samples with and , and then record the that maximizes .

## Basic Sampling Methods

The key question left is how we can sample data from a distribution. For some standard distributions like Gaussian distribution, we can draw sample directly with some well-developed packages. However, there is no direct way of drawing sample for many regular distribution, not to mention those do not even have a standard form. There are ways to sample any arbitary distributions, we will mention a couple simple ones here.

### Rejection Sampling

Probably the simplest sampling method is the rejection sampling. Consider drawing sample . Select any “sampleable” distribution such that with some constant . Now, instead of drawing sample from , we will draw from instead. However, in order to have the sample appear to have the same distribution of , we will only keep a fraction of whenever is drawn and discard the rest. To do this, we simply sample a from uniformly after each sampled. And keep the current only if .

### Importance Sampling

Rejection sampling is generally very inefficient as a large number of samples can be discarded. If we only care about computing the expection of some function, then we may not need to discard any sample but adjust the weight of each sample instead. Note that

.

Thus, we can estimate the expectation by drawing samples from and compute weighted average of instead. And the corresponding weights are .

Even though we can now utilize all samples, importance sampling has two concerns.

- Unlike rejection sampling, we do not directly draw samples with the desired distribution. So we can use those samples to do other things rather than computing expectation. For example, we cannot use that to maximize as described in the inference problem. Or at least, we would anticipate bias from our estimate.
- The variance of the estimate can be highly sensitive with the choice of . In particular, since the variance of the estimate is , the variance will be especially large if a more probable region in is not covered well by , i.e., we have extensive region where large but .

## Markov Chain Monte Carlo

Instead of sampling from directly, Markov chain Monte Carlo (MCMC) methods try to sample from a Markov chain (essentially a probabilistic state model). Probably two most important properties of the Markov chain are irreducible and aperiodic. We say a Markov chain is irreducible if we can reach any one state to any other state. And we say a Markov chain is periodic if there exist two states such that one state can reach the other state only in a multiple of steps with . If a Markov chain is not periodic, we say it is aperiodic. Under the above two conditions (aperiodic and irreducible), regardless the initial state, the distribution of states will converge to the steady state probability distribution asymptoically as time goes to infinity.

Consider any two connected states with transition probabilities (from to ) and (from to ). We say the detailed balance equations are satisfied if . Note that if detailed balance are satisfied among all states, has to be the steady state probability of state . Because the probability “flux” going out from to is exactly canceled by the “flux” coming in from to when the chain reaches this equalibrium.

With the disucssion above, we see that one can sample if we can create a Markov chain with designed to be the steady state probability of the chain (by making sure that detailed balance are satisfied). Note that, however, we have to let the chain to run for a while before the probability distribution converges to the steady state probabilty. Thus, samples before the chain reaching equilibrium are discard. This initial step is known as the “burn-in”. Moreover, since adjacent samples drawn from the chain (even after burn-in) are highly correlated, we may also skip every several samples to reduced correlation.

### Metropolis-Hastings

The most well-known MCMC method is the Metropolis-Hastings algorithm. Just as the discussion above, given the distribution , we want to design Markov chain such that satisfies the detailed balance for all states . Given the current state , the immediate question is to which state we should transit to. Assuming that , a simple possibility is just to do a random walk. Essentially perturb with a zero-mean Gaussian random noise. The problem is that the transition probability and the “reverse” transition probability most likely will not satisfy the detailed balance equation . Without loss of generality, we may have . To “balance” the equation, we may reject some of the transition to reduce the probability “flow” on the left hand side. More precisely, let’s denote . Now, we will randomly reject of the transition by drawing a uniform and only allowing transition if . And similar adjustment is applied to all transitions (including to ). This way, the transition probability from reduces to and so the detailed balance equation is satisfied.

When the transition probabilities from to and from to are equal (i.e., ), note that just simplifies to .

### Gibbs Sampling

When the state can be split into multiple component, say . We can transit one component at a time while keeping the rest fixed. For example, we can transit from to with probability . After updating one component, we can update another component in a similar manner until all components are updated. Then, the same procedure can be repeated starting with . As we continue to update the state, the sample drawn will again converge to as the Markov chain reaches equilibrium. This sampling method is known as the Gibbs sampling and can be shown as a special case of Metropolis-Hastings sampling as follows.

Consider the step when transiting from to while keeping the rest of components fixed. $A(x_1 \rightarrow x’_1)$ as defined earlier is $\frac{p(x_1,x_2,\cdots,x_n)p(x’_1|x_2,\cdots,x_n)}{p(x’_1,x_2,\cdots,x_n)p(x_1|x_2,\cdots,x_n)}=\frac{p(x_2,\cdots,x_n)p(x_1|x_2,\cdots,x_n)p(x’_1|x_2,\cdots,x_n)}{p(x_2,\cdots,x_n)p(x’_1|x_2,\cdots,x_n)p(x_1|x_2,\cdots,x_n)}=1$. Thus, Gibbs sampling is really Metropolis-Hasting sampling but with all transitions always be accepted.

### Hermiltonian Monte Carlo (HMC)

The trajectory sampled by Metropolis-Hasting method is essentially random walk like a drunk man. But we have the complete information of and we know how it looks like. Why don’t we leverage the “geometrical” information of ?

#### Power of Physics

We definitely can. And recall the Boltzmann distribution (ignoring temperature here) from statistical physics and we can model any distribution with a Boltzmann distribution with appropriate energy function . Further, we expect lower energy states are more likely to happen than higher energy states as expected.

If we think of as the potential energy, a “particle” naturally moves towards lower energy state and the excessive energy will convert to kinetic energy as we learn in Newtonian mechanics. Let’s write the total energy as , where the potential energy is just here. *(Sorry for the overloading of symbol here, is commonly used to represent momentum in physics and so we are sticking to that convention here. Please don’t be confuse with the in .)* And the kinetic energy with and being the momentum and the mass, respectively. The total energy, , also known as the Hamiltonian is supposed to be conserved as and naturally vary in the phase space . Therefore, .

As we know from classical mechanics, and . For example, let’s consider an object just moving vertically and is the height of the object, then , where is the gravitational force constant. Then with being the gravitational force and as desired. Moreover, the total energy indeed conserves as and changes as .

#### Back to Monte Carlo

Why are we talking all these? Because we can draw samples following natural physical trajectories more efficiently than random walks as in Metropolis-Hastings. Given the distribution of interest , we again define the Hamiltonian . Now, instead of trying to draw samples of , we will draw samples of instead. And . So if we marginalize out the momentum , we get back as desired.

And as we samples from the phase space , rather than random walking in the phase space, we can just follow the flow according to Hamiltonian mechanics as described earlier. For example, as we start from , we may simulate a short time instace to with and . One can also update first and then update . The latter has many different forms and sometimes known as the leapfrog integration. As we apply multiple () leapfrog steps and reach , we may decide whether to accept the sample as in Metropolis-Hasting by evaluating as the transition probabilities are assumed to be the same for both forward and reverse directions. Moreover, if the leapfrog integration is perfect, is supposed to the same as because of conservation of energy. So we have a high chance of accepting a sample.

### No-U-Turn Sampling (NUTS)

The main challenge of applying HMC is that the algorithm is quite sensitive to the number of leapfrog step and the step size (more commonly known as ). The goal of NUTS is to automatically select the above two parameters. The main idea is to simulate both forward and backward directions until the algorithm detects reaching a “boundary” and needed to go U-turn. By detecting U-turns, the algorithm can adjust the parameters accordingly. The criterion is simply to check if the momentum starts to turn direction, i.e., or , where and are the two extremes as we go forward and backward in time.

## Reference:

- https://en.wikipedia.org/wiki/Hamiltonian_Monte_Carlo
- Mackay, Information Theory, Inference, and Learning Algorithms
*Pattern Recognition and Machine Learning by Bishop*- A Conceptual Introduction to Hamiltonian Monte Carlo by Michael Betancourt
- The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo by Matthew D. Hoffman, Andrew Gelman