我正在使用PyTorch训练卷积神经网络(CNN)来解决一个回归问题,其中输出是包含20个值的张量。我计划使用均方根误差(RMSE)作为模型的损失函数,并尝试使用PyTorch的nn.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
但是我的loss_function()
输出结果与PyTorch使用nn.MSELoss()
实现的不同。我不确定是我的实现有误还是我错误地使用了nn.MSELoss()
。
torch.sqrt()
和nn.MSELoss()
来获取 RMSE。我已经在我的问题中更新了这个。然而问题是,在我的原始损失函数中,如果我在批量大小平均化之后再取平方根,它符合 PyTorch 的版本,但如果我像在我的帖子中所做的那样在之前应用它,结果就会不同。 - cronin