Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

Effectively you have a matrix delta_new which is being compared to another matrix epsilon**2 * delta_0 which produces multiple truth values.

With multiple truth values, there is not definitive yes or no.

So that condition can use .all (and for each element) or .any (or for each element) to resolve this multiplicity.

Solution 3:

delta_new is a matrix. Linear arithmetic comparison operations are not defined for matrices. You tried to compare a matrix of values to another matrix of values with a simple scalar comparison. Python doesn't know how to give you a single T/F result from this.

I suspect that you want some scalar property on the matrices, such as determinant.

Solution 4:

this also occurs for sparse matrices e.g.: `scipy.sparse.csr.csr_matrix

workaround is to add todense()

Post a Comment for "Numpy Error: The Truth Value Of An Array With More Than One Element Is Ambiguous. Use A.any() Or A.all()"