Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

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

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

I get the below error:

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

on line while i < imax and delta_new > epsilon**2 * delta_0:

Could anyone please tell me what am I doing wrong ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...