【发布时间】:2020-07-31 04:40:27
【问题描述】:
问题 我试图回答这个问题:考虑两个文档 A 和 B,它们的欧几里得距离为 d,余弦相似度为 c(除了原始词频之外不使用归一化)。如果我们通过将 A 附加到自身来创建一个新文档 A',并通过将 B 附加到自身来创建另一个文档 B',那么:
a.A' 和 B' 之间的欧几里得距离是多少(使用原始词频)?
我的解决方案
doc1 = "the quicker brown dogs easily jumps over the lazy dogs"
doc2 = "the quicker dogs pose a serious problem for lazy dogs"
def calc_term_frequency(doc : list):
dic = {}
for word in doc.split():
if word in dic:
dic[word] = dic[word] + 1
else:
dic[word]= 1
for word, frequency in dic.items():
dic[word]= frequency / len(doc.split())
return dic
tfs_doc1 = calc_term_frequency(doc1)
tfs_doc2 = calc_term_frequency(doc2)
print(tfs_doc1)
将 tfs_doc1 输出为: {'the': 0.2, 'quicker': 0.1, 'brown': 0.1, 'dogs': 0.2, 'easy': 0.1, 'jumps': 0.1, 'over': 0.1, 'lazy': 0.1} 这似乎应该起作用。然后我继续计算欧几里得距离,首先在 doc1 和 doc1 之间,然后在 doc1 和 doc2 之间,如下所示。
import math
math.sqrt(sum((tfs_doc1.get(k, 0) - tfs_doc1.get(k, 0))**2 for k in set(tfs_doc1.keys()).union(set(tfs_doc1.keys())))) # output: 0
math.sqrt(sum((tfs_doc1.get(k, 0) - tfs_doc2.get(k, 0))**2 for k in set(tfs_doc1.keys()).union(set(tfs_doc2.keys())))) # output: 0.316227766016838
这给了我 0.316227766016838 的分数。当我尝试使用 sklearn 验证这是否正确时,如下所示:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import euclidean_distances
corpus_vect = CountVectorizer().fit_transform(corpus).todense()
print(euclidean_distances(corpus_vect[0], corpus_vect[0])) # output: 0
print(euclidean_distances(corpus_vect[0], corpus_vect[1] )) # output: 3.
我得到 [[0.]] [[3.]] 的输出,它转换为我的“手动”结果的 round(, 1)。
问题:当我尝试回答最初的问题并“加倍”字符串时,例如
doc1 = "the quicker brown dogs easily jumps over the lazy dogs the quicker brown dogs easily jumps over the lazy dogs"
doc2 = "the quicker dogs pose a serious problem for lazy dogs the quicker dogs pose a serious problem for lazy dogs"
使用“sklearn 方法”/矢量化器时,我得到了手动技术 (0.316227766016838) 的相同输出,但是 [[0.]] [[6.]]。因此,使用一种方法 ED 保持不变,使用另一种方法则加倍!
什么是正确的解决方案以及导致差异的原因是什么?真的卡在这里了。提前致谢。
【问题讨论】:
标签: python scikit-learn nlp data-science