gpt4 book ai didi

python - 测试:比较 numpy 数组,同时允许一定的不匹配

转载 作者:太空宇宙 更新时间:2023-11-03 11:00:48 25 4
gpt4 key购买 nike

我有两个包含整数的 numpy 数组,我正在与 numpy.testing.assert_array_equal 进行比较.数组“足够相等”,即一些元素不同,但考虑到我的数组的大小,这没关系(在这种特定情况下)。但是当然测试失败了:

AssertionError:
Arrays are not equal

(mismatch 0.0010541406645359075%)
x: array([[ 0., 0., 0., ..., 0., 0., 0.],
[ 0., 0., 0., ..., 0., 0., 0.],
[ 0., 0., 0., ..., 0., 0., 0.],...
y: array([[ 0., 0., 0., ..., 0., 0., 0.],
[ 0., 0., 0., ..., 0., 0., 0.],
[ 0., 0., 0., ..., 0., 0., 0.],...

----------------------------------------------------------------------
Ran 1 test in 0.658s

FAILED (failures=1)

当然,有人可能会争辩说(长期)干净的解决方案是调整引用解决方案或诸如此类的东西,但我更喜欢的是在测试失败的情况下简单地允许一些不匹配。我本来希望 assert_array_equal 有一个选项,但事实并非如此。

我已经写了一个函数,它允许我做我想做的事,所以问题可能被认为已经解决了,但是我只是想知道是否有更好、更优雅的方法来做到这一点 .此外,解析错误字符串的方法感觉很老套,但我还没有找到更好的方法来获取不匹配百分比值。

def assert_array_equal_tolerant(arr1,arr2,threshold):
"""Compare equality of two arrays while allowing a certain mismatch.

Arguments:
- arr1, arr2: Arrays to compare.
- threshold: Mismatch (in percent) above which the test fails.
"""
try:
np.testing.assert_array_equal(arr1,arr2)
except AssertionError as e:
for arg in e.args[0].split("\n"):
match = re.search(r'mismatch ([0-9.]+)%',arg)
if match:
mismatch = float(match.group(1))
break
else:
raise
if mismatch > threshold:
raise

需要说明的是:我不是在谈论 assert_array_almost_equal , 并且使用它也是不可行的,因为误差不小,对于单个元素可能很大,但仅限于极少数元素。

最佳答案

您可以尝试(如果它们是整数)在没有正则表达式的情况下检查不相等的元素数

unequal_pos = np.where(arr1 != arr2)
len(unequal_pos[0]) # gives you the number of elements that are not equal.

我不知道你是否认为这样更优雅。

由于np.where的结果可以作为索引,所以可以得到不匹配的元素

arr1[unequal_pos]

因此,您几乎可以使用该结果进行任何您喜欢的测试。取决于您希望如何通过不同元素的数量或元素之间的差异或更奇特的东西来定义不匹配。

关于python - 测试:比较 numpy 数组,同时允许一定的不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32934117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com