Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.vectorize returns incorrect values

I am having some problems with the numpy.vectorize function.

I have defined a function that works well for single element input but the vectorized version returns different results - What am I doing wrong?

Code:

def c_inf_comp(z):
    if z>0:
        return np.exp(-1./(z*z))
    else:
        return 0


>>> x = np.array([-10., 10.])
>>> x
array([-10.,  10.])
>>> c_inf_comp(x[0])
0
>>> c_inf_comp(x[1])
0.99004983374916811
>>> vfunz = np.vectorize(c_inf_comp)
>>> vfunz(x)
array([0, 0])
like image 928
Donbeo Avatar asked Oct 11 '14 15:10

Donbeo


People also ask

What does vectorize do in numpy?

Define a vectorized function which takes a nested sequence of objects or numpy arrays as inputs and returns a single numpy array or a tuple of numpy arrays. The vectorized function evaluates pyfunc over successive tuples of the input arrays like the python map function, except it uses the broadcasting rules of numpy.

Is numpy vectorize faster than for loop?

Vectorized implementations (numpy) are much faster and more efficient as compared to for-loops. To really see HOW large the difference is, let's try some simple operations used in most machine learnign algorithms (especially deep learning).

Why is numpy vectorize fast?

You will often come across this assertion in the data science, machine learning, and Python community that Numpy is much faster due to its vectorized implementation and due to the fact that many of its core routines are written in C (based on CPython framework).


1 Answers

Because you don't specify otypes (the output data type) when you vectorize your function, NumPy assumes you want to return an array of int32 values.

When given x the vectorized function vfunz first sees -10., returns the integer 0, and so decides that the dtype of the returned array should be int32.

To fix this, specify otypes to be np.float values:

vfunz = np.vectorize(c_inf_comp, otypes=[np.float])

You then get your expected result:

>>> vfunz(x)
array([ 0.        ,  0.99004983])

(Alternatively, the issue can be fixed by returning a float value in the else condition of c_inf_comp, i.e. return 0.0. That way, the function generated by np.vectorize(c_inf_comp) will return an array of float values even if it sees a negative number first.)

like image 140
Alex Riley Avatar answered Oct 12 '22 02:10

Alex Riley