1. Text embeddings

Thomas W. Jones


Text embeddings

Text embeddings are particularly hot right now. While textmineR doesn’t (yet) explicitly implement any embedding models like GloVe or word2vec, you can still get embeddings. Text embedding algorithms aren’t conceptually different from topic models. They are, however, operating on a different matrix. Instead of reducing the dimensions of a document term matrix, text embeddings are obtained by reducing the dimensions of a term co-occurrence matrix. In principle, one can use LDA or LSA in the same way. In this case, rows of theta are embedded words. A phi_prime may be obtained to project documents or new text into the embedding space.

Create a term co-occurrence matrix

The first step in fitting a text embedding model is to create a term co-occurrence matrix or TCM. In a TCM, both columns and rows index tokens. The \((i,j)\) entries of the matrix are a count of the number of times word \(i\) co-occures with \(j\). However, there are several ways to count co-occurrence. textmineR gives you three.

The most useful way of counting co-occurrence for text embeddings is called the skip-gram model. Under the skip-gram model, the count would be the number of times word \(j\) appears within a certain window of \(i\). A skip-gram window of two, for example, would count the number of times word \(j\) occured in the two words immediately before word \(i\) or the two words immediately after word \(i\). This helps capture the local context of words. In fact, you can think of a text embedding as being a topic model based on the local context of words. Whereas a traditional topic model is modeling words in their global context.

To read more about the skip-gram model, which was popularized in the embedding model word2vec, look here.

The other types of co-occurence matrix textmineR provides are both global. One is a count of the number of documents in which words \(i\) and \(j\) co-occur. The other is the number of terms that co-occur between documents \(i\) and \(j\). See help(CreateTcm) for info on these.

# load the NIH data set

# load nih_sample data set from textmineR

# First create a TCM using skip grams, we'll use a 5-word window
# most options available on CreateDtm are also available for CreateTcm
tcm <- CreateTcm(doc_vec = nih_sample$ABSTRACT_TEXT,
                 skipgram_window = 5,
                 verbose = FALSE,
                 cpus = 2)

# a TCM is generally larger than a DTM
#> [1] 5210 5210

Fitting a model

Once we have a TCM, we can use the same procedure to make an embedding model as we used to make a topic model. Note that it may take considerably longer (because of dimensionality of the matrix) or shorter (because of sparsity) to fit an embedding on the same corpus.

# use LDA to get embeddings into probability space
# This will take considerably longer as the TCM matrix has many more rows 
# than a DTM
embeddings <- FitLdaModel(dtm = tcm,
                          k = 100,
                          iterations = 500,
                          cpus = 2)

Interpretation of \(\Phi\) and \(\Theta\)

In the language of text embeddings, \(\Theta\) gives us our tokens embedded in a probability space (because we used LDA, Euclidean space if we used LSA). \(\Phi\) defines the dimensions of our embbeding space. The rows of \(\Phi\) can still be interpreted as topics. But they are topics of local contexts, rather than within whole documents.

Evaluating the model

As it happens, the same evaluation metrics developed for topic modeling also apply here. There are subtle differences in interpretation because we are using a TCM not a DTM. i.e. occurrences relate words to each other, not to documents.

# Get an R-squared for general goodness of fit
embeddings$r2 <- CalcTopicModelR2(dtm = tcm, 
                                  phi = embeddings$phi,
                                  theta = embeddings$theta,
                                  cpus = 2)

#> [1] 0.2842953

# Get coherence (relative to the TCM) for goodness of fit
embeddings$coherence <- CalcProbCoherence(phi = embeddings$phi,
                                          dtm = tcm)

#>     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
#> -0.01198  0.01593  0.05257  0.06208  0.09449  0.20367

We will create a summary table as we did with a topic model before.

# Get top terms, no labels because we don't have bigrams
embeddings$top_terms <- GetTopTerms(phi = embeddings$phi,
                                    M = 5)
# Create a summary table, similar to the above
embeddings$summary <- data.frame(topic = rownames(embeddings$phi),
                                 coherence = round(embeddings$coherence, 3),
                                 prevalence = round(colSums(embeddings$theta), 2),
                                 top_terms = apply(embeddings$top_terms, 2, function(x){
                                   paste(x, collapse = ", ")
                                 stringsAsFactors = FALSE)

Here it is ordered by prevalence. (Here, we might say density of tokens along each embedding dimension.)

embeddings$summary[ order(embeddings$summary$prevalence, decreasing = TRUE) , ][ 1:10 , ]
Summary of top 10 embedding dimensions
topic coherence prevalence top_terms
t_91 t_91 0.170 142.28 aim, specific, study, research, studies
t_70 t_70 0.160 108.97 research, core, program, support, training
t_46 t_46 0.155 89.50 health, research, cancer, clinical, prevention
t_22 t_22 0.148 87.55 cells, cell, human, mast, aim
t_29 t_29 0.094 77.72 response, brain, human, tissue, responses
t_69 t_69 0.095 72.85 data, studies, work, results, molecular
t_90 t_90 0.123 69.92 genetic, mechanisms, expression, gene, specific
t_59 t_59 0.113 67.57 factor, carbon, genes, pathways, information
t_12 t_12 0.080 65.98 treatment, effect, intervention, therapy, design
t_49 t_49 0.073 65.78 hiv, based, assess, programs, strategies

And here is the table ordered by coherence.

embeddings$summary[ order(embeddings$summary$coherence, decreasing = TRUE) , ][ 1:10 , ]
Summary of 10 most coherent embedding dimensions
topic coherence prevalence top_terms
t_44 t_44 0.204 52.02 microbiome, gut, composition, crc, bas
t_34 t_34 0.181 52.77 fertility, ethnic, race, differences, study
t_95 t_95 0.181 52.14 memory, sleep, dependent, cellular, cognitive
t_73 t_73 0.170 51.11 secondary, ptc, primary, brafv, pathways
t_91 t_91 0.170 142.28 aim, specific, study, research, studies
t_72 t_72 0.163 47.03 signaling, mediated, activation, nrf, critical
t_70 t_70 0.160 108.97 research, core, program, support, training
t_71 t_71 0.156 55.49 influenza, vaccine, strain, antigen, protective
t_46 t_46 0.155 89.50 health, research, cancer, clinical, prevention
t_21 t_21 0.151 45.04 power, family, force, sarcomere, dependence

Embedding documents under the model

You can embed whole documents under your model. Doing so, effectively makes your embeddings a topic model that have topics of local contexts, instead of global ones. Why might you want to do this? The short answer is that you may have reason to believe that an embedding model may give you better topics, especially if you are trying to pick up on more subtle topics. In a later example, we’ll be doing that to build a document summarizer.

# Make a DTM from our documents
dtm_embed <- CreateDtm(doc_vec = nih_sample$ABSTRACT_TEXT,
                       doc_names = nih_sample$APPLICATION_ID,
                       ngram_window = c(1,1),
                       verbose = FALSE,
                       cpus = 2)

dtm_embed <- dtm_embed[ , colnames(tcm) ] # make sure vocab lines up

# Get phi_prime, the projection matrix
embeddings$phi_prime <- CalcPhiPrime(phi = embeddings$phi,
                                     theta = embeddings$theta)

# Project the documents into the embedding space
embedding_assignments <- dtm_embed / rowSums(dtm_embed)

embedding_assignments <- embedding_assignments %*% t(embeddings$phi_prime)

embedding_assignments <- as.matrix(embedding_assignments)

Once you’ve embedded your documents, you effectively have a new \(\Theta\). We can use that to evaluate how well the embedding topics fit the documents as a whole by re-calculaing R-squared and coherence.

# get a goodness of fit relative to the DTM
embeddings$r2_dtm <- CalcTopicModelR2(dtm = dtm_embed, 
                                      phi = embeddings$phi,
                                      theta = embedding_assignments,
                                      cpus = 2)

#> [1] 0.1665389

# get coherence relative to DTM
embeddings$coherence_dtm <- CalcProbCoherence(phi = embeddings$phi,
                                              dtm = dtm_embed)

#>     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
#> -0.06445  0.01766  0.05761  0.09177  0.13063  0.60910

Where to next?

Embedding research is only just beginning. I would encourage you to play with them and develop your own methods.