0

我想通过仅使用特定 POS 标签的单词来计算文本相似度。目前我正在使用余弦方法计算相似度,但它没有考虑 POS 标记。

A <- data.frame(name = c(
  "X-ray right leg arteries",
  "consultation of gynecologist",
  "x-ray leg arteries",
  "x-ray leg with 20km distance"
), stringsAsFactors = F)

B <- data.frame(name = c(
  "X-ray left leg arteries",
  "consultation (inspection) of gynecalogist",
  "MRI right leg arteries",
  "X-ray right leg arteries with special care"
), stringsAsFactors = F)

corp1 <- corpus(A, text_field = "name")
corp2 <- corpus(B, text_field = "name")

docnames(corp1) <- paste("A", seq_len(ndoc(corp1)), sep = ".")
docnames(corp2) <- paste("B", seq_len(ndoc(corp2)), sep = ".")

dtm3 <- rbind(dfm(corp1, ngrams=2), dfm(corp2, ngrams=2))
cosines <- lapply(docnames(corp2), 
                  function(x) textstat_simil(dtm3[c(x, docnames(corp1)), ],
                                             method = "cosine",
                                             selection = x)[-1, , drop = FALSE])
do.call(cbind, cosines)

在上面的示例中,“X 射线右腿动脉”不应映射到“MRI 右腿动脉”,因为这是两种不同的服务类别。不幸的是,我没有明确的服务分类。我只有服务文本。是否有可能通过使用 POS 标记,我可以更加重视这些词——“X 射线”、“咨询”、“腿”和“动脉”。代码中提到的服务只是一个示例。实际上,我有超过 10K 的服务。我探索了用于 PoS 标记的 udpipe 包,但没有取得多大成功。

4

1 回答 1

3

为了使用 udpipe 进行 pos 标记,您可以执行以下操作(基于您的示例数据 A 和 B)。

library(udpipe)
library(magrittr)
library(data.table)
txt <- rbindlist(list(A = A, B = B), idcol = "dataset")
txt$id <- sprintf("dataset%s_id%s", txt$dataset, seq_len(nrow(txt)))

# Tag using udpipe version 0.6 on CRAN which allows to show annotation progress
udmodel <- udpipe_download_model("english")
udmodel <- udpipe_load_model(udmodel$file_model)
txt_anno <- udpipe_annotate(udmodel, x = txt$name, doc_id = txt$id, trace = 5)
txt_anno <- as.data.table(txt_anno)

如果要根据引理的文档术语矩阵计算相似度,请执行以下操作(使用sim2Rtext2vec包)

# construct DTM with only nouns based on lemmas
dtm1 <- subset(txt_anno, upos %in% c("NOUN"), select = c("doc_id", "lemma")) %>% 
  document_term_frequencies %>% 
  document_term_matrix
library(text2vec)
sim2(dtm1, dtm1, method = "cosine")

如果您还想在游戏中添加名词的 ngram,请执行以下操作。提取一个接一个的名词,为这个新的复合术语创建一个文档/术语/矩阵,并将其与现有的文档术语矩阵结合起来,以便轻松运行文档相似性。

# Add ngrams of nouns in the game (2 nouns following one another with an optional punctuation in between)
keyw <- txt_anno[, keywords_phrases(x = upos, term = lemma, pattern = "NOUN(PUNCT)*NOUN", is_regex = TRUE), by = "doc_id"]
keyw <- keyw[, list(freq = .N), by = c("keyword", "ngram")]

# add a new column of this n-gram and create DTM
txt_anno <- txt_anno[, term := txt_recode_ngram(x = lemma, compound = keyw$keyword, ngram = keyw$ngram), by = "doc_id"]

dtm2 <- subset(txt_anno, term %in% keyw$keyword, select = c("doc_id", "term")) %>% 
  document_term_frequencies %>% 
  document_term_matrix

dtmcombined <- dtm_cbind(dtm1, dtm2)
colnames(dtmcombined)
sim2(dtmcombined, dtmcombined, method = "cosine")
于 2018-05-17T18:56:55.220 回答