gpt4 book ai didi

python - 逻辑回归的 MLE 对数似然给出除以零误差

转载 作者:行者123 更新时间:2023-11-30 09:08:23 26 4
gpt4 key购买 nike

我想计算逻辑回归模型的对数似然。

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

def logll(y, X, w):
""""
Parameters
y : ndarray of shape (N,)
Binary labels (either 0 or 1).
X : ndarray of shape (N,D)
Design matrix.
w : ndarray of shape (D,)
Weight vector.
"""
p = sigma(X @ w)
y_1 = y @ np.log(p)
y_0 = (1 - y) @ (1 - np.log(1 - p))
return y_1 + y_0

logll(y, Xz, np.linspace(-5,5,D))

应用此函数会导致

/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:16: 
RuntimeWarning: divide by zero encountered in log
app.launch_new_instance()

我希望 y_0 是负 float 。如何避免此错误?代码中是否存在错误?

编辑 1

X @ w statistics:
Max: 550.775133944
Min: -141.972597608
Sigma(max): 1.0 => Throws error in y_0 in np.log(1 - 1.0)
Sigma(min): 2.19828642169e-62

编辑2

我还可以访问这个在对数空间中计算 sigma 的 Logsigma 函数:

def logsigma (x):
return np.vectorize(np.log)(sigma(x))

不幸的是,我没有找到重写 y_0 的方法。以下是我的做法,但显然不正确。

def l(y, X, w):
y_1 = np.dot(y, logsigma(X @ w))
y_0 = (1 - y) @ (1 - np.log(1 - logsigma(X @ w)))
return y_1 + y_0

最佳答案

首先,我认为您在对数似然公式中犯了一个错误:它应该是 y_0y_1 的简单总和,而不是指数:

log-likelihood

除以零可能是由 X @ w 中较大的负值(我的意思是绝对值较大)引起的,例如sigma(-800) 在我的机器上恰好是 0.0,因此它的日志会导致“RuntimeWarning:在日志中遇到除零” .

确保使用接近零的小值初始化网络,并且在多次反向传播迭代后不会出现梯度爆炸。

顺便说一句,这是我用于交叉熵损失的代码,它也适用于多类问题:

def softmax_loss(x, y):
"""
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth class
for the ith input.
- y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and
0 <= y[i] < C
"""
probs = np.exp(x - np.max(x, axis=1, keepdims=True))
probs /= np.sum(probs, axis=1, keepdims=True)
N = x.shape[0]
return -np.sum(np.log(probs[np.arange(N), y])) / N

UPD:当没有其他帮助时,还有一个数字技巧(在评论中讨论):计算 log(p+epsilon)log(1-p+epsilon) 具有较小的正 epsilon 值。这可以确保 log(0.0) 永远不会发生。

关于python - 逻辑回归的 MLE 对数似然给出除以零误差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46510929/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com