需要协助编写余弦相似性的测试用例

问题描述 投票:2回答:1

这是我在下面执行的功能。

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):
python pycharm
1个回答
0
投票

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

根据上面的评论,您似乎正在寻求单元测试解决方案。本质上,您要在此处执行的操作是

  1. 提供一个替代实现-除非您能提出一种不同的测试余弦相似度的方法(例如,您可以生成先验已知余弦相似度的情况,但是除了特殊情况外,我不知道如何做到这一点)。
  2. 随机生成向量对。
  3. 对于每个向量对,请评估您的功能和替代实现,然后比较结果。注意舍入错误。
© www.soinside.com 2019 - 2024. All rights reserved.