在对神经网络的损失函数进行修改时遇到标题中的问题
修改过程如下:
- 原始损失函数在网络训练框架下继承自:
class BCL(nn.Module):
"""
批次平衡对比损失变化,-1与1
"""
def __init__(self, margin=2.0):
super(BCL, self).__init__()
self.margin = margin
def forward(self, distance, label):
label[label == 255] = 1
mask = (label != 255).float()
distance = distance * mask
pos_num = torch.sum((label == 1).float()) + 0.0001
neg_num = torch.sum((label == -1).float()) + 0.0001
loss_1 = torch.sum((1 + label) / 2 * torch.pow(distance, 2)) / pos_num
loss_2 = torch.sum((1 - label) / 2 * mask *
torch.pow(torch.clamp(self.margin - distance, min=0.0), 2)
) / neg_num
loss = loss_1 + loss_2
return loss
- 在修改过程中替换为BCE损失:
class BCE(nn.Module):
def __init__(self):
super(BCE, self).__init__()
self.bce = nn.BCE()
def forward(self, pred, label):
mask = (label != 255).float()
bce = self.bce(pred, mask)
return bce
- 经过多方验证与修改,未能解决问题。
经调试发现,在传播过程中BCE在网络返回值与标签值均为内存地址,而BCL为Tensor张量可见
其中,在反向传播位置参考方法:https://blog.csdn.net/wu_xin1/article/details/116502378进行了修改,能够解决报错问题,但是能够从评论区看出该方法治标不治本,并且存在漏洞,在本实验中表现为初轮iteration损失巨巨巨高(高达97…,而正常损失之介于0…~20)
-
经多方查阅,采用BCEWithLogitsLoss方法,参考博客:https://www.cnblogs.com/zhangxianrong/p/14773075.html
能够有效解决该问题 -
经测试发现,该处报错与损失计算时传入的结果数据有关联,由于在网络输出时,对神经网络输出结果进行了适当处理,发现在进行计算时需要传入网络类出口值(涉及前向传播反向传播与梯度计算问题)才能避免报错,同类型报错包括RuntimeError: Boolean value of Tensor with more than one value is ambiguous