Calculate Cosine Similarity Between Vectors

Easy
Machine Learning

Task: Implement Cosine Similarity

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.

Input:

  • v1 and v2: Numpy arrays representing the input vectors.

Output:

  • A float representing the cosine similarity.

Constraints:

  • Both input vectors must have the same shape.
  • Input vectors cannot be empty or have zero magnitude.

Examples

Example 1:
Input: import numpy as np v1 = np.array([1, 2, 3]) v2 = np.array([2, 4, 6]) print(round(cosine_similarity(v1, v2), 3))
Output: 1.0
Explanation: The cosine similarity between v1 and v2 is 1.0, indicating perfect similarity (vectors point in the same direction).

Starter Code

import numpy as np

def cosine_similarity(v1, v2):
	"""
	Calculate the cosine_similarity of two vectors.
	Args:
		vec1 (numpy.ndarray): 1D array representing the first vector.
		vec2 (numpy.ndarray): 1D array representing the second vector.
	Returns:
		The cosine_similarity of the two vectors.
	"""
	# Implement your code here
	pass
Lines: 1Characters: 0
Ready
The AI Interview - Master AI/ML Interviews