One critical component in Gibbs sampling for complex graphical models is to be able to draw samples from discrete distributions. Take latent Dirichlet allocation (LDA) as an example, the main computation focus is to draw samples from the following distribution:
(1)
where










So, a straightforward sampling algorithm works as follows:
- Let
be the right-hand side of Equation \eqref{eq:lda} for topic
, which is an un-normalized probability.
- We compute the accumulated weights as:
and
.
- Draw
and find
where
and
The last line is essentially to find the minimum index that the array value is greater than the random number .
One difficulty to deal with \eqref{eq:lda} is that the right hand side might be too small and therefore overflow (thinking about too many near-zero numbers multiplying). Thus, we want to deal with probabilities in log-space. We start to work with:
(2)

![Rendered by QuickLaTeX.com u \sim \mathcal{U}(0, 1) + \log C[K-1]](https://www.hongliangjie.com/wp-content/ql-cache/quicklatex.com-757adacd76c3040fd1dc0b04f9eb7e07_l3.png)

Notes:
- The log-sampling algorithm for LDA is implemented in Fugue Topic Modeling Package.
- Unless you really face the issue of overflow, sampling in log-space is usually much slower than the original space as log and exp are expensive functions to compute.