梯度计算所需的变量之一已通过就地操作进行了修改



这是我的LosFunction,当我使用这个函数时,它会出错
我已经使用nn.L1Loss()而不是LossFunction进行了测试,网络正常。
我该怎么办?谢谢你的帮助!

class LossV1(nn.Module):
def __init__(self,weight=1,pos_weight=1,scale_factor=2.5):
super(LossV1,self).__init__()
self.weight = weight
self.pos_weight = pos_weight
self.scale_factor = scale_factor
def forward(self,pred,truth):
objmask = torch.tensor(truth[:,:6,:,:],dtype=torch.float32,requires_grad=False)
#没有物体的Boxes,置信度损失*0.4
objmask[objmask<0.65] = 0.4
#辅助Boxes,系数0.8
objmask[(objmask>0.649)*(objmask<0.949)] = 0.8
objLoss = torch.sum(objmask*self.myBCEWithLogitsLoss(pred[:,:6,:,:],truth[:,:6,:,:]))
#没有物体的Boxes,只计算置信度损失
objmask[objmask<0.41] = 0
personLoss = torch.sum(objmask*self.myBCEWithLogitsLoss(pred[:,6:12,:,:],truth[:,6:12,:,:]))
carLoss = torch.sum(objmask*self.myBCEWithLogitsLoss(pred[:,12:18,:,:],truth[:,12:18,:,:]))
wLoss = torch.sum(objmask*self.myL2Loss(pred[:,18:24,:,:],truth[:,18:24,:,:]))
hLoss = torch.sum(objmask*self.myL2Loss(pred[:,24:,:,:],truth[:,24:,:,:]))
return objLoss+personLoss+carLoss+wLoss+hLoss
def myBCEWithLogitsLoss(self,x,y):
#pos_weight>1增加召回,pos_weight<1提高精度
return -self.weight*(self.pos_weight*y*torch.log(torch.sigmoid(x))+(1-y)*torch.log(1-torch.sigmoid(x)))
def myL2Loss(self,x,y):
return torch.pow(self.scale_factor*torch.sigmoid(x/self.scale_factor) - y,2)

我只需删除objmask,并在生成函数中计算它,然后将它传递给带有真值标签的LosFunction,网络就可以工作了
我不明白我已经做了requires_grad=False,为什么pytroch仍然计算梯度。

最新更新