Cosine Similarity

Easy
~15 min
code completion

Cosine Similarity

Cosine similarity measures the angle between two vectors, ranging from -1 (opposite) to 1 (identical direction):

It's widely used in NLP (comparing word embeddings) and recommendation systems (comparing user/item vectors).

In NumPy:

np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v))

Your task:

Implement cosine_similarity(u, v) that returns the cosine similarity between two 1D vectors.

Example Tests

Identical vectors: similarity = 1.0

Input: {"u":[1,0],"v":[1,0]}

Expected: 1

Orthogonal vectors: similarity = 0.0

Input: {"u":[1,0],"v":[0,1]}

Expected: 0

Parallel vectors (not unit): similarity = 1.0

Input: {"u":[1,1],"v":[3,3]}

Expected: 1

Sign in to solve this problem

You can read the full problem statement above. Create a free account to run code in the browser, submit solutions, and track your progress.