如何在 PyTorch 中添加自定义定位损失函数?

How to add a custom localization loss function in PyTorch?

我有一个 PyTorch 网络,可以使用 Wi-Fi RSS 数据预测设备的位置。所以输出层包含两个对应于 x 和 y 坐标的神经元。我想使用平均定位误差作为损失函数。

ie. loss = mean(sqrt((x_predicted - X_real)^2 + (y_predicted - y_real)^2))

该方程计算预测位置和实际位置之间的误差距离。我怎样才能包含这个而不是 MSE?

正如您在 tutorial 中看到的那样,只需实现一个 criterion 函数(您可以随意命名)并使用它:

def custom_loss(output, label):
   return torch.mean(torch.sqrt(torch.sum((output - label)**2))) 

和代码中的(从链接教程中窃取):

for epoch in range(2):  # loop over the dataset multiple times

    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # get the inputs; data is a list of [inputs, labels]
        inputs, labels = data

        # zero the parameter gradients
        optimizer.zero_grad()

        # forward + backward + optimize
        outputs = net(inputs)
        loss = custom_loss(outputs, labels)
        loss.backward()
        optimizer.step()

        # print statistics
        running_loss += loss.item()
        if i % 2000 == 1999:    # print every 2000 mini-batches
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0

print('Finished Training')

HTH