首页 > 解决方案 > 需要帮助编写余弦相似度的测试用例

问题描述

这是我在下面制作的功能。

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)

我在编写测试用例方面需要帮助 我已经开始了它,但是因为我从未编写过测试用例而迷失了方向

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

标签: pythonpycharm

解决方案


用于在 python 中进行测试的经典库是doctestunittest。如果您只是想使用一些手动创建的测试用例,我建议您使用 doctest。为了使用随机生成的测试用例进行更彻底的测试,unittest 是要使用的库。

从您上面的评论来看,您似乎正在寻求一个单元测试解决方案。本质上,你在这里想要做的,它

  1. 提供一个替代实现——除非你能想出一种不同的测试余弦相似度的方法(例如,你可以生成余弦相似度是先验已知的情况,但除了特殊情况外,我看不到你如何做到这一点)。
  2. 随机生成向量对。
  3. 对于每个向量对,评估您的函数和替代实现,并比较结果。小心舍入错误。

推荐阅读