Given the following numpy matrix:
import numpy as np
mymatrix = mymatrix = np.matrix(\'-1 0 1; -2 0 2; -4 0 4\')
matrix([[-1, 0, 1],
[-2, 0, 2]
Apparently the way to apply a function to elements is to convert your function into a vectorized version that takes arrays as input and return arrays as output.
You can easily convert your function to vectorized form using numpy.vectorize
as follows:
myfunc_vec = np.vectorize(myfunc)
result = myfunc_vec(mymatrix)
or for a one shot usage:
np.vectorize(myfunc)(mymatrix)
As pointed out by @Divakar, it's better (performance-wise) if you can write an already vectorized function from scratch (using numpy built ufuncs without using numpy.vectorize
) like so:
def my_vectorized_func(m):
return 1/(1+np.exp(-m)) # np.exp() is a built-in ufunc
myvectorized_func(mymatrix)
Since numpy.exp is already vectorized (and math.exp
wasn't) the whole expression 1/(1+np.exp(-m))
will be vectorized (and faster that applying my original function to each element).
The following complete example produced the required output:
import numpy as np
mymatrix = mymatrix = np.matrix('-1 0 1; -2 0 2; -4 0 4')
import math
def myfunc(z):
return 1/(1+math.exp(-z))
np.vectorize(myfunc)(mymatrix) # ok, but slow
def my_vectorized_func(m):
return 1/(1+np.exp(-m))
my_vectorized_func(mymatrix) # faster using numpy built-in ufuncs
Just in case this helps, scipy has a sigmoid function you can directly call on a matrix.