This is a logistic sigmoid function:

I know x. How can I calculate F(x) in Python now?
Let's say x = 0.458.
F(x) = ?
This is a logistic sigmoid function:

I know x. How can I calculate F(x) in Python now?
Let's say x = 0.458.
F(x) = ?
Use the numpy package to allow your sigmoid function to parse vectors.
In conformity with Deeplearning, I use the following code:
import numpy as np
def sigmoid(x):
s = 1/(1+np.exp(-x))
return s
A numerically stable version of the logistic sigmoid function.
def sigmoid(x):
pos_mask = (x >= 0)
neg_mask = (x < 0)
z = np.zeros_like(x,dtype=float)
z[pos_mask] = np.exp(-x[pos_mask])
z[neg_mask] = np.exp(x[neg_mask])
top = np.ones_like(x,dtype=float)
top[neg_mask] = z[neg_mask]
return top / (1 + z)
A one liner...
In[1]: import numpy as np
In[2]: sigmoid=lambda x: 1 / (1 + np.exp(-x))
In[3]: sigmoid(3)
Out[3]: 0.9525741268224334
pandas DataFrame/Series or numpy array:The top answers are optimized methods for single point calculation, but when you want to apply these methods to a pandas series or numpy array, it requires apply, which is basically for loop in the background and will iterate over every row and apply the method. This is quite inefficient.
To speed up our code, we can make use of vectorization and numpy broadcasting:
x = np.arange(-5,5)
np.divide(1, 1+np.exp(-x))
0 0.006693
1 0.017986
2 0.047426
3 0.119203
4 0.268941
5 0.500000
6 0.731059
7 0.880797
8 0.952574
9 0.982014
dtype: float64
Or with a pandas Series:
x = pd.Series(np.arange(-5,5))
np.divide(1, 1+np.exp(-x))
you can calculate it as :
import math
def sigmoid(x):
return 1 / (1 + math.exp(-x))
or conceptual, deeper and without any imports:
def sigmoid(x):
return 1 / (1 + 2.718281828 ** -x)
or you can use numpy for matrices:
import numpy as np #make sure numpy is already installed
def sigmoid(x):
return 1 / (1 + np.exp(-x))
import numpy as np
def sigmoid(x):
s = 1 / (1 + np.exp(-x))
return s
result = sigmoid(0.467)
print(result)
The above code is the logistic sigmoid function in python.
If I know that x = 0.467 ,
The sigmoid function, F(x) = 0.385. You can try to substitute any value of x you know in the above code, and you will get a different value of F(x).
Below is the python function to do the same.
def sigmoid(x) :
return 1.0/(1+np.exp(-x))
You can simply declare 1 / np.exp(x) if putting - before x confuse you.
>>> def sigmoid(x):
... return 1 /(1 + 1 / np.exp(x))
...
>>> sigmoid(0.458)