【发布时间】:2020-02-25 01:31:08
【问题描述】:
我想在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
如何正确实现损失函数?
【问题讨论】:
标签: pytorch loss-function