我希望有一种方法可以高效地计算tm :: DocumentTermMatrix文件之间的Jaccard相似度。我可以使用slam包中的类似方法来计算余弦相似度,如此答案所示。我在CrossValidated上遇到了一个与R相关但关于矩阵代数而不是最有效路线的另一个问题和回答。我尝试使用更有效的slam函数实现该解决方案,但与将DTM强制转换为矩阵并使用
#数据和软件包
我预期元素1和2之间的距离为0,元素3比元素1和4更接近元素1(我预期最远距离为0,因为没有共享单词),这在
编辑
请注意,即使在中等大小的DTM上,矩阵也会变得非常庞大。以下是使用vegan包的示例。注意需要4分钟来解决,而余弦相似性只需要约5秒钟。
proxy :: dist
时获得的解决方案不同。
我该如何在R中高效地计算大型DocumentTermMatrix文件之间的Jaccard相似度?#数据和软件包
library(Matrix);library(proxy);library(tm);library(slam);library(Matrix)
mat <- structure(list(i = c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 3L, 1L,
2L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), j = c(1L, 1L, 2L, 2L, 3L, 3L,
4L, 4L, 4L, 5L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L), v = c(1,
1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1), nrow = 4L,
ncol = 12L, dimnames = structure(list(Docs = c("1", "2",
"3", "4"), Terms = c("computer", "is", "fun", "not", "too",
"no", "it's", "dumb", "what", "should", "we", "do")), .Names = c("Docs",
"Terms"))), .Names = c("i", "j", "v", "nrow", "ncol", "dimnames"
), class = c("DocumentTermMatrix", "simple_triplet_matrix"), weighting = c("term frequency",
"tf"))
#低效计算(期望输出)
proxy::dist(as.matrix(mat), method = 'jaccard')
## 1 2 3
## 2 0.000
## 3 0.875 0.875
## 4 1.000 1.000 1.000
#我的尝试
A <- slam::tcrossprod_simple_triplet_matrix(mat)
im <- which(A > 0, arr.ind=TRUE)
b <- slam::row_sums(mat)
Aim <- A[im]
stats::as.dist(Matrix::sparseMatrix(
i = im[,1],
j = im[,2],
x = Aim / (b[im[,1]] + b[im[,2]] - Aim),
dims = dim(A)
))
## 1 2 3
## 2 2.0
## 3 0.1 0.1
## 4 0.0 0.0 0.0
输出结果不匹配。
以下是原始文本供参考:
c("Computer is fun. Not too fun.", "Computer is fun. Not too fun.",
"No it's not, it's dumb.", "What should we do?")
我预期元素1和2之间的距离为0,元素3比元素1和4更接近元素1(我预期最远距离为0,因为没有共享单词),这在
proxy::dist
解决方案中可以看到。编辑
请注意,即使在中等大小的DTM上,矩阵也会变得非常庞大。以下是使用vegan包的示例。注意需要4分钟来解决,而余弦相似性只需要约5秒钟。
library(qdap); library(quanteda);library(vegan);library(slam)
x <- quanteda::convert(quanteda::dfm(rep(pres_debates2012$dialogue), stem = FALSE,
verbose = FALSE, removeNumbers = FALSE), to = 'tm')
## <<DocumentTermMatrix (documents: 2912, terms: 3368)>>
## Non-/sparse entries: 37836/9769780
## Sparsity : 100%
## Maximal term length: 16
## Weighting : term frequency (tf)
tic <- Sys.time()
jaccard_dist_mat <- vegan::vegdist(as.matrix(x), method = 'jaccard')
Sys.time() - tic #Time difference of 4.01837 mins
tic <- Sys.time()
tdm <- t(x)
cosine_dist_mat <- 1 - crossprod_simple_triplet_matrix(tdm)/(sqrt(col_sums(tdm^2) %*% t(col_sums(tdm^2))))
Sys.time() - tic #Time difference of 5.024992 secs