我在用一维卷积网络进行二进制分类。为了研究的目的,我必须实现我自己的损失函数,它类似于BCELoss。因此,我开始尝试用autograd实现我自己的BCE loss函数:
class DiscriminatorLoss(torch.autograd.Function):
@staticmethod
def forward(ctx,d_out,labels):
loss = labels*torch.log(d_out)+(1-labels)*torch.log(1-d_out)
ctx.d_out,ctx.labels = input,labels
return loss
@staticmethod
def backward(ctx, grad_output):
d_out,labels = ctx.d_out,ctx.labels
grad_input = -labels/d_out + ((1-labels)/(1-d_out))
return grad_input,None
其中d_out
和labels
是类张量:
d_out=tensor([[0.5412, 0.5225], | labels=tensor([[0, 1],
[0.5486, 0.5167], | [0, 1],
[0.5391, 0.5061],...])| [0, 1],...])
但是,这不能正常工作。问题是在训练过程的中间,网络(d_out
)的输出会变成奇怪的值,如:
tensor([[9.9000e-08, 9.9000e-01],
[9.9000e-08, 9.9000e-01],
[9.9000e-08, 9.9000e-01],....])
在剩下的训练中它会被卡在那里。你知道吗
我还从Pytorchnn.BCELoss()
(https://pytorch.org/docs/stable/nn.html#loss-functions)实现了BCELoss函数。有了这个函数,网络就起作用了,所以我相信问题出在我的损失函数上。更确切地说,forward()工作得很好,因为它返回与forward()相同的损失nn.b塞洛斯. 所以问题出在backward()中。你知道吗
有人能帮我吗?我在backward()函数中做错了什么?你知道吗
谢谢!你知道吗
注:为了不产生交叉熵损失中的NaN
和-inf
值,网络的输出被视为不完全是0或1。你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐