Cosine Similarity Between Vectors

EasyML Coding

Problem statement

Cosine Similarity

Implement cosine_similarity(v1, v2) that returns the cosine of the angle between two vectors, a measure of direction that ignores length.

Input: v1, v2: NumPy arrays of the same shape, non-empty and with nonzero magnitude.

Output: a float in $[-1, 1]$.

Example

Input:

v1 = np.array([1, 2, 3])
v2 = np.array([2, 4, 6])
print(round(cosine_similarity(v1, v2), 3))

Output:

1.0

Reasoning: v2 is 2 times v1, so the two vectors point in exactly the same direction.

Show hint

Which quantity measures how aligned two vectors are, before any normalization?

Relevant roles: ML Engineer, AI Engineer, LLM Engineer, Data Scientist and Applied Scientist.

Related free problems