【问题标题】:How to avoid an overflow in numpy.exp()如何避免 numpy.exp() 中的溢出
【发布时间】:2018-04-13 03:52:47
【问题描述】:

我阅读了很多关于堆栈溢出的内容,但我仍然无法理解如何避免溢出错误。我正在构建一个使用sigmoid function 的神经网络。 但如果不转换或找到解决这些错误的方法,我就无法继续。

def activation(x):
    return  1/(1+np.exp(-x))

  def dactivation(x):
    return  activation(x)*(1-activation(x))


  def propagateb(self, target, lrate=8.1, momentum=0.1):
        deltas = []
        error = target - self.layers[-1]
        delta = error*dactivation(self.layers[-1])
        deltas.append(delta)
        for i in range(len(self.shape)-2,0,-1):
            delta =np.dot(deltas[0],self.weights[i].T)*dactivation(self.layers[i])
            deltas.insert(0,delta)
        for i in range(len(self.weights)):
            layer = np.atleast_2d(self.layers[i])
            delta = np.atleast_2d(deltas[i])
            dw = np.dot(layer.T,delta)
            self.weights[i] += lrate*dw + momentum*self.dw[i]
            self.dw[i] = dw

        # Return error
        return (error**2).sum()

提高

ann.py:5: RuntimeWarning: overflow encountered in exp
  return  1/(1+np.exp(-x))

【问题讨论】:

    标签: python numpy exp


    【解决方案1】:

    看起来传入的数据必须是整数,尽管这个激活函数应该返回一个浮点数。我认为修复就像

    一样简单
    return  1./(1.+np.exp(-x))
    

    我猜如果没有这个更改,代码会尝试进行整数除法,从而产生错误。

    【讨论】:

      【解决方案2】:

      SciPy comes with a function to do that,它不会给你那个警告:

      scipy.special.expit(x)
      

      【讨论】:

        【解决方案3】:

        使用 numpy 整数时必须小心,因为它们不具有任意精度,如此处所述Can Integer Operations Overflow in Python?

        对于 numpy double,该范围是 (-1.79769313486e+308, 1.79769313486e+308)

        还可以看看这个answer,它描述得很好。

        Here 是有关 numpy dtypes 及其允许范围的更多信息。

        【讨论】:

          【解决方案4】:

          这个想法是你应该避免在something 太大的情况下调用exp(something)。所以避免在x >> 0时使用exp(x),在x << 0时避免使用exp(-x)

          为了实现这一点,您可以先编写一个适用于 x > 0 的表达式和另一个适用于 x

          1. 使用 x > 0,您可以安全地使用您的表达式:1/(1+exp(-x))
          2. 对于 x exp(x) 来重写该表达式,得到 exp(x) / (1+exp(x))。如您所见,这里不再有exp(-x)

          您可以找到适用于这两种情况的表达式:

          鉴于 x 是一个矩阵,我在这里的个人实验中使用了np.exp(np.fmin(x, 0)) / (1 + np.exp(-np.abs(x)))https://github.com/thirionjl/chains/blob/master/chains/operations/activation_ops.py#L42

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-08-28
            • 1970-01-01
            • 1970-01-01
            • 2010-11-30
            • 1970-01-01
            • 2011-11-23
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多