NumPy错误:具有多个元素的数组的真值不明确.使用a.any()或a.all() [英] NumPy Error: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

查看:179
本文介绍了NumPy错误:具有多个元素的数组的真值不明确.使用a.any()或a.all()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用numpy处理图像卷积代码:

I am working on an Image Convolution code using 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:

任何人都可以告诉我我做错了什么吗?

Could anyone please tell me what am I doing wrong ?

推荐答案

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

It looks like delta_new and delta_0 are Numpy arrays, and Numpy doesn't know how to compare them.

作为一个例子,假设您是否采用了两个随机的Numpy数组并尝试进行比较:

As an example, imagine if you took two random Numpy arrays and tried to compare them:

>>> 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()

您必须基本上选择"如何将所有数组中所有值的比较折叠成一个布尔值.

You have to basically "pick" how to collapse the comparisons of all of the values across all of your arrays down to a single bool.

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

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

这篇关于NumPy错误:具有多个元素的数组的真值不明确.使用a.any()或a.all()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆