【问题标题】:Do I need to define the backward() in custom loss function?我需要在自定义损失函数中定义backward()吗?
【发布时间】:2018-03-06 02:29:33
【问题描述】:

我已经定义了自己的损失函数。它确实有效。前馈可能没有问题。但是我不确定它是否正确,因为我没有定义backward()。

class _Loss(nn.Module):
    def __init__(self, size_average=True):
        super(_Loss, self).__init__()
        self.size_average = size_average
class MyLoss(_Loss):
    def forward(self, input, target):
        loss = 0
        weight = np.zeros((BATCH_SIZE,BATCH_SIZE))
        for a in range(BATCH_SIZE):
            for b in range(BATCH_SIZE):
                weight[a][b] = get_weight(target.data[a][0])
        for i in range(BATCH_SIZE):
            for j in range(BATCH_SIZE):
                a_ij= (input[i]-input[j]-target[i]+target[j])*weight[i,j]
                loss += F.relu(a_ij)
        return loss

我想问的问题是

1) 我需要定义backward() 到损失函数吗?

2) 如何定义backward()?

3) 在torch中做SGD的时候有什么办法可以做数据的索引吗?

【问题讨论】:

    标签: python-2.7 torch pytorch


    【解决方案1】:

    您可以编写如下所示的损失函数。

    def mse_loss(input, target):
                return ((input - target) ** 2).sum() / input.data.nelement() 
    

    您不需要实现后向功能。损失函数的上述所有参数都应该是 PyTorch 变量,其余的由 torch.autograd 函数处理。

    【讨论】:

    • 感谢您的帮助。但是如果我想倒写怎么办?我知道如何使用链式法则来计算梯度,但我认为我不能为神经网络中的每个权重或偏差编写导数。你有什么指导意见吗?
    • 计算 pyTorch 变量后,调用后向函数将为所有因变量创建梯度。您不需要手动操作。
    猜你喜欢
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 2020-12-19
    • 2017-04-04
    • 2017-12-18
    • 2020-03-27
    • 2020-11-16
    • 2019-05-27
    相关资源
    最近更新 更多