Applying a function along a numpy array

后端 未结 4 689
情话喂你
情话喂你 2021-02-07 05:00

I\'ve the following numpy ndarray.

[ -0.54761371  17.04850603   4.86054302]

I want to apply this function to all elements of the array

4条回答
  •  不知归路
    2021-02-07 05:49

    Function numpy.apply_along_axis is not good for this purpose. Try to use numpy.vectorize to vectorize your function: https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html This function defines a vectorized function which takes a nested sequence of objects or numpy arrays as inputs and returns an single or tuple of numpy array as output.

    import numpy as np
    import math
    
    # custom function
    def sigmoid(x):
      return 1 / (1 + math.exp(-x))
    
    # define vectorized sigmoid
    sigmoid_v = np.vectorize(sigmoid)
    
    # test
    scores = np.array([ -0.54761371,  17.04850603,   4.86054302])
    print sigmoid_v(scores)
    

    Output: [ 0.36641822 0.99999996 0.99231327]

    Performance test which shows that the scipy.special.expit is the best solution to calculate logistic function and vectorized variant comes to the worst:

    import numpy as np
    import math
    import timeit
    
    def sigmoid_(x):
      return 1 / (1 + math.exp(-x))
    sigmoidv = np.vectorize(sigmoid_)
    
    def sigmoid(x):
       return 1 / (1 + np.exp(x))
    
    print timeit.timeit("sigmoidv(scores)", "from __main__ import sigmoidv, np; scores = np.random.randn(100)", number=25),\
    timeit.timeit("sigmoid(scores)", "from __main__ import sigmoid, np; scores = np.random.randn(100)",  number=25),\
    timeit.timeit("expit(scores)", "from scipy.special import expit; import numpy as np;   scores = np.random.randn(100)",  number=25)
    
    print timeit.timeit("sigmoidv(scores)", "from __main__ import sigmoidv, np; scores = np.random.randn(1000)", number=25),\
    timeit.timeit("sigmoid(scores)", "from __main__ import sigmoid, np; scores = np.random.randn(1000)",  number=25),\
    timeit.timeit("expit(scores)", "from scipy.special import expit; import numpy as np;   scores = np.random.randn(1000)",  number=25)
    
    print timeit.timeit("sigmoidv(scores)", "from __main__ import sigmoidv, np; scores = np.random.randn(10000)", number=25),\
    timeit.timeit("sigmoid(scores)", "from __main__ import sigmoid, np; scores = np.random.randn(10000)",  number=25),\
    timeit.timeit("expit(scores)", "from scipy.special import expit; import numpy as np;   scores = np.random.randn(10000)",  number=25)
    

    Results:

    size        vectorized      numpy                 expit
    N=100:   0.00179314613342 0.000460863113403 0.000132083892822
    N=1000:  0.0122890472412  0.00084114074707  0.000464916229248
    N=10000: 0.109477043152   0.00530695915222  0.00424313545227
    

提交回复
热议问题