【发布时间】:2021-08-04 11:22:04
【问题描述】:
我在这个堆栈溢出问题中遵循了 Fred Foo 的解释:How to compute the similarity between two text documents?
我已经运行了他编写的以下代码:
from sklearn.feature_extraction.text import TfidfVectorizer
corpus = ["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.T
print(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 = ["I'd like an apple",
"An apple a day keeps the doctor away"]
再次运行相同的代码,我得到了矩阵:
[[1. 0.19431434]
[0.19431434 1. ]]
因此它们的相似度发生了变化(在第一个矩阵中,它们的相似度为 0.17668795)。为什么会这样?我真的很困惑。 提前谢谢!
【问题讨论】:
-
它使用语料库中的所有单词计算相似度 - 结果取决于语料库中所有句子中的单词数。当语料库中的单词较少时,相似度可能会有所不同。
-
如果你把同一个句子放入语料库,那么它也会改变结果。如果你把它两次,那么它也会改变结果。它不仅检查两个句子的相似之处,还检查它们与其余句子的不同之处
-
哦,好吧好吧,这很有道理!感谢您清晰而直接的解释。请把它作为答案,我会接受的! :) 祝你好运!
标签: python machine-learning nlp text-processing