0

我正在用python做一个问答项目。我已经有了问答文档的向量以及 tfidf 的值。但后来我不知道如何在 python 中计算相似度匹配。

4

3 回答 3

1

您可以使用 Levenshtein 距离,请看这里:http ://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python代码,这里:http : //en.wikipedia.org/wiki/Levenshtein_distance算法的讨论。

这是从上面的链接复制的片段:

def levenshtein(s1, s2):
    if len(s1) < len(s2):
        return levenshtein(s2, s1)
    if not s1:
        return len(s2)

    previous_row = xrange(len(s2) + 1)
    for i, c1 in enumerate(s1):
        current_row = [i + 1]
        for j, c2 in enumerate(s2):
            insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer
            deletions = current_row[j] + 1       # than s2
            substitutions = previous_row[j] + (c1 != c2)
            current_row.append(min(insertions, deletions, substitutions))
        previous_row = current_row

    return previous_row[-1]
于 2012-05-19T23:04:37.283 回答
1

余弦相似度

length_question = .0
length_answer = .0

for word_tfidf in question:
    length_question += word_tfidf**2

for word_tfdif in answer:
     length_answer += word_tfidf**2

similarity = .0
for word in question:
    question_word_tfidf = question[word]
    answer_word_tfidf = answer.get(word, 0)
    similarity += question_word_tfidf * answer_word_tfidf
similarity /= math.sqrt(length_question * length_answer)
于 2012-05-19T22:29:46.190 回答
1

您可以使用两个向量之间的欧几里得距离,或另一个距离度量(例如,汉明距离),或向量的互相关

于 2012-05-19T22:19:04.750 回答