我使用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
Run Code Online (Sandbox Code Playgroud)
对于我的用例,我需要为每个文档保持结果分开,所以任何涉及粘贴d元素的东西都不会起作用,但肯定必须有比我拼凑的更好的方法.我觉得我必须遗漏一些相当明显的东西.
任何帮助将不胜感激.
您需要使用高效的线性代数矩阵运算以"批处理"模式执行此操作.我们的想法是为文档提供文档术语矩阵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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
658 次 |
| 最近记录: |