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 object...
##  ...complete, elapsed time: 1.01 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  [06:52:39.256] epoch 1, loss 0.1622
## INFO  [06:52:48.035] epoch 2, loss 0.1234
## INFO  [06:52:56.628] epoch 3, loss 0.1075
## INFO  [06:53:05.277] epoch 4, loss 0.0994
## INFO  [06:53:13.767] epoch 5, loss 0.0944
## INFO  [06:53:22.553] epoch 6, loss 0.0909
## INFO  [06:53:31.320] epoch 7, loss 0.0883
## INFO  [06:53:39.956] epoch 8, loss 0.0862
## INFO  [06:53:48.601] epoch 9, loss 0.0845
## INFO  [06:53:57.085] 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)
##    berlin     paris    munich   germany    vienna 
## 0.7759296 0.7564411 0.6913558 0.6839486 0.6821692

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      york   england        uk        at 
## 0.8227079 0.7770074 0.7607893 0.7503975 0.7293530