Pytorch 中的自定义距离损失函数?

Custom distance loss function in 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的pairwise loss但是由于它的一些限制,我不得不自己实现它。

根据 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

如何正确实现损失函数?

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

你可以替换

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

通过手电筒操作

loss = torch.norm(output-target)

这应该可以正常工作。