This is intended to show how quanteda can be used with the text2vec package in order to replicate its gloVe example.

Download the corpus

Download a corpus comprising the texts used in the text2vec vignette:

wiki_corp <- quanteda.corpora::download(url = "https://www.dropbox.com/s/9mubqwpgls3qi9t/data_corpus_wiki.rds?dl=1")

Select features

First, we tokenize the corpus, and then get the names of the features that occur five times or more. Trimming the features before constructing the fcm:

wiki_toks <- tokens(wiki_corp)
feats <- dfm(wiki_toks, verbose = TRUE) %>%
    dfm_trim(min_termfreq = 5) %>%
    featnames()
## Creating a dfm from a tokens input...
##  ...lowercasing
##  ...found 1 document, 253,854 features
##  ...complete, elapsed time: 1.43 seconds.
## Finished constructing a 1 x 253,854 sparse dfm.
# leave the pads so that non-adjacent words will not become adjacent
wiki_toks <- tokens_select(wiki_toks, feats, padding = TRUE)

Construct the feature co-occurrence matrix

wiki_fcm <- fcm(wiki_toks, context = "window", count = "weighted", weights = 1 / (1:5), tri = TRUE)

Fit word embedding model

Fit the GloVe model using rsparse.

GloVe is an unsupervised learning algorithm for obtaining vector representations for words. Training is performed on aggregated global word-word co-occurrence statistics from a corpus, and the resulting representations showcase interesting linear substructures of the word vector space.

GloVe encodes the ratios of word-word co-occurrence probabilities, which is thought to represent some crude form of meaning associated with the abstract concept of the word, as vector difference. The training objective of GloVe is to learn word vectors such that their dot product equals the logarithm of the words’ probability of co-occurrence.

glove <- GlobalVectors$new(rank = 50, x_max = 10)
wv_main <- glove$fit_transform(wiki_fcm, n_iter = 10,
                               convergence_tol = 0.01, n_threads = 8)
## INFO  [18:43:23.603] epoch 1, loss 0.1619 
## INFO  [18:43:40.144] epoch 2, loss 0.1234 
## INFO  [18:43:56.243] epoch 3, loss 0.1074 
## INFO  [18:44:12.093] epoch 4, loss 0.0992 
## INFO  [18:44:28.221] epoch 5, loss 0.0943 
## INFO  [18:44:44.084] epoch 6, loss 0.0908 
## INFO  [18:44:59.947] epoch 7, loss 0.0882 
## INFO  [18:45:16.236] epoch 8, loss 0.0862 
## INFO  [18:45:32.448] epoch 9, loss 0.0845 
## INFO  [18:45:48.740] epoch 10, loss 0.0831
dim(wv_main)
## [1] 71290    50

Averaging learned word vectors

The two vectors are main and context. According to the Glove paper, averaging the two word vectors results in more accurate representation.

wv_context <- glove$components
dim(wv_context)
## [1]    50 71290
word_vectors <- wv_main + t(wv_context)

Examining term representations

Now we can find the closest word vectors for paris - france + germany

berlin <- word_vectors["paris", , drop = FALSE] -
  word_vectors["france", , drop = FALSE] +
  word_vectors["germany", , drop = FALSE]
library("quanteda.textstats")
cos_sim <- textstat_simil(x = as.dfm(word_vectors), y = as.dfm(berlin),
                          method = "cosine")
head(sort(cos_sim[, 1], decreasing = TRUE), 5)
##     paris   germany    berlin    munich        at 
## 0.7871978 0.6831811 0.6639100 0.6412553 0.6327915

Here is another example for london = paris - france + uk + england

london <-  word_vectors["paris", , drop = FALSE] -
    word_vectors["france", , drop = FALSE] +
    word_vectors["uk", , drop = FALSE] +
    word_vectors["england", , drop = FALSE]

cos_sim <- textstat_simil(as.dfm(word_vectors), y = as.dfm(london),
                          margin = "documents", method = "cosine")
head(sort(cos_sim[, 1], decreasing = TRUE), 5)
##    london   england        uk        at      york 
## 0.7727412 0.7699522 0.7602181 0.7554082 0.7486472