Implement Cosine Similarity
Implement Cosine Similarity
Implement a function to compute the cosine similarity between two vectors a and b.
Cosine similarity measures the angle between two vectors in a high-dimensional space.
cosine_similarity(a,b)=∣∣a∣∣∣∣b∣∣a⋅bwhere:
- a · b is the dot product
- ||a|| and ||b|| are the Euclidean norms of a and b
Examples
Input: a=[1,2,3], b=[2,4,6]
Output: 1.0 (perfect alignment)
Input: a=[1,0], b=[0,1]
Output: 0.0 (orthogonal)
Hint 1
Use np.dot() for dot product and np.linalg.norm() for norms.
Hint 2
Handle zero vectors gracefully by checking if either norm is 0 and returning 0.0 in that case.
Requirements
- Input: 1D NumPy arrays of equal length
- Output: scalar float
- Must be fully vectorized (no loops)
- Handle zero vectors gracefully (return 0 if either norm is 0)
Constraints
- len(a) == len(b) ≤ 10⁶
- Use only NumPy
Log in to take notes on this problem
Accepts: array
Accepts: array
Implement Cosine Similarity
Implement Cosine Similarity
Implement a function to compute the cosine similarity between two vectors a and b.
Cosine similarity measures the angle between two vectors in a high-dimensional space.
cosine_similarity(a,b)=∣∣a∣∣∣∣b∣∣a⋅bwhere:
- a · b is the dot product
- ||a|| and ||b|| are the Euclidean norms of a and b
Examples
Input: a=[1,2,3], b=[2,4,6]
Output: 1.0 (perfect alignment)
Input: a=[1,0], b=[0,1]
Output: 0.0 (orthogonal)
Hint 1
Use np.dot() for dot product and np.linalg.norm() for norms.
Hint 2
Handle zero vectors gracefully by checking if either norm is 0 and returning 0.0 in that case.
Requirements
- Input: 1D NumPy arrays of equal length
- Output: scalar float
- Must be fully vectorized (no loops)
- Handle zero vectors gracefully (return 0 if either norm is 0)
Constraints
- len(a) == len(b) ≤ 10⁶
- Use only NumPy
Log in to take notes on this problem
Accepts: array
Accepts: array