Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

A numpy vectorized function doesn't return the expected result

First I define a relu function and vectorize it.

Then I feed an arbitrary list into this relu function, but it returns the wrong result, because the value of relu(1.5) should be 1.5.

The code is as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import numpy as np

def relu(x):
    return x if x > 0 else 0

relu = np.vectorize(relu)

print(relu([-3,-1.5,0,1.5,3]))
# result: array([0, 0, 0, 1, 3])

Could you please explain to me why this happens?

>Solution :

Because vectorize assumes the type from the first element unless output type is specified. Use

relu = np.vectorize(relu,otypes=[float])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading