I'm trying to implement cosine similarity for two vectors, but I ran into a special case where the two vectors only have one component, like this:
v1 = [3]
v2 = [4]
Here is my implementation for the cosine similarity:
def dotProduct(v1, v2):
if len(v1) != len(v2):
return 0
return sum([x * y for x, y in zip(v1, v2)])
def cosineSim(v1, v2):
dp = dotProduct(v1, v2)
mag1 = math.sqrt(dotProduct(v1, v1))
mag2 = math.sqrt(dotProduct(v2, v2))
return dp / (mag1 * mag2)
The cosine similarity for any two vectors that only have one component is always 1 then. Can someone guide me through how to handle this special case? Thank you.