计算2个向量中每个单词之间的Jaccard相似度

时间:2016-11-25 11:17:51

标签: r stringdist

我需要计算2个向量中每个单词之间的Jaccard相似度。每个单词由每个单词组成。并提取最相似的词。

这是我糟糕的慢速代码:

txt1 <- c('The quick brown fox jumps over the lazy dog')
txt2 <- c('Te quick foks jump ovar lazey dogg')

words <- strsplit(as.character(txt1), " ")
words.p <- strsplit(as.character(txt2), " ")

r <- length(words[[1]])
c <- length(words.p[[1]])

m <- matrix(nrow=r, ncol=c)
for (i in 1:r){
  for (j in 1:c){
    m[i,j] = stringdist(tolower(words.p[[1]][j]), tolower(words[[1]][i]), method='jaccard', q=2)
  }
}

ind <- which(m == min(m))-nrow(m)
words[[1]][ind]

请帮助我改进和美化大数据框架的代码。

1 个答案:

答案 0 :(得分:3)

准备(在此处添加tolower):

txt1 <- c('The quick brown fox jumps over the lazy dog')
txt2 <- c('Te quick foks jump ovar lazey dogg')

words <- unlist(strsplit(tolower(as.character(txt1)), " "))
words.p <- unlist(strsplit(tolower(as.character(txt2)), " "))

获取每个单词的距离:

dists <- sapply(words, Map, f=stringdist, list(words.p), method="jaccard")

words中的每个单词都会找到words.p中最接近的单词:

matches <- words.p[sapply(dists, which.min)]

cbind(words, matches)
              matches
 [1,] "the"   "te"
 [2,] "quick" "quick"
 [3,] "brown" "ovar"
 [4,] "fox"   "foks"
 [5,] "jumps" "jump"
 [6,] "over"  "ovar"
 [7,] "the"   "te"
 [8,] "lazy"  "lazey"
 [9,] "dog"   "dogg"

编辑:

要获得最匹配的单词对,首先需要选择words中每个单词与words.p中所有单词的最小距离:

mindists <- sapply(dists, min)

这将为每个单词提供最佳距离。然后从words选择具有最小距离的单词:

words[which.min(mindists)]

或者在一行中:

words[which.min(sapply(dists, min))]