NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

后端 未结 3 667
情歌与酒
情歌与酒 2020-12-05 15:27

I was calculating eigenvectors and eigenvalues of a matrix in NumPy and just wanted to check the results via assert(). This would throw a ValueError that I don\

相关标签:
3条回答
  • 2020-12-05 16:05

    try this=> numpy.array(yourvariable) followed by the command to compare, whatever you wish to.

    0 讨论(0)
  • 2020-12-05 16:08

    The error message explains it pretty well:

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

    What should bool(np.array([False, False, True])) return? You can make several plausible arguments:

    (1) True, because bool(np.array(x)) should return the same as bool(list(x)), and non-empty lists are truelike;

    (2) True, because at least one element is True;

    (3) False, because not all elements are True;

    and that's not even considering the complexity of the N-d case.

    So, since "the truth value of an array with more than one element is ambiguous", you should use .any() or .all(), for example:

    >>> v = np.array([1,2,3]) == np.array([1,2,4])
    >>> v
    array([ True,  True, False], dtype=bool)
    >>> v.any()
    True
    >>> v.all()
    False
    

    and you might want to consider np.allclose if you're comparing arrays of floats:

    >>> np.allclose(np.array([1,2,3+1e-8]), np.array([1,2,3]))
    True
    
    0 讨论(0)
  • 2020-12-05 16:10

    As it says, it is ambiguous. Your array comparison returns a boolean array. Methods any() and all() reduce values over the array (either logical_or or logical_and). Moreover, you probably don't want to check for equality. You should replace your condition with:

    np.allclose(A.dot(eig_vec[:,col]), eig_val[col] * eig_vec[:,col])
    
    0 讨论(0)
提交回复
热议问题