【问题标题】:Handling numpy.exp overflow when using function on 2d-array在二维数组上使用函数时处理 numpy.exp 溢出
【发布时间】:2019-09-04 15:09:29
【问题描述】:

我有一个 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

【问题讨论】:

  • 你的数组dtype是什么?
  • 数据类型为float64
  • 为什么不使用scipy.special.expit?或者,忽略或抑制警告;它们是无害的,因为无论如何你都应该得到正确的浮点结果。

标签: python numpy exponentiation sigmoid


【解决方案1】:

您可以使用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

【讨论】:

    【解决方案2】:

    您可以将输入转换为日志空间并在之后运行 sigmoid,这会显着缩小较大的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 2014-07-13
      • 1970-01-01
      • 2015-09-23
      • 2017-10-28
      • 2013-02-16
      相关资源
      最近更新 更多