【问题标题】:Numpy : The truth value of an array with more than one element is ambiguousNumpy : 具有多个元素的数组的真值是不明确的
【发布时间】:2015-03-06 22:05:33
【问题描述】:

我真的很困惑为什么会出现这个错误。这是我的代码:

import numpy as np

x = np.array([0, 0])
y = np.array([10, 10])
a = np.array([1, 6])
b = np.array([3, 7])
points = [x, y, a, b]
max_pair = [x, y]
other_pairs = [p for p in points if p not in max_pair]
>>>ValueError: The truth value of an array with more than one element is ambiguous. 
Use a.any() or a.all()
(a not in max_paix)
>>>ValueError: The truth ...

让我感到困惑的是以下工作正常:

points = [[1, 2], [3, 4], [5, 7]]
max_pair = [[1, 2], [5, 6]]
other_pairs = [p for p in points if p not in max_pair]
>>>[[3, 4], [5, 7]]
([5, 6] not in max_pair)
>>>False

为什么在使用 numpy 数组时会发生这种情况? not in/in 是否存在模棱两可?
使用any()\all() 的正确语法是什么?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    Numpy 数组定义了一个自定义相等运算符,即它们是实现 __eq__ 魔术函数的对象。因此,== 运算符和所有其他依赖于这种相等性的函数/运算符调用此自定义相等函数。

    Numpy 的相等性基于数组的元素比较。因此,作为回报,您会得到另一个带有布尔值的 numpy 数组。例如:

    x = np.array([1,2,3])
    y = np.array([1,4,5])
    x == y
    

    返回

    array([ True, False, False], dtype=bool)
    

    但是,in 运算符与 lists 组合需要仅返回 single 布尔值的相等比较。这就是错误要求allany 的原因。例如:

    any(x==y)
    

    返回True,因为结果数组中至少有一个值是True。 对比一下

    all(x==y) 
    

    返回False,因为不是结果数组的所有值都是True

    因此,在您的情况下,解决问题的方法如下:

    other_pairs = [p for p in points if all(any(p!=q) for q in max_pair)]
    

    print other_pairs 打印出预期的结果

    [array([1, 6]), array([3, 7])]
    

    为什么会这样?好吧,我们从 points 中寻找一个项目 p,其中 any 的条目不等于 all 的条目max_pair 中的项目 q

    【讨论】:

    • in 运算符需要相等比较,这非常有帮助!我想得到的结果(not in)是用[p for p in points if all(any(p!=q) for q in max_pair)]得到的。
    • 啊,是的,对不起,我更正了 :-),错过了 not in
    【解决方案2】:

    背后的原因是它们完全是两个不同的对象。 np.array 有自己的操作员在上面工作。

    它们与全局运算符anyall 命名相同,但工作方式不完全相同,这种区别反映在它们是np.array 的方法这一事实上。

    >>> x = np.array([0,9])
    >>> x.any(axis=0)
    True
    >>> y = np.array([10, 10])
    >>> y.all()
    True
    >>> y.all(axis=0)
    True
    

    同时:

    >>> bool([])
    False
    >>> bool([[]])
    True
    >>> bool([[]][0])
    False
    

    注意第一个结果如何为假(在 python2 中)一个空列表被视为False。但是,其中包含另一个列表的列表,即使该列表为空,也不是False,而是True。评估内部列表再次返回False,因为它是空的。由于anyall 是在转换为bool 时定义的,因此您看到的结果是不同的。

    >>> help(all)
    all(...)
        all(iterable) -> bool
        Return True if bool(x) is True for all values x in the iterable.
    
    >>> help(any)
    any(...)
        any(iterable) -> bool
        Return True if bool(x) is True for any x in the iterable.
    

    查看逻辑 numpy 运算符的更好解释here

    【讨论】:

      猜你喜欢
      • 2019-03-19
      • 2020-03-15
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 2019-08-21
      • 2021-07-06
      相关资源
      最近更新 更多