将 text2vec 嵌入应用于新数据

Apply text2vec embeddings to new data

我使用 text2vec 从包含大量行业特定行话的专有文本数据语料库生成自定义词嵌入(因此 google 提供的股票嵌入将不起作用)。类比效果很好,但我很难应用嵌入来评估新数据。我想使用我已经训练过的嵌入来理解新数据中的关系。我正在使用的方法(如下所述)看起来很复杂,而且速度慢得令人痛苦。有更好的方法吗?也许我只是错过了包中已经内置的东西?

这是我的方法(假设我使用的是专有数据源,我可以生成最接近可重现代码的方法):

d = 包含新数据的列表。每个元素都是class个字符

vecs = 从 text2vec 的 glove 实现中获得的词向量化

  new_vecs <- sapply(d, function(y){             
                    it <- itoken(word_tokenizer(y), progressbar=FALSE) # for each statement, create an iterator punctuation
                    voc <- create_vocabulary(it, stopwords= tm::stopwords()) # for each document, create a vocab 
                    vecs[rownames(vecs) %in% voc$vocab$terms, , drop=FALSE] %>% # subset vecs for the words in the new document, then 
                    colMeans # find the average vector for each document
                    })  %>% t # close y function and sapply, then transpose to return matrix w/ one row for each statement

对于我的用例,我需要将每个文档的结果分开,因此涉及将 d 的元素粘贴在一起的任何操作都不会起作用,但肯定有比我的方法更好的方法拼凑而成。我觉得我一定遗漏了一些相当明显的东西。

任何帮助将不胜感激。

您需要使用高效的线性代数矩阵运算以 "batch" 模式进行。这个想法是为文档d设置document-term矩阵。该矩阵将包含有关每个单词在每个文档中出现多少次的信息。然后只需要将 dtm 乘以嵌入矩阵:

library(text2vec)
# we are interested in words which are in word embeddings
voc = create_vocabulary(rownames(vecs))
# now we will create document-term matrix
vectorizer = vocab_vectorizer(voc)
dtm = itoken(d, tokenizer = word_tokenizer) %>% 
  create_dtm(vectorizer)

# normalize - calculate term frequaency - i.e. divide count of each word 
# in document by total number of words in document. 
# So at the end we will receive average of word vectors (not sum of word vectors!)
dtm = normalize(dtm)
# and now we can calculate vectors for document (average of vecors of words)
# using dot product of dtm and embeddings matrix
document_vecs = dtm %*% vecs