I am working on an Image Convolution code using numpy:
JavaScript
x
23
23
1
def CG(A, b, x, imax=10, epsilon = 0.01):
2
steps=np.asarray(x)
3
i = 0
4
r = b - A * x
5
d = r.copy()
6
delta_new = r.T * r
7
delta_0 = delta_new
8
while i < imax and delta_new > epsilon**2 * delta_0:
9
q = A * d
10
alpha = float(delta_new / (d.T * q))
11
x = x + alpha * d
12
if i%50 == 0:
13
r = b - A * x
14
else:
15
r = r - alpha * q
16
delta_old = delta_new
17
delta_new = r.T * r
18
beta = float(delta_new / delta_old)
19
d = r + beta * d
20
i = i + 1
21
steps = np.append(steps, np.asarray(x), axis=1)
22
return steps
23
I get the below error:
JavaScript
1
2
1
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
2
on line while i < imax and delta_new > epsilon**2 * delta_0:
Could anyone please tell me what am I doing wrong ?
Advertisement
Answer
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:
JavaScript
1
7
1
>>> a = np.array([1, 3, 5])
2
>>> b = np.array([5, 3, 1])
3
>>> print(a<b)
4
array([True, False, False])
5
>>> bool(a<b)
6
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
7
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.
JavaScript
1
6
1
>>> (a<b).any()
2
True
3
4
>>> (a<b).all()
5
False
6