首页 > 解决方案 > Pytorch中的自定义距离损失函数?

问题描述

我想在 pytorch 中实现以下距离损失函数。我正在关注来自 pytorch 论坛的 https://discuss.pytorch.org/t/custom-loss-functions/29387/4线程

np.linalg.norm(output - target)
# where output.shape = [1, 2] and target.shape = [1, 2]

所以我已经实现了这样的损失函数

def my_loss(output, target):    
    loss = torch.tensor(np.linalg.norm(output.detach().numpy() - target.detach().numpy()))
    return loss

使用此损失函数,向后调用会产生运行时错误

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

我的整个代码看起来像这样

model = nn.Linear(2, 2)

x = torch.randn(1, 2)
target = torch.randn(1, 2)
output = model(x)

loss = my_loss(output, target)
loss.backward()   <----- Error here

print(model.weight.grad)

PS:我知道pytorch的成对丢失,但由于它的一些限制,我必须自己实现它。

在 pytorch 源代码之后,我尝试了以下操作,

class my_function(torch.nn.Module): # forgot to define backward()
    def forward(self, output, target):

        loss = torch.tensor(np.linalg.norm(output.detach().numpy() - target.detach().numpy()))
        return loss

model = nn.Linear(2, 2)
x = torch.randn(1, 2)
target = torch.randn(1, 2)
output = model(x)

criterion = my_function()

loss = criterion(output, target)


loss.backward()
print(model.weight.grad)

我得到运行时错误

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

如何正确实现损失函数?

标签: pytorchloss-function

解决方案


发生这种情况是因为,在损失函数中,您正在分离张量。您必须分离,因为您想使用np.linalg.norm. 这会破坏图表,您会得到张量没有 grad fn 的错误。

你可以更换

loss = torch.tensor(np.linalg.norm(output.detach().numpy() - target.detach().numpy()))

通过火炬操作作为

loss = torch.norm(output-target)

这应该可以正常工作。


推荐阅读