我想在pytorch中实现以下距离损失函数。我一直在关注这个https://discuss.pytorch.org/t/custom-loss-functions/29387/4来自pytorch论坛的线程
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
有了这个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)
附言:我知道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
如何正确实现损失功能?
之所以会发生这种情况,是因为在loss函数中,您正在分离张量。您必须分离,因为您想使用np.linalg.norm
。这破坏了图,你得到的错误是张量没有梯度fn。
您可以更换
loss = torch.tensor(np.linalg.norm(output.detach().numpy() - target.detach().numpy()))
通过火炬操作作为
loss = torch.norm(output-target)
这应该很好用。