Optimized method for calculating cosine distance in Python

前端 未结 8 892
被撕碎了的回忆
被撕碎了的回忆 2021-02-14 21:27

I wrote a method to calculate the cosine distance between two arrays:

def cosine_distance(a, b):
    if len(a) != len(b):
        return False
    numerator = 0
         


        
8条回答
  •  终归单人心
    2021-02-14 21:58

    This is faster for arrays of around 1000+ elements.

    from numpy import array
    def cosine_distance(a, b):
        a=array(a)
        b=array(b)
        numerator=(a*b).sum()
        denoma=(a*a).sum()
        denomb=(b*b).sum()
        result = 1 - numerator / sqrt(denoma*denomb)
        return result
    

提交回复
热议问题