我正在训练CNN架构,以使用PyTorch解决回归问题,其中我的输出是20个值的张量。我计划使用RMSE作为模型的损失函数,并尝试使用PyTorch的nn.MSELoss()
,但在获得结果后感到困惑。我将尽力解释原因。显然,对于批处理大小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()
。
MSE损失是错误的平方的平均值。您需要在计算出MSE之后取平方根,因此无法将损失函数的输出与PyTorch nn.MSELoss()
函数的输出进行比较-它们正在计算不同的值。
但是,您可以只使用nn.MSELoss()
创建自己的RMSE损失函数,如下:
loss_fn = nn.MSELoss()
RMSE_loss = torch.sqrt(loss_fn(prediction, target))
RMSE_loss.backward()
希望有所帮助。
要复制默认的PyTorch的MSE(均方误差)损失函数,您需要将loss_function
方法更改为以下内容:
def loss_function (predicted_x , target ):
loss = torch.sum(torch.square(predicted_x - target) , axis= 1)/(predicted_x.size()[1])
loss = torch.sum(loss)/loss.shape[0]
return loss
这是上述方法起作用的原因-MSE损失是指均方误差损失。因此,您不必在代码中实现平方根(torch.sqrt
)。默认情况下,PyTorch中的损失会计算批次中所有示例的平均值,以计算损失。因此,该方法的第二行。
要实施RMSELoss并将其集成到您的培训中,您可以这样做:
class RMSELoss(torch.nn.Module):
def __init__(self):
super(RMSELoss,self).__init__()
def forward(self,x,y):
criterion = nn.MSELoss()
loss = torch.sqrt(criterion(x, y))
return loss
并且您可以像调用PyTorch中的任何损失函数一样调用此类。