python - NumPy 错误 : The truth value of an array with more than one element is ambiguous. 使用 a.any() 或 a.all()

标签 python python-3.x numpy

我正在使用 numpy 编写图像卷积代码:

def CG(A, b, x, imax=10, epsilon = 0.01):
    steps=np.asarray(x)
    i = 0
    r = b - A * x
    d = r.copy()
    delta_new = r.T * r
    delta_0 = delta_new
    while i < imax and delta_new > epsilon**2 * delta_0:
        q = A * d
        alpha = float(delta_new / (d.T * q))
        x = x + alpha * d
        if i%50 == 0:
            r = b - A * x
        else:
            r = r - alpha * q
        delta_old = delta_new
        delta_new = r.T * r
        beta = float(delta_new / delta_old)
        d = r + beta * d
        i = i + 1
        steps = np.append(steps, np.asarray(x), axis=1)
    return steps

我收到以下错误:

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

在线 while i < imax and delta_new > epsilon**2 * delta_0:

谁能告诉我我做错了什么?

最佳答案

看起来 delta_newdelta_0 是 Numpy 数组,Numpy 不知道如何比较它们。

举个例子,想象一下如果你拿了两个随机的 Numpy 数组并尝试比较它们:

>>> a = np.array([1, 3, 5])
>>> b = np.array([5, 3, 1])
>>> print(a<b)
array([True, False, False])
>>> bool(a<b)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

基本上,您必须“选择”如何将所有数组中所有值的比较折叠为一个 bool 值。

>>> (a<b).any()
True

>>> (a<b).all()
False

关于python - NumPy 错误 : The truth value of an array with more than one element is ambiguous. 使用 a.any() 或 a.all(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54191677/

相关文章:

python - 当pandas中有混合列数据时添加条件滚动计数

python-3.x - 适用于 Windows 的 Python 3.5 缺少 tkinter

python-3.x - 传递值的长度为 1,索引意味着 260

python - 3D 二进制数组中到其他类型最近点的距离

python - 使用np.where使用自创建函数向pandas添加列

python - 使用 python 实现 Json 的 Excel

python - 应用程序启动失败,因为它的并行配置不正确 (Python/Pyinstaller/Tkinter)

python - 优化成对减法

python - Healpy 在 Windows 上安装 Python 3.4

python - 无法使用 Firefox 驱动程序打开网站