【问题标题】:Custom distance loss function in Pytorch?Pytorch中的自定义距离损失函数?
【发布时间】: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


    【解决方案1】:

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

    你可以替换

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

    通过火炬操作作为

    loss = torch.norm(output-target)

    这应该可以正常工作。

    【讨论】:

    • 所以我猜都需要一直使用火炬操作?我需要写回传吗?
    • 你不需要自己写backward pass只要你使用了所有的torch函数和PyTorch的自动微分(调用backward函数)。
    • 正如@akshayk07 所说,使用可微分的火炬函数,这将确保计算图可微分并且.backward 可以工作
    猜你喜欢
    • 2019-05-27
    • 2018-07-14
    • 2021-11-13
    • 1970-01-01
    • 2020-02-09
    • 2018-09-24
    • 2021-02-20
    • 2021-01-14
    • 2018-08-04
    相关资源
    最近更新 更多