Car*_*rbo 3 nlp r similarity quanteda
我有一个包含 2 个文本字段的数据框:评论和主帖子
基本上这是结构
id comment post_text
1 "I think that blabla.." "Why is blabla.."
2 "Well, you should blabla.." "okay, blabla.."
3 ...
Run Code Online (Sandbox Code Playgroud)
我想计算第一行注释中的文本与第一行 post_text 中的文本之间的相似度,并对所有行执行此操作。据我所知,我必须为两种类型的文本创建单独的 dfm 对象
corp1 <- corpus(r , text_field= "comment")
corp2 <- corpus(r , text_field= "post_text")
dfm1 <- dfm(corp1)
dfm2 <- dfm(corp2)
Run Code Online (Sandbox Code Playgroud)
最后,我想获得这样的东西:
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 ...
Run Code Online (Sandbox Code Playgroud)
我不知道如何继续,我在 StackOverflow 文档之间的成对距离上找到了这个 ,但它们正在计算 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)
Run Code Online (Sandbox Code Playgroud)
但对角线只是 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
Run Code Online (Sandbox Code Playgroud)
现在,您可以使用矩阵子集划分出您想要的内容。(用于as.matrix()将输出转换textstat_simil()为矩阵。)