【问题标题】:Apply text2vec embeddings to new data将 text2vec 嵌入应用到新数据
【发布时间】:2017-02-03 14:38:59
【问题描述】:

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

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

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

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 的元素粘贴在一起的操作都行不通,但肯定有比我拼凑的更好的方法.我觉得我一定遗漏了一些相当明显的东西。

任何帮助将不胜感激。

【问题讨论】:

    标签: r text2vec


    【解决方案1】:

    您需要使用高效的线性代数矩阵运算以“批处理”模式进行。这个想法是为文档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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 2018-08-13
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      相关资源
      最近更新 更多