python - 如何在pytorch中实现可微分的汉明损失?

标签 python pytorch loss-function hamming-distance differentiation

如何实现计算错误预测次数的可微损失函数?

output = [1,0,4,10]
target = [1,2,4,15]
loss = np.count_nonzero(output != target) / len(output) # [0,1,0,1] -> 2 / 4 -> 0.5

enter image description here

我已经尝试了一些实现,但它们是不可区分的。 RuntimeError:张量的元素 0 不需要 grad 并且没有 grad_fn

def hamming_loss(output, target):
  #loss = torch.tensor(torch.nonzero(output != target).size(0)).double() / target.size(0)
  #loss = torch.sum((output != target), dim=0).double() / target.size(0)
  loss = torch.mean((output != target).double())
  return loss

也许有一些相似但不同的损失函数?

最佳答案

为什么不将离散预测(例如,[1, 0, 4, 10])转换为“软”预测,即每个标签的概率(例如,输出 变成一个 4x(num labels) 个概率向量。
一旦有了“软”预测,就可以计算预测输出概率与所需目标之间的交叉熵损失。

关于python - 如何在pytorch中实现可微分的汉明损失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60599365/

相关文章:

pytorch - 谷歌合作实验室导入 torch 错误

keras - 使用不同的损失函数恢复训练

pytorch - 将张量元组/列表视为单个张量

python - 将字符串传递给python中的文件打开函数

python - Pyparsing 生成带组的二叉 AST 树

python - 查找函数的最小值和最大值

python - torch 服务加载模型失败

python - 属性错误 : 'Tensor' object has no attribute 'numpy' when using a Keras-based custom loss function

python - Keras 中带有权重的自定义损失函数

python - 在 Python 3 中使用 Open Arbitrary 标签解析 SGML