我正在寻找一种有效的方法来为语料库中的(每个)目标词创建一个术语共现矩阵,这样每个词的出现都将在一个中医学中构成自己的向量(行),其中列是上下文单词(即基于标记的共现模型)。这与向量语义中使用的更常见的方法形成了对比,在向量语义中,每个术语(类型)都在对称的tcm中获得一行和一列,并且值被聚集在类型的标记的(共)点上。
显然,这可以从零开始使用基本的R功能,也可以通过过滤现有软件包生成的一个tcm来实现,但我正在处理的语料库数据相当大(数百万字)--而且已经有很好的语料库/NLP包可供R使用,可以高效地完成这些任务,并将结果存储在对内存友好的稀疏矩阵中--比如text2vec (function tcm)、quanteda (fcm)和tidytext (cast_dtm)。因此,尝试重新发明轮子似乎没有意义(在迭代器、散列和诸如此类方面)。但是,我也找不到一种简单的方法来创建一个基于令牌的中医,这也是一个问题。
最起码的例子:
library(text2vec)
library(Matrix)
library(magrittr)
# default approach to tcm with text2vec:
corpus = strsplit(c("here is a short document", "here is a different short document"), " ")
it = itoken(corpus)
tcm = create_vocabulary(it) %>% vocab_vectorizer() %>% create_tcm(it, . , skip_grams_window = 2, weights = rep(1,2))
# results in this:
print(as.matrix(forceSymmetric(tcm, "U")))
different here short document is a
different 0 0 1 1 1 1
here 0 0 0 0 2 2
short 1 0 0 2 1 2
document 1 0 2 0 0 1
is 1 2 1 0 0 2
a 1 2 2 1 2 0尝试获取基于令牌的模型,用于目标单词"short":
i=0
corpus = lapply(corpus, function(x)
ifelse(x == "short", {i<<-i+1;paste0("short", i)}, x )
) # appends index to each occurrence so itoken distinguishes them
it = itoken(corpus)
tcm = create_vocabulary(it) %>% vocab_vectorizer() %>% create_tcm(it, . , skip_grams_window = 2, weights = rep(1,2))
attempt = as.matrix(forceSymmetric(tcm, "U") %>%
.[grep("^short", rownames(.)), -grep("^short", colnames(.))]
) # filters the resulting full tcm
# yields intended result but is hacky/slow:
print(attempt)
different here document is a
short2 1 0 1 0 1
short1 0 0 1 1 1有什么更好/更快的替代方法来派生基于令牌的中医,如上一个示例所示?(可能使用一个已经完成基于类型的tcms的R包)
发布于 2018-10-23 18:12:50
quanteda的fcm是一种非常有效的方法,可以在文档级别或用户定义的上下文中记录特征共生矩阵,从而形成稀疏、对称的特征矩阵,但听起来似乎您希望每个唯一的特征都成为自己的行,并将其目标词围绕在这一行中。
从示例中可以看出,您需要一个+/- 2单词的上下文窗口,因此,我已经为目标单词"short“这样做了。
首先,我们使用上下文中的关键字获取上下文:
library("quanteda")
txt <- c("here is a short document", "here is a different short document")
(shortkwic <- kwic(txt, "short", window = 2))
#
# [text1, 4] is a | short | document
# [text2, 5] a different | short | document然后从上下文创建一个语料库,关键字作为唯一的文档名称:
shortcorp <- corpus(shortkwic, split_context = FALSE, extract_keyword = TRUE)
docnames(shortcorp) <- make.unique(docvars(shortcorp, "keyword"))
texts(shortcorp)
# short short.1
# "is a short document" "a different short document" 然后创建一个dfm,选择所有单词,但移除目标:
dfm(shortcorp) %>%
dfm_select(dfm(txt)) %>%
dfm_remove("short")
# Document-feature matrix of: 2 documents, 5 features (40% sparse).
# 2 x 5 sparse Matrix of class "dfm"
# features
# docs here is a document different
# short 0 1 1 1 0
# short.1 0 0 1 1 1https://stackoverflow.com/questions/52954330
复制相似问题