Cosine Similarity Function
Implement cosine_similarity(vec1, vec2) from scratch using NumPy, exactly as shown in the notes, and test it on two given vectors.
Approach: compute the dot product of the two vectors, divide by the product of their magnitudes (norms).
Input: Two lines: the two vectors, each as space-separated numbers of the same length.
Output: One line: the cosine similarity, to 4 decimal places.
1 0 0 1 0 0
1.0000
- Neither vector is all zeros.
Hint 1
np.dot(vec1, vec2) computes the dot product.
Hint 2
np.linalg.norm(vec) computes a vector's magnitude (length).
Hint 3
Cosine similarity is dot_product / (norm1 * norm2) — a value close to 1 means very similar direction/meaning.
Cosine similarity measures the angle between two vectors: np.dot(vec1, vec2) gives their dot product, and dividing by the product of both vectors' magnitudes (np.linalg.norm) normalizes away any difference in length, leaving just a measure of direction — 1 for identical direction (perfectly similar), 0 for perpendicular (unrelated), matching the notes' own explanation exactly.