Reputation: 428
How can I implement with numpy the following piecewise function and its derivative?:
I tried to:
def func(n):
return beta * ((0 < n) * n + (n <= 0) * (k * np.exp(n) - alpha))
with its derivative (back propagation):
def func_prime(n)
return (n <= 0) * np.multiply(beta ,k, np.exp(n)) + (beta)
However its not working. Thus, how can I implement the above function with numpy (note that n is an array).
Upvotes: 1
Views: 630
Reputation: 552
To compute the function and its derivative you can follow below procedure:
fun = np.where(n<=0, beta*K*(np.exp(n)-1), beta*n)
derivativ = np.where(n<=0, beta*K*(np.exp(n)), beta)
you can also use scipy.misc.derivative.https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.misc.derivative.html
Upvotes: 1
Reputation: 1294
Probably you need numpy.where
for you goal.
Also keep in mind, numpy arrays could be used for vector operations directly (most times).
Sample code below:
In [1]: import numpy as np
In [2]: n = np.random.random(10)-0.5
In [3]: n
Out[3]:
array([ 0.15714377, -0.30756307, 0.02925383, -0.05156817, -0.32182295,
-0.32772489, 0.15692736, -0.24274195, -0.19055825, 0.25264444])
In [4]: beta=1.0
In [5]: K=2.0
In [6]: np.where(n<=0, beta*K*(np.exp(n)-1), beta*n)
Out[6]:
array([ 0.15714377, -0.52952701, 0.02925383, -0.10052219, -0.55034698,
-0.55887755, 0.15692736, -0.43105215, -0.34700477, 0.25264444])
In [7]:
From numpy.where
manual:
numpy.where(condition[, x, y])
Return elements, either from x or y, depending on condition.
Upvotes: 1