我按照Fred Foo在Stack Overflow上的解释执行了以下代码:如何计算两个文本文档之间的相似度?
我运行了他写的以下代码:
from sklearn.feature_extraction.text import TfidfVectorizercorpus = ["I'd like an apple", "An apple a day keeps the doctor away", "Never compare an apple to an orange", "I prefer scikit-learn to Orange", "The scikit-learn docs are Orange and Blue"]vect = TfidfVectorizer(min_df=1, stop_words="english")tfidf = vect.fit_transform(corpus)pairwise_similarity = tfidf * tfidf.Tprint(pairwise_similarity.toarray())
结果是:
[[1. 0.17668795 0.27056873 0. 0. ] [0.17668795 1. 0.15439436 0. 0. ] [0.27056873 0.15439436 1. 0.19635649 0.16815247] [0. 0. 0.19635649 1. 0.54499756] [0. 0. 0.16815247 0.54499756 1. ]]
但我注意到当我将corpus设置为:
corpus = ["I'd like an apple", "An apple a day keeps the doctor away"]
并再次运行相同的代码时,我得到了以下矩阵:
[[1. 0.19431434] [0.19431434 1. ]]
因此它们的相似度发生了变化(在第一个矩阵中,它们的相似度是0.17668795)。为什么会这样?我真的很困惑。提前感谢您!
回答:
在维基百科上,您可以看到如何计算Tf-idf
N
– 语料库中的文档数量。
因此,相似度取决于语料库中所有文档/句子的数量。
如果您有更多的文档/句子,那么结果就会改变。
如果您多次添加相同的文档/句子,结果也会改变。