Predictions vector incorrect

predictions = [1 if x > 0.5 else 0 for x in A2]

I am getting an error for this predictione vector. Please Help understand what is wrong

ValueError                                Traceback (most recent call last)
<ipython-input-70-eb08347ef392> in <module>
      1 parameters, t_X = predict_test_case()
      2 
----> 3 predictions = predict(parameters, t_X)
      4 print("Predictions: " + str(predictions))
      5 

<ipython-input-69-d130e4af21c3> in predict(parameters, X)
     20 
     21     A2,cache = forward_propagation(X, parameters)
---> 22     predictions = [1 if x > 0.5 else 0 for x in A2]
     23 
     24     # YOUR CODE ENDS HERE

<ipython-input-69-d130e4af21c3> in <listcomp>(.0)
     20 
     21     A2,cache = forward_propagation(X, parameters)
---> 22     predictions = [1 if x > 0.5 else 0 for x in A2]
     23 
     24     # YOUR CODE ENDS HERE

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

Expected output

Predictions: [[ True False  True]]
All tests passed!

I think this is related to your other thread regarding errors when plotting the decision boundary.

The predictions are supposed to be “True” or “False”, not integer values of 1 or 0. Mathematically they are the same, but functionally they are different types.

Your code is working too hard. You don’t need an iterator. All you need is a single statement that contains a comparison with >= 0.5. The logical operator will return booleans, and it will do that for the entire vector of A2 values.

2 Likes

The question is what is x is in that expression? It looks like saying “for x in A2” doesn’t do what you think it does.

There is a much simpler way to write code like that which will also probably run a lot faster. Suppose I have an array and I want to know which elements are greater than 0.7? Try this:

myAnswer = (myArray > 0.7)

That will return an array of Booleans of the same shape as myArray.

1 Like

Thankyou I understood what the problem is, the predictions vector i am creating is incorrectly created in python. I am able to resolve it now.

1 Like