我需要计算模型的损失。损失需要输出的对数。这是为那些想知道的人提供的演员评论家模型。 我使用一个使用 relu 和 softmax 的网络来确保这些值不会太高或为负值。但有时它们是 0。这不好,因为我无法记录它的日志。
我该怎么做才能避免这种情况?
我尝试使用自定义 relu 函数,但由于某种原因它不起作用。
我还尝试在值为 0 的情况下将值增加 0.01,但随后出现错误,表明存在本地更改。
损失函数如下所示。其中P是模型的输出,eta和值常量是一些不重要的值。 a[t] 是时间 t 的动作。这也不重要。重要的是 P 输出不应该是 0.0。
x = self.eta*P*torch.log(P)
theta_loss += -value_constant*torch.log(P[a[t]])+torch.sum(x)
这是relu函数
class MyReLU(torch.autograd.Function):
@staticmethod
def forward(ctx, inp):
ctx.save_for_backward(inp)
# out = torch.zeros_like(inp).cuda()
# out[inp > 0.01] = inp
return torch.where(inp < 0.01, 0.01, inp)
@staticmethod
def backward(ctx, grad_output):
inp, = ctx.saved_tensors
# grad_input = grad_output.clone()
# grad_input[inp < 0.01] = 0
grad = torch.where(inp <= 0.01,0.0,1)
return grad_output * grad
下面的方法使用
nn.Softplus
和 .clamp
在获取对数之前将任意值张量映射到非零值。
P_nonneg = nn.Softplus(P_original) #constrain it to be >= 0
P_nonzero = torch.clamp(P_nonneg, min=1e-10) #prevent 0
loss = torch.log(P_nonzero) #safely take log