This repo contains my attempt on implementing inference for Latent Dirichlet Allocation (LDA, sometimes also called "topic model"), a generative probabilistic model by Blei, Ng & Jordan (2003), with TensorFlow. I use the popular toy model from Griffiths & Steyvers (2004) to overwatch performance or at least whether the different approaches work at all.
The repo is structured in 3 notebooks:
tfp_monte_carlo.ipynbpresents a Hamiltonian Markov Chain Monte Carlo Approach that can be performed directly with the functionalities of the TensorFlow Probability package (tfp).tfp_variational_inference.ipynbpresents an (approximate) Variational Inference approach which can yet again be performed directly withintfp.custom_gibbs_sampling.ipynbpresents a custom approach, that implements both a Gibbs sampler (fully vectorized) and a collapsed Gibbs sampler (partly vectorized) as presented in the lecture by Philipp Hennig which was the initial reason for this repo.
These notebooks are complemented and source from a couple of .py-scripts files that add wrappers and the actual functionality of the Gibbs samplers as well as some data generation utlitiy.
Please understand that I will not provide full background infromation and mathematical "derivations" for everything; this is just a fun/side-project. Please refer to the resources mentioned above for details. I widely rely on the notation from the already mentioned lecture and use code like C_DIdK as representations for objects like
-
$K$ is the number of topics -
$D$ is the number of documents -
$I_d$ is the number of words in document$d$ -
$N_{\mathrm{max}}$ is the maximum number of words per doument, i. e.$N_{\mathrm{max}} = \max_d {I_d}$ -
$T$ is the total number of words, i. e.$T = \sum_d I_d$ -
$V$ is the vocabulary size which should be a square of an integer for the visualization purposes of this notebook.
The joint Distribution of LDA consists of:
1. Topic-Token prevalences (how much a topic "likes" a word):
2. Document-Topic prevalences (how much a document "likes" a topic):
3. Topic-word assignments in each document (iid for all
4. Actual words in a document:
This is equivalend to
Together this can be used to set up the joint:
In the Gibbs sampling implementation the Quantities from the mentioned lecture are needed, i. e.
1.
as much as possible. If the document lengths are variable, there is the choice between looping over the number of documents or padding the documents to a unique length. When padded this can be vectorized as the elementwise product of 2 tensors in
2.
which can be identitfied as a categorical distribution.
3.