Optimized method for calculating cosine distance in Python

前端 未结 8 882
被撕碎了的回忆
被撕碎了的回忆 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 22:04

    def cd(a,b):
        if(len(a)!=len(b)):
            raise ValueError, "a and b must be the same length"
        rn = range(len(a))
        adb = sum([a[k]*b[k] for k in rn])
        nma = sqrt(sum([a[k]*a[k] for k in rn]))
        nmb = sqrt(sum([b[k]*b[k] for k in rn]))
    
        result = 1 - adb / (nma*nmb)
        return result
    

提交回复
热议问题