使用sklearn找到两个文本之间的字符串相似度,处理大量文档
假设你有一大堆文档,比如书名,现在你想比较两个不在这堆文档里的书名,或者不想重新计算整个TF-IDF矩阵,该怎么做呢?
举个例子,
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
book_titles = ["The blue eagle has landed",
"I will fly the eagle to the moon",
"This is not how You should fly",
"Fly me to the moon and let me sing among the stars",
"How can I fly like an eagle",
"Fixing cars and repairing stuff",
"And a bottle of rum"]
vectorizer = TfidfVectorizer(stop_words='english', norm='l2', sublinear_tf=True)
tfidf_matrix = vectorizer.fit_transform(book_titles)
如果你想检查第一个书名和第二个书名的相似度,可以这样做:
cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:2])
这样做的前提是TF-IDF是基于矩阵里的所有条目来计算的,所以每个词的权重会根据它在所有文档中出现的次数来决定。
现在假设你要比较两个书名,title1和title2,它们不在原来的书名列表里。你可以把这两个书名加到书名集合里,然后再进行比较,这样“rum”这个词就会被计算在内,包括之前文档里的出现次数:
title1="The book of rum"
title2="Fly safely with a bottle of rum"
book_titles.append(title1, title2)
tfidf_matrix = vectorizer.fit_transform(book_titles)
index = tfidf_matrix.shape()[0]
cosine_similarity(tfidf_matrix[index-3:index-2], tfidf_matrix[index-2:index-1])
但这样做在文档数量很大或者需要存储在内存之外时,实在是不太实际而且速度很慢。那么在这种情况下该怎么办呢?如果我只比较title1和title2,就不会使用之前的文档集合。
1 个回答
0
你为什么要把它们添加到列表里,然后重新计算所有的东西呢?直接这样做就行了:
new_vectors = vectorizer.transform([title1, title2])