PyTorch 中多输出回归问题的 RMSE 损失

cro*_*nin 7 python artificial-intelligence deep-learning pytorch loss-function

我正在使用 PyTorch 训练 CNN 架构来解决回归问题,其中我的输出是 20 个值的张量。我计划使用 RMSE 作为模型的损失函数,并尝试使用 PyTorchnn.MSELoss()并对其进行平方根,torch.sqrt()但在获得结果后感到困惑。我会尽力解释原因。很明显,对于批量大小,bs我的输出张量的尺寸将为[bs , 20]。我尝试实现我自己的 RMSE 函数:

   def loss_function (predicted_x , target ):
        loss = torch.sum(torch.square(predicted_x - target) , axis= 1)/(predicted_x.size()[1]) #Taking the mean of all the squares by dividing it with the number of outputs i.e 20 in my case
        loss = torch.sqrt(loss)
        loss = torch.sum(loss)/predicted_x.size()[0]  #averaging out by batch-size
        return loss
Run Code Online (Sandbox Code Playgroud)

但是我的输出loss_function()和 PyTorch 如何实现它是nn.MSELoss()不同的。我不确定我的实现是否错误或者我是否nn.MSELoss()以错误的方式使用。

KsE*_*uro 4

MSE 损失是误差平方平均值。您在计算 MSE 后取平方根,因此无法将损失函数的输出与 PyTorch 函数\xe2\x80\x94 的输出进行比较,它们计算不同的值。nn.MSELoss()

\n\n

但是,您可以使用nn.MSELoss()创建自己的 RMSE 损失函数,如下所示:

\n\n
loss_fn = nn.MSELoss()\nRMSE_loss = torch.sqrt(loss_fn(prediction, target))\nRMSE_loss.backward()\n
Run Code Online (Sandbox Code Playgroud)\n\n

希望有帮助。

\n