标签:def png for bsp class from 集成 分享 turn
A:西米喜欢健身
B:超超不爱健身,喜欢打游戏
A:西米/喜欢/健身
B:超超/不/喜欢/健身,喜欢/打/游戏
西米/喜欢/健身/超超/不/打/游戏
A:[1,1,1,0,0,0,0]
B:[0,1,1,1,1,1,1]

余弦值越大,证明夹角越小,两个向量越相似。
from functools import reduce python3中reduce函数集成在functolls里面了
def mix(self):
merge_vdict = set(self.vdict1.keys()) | set(self.vdict2.keys()) #vdict1和vdict2分别为两个句子的TF_IDF值,merge_vdict为并集
for key in merge_vdict:
self.vdict1[key] = self.vdict1.get(key,0)
self.vdict2[key] = self.vdict2.get(key,0) #计算向量
#余弦函数的实现
def similar(self):
self.vector()
self.mix()
sum = 0
for key in self.vdict1:
sum += self.vdict1[key] * self.vdict2[key]
A = sqrt(reduce(lambda x,y: x+y, map(lambda x: x*x,self.vdict1.values())))
B = sqrt(reduce(lambda x,y: x+y, map(lambda x: x*x, self.vdict2.values())))
return sum/(A*B)
参考文献:http://www.ruanyifeng.com/blog/2013/03/tf-idf.html
http://www.ruanyifeng.com/blog/2013/03/cosine_similarity.html
标签:def png for bsp class from 集成 分享 turn
原文地址:http://www.cnblogs.com/guoxueyuan/p/7779239.html