need assistance with writing test cases for cosine similarity

Viewed 101

This is my function I made below.

def cosine_similarity(a,b):
    """
    Determins the similarity between two vectors, by computing the cosine of the angle between them
    :param Union[ndarray, Iterable, int, float] a: a non zero numeric vector
    :param Union[ndarray, Iterable, int, float] b: a non zero numeric vector
    :return: ndarray

    """
    norm_a = numpy.linalg.norm(a)
    norm_b = numpy.linalg.norm(b)
    if norm_a ==0 or norm_b ==0:
        raise ZeroDivisionError("Can not find the cosine between two vectors with following norms:{} {}".format(norm_a,norm_b))
    return numpy.dot(a,b)/(norm_a * norm_b)

I need help with writing test cases I have started it but am lost as i've never writing a test case

class TestCosineSimilarity(TestCase):
    def test_cosine_similarity_with_zero(self):
1 Answers

Classic libraries for testing in python are doctest and unittest. If you are just looking at using a few manually creates test cases, I'd recommend doctest. For more thorough testing using randomly generated test cases unittest is the library to use.

From your comment above, it looks like you are after a unittest solution. In essence, what you'll want to do here, it to

  1. Provide an alternative implementation - unless you can come up with a different way of testing cosine similarity (e.g. you could generate cases where the cosine similarity is known a priori, but I'm not seeing how you can do that except for special cases).
  2. Randomly generate pairs of vectors.
  3. For each vector pair, evaluate your function and the alternative implementation, and compare the results. Beware of rounding errors.
Related