仅针对自写loss函数出现:element 0 of tensors does not require grad and does not have a grad_fn

        于写毕设时碰到,因pytorch不提供Dice损失函数,所以需要自写。。。于是照着公式写,写出如下代码

class DiceLoss(nn.Module):
    def __init__(self, smooth=1.):
        super(DiceLoss, self).__init__()
        self.smooth = smooth

    def forward(self, pred, target):
        pred = torch.sigmoid(pred)
        intersection = torch.sum(torch.logical_and(pred, target))
        union = torch.sum(pred) + torch.sum(target)
        dice_score = (2. * intersection + self.smooth) / (union + self.smooth)
        return 1 - dice_score

        我在Debug时,又报了一错,猛然发现intersection变成了整型,这样就导致计算图在这里断开了,因此不能进行逻辑与操作,那就使用乘法来代替,不过这样会导致实际loss和计算公式的loss不同。

intersection = (pred*target).sum()

        希望对同样情况的人有用。在计算loss时不能改变模型的输出值,这样会导致输出值的计算图断裂。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值