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

quanteda: calculate text similarity by row between two DFMs

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

基本上就是这个结构

         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    ...

我不确定如何继续,我在 Whosebug 上找到了这个 但是他们正在计算 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..

的列表

知道如何解决这个问题吗? 预先感谢您的帮助,

卡罗

我会通过创建单列文档来做到这一点,但使用指示文档类型的文档名来区分它们。

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() 的输出转换为矩阵。)