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 should do it:
import math
def sigmoid(x):
return 1 / (1 + math.exp(-x))
And now you can test it by calling:
>>> sigmoid(0.458)
0.61253961344091512
Update: Note that the above was mainly intended as a straight one-to-one translation of the given expression into Python code. It is not tested or known to be a numerically sound implementation. If you know you need a very robust implementation, I'm sure there are others where people have actually given this problem some thought.
Just because I need it so often to try little things:
sigmoid = lambda x: 1 / (1 + math.exp(-x))
This does not work for extreme negative values of x. I was using this unfortunate implementation until I noticed it was creating NaNs.
If you replace
math.exp
withnp.exp
you won't get NaNs, although you will get runtime warnings.Using
math.exp
with numpy array can yield some errors, like:TypeError: only length-1 arrays can be converted to Python scalars
. To avoid it you should usenumpy.exp
.Can numerical instability be mitigated simply by adding
x = max(-709,x)
before the expression?