# 如何在Python中计算logistic sigmoid函数？

F（x）=？

### 7 Solutions collect form web for “如何在Python中计算logistic sigmoid函数？”

``import math def sigmoid(x): return 1 / (1 + math.exp(-x))` `

` `>>> sigmoid(0.458) 0.61253961344091512` `

` `In [1]: from scipy.stats import logistic In [2]: logistic.cdf(0.458) Out[2]: 0.61253961344091512` `

` `In [3]: from scipy.special import expit In [4]: expit(0.458) Out[4]: 0.61253961344091512` `

## 一些基准：

` `In [5]: def sigmoid(x): ....: return 1 / (1 + math.exp(-x)) ....: In [6]: %timeit -r 1 sigmoid(0.458) 1000000 loops, best of 1: 371 ns per loop In [7]: %timeit -r 1 logistic.cdf(0.458) 10000 loops, best of 1: 72.2 µs per loop In [8]: %timeit -r 1 expit(0.458) 100000 loops, best of 1: 2.98 µs per loop` `

` `In [9]: import numpy as np In [10]: x = np.random.random(1000000) In [11]: def sigmoid_array(x): ....: return 1 / (1 + np.exp(-x)) ....:` `

（你会注意到从`math.exp``np.exp`的细微变化（第一个不支持数组，但是如果你只有一个值计算，速度会快得多））

` `In [12]: %timeit -r 1 -n 100 sigmoid_array(x) 100 loops, best of 1: 34.3 ms per loop In [13]: %timeit -r 1 -n 100 expit(x) 100 loops, best of 1: 31 ms per loop` `

` `def sigmoid(x): "Numerically-stable sigmoid function." if x >= 0: z = exp(-x) return 1 / (1 + z) else: z = exp(x) return z / (1 + z)` `

` `import numpy as np def sigmoid(x): return math.exp(-np.logaddexp(0, -x))` `

` `def nat_to_exp(q): max_q = max(0.0, np.max(q)) rebased_q = q - max_q return np.exp(rebased_q - np.logaddexp(-max_q, np.logaddexp.reduce(rebased_q)))` `

（但是， `logaddexp.reduce`可能更准确。）

` `>>> def sigmoid(x): ... return 1 /(1+(math.e**-x)) ... >>> sigmoid(0.458)` `

` `def sigmoid(x): try: res = 1 / (1 + math.exp(-x)) except OverflowError: res = 0.0 return res` `

` `def normalized_sigmoid_fkt(a, b, x): ''' Returns array of a horizontal mirrored normalized sigmoid function output between 0 and 1 Function parameters a = center; b = width ''' s= 1/(1+np.exp(b*(xa))) return 1*(s-min(s))/(max(s)-min(s)) # normalize function to 0-1` `

` `def draw_function_on_2x2_grid(x): fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) plt.subplots_adjust(wspace=.5) plt.subplots_adjust(hspace=.5) ax1.plot(x, normalized_sigmoid_fkt( .5, 18, x)) ax1.set_title('1') ax2.plot(x, normalized_sigmoid_fkt(0.518, 10.549, x)) ax2.set_title('2') ax3.plot(x, normalized_sigmoid_fkt( .7, 11, x)) ax3.set_title('3') ax4.plot(x, normalized_sigmoid_fkt( .2, 14, x)) ax4.set_title('4') plt.suptitle('Different normalized (sigmoid) function',size=10 ) return fig` `

` `x = np.linspace(0,1,100) Travel_function = draw_function_on_2x2_grid(x)` `

` `sigmoid = lambda x: .5 * (math.tanh(.5 * x) + 1)` `
• 如何使用Python检查文件是否存在？
• 如何将大写字母转换为小写
• Python中的Byte数组
• ImportError：DLL加载失败：％1不是有效的Win32应用程序。 但是DLL在那里
• Python类方法装饰W /自我参数？
• 如何解决：“UnicodeDecodeError：'ascii'编解码器无法解码字节”
• 如何使用“json”模块一次读入一个JSON对象？
• 点构build选项来使用多核
• 在字典中获得最大价值的关键？
• Python - 将UTCdate时间string转换为本地date时间
• 链式方法在Python中调用缩进样式