pytorch - 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的成对丢失,但由于它的一些限制,我必须自己实现它。
在 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)
这应该可以正常工作。
推荐阅读
- java - 使用 Java Stream 实例化具有索引和特定枚举值的不同数量的新对象
- wordpress - buddypress - 手动激活新用户帐户
- java - 为什么 .isNotNull(); 即使我有一个控制器类,断言也会失败?
- java - 找不到具有 com.example.fileprovider 权限的提供者的元数据
- python-2.7 - 对于 udp 封装的 esp 数据包,udp 标头未占用有效负载长度
- linux - Why mktemp with -u option is stated as unsafe in its manual?
- c++ - Omnet++ INET 中修改的数据包有效负载
- java - java - 如何使用java中的spring test resttemplate将结果转换为特定的模型类型以访问该模型中的字段?
- macos - 在 C:\Program Files\Android\AndroidStudio/Contents 找不到 android studio
- spacy - 如何让泡菜变成空旷的二进制文件