在pytorch中编写自己的损失函数时的一些细节

问题描述 投票:0回答:1

当我编写自己的损失函数代码时,我需要计算张量数据类型图像的每个像素的损失值,然后将所有损失值相加计算平均值。但是当我运行代码时,它显示像这样的错误:

element 0 of tensors does not require grad and does not have a grad_fn

因此我想问一下,如果你想自己写损失函数的代码,是不是可以采用单独计算单个像素损失值的方法呢?

任何帮助和建议将不胜感激。

deep-learning pytorch loss-function
1个回答
0
投票

我想说,自定义损失函数的主要要求是它必须可微分,因此 autograd 可以通过它传播误差。

最好的方法是继承torch的

nn.Module
并确保不会破坏计算图,例如:

class MyLoss(nn.Module):
    def __init__(self, reduction="mean"):
        super().__init__()
        self.reduction = reduction

    def forward(self, input, target):
        # Some dummy loss:
        loss = target - input

        # Return mean value of the whole batch:
        if self.reduction == "mean":
            return loss.mean()
        else:
            # Otherwise return raw (no reduction) loss values:
            return loss

我不知道你想要实现什么样的损失,但错误基本上告诉你损失计算中使用的一些张量有

requires_grad=False
所以 autograd 不知道如何计算该特定张量的梯度。

© www.soinside.com 2019 - 2024. All rights reserved.