How to Compute Cosine Similarity Between Two Vectors in Python
This code calculates the cosine similarity between two numeric vectors using the dot product and Euclidean norms, returning a value between -1 and 1.
Python code
19 linesimport math
def cosine_similarity(vec_a, vec_b):
if len(vec_a) != len(vec_b):
raise ValueError("Vectors must have the same length")
dot_product = sum(a * b for a, b in zip(vec_a, vec_b))
norm_a = math.sqrt(sum(a * a for a in vec_a))
norm_b = math.sqrt(sum(b * b for b in vec_b))
if norm_a == 0 or norm_b == 0:
return 0.0
return dot_product / (norm_a * norm_b)
if __name__ == "__main__":
vec1 = [1, 2, 3]
vec2 = [4, 5, 6]
print(cosine_similarity(vec1, vec2))
Output
0.9746318461970762
How it works
The function first validates that both vectors have the same length. It then computes the dot product of the two vectors and their Euclidean norms (square root of the sum of squares). The cosine similarity is the dot product divided by the product of the norms. If either norm is zero, it returns 0.0 to avoid division by zero. The result measures the cosine of the angle between the two vectors, where 1 means identical direction, 0 means orthogonal, and -1 means opposite directions.
Common mistakes
- Forgetting to check that vectors have the same length, causing a zip() to silently ignore extra elements.
- Not handling the case where a vector is all zeros, leading to a division by zero error.
- Using integer division or truncation instead of float division, losing the fractional part.
Variations
- Use numpy: np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) for large vectors.
- Use scipy.spatial.distance.cosine for a direct one-liner implementation.
Real-world use cases
- Computing similarity between document embeddings for a search or recommendation system.
- Comparing user preference vectors to find similar users in a collaborative filtering engine.
- Measuring the similarity between feature vectors in a machine learning model for clustering.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.