0

found this and this but doesn't solve my issue.

I want to perform unit test by comparing two tuples as a whole, not element-wise. The tuples involve with int and list of boolean. Length of the list varies in my real situation. For simplicity, i fix the length of list at 2 for demonstration purpose. so the function i want to unit test gave output format look like this:

A = some_function(input)
where 
$ some_function(input)
> (array([ True, True]), array([ True, False]), 2)

I tried to unit test A by creating B, like so:

B = (np.array([True, True]), np.array([True, False]), 2)

I have tried the followings but both return False instead of True as I'd expect. Why? how can i fix it?

np.array_equal(A,B) 
> False 
np.array_equiv(A,B)
> False 
A==B

>ValueError                                Traceback (most recent call last)
<ipython-input-125-2c88eac8e390> in <module>
      1 A=_tokenwise_to_entitywise(ref,hyp)
----> 2 B== (np.array([True,True]), np.array([True,False]), 2)
      3 
      4 A==B

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
ohmyan
  • 337
  • 2
  • 10

2 Answers2

1
>>> a
(array([ True,  True]), array([ True, False]), 2)
>>> b
(array([ True,  True]), array([ True, False]), 2)
>>> a==b
Traceback (most recent call last):
  File "<pyshell#75>", line 1, in <module>
    a==b
ValueError: The truth value of an array with more than one element is ambiguous. Use  a.any() or a.all()

The equality test compares element-wise. The ndarray comparisons return an ndarray.

>>> a[0]==b[0]
array([ True,  True])
>>> 

As the error message states this can be ambiguous. If you search SO for The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() you will find many Q&A's

>>> bool(a[0]==b[0])
Traceback (most recent call last):
  File "<pyshell#78>", line 1, in <module>
    bool(a[0]==b[0])
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> 

Your first link almost got you there, you just need to apply np.all to each element's comparison.

>>> all(np.all(x==y) for x,y in zip(a,b))
True
>>> #or
>>> any(map(np.all,zip(a,b)))
True
>>>

I'll have to think a bit to see if there is a better way.

wwii
  • 23,232
  • 7
  • 37
  • 77
-1

I can't comment yet but, the answer above should work.

or you could create a function for reusability.

def equality_check(A, B):
    X = True
    if A==B:
        X = True
    else:
        X = False
    return X

Then you can run

print(equality_check(A, B))

on any variables, lists, arrays, tuples, etc

or you can create boolean objects as

x = equality_check(A, B)
print(x)

This lets you store that boolean value for later use.

Hope this helps.

wwii
  • 23,232
  • 7
  • 37
  • 77