torch - 将我的自定义损失函数添加到 torch

标签 torch

我想向 Torch 添加一个损失函数,用于计算预测值和目标值之间的编辑距离。
有没有一种简单的方法来实现这个想法?
还是我必须编写自己的具有向后和向前功能的类?

最佳答案

如果您的标准可以表示为现有模块和标准的组合,那么使用容器简单地构建这样的组合是一个好主意。唯一的问题是标准容器被设计为仅与模块一起使用,而不是标准。区别在于 :forward方法签名:

module:forward(input)
criterion:forward(input, target)

幸运的是,我们可以自由定义自己的容器,它也可以使用标准。例如,顺序:
local GeneralizedSequential, _ = torch.class('nn.GeneralizedSequential', 'nn.Sequential')

function GeneralizedSequential:forward(input, target)
    return self:updateOutput(input, target)
end

function GeneralizedSequential:updateOutput(input, target)
    local currentOutput = input
    for i=1,#self.modules do
        currentOutput = self.modules[i]:updateOutput(currentOutput, target)
    end
    self.output = currentOutput
    return currentOutput
end

下面是如何实现 nn.CrossEntropyCriterion 的图示拥有这个通用的顺序容器:
function MyCrossEntropyCriterion(weights)
    criterion = nn.GeneralizedSequential()
    criterion:add(nn.LogSoftMax())
    criterion:add(nn.ClassNLLCriterion(weights))
    return criterion
end

检查一切是否正确:
output = torch.rand(3,3)
target = torch.Tensor({1, 2, 3})

mycrit = MyCrossEntropyCriterion()
-- print(mycrit)
print(mycrit:forward(output, target))
print(mycrit:backward(output, target))

crit = nn.CrossEntropyCriterion()
-- print(crit)
print(crit:forward(output, target))
print(crit:backward(output, target))

关于torch - 将我的自定义损失函数添加到 torch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33648796/

相关文章:

python - 如何在python2.7中安装pytorch?

c++ - 从Pytorch C++中的c10::Dict <c10::IValue,c10::IValue>获取值

torch - PyTorch 运行时错误 : Assertion `cur_target >= 0 && cur_target < n_classes' failed

lua 将用户数据转换为字符串

c++ - 如何将张量列表转换为 torch::Tensor?

python - 从文档中了解 PyTorch 伯努利分布

python - 如何保存 torchtext 数据集?

numpy - 是否有一个 torch 函数可以导出两个张量的并集?

python - Pytorch: AttributeError: 'function' 对象没有属性 'copy'

lua - 如何使用交互式 lua 或 torch session 正确地要求 lua 包?