← back

Calculate Cosine Similarity Between Vectors

#76 · Linear Algebra · Easy

⊣ Solve on deep-ml.com

Problem

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.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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)

Explanation

  1. Compute the dot product of the two vectors: sum of element-wise products.
  2. Compute the L2 norm (magnitude) of each vector.
  3. Cosine similarity = dot(v1, v2) / (||v1|| * ||v2||).
  4. Result ranges from -1 (opposite directions) through 0 (orthogonal) to 1 (same direction).
  5. Widely used in NLP for comparing document/word embeddings and in recommendation systems.

Complexity

  • Time: O(n) where n is the dimensionality of the vectors
  • Space: O(1)