How to apply a function / map values of each element in a 2d numpy array/matrix?

后端 未结 2 482
自闭症患者
自闭症患者 2020-12-25 09:50

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]         


        
相关标签:
2条回答
  • 2020-12-25 10:26

    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
    
    0 讨论(0)
  • 2020-12-25 10:35

    Just in case this helps, scipy has a sigmoid function you can directly call on a matrix.

    0 讨论(0)
提交回复
热议问题