W3_E9: How to implement predictions logic in One Line

Hello Everyone,

> Requirement:
predictions = 1 (if A2 > 0.5)

  •        = 0 otherwise.*
    

> Possible Solutions:

  1. In C language, it could be : predictions = (A2 > 0.5)?1:0
    Issue: Above syntax does not work in Python.

2. if (A2>0.5):

  •  predictions = 1*
    
  • else:*
  •  predictions = 0*
    

Issue: This is NOT a one line solution.

3. predictions = lambda A2 > 0.5,1
Issue: SyntaxError: invalid syntax

4. predictions = 1 if A2 > 0.5 else 0
Issue: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

5. predictions = 1 if A2 > 0.5
Issue: SyntaxError: invalid syntax

> Query: Is there any other One Line answer possible.

Please assist.
Sincerely,
A

1 Like

See numpy.round

1 Like

There is a hint: As an example, if you would like to set the entries of a matrix X to 0 and 1 based on a threshold you would do: X_new = (X > threshold). So check Numpy doc to see if there is an api for this purpose.

1 Like

I agree with @li400100.

This method is applying an element-wise comparison operator to all elements of a vector. It’s a very handy and efficient coding trick.

1 Like

Thank you all for the guidance.
I was able to find three solutions after referring to numpy doc.

@Balaji, It worked, Thanks.

@li400100, @TMosh,
It worked. Thanks.
Comparison logic OR numpy.greater is a very good way to implement.

Thank you for your assistance.
Sincerely,
A