---
title: "3. Topic modeling"
author: "Thomas W. Jones"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{3. Topic modeling}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```


# Topic modeling

textmineR has extensive functionality for topic modeling. You can fit Latent Dirichlet Allocation (LDA), Correlated Topic Models (CTM), and Latent Semantic Analysis (LSA) from within textmineR. (Examples with LDA and LSA follow below.) As of this writing, textmineR's LDA and CTM functions are wrappers for other packages to facilitate a consistent workflow. (And textmineR takes advantage of the `RSpectra` package for LSA's single-value decomposition.) Plans exist to implement LDA natively with `Rcpp` sometime in 2018.

textmineR's consistent representation of topic models boils down to two matrices. The first, "theta" ($\Theta$), has rows representing a distribution of topics over documents. The second, phi ($\Phi$), has rows representing a distribution of words over topics. In the case of probabilistic models, these are categorical probability distributions. For non-probabilistic models (e.g. LSA) these distributions are, obviously, not probabilities. With LSA, for example, there is a third object representing the singular values in the decomposition.

In addition, textmineR has utility functions for topic models. This includes some original research. Examples include an R-squared for probabilistic topic models ([working paper here](https://drive.google.com/file/d/0Bz2enPyUvnKIQmtDTEswbzdUMU0/view)), probabilistic coherence (a measure of topic quality), and a topic labeling function based on most-probable bigrams. Other utilities are demonstrated below

```{r}
library(textmineR)

# load nih_sample data set from textmineR
data(nih_sample)

str(nih_sample)

# create a document term matrix 
dtm <- CreateDtm(doc_vec = nih_sample$ABSTRACT_TEXT, # character vector of documents
                 doc_names = nih_sample$APPLICATION_ID, # document names
                 ngram_window = c(1, 2), # minimum and maximum n-gram length
                 stopword_vec = c(stopwords::stopwords("en"), # stopwords from tm
                                  stopwords::stopwords(source = "smart")), # this is the default value
                 lower = TRUE, # lowercase - this is the default value
                 remove_punctuation = TRUE, # punctuation - this is the default
                 remove_numbers = TRUE, # numbers - this is the default
                 verbose = FALSE, # Turn off status bar for this demo
                 cpus = 2) # default is all available cpus on the system

dtm <- dtm[,colSums(dtm) > 2]

```


### LDA Example

To fit an LDA model in textmineR, use the `FitLdaModel` function. Input is a document term matrix. textmineR implements 2 methods for LDA, Gibbs sampling, and variational expectation maximization (also known as variational Bayes). The default is Gibbs sampling.

```{r }

# Fit a Latent Dirichlet Allocation model
# note the number of topics is arbitrary here
# see extensions for more info

set.seed(12345)

model <- FitLdaModel(dtm = dtm, 
                     k = 20,
                     iterations = 200, # I usually recommend at least 500 iterations or more
                     burnin = 180,
                     alpha = 0.1,
                     beta = 0.05,
                     optimize_alpha = TRUE,
                     calc_likelihood = TRUE,
                     calc_coherence = TRUE,
                     calc_r2 = TRUE,
                     cpus = 2) 

```

The output from the model is an S3 object of class `lda_topic_model`. It contains several objects. The most important are three matrices: `theta` gives $P(topic_k|document_d)$, `phi` gives $P(token_v|topic_k)$, and `gamma` gives $P(topic_k|token_v)$. (For more on `gamma`, see below.) Then `data` is the DTM or TCM used to train the model. `alpha` and `beta` are the Dirichlet priors for topics over documents and tokens over topics, respectively. The `log_likelihood` is $P(tokens|topics)$ at each iteration. `coherence` gives the probabilistic coherence of each topic. And `r2` is the R-squared of the model given the data. 

```{r }

str(model)

```

Once we have created a model, we need to evaluate it. For overall goodness of fit, textmineR has R-squared and log likelihood. R-squared is interpretable as the proportion of variability in the data explained by the model, as with linear regression. For a full derivation and explanation of properties. See the working paper, [here](https://drive.google.com/file/d/0Bz2enPyUvnKIQmtDTEswbzdUMU0/view).

The log likelihood has a more difficult interpretation. Though, as shown in the R-squared working paper, R-squared and log likelihood are highly correlated.

```{r }

# R-squared 
# - only works for probabilistic models like LDA and CTM
model$r2

# log Likelihood (does not consider the prior) 
plot(model$log_likelihood, type = "l")
```

Next, we turn our attention to topic quality. There are many "topic coherence" metrics available in the literature. For example, see [this paper](https://svn.aksw.org/papers/2015/WSDM_Topic_Evaluation/public.pdf) or [this paper](https://mimno.infosci.cornell.edu/nips2013ws/nips2013tm_submission_7.pdf). textmineR implements a new topic coherence measure based on probability theory. (A formal write up of this metric will be included in my PhD dissertation, expected 2020.)

Probabilistic coherence measures how associated words are in a topic, controlling for statistical independence. For example, suppose you have a corpus of articles from the sports section of a newspaper. A topic with the words {sport, sports, ball, fan, athlete} would look great if you look at correlation, without correcting for independence. But we actually know that it's a terrible topic because the words are so frequent in this corpus as to be meaningless. In other words, they are highly correlated with each other but they are statistically-independent of each other.

For each pair of words $\{a, b\}$ in the top M words in a topic, probabilistic coherence calculates $P(b|a) - P(b)$, where $\{a\}$ is more probable than $\{b\}$ in the topic.

Here's the logic: if we restrict our search to only documents that contain the word $\{a\}$, then the word $\{b\}$ should be more more probable in those documents than if chosen at random from the corpus. $P(b|a)$ measures how probable $\{b\}$ is only in documents containing $\{a\}$. $P(b)$ measures how probable $\{b\}$ is in the corpus as a whole. If $\{b\}$ is not more probable in documents containing $\{a\}$, then the difference $P(b|a) - P(b)$ should be close to zero.

For example, suppose the top 4 words in a topic are $\{a, b, c, d\}$. Then, we calculate

1. $P(a|b) - P(b)$, $P(a|c) - P(c)$, $P(a|d) - P(d)$
2. $P(b|c) - P(c)$, $P(b|d) - P(d)$
3. $P(c|d) - P(d)$

And all 6 differences are averaged together, giving the probabilistic coherence measure.

```{r fig.width = 7.5, fig.height = 4}
# probabilistic coherence, a measure of topic quality
# this measure can be used with any topic model, not just probabilistic ones
summary(model$coherence)

hist(model$coherence, 
     col= "blue", 
     main = "Histogram of probabilistic coherence")
```

We'll see the real value of coherence after calculating a few more objects. In the chunk below, we will 

1. Pull out the top 5 terms for each topic
2. Calculate the most frequent (prevalent) topics in the corpus
3. Get some bi-gram topic labels from a naive labeling algorithm
   (These naive labels are based on $P(\text{bi-gram}|\text{topic}) - P(\text{bi-gram})$. Noticing a theme?)

We'll then pull these together, along with coherence, into a table that summarizes the topic model.

```{r }
# Get the top terms of each topic
model$top_terms <- GetTopTerms(phi = model$phi, M = 5)
```

```{r eval = FALSE}
head(t(model$top_terms)
```


```{r, echo = FALSE}
knitr::kable(head(t(model$top_terms)), 
             col.names = rep("", nrow(model$top_terms)))
```


```{r}
# Get the prevalence of each topic
# You can make this discrete by applying a threshold, say 0.05, for
# topics in/out of docuemnts. 
model$prevalence <- colSums(model$theta) / sum(model$theta) * 100

# prevalence should be proportional to alpha
plot(model$prevalence, model$alpha, xlab = "prevalence", ylab = "alpha")

# textmineR has a naive topic labeling tool based on probable bigrams
model$labels <- LabelTopics(assignments = model$theta > 0.05, 
                            dtm = dtm,
                            M = 1)

head(model$labels)

# put them together, with coherence into a summary table
model$summary <- data.frame(topic = rownames(model$phi),
                            label = model$labels,
                            coherence = round(model$coherence, 3),
                            prevalence = round(model$prevalence,3),
                            top_terms = apply(model$top_terms, 2, function(x){
                              paste(x, collapse = ", ")
                            }),
                            stringsAsFactors = FALSE)

```

```{r eval = FALSE}
model$summary[ order(model$summary$prevalence, decreasing = TRUE) , ][ 1:10 , ]
```

```{r echo = FALSE}
knitr::kable(model$summary[ order(model$summary$prevalence, decreasing = TRUE) , ][ 1:10 , ], caption = "Summary of 10 most prevalent topics")

```

Ok, you've built a topic model. You've decided how well it fits your data. You've examined coherence, top words, and so on. Now you want to get topic distributions for new documents. `textmineR` provides a couple of ways to do this. The full Bayesian approach is to use Gibbs sampling, holding the topic distributions in `phi` fixed. The more frequentist way is using the `gamma` object returned when we ran `FitLdaModel`. (You can also calculate it separately with the `CalcGamma` function.)


`gamma` or $\Gamma$ is a matrix whose entries represent $P(\text{topic}|\text{token}). To calculate this, we need Bayes' Rule.  

The rows of `phi` or $\Phi$ are $P(\text{token}|\text{topic})$. However, to get predictions for new documents, we need $P(\text{topic}|\text{token})$. Remembering Bayes' Rule, we get

\begin{align}
  P(\text{topic}|\text{token}) 
    &= \frac{P(\text{token}|\text{topic})P(\text{topic})}{P(\text{token})}
\end{align}

Detail-oriented readers may wonder how you can get $P(\text{topic})$. We can get this through $\sum_j P(\text{topic}|\text{document}_j)P(\text{document}_j)$. 

For now, textmineR refers to the resulting matrix as $\Gamma$ or "phi prime". (Note: this will be called $\Gamma$ or "gamma" in textmineR version 3.0+.)

textmineR's `CalcPhiPrime` function does the above calculations for you. 

Once you have $\Gamma$, a simple dot product with the DTM of your new documents ($A$) will get new topic predictions. 

\begin{align}
  \Theta_{new} 
    &= A \cdot \Gamma^T
\end{align}

Both methods are available through `predict.lda_topic_model` with the `method` argument ("dot" or "gibbs"). Which method should you use? In most cases, I'd recommend "gibbs". However, "dot" is useful for speed if that's necessary. Also, `gamma` can be examined along with `phi` for corpus analysis.

Do note how much faster "dot" is when running the two below.

```{r fig.width = 7.5, fig.height = 4}

# predictions with gibbs
assignments <- predict(model, dtm,
                       method = "gibbs", 
                       iterations = 200,
                       burnin = 180,
                       cpus = 2)

# predictions with dot
assignments_dot <- predict(model, dtm,
                           method = "dot")


# compare
barplot(rbind(assignments[10,], assignments_dot[10,]),
        col = c("red", "blue"), las = 2, beside = TRUE)
legend("topright", legend = c("gibbs", "dot"), col = c("red", "blue"), 
       fill = c("red", "blue"))
```

If you compare the two methods in the image above, you can see that Gibbs sampling is slower, but has a much less noisy result.

### LSA Example

Latent semantic analysis was arguably the first topic model. [LSA was patented in 1988](https://en.wikipedia.org/wiki/Latent_semantic_analysis). It uses a [single value decomposition](https://en.wikipedia.org/wiki/Singular-value_decomposition) on a document term matrix, TF-IDF matrix, or similar. 

In textmineR's notation:

\begin{align}
  A &= \Theta \cdot S \cdot \Phi
\end{align}

$\Theta$ and $\Phi$ have the same (though non-probabilistic) interpretation as in LDA. $S$ is the matrix of single values. 

The workflow for LSA is largely the same for LDA. Two key differences: we will use the IDF vector mentioned above to create a TF-IDF matrix and we cannot get an R-squared for LSA as it is non-probabilistic. 

```{r }

# get a tf-idf matrix
tf_sample <- TermDocFreq(dtm)

tf_sample$idf[ is.infinite(tf_sample$idf) ] <- 0 # fix idf for missing words

tf_idf <- t(dtm / rowSums(dtm)) * tf_sample$idf

tf_idf <- t(tf_idf)

# Fit a Latent Semantic Analysis model
# note the number of topics is arbitrary here
# see extensions for more info
lsa_model <- FitLsaModel(dtm = tf_idf, 
                     k = 100)

# objects: 
# sv = a vector of singular values created with SVD
# theta = distribution of topics over documents
# phi = distribution of words over topics
# gamma = predition matrix, distribution of topics over words
# coherence = coherence of each topic
# data = data used to train model
str(lsa_model)
```

We cannot get a proper R-squared for an LSA model. (Actually, multiplying $\Phi \cdot S \cdot \Theta$ would give us exactly our document term matrix and an R-squared of $1$. There isn't really a proper interpretation of $\Phi \cdot \Theta$ with LSA.)

However, we can still use probabilistic coherence to evaluate individual topics. We'll also get our top terms and make a summary table as we did with LDA, above.

```{r fig.width = 7.5, fig.height = 4}
# probabilistic coherence, a measure of topic quality
# - can be used with any topic lsa_model, e.g. LSA

summary(lsa_model$coherence)

hist(lsa_model$coherence, col= "blue")

# Get the top terms of each topic
lsa_model$top_terms <- GetTopTerms(phi = lsa_model$phi, M = 5)
```

```{r eval = FALSE}
head(t(lsa_model$top_terms))
```

```{r echo = FALSE}
knitr::kable(head(t(lsa_model$top_terms)), 
             col.names = rep("", nrow(lsa_model$top_terms)))
```

```{r}

# Get the prevalence of each topic
# You can make this discrete by applying a threshold, say 0.05, for
# topics in/out of docuemnts. 
lsa_model$prevalence <- colSums(lsa_model$theta) / sum(lsa_model$theta) * 100

# textmineR has a naive topic labeling tool based on probable bigrams
lsa_model$labels <- LabelTopics(assignments = lsa_model$theta > 0.05, 
                            dtm = dtm,
                            M = 1)
```

```{r eval = FALSE}
head(lsa_model$labels)
```

```{r echo = FALSE}
knitr::kable(head(lsa_model$labels))

```

```{r}

# put them together, with coherence into a summary table
lsa_model$summary <- data.frame(topic = rownames(lsa_model$phi),
                            label = lsa_model$labels,
                            coherence = round(lsa_model$coherence, 3),
                            prevalence = round(lsa_model$prevalence,3),
                            top_terms = apply(lsa_model$top_terms, 2, function(x){
                              paste(x, collapse = ", ")
                            }),
                            stringsAsFactors = FALSE)
```

```{r eval = FALSE}
lsa_model$summary[ order(lsa_model$summary$prevalence, decreasing = TRUE) , ][ 1:10 , ]
```

```{r echo = FALSE}
knitr::kable(lsa_model$summary[ order(lsa_model$summary$prevalence, decreasing = TRUE) , ][ 1:10 , ], caption = "Summary of 10 most prevalent LSA topics")

```


One key mathematical difference is how you calculate $\Gamma$. For LSA the operation is

\begin{align}
  \Gamma &=
    (S\cdot\Phi)^{-1}
\end{align}


```{r}
# Get topic predictions for all 5,000 documents

# set up the assignments matrix and a simple dot product gives us predictions
lsa_assignments <- t(dtm / rowSums(dtm)) * tf_sample$idf

lsa_assignments <- t(lsa_assignments)

lsa_assignments <- predict(lsa_model, lsa_assignments)


```

In this case, there is no Bayesian/frequentist difference. So there's only one way to predict. Note that in the case above, we had to do the IDF reweighting before passing to `predict.lsa_topic_model`. 

```{r fig.width = 7.5, fig.height = 4}
# compare the "fit" assignments to the predicted ones
barplot(rbind(lsa_model$theta[ rownames(dtm)[ 1 ] , ],
              lsa_assignments[ rownames(dtm)[ 1 ] , ]), 
        las = 2,
        main = "Comparing topic assignments in LSA",
        beside = TRUE,
        col = c("red", "blue"))

legend("topleft", 
       legend = c("During fitting", "Predicted"),
       fill = c("red", "blue"))

```

### Other topic models

As of this writing, textmineR has implementations of

* LDA using Gibbs sampling implemented natively in textmineR
* LSA using a single value decomposition from the [`RSpectra`](https://CRAN.R-project.org/package=RSpectra) package
* Correlated topic models (CTM) from the [`topicmodels`](https://CRAN.R-project.org/package=topicmodels) package

A future version of textmineR will have an implementation of a structural topic model from the [`stm`](https://CRAN.R-project.org/package=stm) package. 

All of the above have nearly identical syntax and workflows as detailed above.

### Extensions

#### Document clustering is just a special topic model
Document clustering can be thought of as a topic model where each document contains exactly one topic. textmineR's `Cluster2TopicModel` function allows you to take a clustering solution and a document term matrix and turn it into a probabilistic topic model representation. You can use many of textmineR's topic model utilities to evaluate your clusters (e.g. R-squared, coherence, labels, etc.)

#### Choosing the number of topics
There is no commonly accepted way to choose the number of topics in a topic model. Fear not! Probabilistic coherence can help you. In forthcoming research, I show that probabilistic coherence can find the correct number of topics on a simulated corpus where the number of topics is known beforehand. (This will be part of a PhD dissertation, sometime around 2021. Stand by!)

Users can implement this procedure. Simply fit several topic models across a range of topics. Then calculate the probabilistic coherence for each topic in each model. Finally, average the probabilistic coherence across all topics in a model. This is similar to using the [silhouette coefficient](https://en.wikipedia.org/wiki/Silhouette_(clustering)) to select the number of clusters when clustering.

Some example code (on a trivially small dataset packaged with textmineR) is below.

```{r fig.width = 7.5, fig.height = 4}
# load a sample DTM
data(nih_sample_dtm)

# choose a range of k 
# - here, the range runs into the corpus size. Not recommended for large corpora!
k_list <- seq(10,85, by=15)

# you may want toset up a temporary directory to store fit models so you get 
# partial results if the process fails or times out. This is a trivial example, 
# but with a decent sized corpus, the procedure can take hours or days, 
# depending on the size of the data and complexity of the model.
# I suggest using the digest package to create a hash so that it's obvious this 
# is a temporary directory
model_dir <- paste0("models_", digest::digest(colnames(nih_sample_dtm), algo = "sha1"))

# Fit a bunch of LDA models
# even on this trivial corpus, it will take a bit of time to fit all of these models
model_list <- TmParallelApply(X = k_list, FUN = function(k){

  m <- FitLdaModel(dtm = nih_sample_dtm, 
                   k = k, 
                   iterations = 200, 
                   burnin = 180,
                   alpha = 0.1,
                   beta = colSums(nih_sample_dtm) / sum(nih_sample_dtm) * 100,
                   optimize_alpha = TRUE,
                   calc_likelihood = FALSE,
                   calc_coherence = TRUE,
                   calc_r2 = FALSE,
                   cpus = 1)
  m$k <- k
  
  m
}, export= ls(), # c("nih_sample_dtm"), # export only needed for Windows machines
cpus = 2) 

# Get average coherence for each model
coherence_mat <- data.frame(k = sapply(model_list, function(x) nrow(x$phi)), 
                            coherence = sapply(model_list, function(x) mean(x$coherence)), 
                            stringsAsFactors = FALSE)


# Plot the result
# On larger (~1,000 or greater documents) corpora, you will usually get a clear peak
plot(coherence_mat, type = "o")
    

```


#### Using topic models from other packages

Topic models from other packages can be used with textmineR. The workflow would look something like this:

1. Use `CreateDtm` to create a curated DTM
2. Use `Dtm2Docs` to re-create a text vector of curated tokens from your DTM
3. Fit a topic model using your desired package (for example, [mallet](https://CRAN.R-project.org/package=mallet))
4. Format the raw output to have two matrices, phi and theta as above
5. Use textmineR's suite of utility functions with your model

