Applying a function along a numpy array

后端 未结 4 692
情话喂你
情话喂你 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:45

    Use np.exp and that will work on numpy arrays in a vectorized fashion:

    >>> def sigmoid(x):
    ...     return 1 / (1 + np.exp(-x))
    ...
    >>> sigmoid(scores)
    array([  6.33581776e-01,   3.94391811e-08,   7.68673281e-03])
    >>>
    

    You will likely not get any faster than this. Consider:

    >>> def sigmoid(x):
    ...     return 1 / (1 + np.exp(-x))
    ...
    

    And:

    >>> def sigmoidv(x):
    ...   return 1 / (1 + math.exp(-x))
    ...
    >>> vsigmoid = np.vectorize(sigmoidv)
    

    Now, to compare the timings. With a small (size 100) array:

    >>> t = timeit.timeit("vsigmoid(arr)", "from __main__ import vsigmoid, np; arr = np.random.randn(100)", number=100)
    >>> t
    0.006894525984534994
    >>> t = timeit.timeit("sigmoid(arr)", "from __main__ import sigmoid, np; arr = np.random.randn(100)", number=100)
    >>> t
    0.0007238480029627681
    

    So, still an order-of-magnitude difference with small arrays. This performance differences stays relatively constant, with a 10,000 size array:

    >>> t = timeit.timeit("vsigmoid(arr)", "from __main__ import vsigmoid, np; arr = np.random.randn(10000)", number=100)
    >>> t
    0.3823414359940216
    >>> t = timeit.timeit("sigmoid(arr)", "from __main__ import sigmoid, np; arr = np.random.randn(10000)", number=100)
    >>> t
    0.011259705002885312
    

    And finally with a size 100,000 array:

    >>> t = timeit.timeit("vsigmoid(arr)", "from __main__ import vsigmoid, np; arr = np.random.randn(100000)", number=100)
    >>> t
    3.7680041620042175
    >>> t = timeit.timeit("sigmoid(arr)", "from __main__ import sigmoid, np; arr = np.random.randn(100000)", number=100)
    >>> t
    0.09544878199812956
    

提交回复
热议问题