TensorTonicTensorTonic
Problems
Study PlansProjectsNewInterviewPricingFeedback
Problems
Loading...
1 / 1

Implement Cosine Similarity

Linear Algebra
Easy

Compute the cosine similarity between two vectors:

cosine⁡(a,b)=a⋅b∥a∥2 ∥b∥2\operatorname{cosine}(a,b) = \frac{a \cdot b}{\lVert a \rVert_2 \, \lVert b \rVert_2}cosine(a,b)=∥a∥2​∥b∥2​a⋅b​

Here, a⋅ba \cdot ba⋅b is the dot product and ∥a∥2\lVert a \rVert_2∥a∥2​ and ∥b∥2\lVert b \rVert_2∥b∥2​ are Euclidean norms. For this problem, return 0.0 when either vector has zero norm. Otherwise, return the similarity as a Python float.

Loading visualization...

Examples

Input: a = [1, 2, 3], b = [2, 4, 6]

Output: 1.0

Explanation: One vector is a positive multiple of the other, so they point in the same direction.

Input: a = [1, 0], b = [0, 1]

Output: 0.0

Hint 1

Use np.dot(a, b) for the numerator.

Hint 2

Use np.linalg.norm() on both vectors before dividing.

Requirements

  • Compute the dot product and both Euclidean norms with NumPy
  • Return 0.0 when either vector has zero norm
  • Return a Python float

Constraints

  • a and b are equal-length, nonempty one-dimensional numeric lists
  • Each vector contains at most 10610^6106 values
  • Use NumPy only
Try Similar Problems
Dot ProductEuclidean DistanceManhattan DistanceJaccard SimilarityCosine Embedding Loss

Sign in to take notes on this problem

Case 1
Case 2

Accepts: array

Accepts: array

You must run your code first.
PrevNext

Implement Cosine Similarity

Linear Algebra
Easy

Compute the cosine similarity between two vectors:

cosine⁡(a,b)=a⋅b∥a∥2 ∥b∥2\operatorname{cosine}(a,b) = \frac{a \cdot b}{\lVert a \rVert_2 \, \lVert b \rVert_2}cosine(a,b)=∥a∥2​∥b∥2​a⋅b​

Here, a⋅ba \cdot ba⋅b is the dot product and ∥a∥2\lVert a \rVert_2∥a∥2​ and ∥b∥2\lVert b \rVert_2∥b∥2​ are Euclidean norms. For this problem, return 0.0 when either vector has zero norm. Otherwise, return the similarity as a Python float.

Loading visualization...

Examples

Input: a = [1, 2, 3], b = [2, 4, 6]

Output: 1.0

Explanation: One vector is a positive multiple of the other, so they point in the same direction.

Input: a = [1, 0], b = [0, 1]

Output: 0.0

Hint 1

Use np.dot(a, b) for the numerator.

Hint 2

Use np.linalg.norm() on both vectors before dividing.

Requirements

  • Compute the dot product and both Euclidean norms with NumPy
  • Return 0.0 when either vector has zero norm
  • Return a Python float

Constraints

  • a and b are equal-length, nonempty one-dimensional numeric lists
  • Each vector contains at most 10610^6106 values
  • Use NumPy only
Try Similar Problems
Dot ProductEuclidean DistanceManhattan DistanceJaccard SimilarityCosine Embedding Loss

Sign in to take notes on this problem

Case 1
Case 2

Accepts: array

Accepts: array

You must run your code first.