Optimized method for calculating cosine distance in Python

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

    No need to take abs() of a[i] and b[i] if you're squaring it.

    Store a[i] and b[i] in temporary variables, to avoid doing the indexing more than once. Maybe the compiler can optimize this, but maybe not.

    Check into the **2 operator. Is it simplifying it into a multiply, or is it using a general power function (log - multiply by 2 - antilog).

    Don't do sqrt twice (though the cost of that is small). Do sqrt(denoma * denomb).

提交回复
热议问题