距离矩阵计算在 R 中花费的时间太长

Distance matrix calculation taking too long in R

我在 R 中有一个术语文档矩阵 (tdm)(由大约 16,000 个文本的语料库创建),我正在尝试创建一个距离矩阵,但它没有加载,我不确定它需要多长时间应该采取(它已经超过 20 分钟)。我还尝试使用文档术语矩阵格式创建距离矩阵,但它仍然无法加载。有什么我可以做的来加快这个过程。对于 tdm,行是文本文档,列是可能的词,因此矩阵单元格中的条目是每个文档中每个给定词的计数。 这是我的代码的样子:

library(tm)
library(slam)
library(dplyr)
library(XLConnect)
wb <- loadWorkbook("Descriptions.xlsx")
df <- readWorksheet(wb, sheet=1) 
docs <- Corpus(VectorSource(df$Long_Descriptions))
docs <- tm_map(docs, removePunctuation) %>%
  tm_map(removeNumbers) %>%
  tm_map(content_transformer(tolower), lazy = TRUE) %>%
  tm_map(removeWords, stopwords("english"), lazy = TRUE) %>%
  tm_map(stemDocument, language = c("english"), lazy = TRUE) 
dtm <- DocumentTermMatrix(docs)
tdm <- TermDocumentMatrix(docs, control = list(removePunctuation = TRUE, stopwords = TRUE))
z<-as.matrix(dist(t(tdm), method = "cosine"))

(我知道我的代码应该是可重现的,但我不确定如何共享我的数据。excel 文档只有一列标题 Long_Descriptions,行值的示例是逗号分隔如下:我喜欢猫,我是狗人,我有三只兔子,我是猫人,但我想要一只宠物兔)

余弦距离是两个具有 L2 归一化的矩阵的简单点积。在您的情况下,它甚至更简单 - L2 标准化 dtm 在 dtm 转置上的乘积。这是使用 Matrixtext2vec 包的可重现示例:

library(text2vec)
library(Matrix)

cosine <- function(m) {
  m_normalized <- m / sqrt(rowSums(m ^ 2))
  tcrossprod(m_normalized)
}

data("movie_review")
data = rep(movie_review$review, 3)
it = itoken(data, tolower, word_tokenizer)
v = create_vocabulary(it) %>% 
  prune_vocabulary(term_count_min = 5)
vectorizer = vocab_vectorizer(v)
it = itoken(data, tolower, word_tokenizer)
dtm = create_dtm(it, vectorizer)
dim(dtm)
# 15000 24548

system.time( dtm_cos <- cosine(dtm) )
# user  system elapsed 
# 41.914   6.963  50.761 
dim(dtm)
# 15000 15000

编辑: 对于 tm 包,请参阅此问题: