我想计算语料库作者之间的余弦距离.我们来看一个包含20个文档的语料库.
require(tm)
data("crude")
length(crude)
# [1] 20
Run Code Online (Sandbox Code Playgroud)
我想找出这20个文件中的余弦距离(相似度).我创建了一个术语 - 文档矩阵
tdm <- TermDocumentMatrix(crude,
control = list(removePunctuation = TRUE,
stopwords = TRUE))
Run Code Online (Sandbox Code Playgroud)
那么我将它转化成一个矩阵,它传递给dist()了的代理包
tdm <- as.matrix(tdm)
require(proxy)
cosine_dist_mat <- as.matrix(dist(t(tdm), method = "cosine"))
Run Code Online (Sandbox Code Playgroud)
最后我删除了余弦距离矩阵的对角线(因为我对文档与其自身之间的距离不感兴趣)并计算每个文档与语料库的另外19个文档之间的平均距离
diag(cosine_dist_mat) <- NA
cosine_dist <- apply(cosine_dist_mat, 2, mean, na.rm=TRUE)
cosine_dist
# 127 144 191 194
# 0.6728505 0.6788326 0.7808791 0.8003223
# 211 236 237 242
# 0.8218699 0.6702084 0.8752164 0.7553570
# 246 248 273 349
# 0.8205872 0.6495110 0.7064158 0.7494145
# 352 353 …Run Code Online (Sandbox Code Playgroud)