quanteda:计算两个DFM之间的行的文本相似度

问题描述 投票:1回答:1

我有一个包含2个文本字段的数据框:评论和主要帖子

基本上这是结构

         id  comment                        post_text
          1   "I think that blabla.."        "Why is blabla.."
          2   "Well, you should blabla.."    "okay, blabla.."
          3    ...

我想计算第一行注释中的文本与第一行中post_text中的文本之间的相似性,并对所有行执行此操作。据我所知,我必须为两种类型的文本创建单独的dfm对象

          corp1 <- corpus(r , text_field= "comment")
          corp2 <- corpus(r , text_field= "post_text")
          dfm1 <- dfm(corp1)
          dfm2 <- dfm(corp2)

最后,我想得到这样的东西:

id  comment                     post_text          similarity
1   "I think that blabla.."     "Why is blabla.."  *similarity between comment1 and post_text1
2   "Well, you should blabla.." "okay, blabla.."  *similarity between comment2 and post_text2
3    ...

我不知道如何继续,我在StackOverflow Pairwise Distance between documents上发现了这个,但他们正在计算dfm之间的交叉相似性,而我需要按行相似,

所以基本上我认为是做以下事情:

      dtm <- rbind(dfm(corp1), dfm(corp2))
      d2 <- textstat_simil(dtm, method = "cosine", diag = TRUE)
      matrixsim<- as.matrix(d2)[docnames(corp1), docnames(corp2)]
      diagonale <- diag(matrixsim)

但对角线只是1 1 1 1的列表..

关于如何解决这个问题的任何想法?预先感谢您的帮助,

卡罗

r nlp similarity quanteda
1个回答
1
投票

我是通过创建一列文档来实现的,但是使用指示文档类型的文档名来区分它们。

df <- data.frame(
  id = c(1, 2),
  comment = c(
    "I think that blabla..",
    "Well, you should blabla"
  ),
  post_text = c(
    "Why is blabla",
    "okay, blabla"
  ),
  stringsAsFactors = FALSE
)

# stack these into a single "document" column, plus a docvar
# identifying the document type
df <- tidyr::gather(df, "source", "text", -id)
df
##   id    source                    text
## 1  1   comment   I think that blabla..
## 2  2   comment Well, you should blabla
## 3  1 post_text           Why is blabla
## 4  2 post_text            okay, blabla

library("quanteda")
## Package version: 1.4.3
## Parallel computing: 2 of 12 threads used.
## See https://quanteda.io for tutorials and examples.
## 
## Attaching package: 'quanteda'
## The following object is masked from 'package:utils':
## 
##     View

corp <- corpus(df)
docnames(corp) <- paste(df$id, df$source, sep = "_")
dfm(corp) %>%
  textstat_simil()
##               1_comment   2_comment 1_post_text
## 2_comment   -0.39279220                        
## 1_post_text -0.14907120 -0.09759001            
## 2_post_text -0.14907120  0.29277002  0.11111111

您现在可以使用矩阵子集切出您想要的内容。 (使用as.matrix()textstat_simil()的输出转换为矩阵。)

© www.soinside.com 2019 - 2024. All rights reserved.