In this task, you need to implement a function cosine_similarity(v1, v2)
that calculates the cosine similarity between two vectors. Cosine similarity measures the cosine of the angle between two vectors, indicating their directional similarity.
v1
and v2
: Numpy arrays representing the input vectors.Input: v1 = np.array([1, 2, 3]) v2 = np.array([2, 4, 6]) print(cosine_similarity(v1, v2)) Output: 1.0
Example: import numpy as np v1 = np.array([1, 2, 3]) v2 = np.array([2, 4, 6]) print(cosine_similarity(v1, v2)) Output: 1.0
Measures the cosine of the angle between two vectors. Doesn't take into consideration the magnitude of the vectors but focuesses on the angle
\[ cos(\theta) = \frac{\sum_{i=1}^{p} A_i B_i}{\sqrt{\sum_{i=1}^{p} A_i^2} \sqrt{\sum_{i=1}^{p} B_i^2}} \]
Pitfalls
import numpy as np def cosine_similarity(v1, v2): if v1.shape != v2.shape: raise ValueError("Arrays must have the same shape") if v1.size == 0: raise ValueError("Arrays cannot be empty") # Flatten arrays in case of 2D v1_flat = v1.flatten() v2_flat = v2.flatten() dot_product = np.dot(v1_flat, v2_flat) magnitude1 = np.sqrt(np.sum(v1_flat**2)) magnitude2 = np.sqrt(np.sum(v2_flat**2)) if magnitude1 == 0 or magnitude2 == 0: raise ValueError("Vectors cannot have zero magnitude") return round(dot_product / (magnitude1 * magnitude2), 3)
There’s no video solution available yet 😔, but you can be the first to submit one at: GitHub link.