Calculate the cosine similarity between two vectors. Cosine similarity measures the cosine of the angle between two non-zero vectors, indicating how similar their directions are regardless of magnitude.
import numpy as np
def cosine_similarity(v1, v2):
v1 = np.array(v1, dtype=float)
v2 = np.array(v2, dtype=float)
dot_product = np.dot(v1, v2)
norm_v1 = np.linalg.norm(v1)
norm_v2 = np.linalg.norm(v2)
if norm_v1 == 0 or norm_v2 == 0:
return 0.0
similarity = dot_product / (norm_v1 * norm_v2)
return round(float(similarity), 4)