Testing: compare numpy arrays, allowing for specific mismatch

I have two numpy arrays containing integers that I compare with numpy.testing.assert_array_equal. Arrays are "fairly equal", i.e. Several elements are different, but given the size of my arrays, which is OK (in this particular case). But of course the test fails:

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)

Of course, it can be argued that a (long-term) clean solution for this would be to adapt the reference solution or something else, but I would prefer to simply resolve some inconsistency without failing the test. I would hope that for assert_array_equal there will be an option for this, but it is not.

, , , , , , . , , .

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, , , , .

+4
2

( ) ,

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]

, , . , , - .

+2

, , , , numpy.testing.assert_array_equal :

In [71]: x=np.arange(100).reshape(10,10)    
In [72]: y=np.arange(100).reshape(10,10)
In [73]: y[(5,7),(3,5)]=(3,5)

In [74]: np.sum(np.abs(x-y)>1)
Out[74]: 2

In [80]: np.sum(x!=y) 
Out[80]: 2

count_nonzero - ( numpy )

In [90]: np.count_nonzero(x!=y)
Out[90]: 2

:

assert_array_compare(operator.__eq__, x, y, err_msg=err_msg)

np.testing.utils.assert_array_compare - , nan inf.

x==y

count err_msg. , err_msg , .

, nan, .

+1

Source: https://habr.com/ru/post/1610173/


All Articles