Far*_*han 0 pytorch loss-function
我想在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]
Run Code Online (Sandbox Code Playgroud)
所以我实现了这样的损失功能
def my_loss(output, target):
loss = torch.tensor(np.linalg.norm(output.detach().numpy() - target.detach().numpy()))
return loss
Run Code Online (Sandbox Code Playgroud)
使用此损失函数,向后调用会产生运行时错误
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
Run Code Online (Sandbox Code Playgroud)
我的整个代码看起来像这样
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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
我得到运行时错误
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
Run Code Online (Sandbox Code Playgroud)
如何正确实现损失功能?
发生这种情况的原因是,在损失函数中,您正在分离张量。您必须分离,因为您想使用np.linalg.norm。这会破坏图形,并且您会得到张量没有梯度fn的错误。
您可以更换
loss = torch.tensor(np.linalg.norm(output.detach().numpy() - target.detach().numpy()))
通过火炬操作
loss = torch.norm(output-target)
这应该工作正常。
| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |