在二维数组上使用函数时处理 numpy.exp 溢出
Handling numpy.exp overflow when using function on 2d-array
我有一个 2d numpy 数组,我想在上面使用我的函数 sigmoid(x),它是:
def sigmoid(x):
return 1 / (1 + np.exp(-x))
我的问题是我的输入太大了,比如 3000,我收到了这个警告:
RuntimeWarning: overflow encountered in exp
return 1 / (1 + np.exp(-x/8.))
我试图将值分配给超过某个数字的输入,例如 700 -> 1 和 -700 -> 0,但是,这非常慢,因为我必须以这种方式遍历整个数组。
我也调查了 np.logandexp(x1, x2)
但我无法让它工作...
编辑:
数据类型是 float64 btw
您可以将您的输入转换为对数 space 和 运行 sigmoid 之后,这将显着降低大值 运行ken。
您可以使用 SciPy's expit()
function,它表现得很好:
In [114]: from scipy.special import expit
# sample input array
In [115]: x = np.arange(50000, dtype=np.float64)
In [116]: sigm = expit(x)
# sanity check for no `np.inf`
In [117]: expit(70000.0)
Out[117]: 1.0
我有一个 2d numpy 数组,我想在上面使用我的函数 sigmoid(x),它是:
def sigmoid(x):
return 1 / (1 + np.exp(-x))
我的问题是我的输入太大了,比如 3000,我收到了这个警告:
RuntimeWarning: overflow encountered in exp
return 1 / (1 + np.exp(-x/8.))
我试图将值分配给超过某个数字的输入,例如 700 -> 1 和 -700 -> 0,但是,这非常慢,因为我必须以这种方式遍历整个数组。
我也调查了 np.logandexp(x1, x2)
但我无法让它工作...
编辑: 数据类型是 float64 btw
您可以将您的输入转换为对数 space 和 运行 sigmoid 之后,这将显着降低大值 运行ken。
您可以使用 SciPy's expit()
function,它表现得很好:
In [114]: from scipy.special import expit
# sample input array
In [115]: x = np.arange(50000, dtype=np.float64)
In [116]: sigm = expit(x)
# sanity check for no `np.inf`
In [117]: expit(70000.0)
Out[117]: 1.0