R 将text2vec嵌入应用于新数据

R 将text2vec嵌入应用于新数据,r,text2vec,R,Text2vec,我使用text2vec从包含大量行业专用术语的专有文本数据语料库中生成自定义单词嵌入(因此,像谷歌提供的那些股票嵌入将不起作用)。类比很有效,但我很难应用嵌入来评估新数据。我想使用我已经培训过的嵌入来理解新数据中的关系。我正在使用的方法(如下所述)看起来很复杂,而且速度非常慢。有更好的方法吗?也许包中已经有一些东西我只是错过了 以下是我的方法(提供了最接近可复制代码的方法,因为我使用的是专有数据源): d=包含新数据的列表。每个元素都具有类特征 vecs=从text2vec的手套实现中获得的单词

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

以下是我的方法(提供了最接近可复制代码的方法,因为我使用的是专有数据源):

d=包含新数据的列表。每个元素都具有类特征

vecs=从text2vec的手套实现中获得的单词矢量化

  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
new_vecs您需要在“批处理”模式下使用有效的线性代数矩阵运算来完成此操作。其思想是为文档
d
建立文档术语矩阵。该矩阵将包含每个单词在每个文档中出现多少次的信息。然后只需将
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