Skip to content
DeepForgeby svx
All problems
EasyML Fundamentalsml-046

Cosine Similarity of Feature Vectors

Problem

Compute the cosine similarity between two vectors: (a . b) / (||a|| * ||b||).

If the lengths differ or either vector has zero norm, return 0.0.

Hint

Normalize the dot product by both vector norms.

Test cases

case 1
in: [[1,2,3],[1,2,3]]
expected: 1
case 2
in: [[1,0],[0,1]]
expected: 0
case 3
in: [[1,2],[2,4]]
expected: 0.9999999999999998
case 4
in: [[1,2,3],[-1,-2,-3]]
expected: -1
Starter codePython
import math
def cosine_similarity(a, b):
    # Your code here
    pass

4 test cases · run your code against them in the editor