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

标签 r nlp similarity quanteda

我有一个包含 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.. 的列表

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

卡罗

最佳答案

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

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

关于r - quanteda:按行计算两个 DFM 之间的文本相似度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55629899/

相关文章:

r - 如何在 r 中从 gridExtra 主题化 tableGrob 对象

r - 在整行上按行使用 purrr 而不是 apply()

python - 随机生成相似的向量?

php - 从 facebook 和 twitter 好友中找到相似度分数的算法?

r - 2 个连续的嵌套 for 循环 - 是否可以使用 data.table 或 apply 进行优化?添加了 data.table 尝试尚未优化

c++ - 通过命令行使用 R 时出错

python - 不同长度向量的余弦相似度?

python - 使用 WN-Affect 检测字符串的情绪/心情

python - 如何将 CRAFT 语料库中的 XML NER 数据转换为 spaCy 的 JSON 格式?

NLTK wordnet 相似度返回 "None"形容词