Join Our 5-Week ML/AI Engineer Interview Bootcamp π led by ML Tech Leads at FAANGs
Compute cosine similarity between two vectors, a common linear algebra measure of how aligned they are. Itβs especially useful when you care about direction more than magnitude.
Implement the function
Rules:
float.scipy).np.dot, np.linalg.norm).Output:
| Argument | Type |
|---|---|
| x | np.ndarray |
| y | np.ndarray |
| Return Name | Type |
|---|---|
| value | float |
Use only NumPy; no SciPy similarity functions.
Return a single Python float.
Inputs same length; treat as 1D vectors.
Use np.dot(x, y) to compute the dot product (numerator).
Compute L2 norms using np.linalg.norm(x) and np.linalg.norm(y) (denominator).
Return dot / (norm_x * norm_y); guard against division by zero if needed.