【问题标题】:Code gets stuck at loop number 34/100 "overflow encountered in exp"代码卡在循环号 34/100“exp 中遇到溢出”
【发布时间】:2022-01-25 23:59:11
【问题描述】:

我的代码中有一个特定的for 循环(迭代次数为 100)。不知何故,代码卡在了第 34/100 次迭代。我很确定这个问题与我在循环中使用的这两个函数有关,

def sigmoid(self, a: np.float128):
        """
        inputs:
            v: float

        returns:
            the logistic sigmoid evaluated at a
        """
        return 1 / (1 + scipy.special.expit(-a))
        # return 1 / (1 + np.exp(-a))

def loss(self, w, X, y):
        """
        inputs: w: an array of the current weights, of shape (d,)
                X: an array of n datapoints, of shape (n, d)

        outputs: the loss. This is exactly the negative log likelihood
        """
        E = 10 ** (-8)
        y_pred = self.sigmoid(np.dot(X, w))
        cost = -np.sum(y * np.log(y_pred + E) + (1 - y) * np.log(1 - y_pred + E))
        return cost

代码在开头给出警告:

<ipython-input-65-26bf85bda945>:72: RuntimeWarning:

overflow encountered in exp

所以我通过使用scipy.special.expit(x) 而不是np.exp(x) 摆脱了这个警告。但这似乎并不能解决循环问题。有什么想法吗?

【问题讨论】:

    标签: python numpy loops scipy


    【解决方案1】:

    不要将exp 替换为expit;将sigmoid 替换为expitscipy.special.expit 逻辑sigmoid函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      相关资源
      最近更新 更多