python中的sigmoid函数
我试图理解为什么我的sigmoid函数当输入为37时,输出为1。S形函数:python中的sigmoid函数,python,math,sigmoid,Python,Math,Sigmoid,我试图理解为什么我的sigmoid函数当输入为37时,输出为1。S形函数: import math def sigmoid(x): return 1 / (1 + math.e ** -x) def p5map(n, start1, stop1, start2, stop2): return ((float(n)-start1)/(stop1-start1))*(stop2-start2)+start2 我的数学不好,但我认为永远不应该有f(x)等于1的时刻,对吗?也许是因
import math
def sigmoid(x):
return 1 / (1 + math.e ** -x)
def p5map(n, start1, stop1, start2, stop2):
return ((float(n)-start1)/(stop1-start1))*(stop2-start2)+start2
我的数学不好,但我认为永远不应该有f(x)等于1的时刻,对吗?也许是因为e常数不够精确,但我真正的问题是,当f(x)为0时,我想把一个介于0和1之间的数字映射到x,当f(x)为1时,x是什么。我的地图功能:
import math
def sigmoid(x):
return 1 / (1 + math.e ** -x)
def p5map(n, start1, stop1, start2, stop2):
return ((float(n)-start1)/(stop1-start1))*(stop2-start2)+start2
举个例子,我想做
p5map(y, 0, 1, -37, 37)
其中y在s形曲线中为f(x),而-37和37分别为f(x)为0和1。使用-37和37对我来说不起作用,所以我要问的是为什么它是37,我如何修正它,使它介于-1和1之间。例如,您使用的是常规浮点数,它只能容纳15或16个有效数字。当您计算
math.e**-37
时,结果是
8.533047625744083e-17
当您将其添加到一个中时,您可能希望
1.00000000000000008533047625744083
但实际上,计算机删除了除前16位以外的所有数字,并给出
1.000000000000000
这只是1
。事实上,将1e-16
添加到1
只会得到1
。当您添加1e-15
时,您确实会得到一个以外的结果,但这比您正在尝试的要大
有几种方法可以得到你想要的。一种方法是使用Python的decimal模块,它向数字和计算中添加更多的有效数字,您可以添加任意数量的数字。使用十进制
from decimal import Decimal
print(1 / (1 + Decimal(-37).exp()))
你得到
Decimal('0.9999999999999999146695237430')
对于-37
得到的sigmoid函数1/(1+D(37).exp())
给出
Decimal('8.533047625744065066149031992E-17')
这不是零
另一个解决方案是使用另一个不同于您使用的sigmoid函数,它比您的函数更慢地接近1。缓慢接近1
的是
0.5 * (1 + x / (1 + abs(x)))
对37
执行此操作会产生
0.986842105263158
这远远不是1
,而-37
的结果是
0.01315789473684209
选择您想要的解决方案。很简单:
math.e**-37
近似于0,将整个表达式计算为1/1
,即1。但是使用math.exp(x)
而不是math.e**x
。答案非常漂亮,解释得很好。