首页 > 编程语言 > 详细

余弦相似性计算及python代码实现

时间:2017-11-03 18:03:34      阅读:329      评论:0      收藏:0      [点我收藏+]

A:西米喜欢健身

B:超超不爱健身,喜欢打游戏

step1:分词

A:西米/喜欢/健身

B:超超/不/喜欢/健身,喜欢/打/游戏

step2:列出两个句子的并集

西米/喜欢/健身/超超/不/打/游戏

step3:计算词频向量

A:[1,1,1,0,0,0,0]

B:[0,1,1,1,1,1,1]

step4:计算余弦值

技术分享

 余弦值越大,证明夹角越小,两个向量越相似。

step5:python代码实现

    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

  

余弦相似性计算及python代码实现

原文:http://www.cnblogs.com/guoxueyuan/p/7779239.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!